change phpdoc api generator to phpdoc

This commit is contained in:
Manuel Raynaud
2013-08-08 13:26:49 +02:00
parent a70ea40c3e
commit df371355b9
3674 changed files with 3538567 additions and 1503017 deletions

View File

@@ -0,0 +1,80 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core;
use Symfony\Component\Console\Application as BaseApplication;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\HttpKernel\KernelInterface;
class Application extends BaseApplication
{
public $kernel;
public function __construct(KernelInterface $kernel)
{
$this->kernel = $kernel;
parent::__construct("Thelia", Thelia::THELIA_VERSION);
$this->getDefinition()->addOption(new InputOption('--env', '-e', InputOption::VALUE_REQUIRED, 'The Environment name.', $kernel->getEnvironment()));
$this->getDefinition()->addOption(new InputOption('--no-debug', null, InputOption::VALUE_NONE, 'Switches off debug mode.'));
}
public function getKernel()
{
return $this->kernel;
}
public function getContainer()
{
return $this->kernel->getContainer();
}
public function doRun(InputInterface $input, OutputInterface $output)
{
$this->registerCommands();
return parent::doRun($input, $output);
}
protected function registerCommands()
{
$this->kernel->boot();
$container = $this->kernel->getContainer();
foreach ($container->getParameter("command.definition") as $command) {
$r = new \ReflectionClass($command);
if ($r->isSubclassOf('Symfony\\Component\\Console\\Command\\Command') && !$r->isAbstract()) {
$this->add($r->newInstance());
}
}
}
}

View File

@@ -0,0 +1,62 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Bundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Scope;
use Thelia\Core\DependencyInjection\Compiler\RegisterListenersPass;
use Thelia\Core\DependencyInjection\Compiler\RegisterParserPluginPass;
/**
* First Bundle use in Thelia
* It initialize dependency injection container.
*
* @TODO load configuration from thelia plugin
* @TODO register database configuration.
*
*
* @author Manuel Raynaud <mraynaud@openstudio.fr>
*/
class TheliaBundle extends Bundle
{
/**
*
* Construct the depency injection builder
*
* @param \Symfony\Component\DependencyInjection\ContainerBuilder $container
*/
public function build(ContainerBuilder $container)
{
parent::build($container);
$container->addScope(new Scope('request'));
$container->addCompilerPass(new RegisterListenersPass());
$container->addCompilerPass(new RegisterParserPluginPass());
}
}

View File

@@ -0,0 +1,74 @@
<?php
namespace Thelia\Core\Controller;
use Symfony\Component\HttpKernel\Controller\ControllerResolver as BaseControllerResolver;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
/**
* ControllerResolver that supports "a:b:c", "service:method" and class::method" notations in routes definition
* thus allowing the definition of controllers as service (see http://symfony.com/fr/doc/current/cookbook/controller/service.html)
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Franck Allimant <franck@cqfdev.fr>
*/
class ControllerResolver extends BaseControllerResolver
{
protected $container;
/**
* Constructor.
*
* @param ContainerInterface $container A ContainerInterface instance
* @param LoggerInterface $logger A LoggerInterface instance
*/
public function __construct(ContainerInterface $container, LoggerInterface $logger = null)
{
$this->container = $container;
parent::__construct($logger);
}
/**
* Returns a callable for the given controller.
*
* @param string $controller A Controller string
*
* @return mixed A PHP callable
*
* @throws \LogicException When the name could not be parsed
* @throws \InvalidArgumentException When the controller class does not exist
*/
protected function createController($controller)
{
if (false === strpos($controller, '::')) {
$count = substr_count($controller, ':');
if (2 == $count) {
// controller in the a:b:c notation then
$controller = $this->parser->parse($controller);
} elseif (1 == $count) {
// controller in the service:method notation
list($service, $method) = explode(':', $controller, 2);
return array($this->container->get($service), $method);
} else {
throw new \LogicException(sprintf('Unable to parse the controller name "%s".', $controller));
}
}
list($class, $method) = explode('::', $controller, 2);
if (!class_exists($class)) {
throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
}
$controller = new $class();
if ($controller instanceof ContainerAwareInterface) {
$controller->setContainer($this->container);
}
return array($controller, $method);
}
}

View File

@@ -0,0 +1,78 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
/**
* Class RegisterListenersPass
* @package Thelia\Core\DependencyInjection\Compiler
*
* Source code come from Symfony\Bundle\FrameworkBundle\DependencyInjection\Compiler\RegisterKernelListenersPass class
*/
class RegisterListenersPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition('event_dispatcher')) {
return;
}
$definition = $container->getDefinition('event_dispatcher');
foreach ($container->findTaggedServiceIds('kernel.event_listener') as $id => $events) {
foreach ($events as $event) {
$priority = isset($event['priority']) ? $event['priority'] : 0;
if (!isset($event['event'])) {
throw new \InvalidArgumentException(sprintf('Service "%s" must define the "event" attribute on "kernel.event_listener" tags.', $id));
}
if (!isset($event['method'])) {
$event['method'] = 'on'.preg_replace(array(
'/(?<=\b)[a-z]/ie',
'/[^a-z0-9]/i'
), array('strtoupper("\\0")', ''), $event['event']);
}
$definition->addMethodCall('addListenerService', array($event['event'], array($id, $event['method']), $priority));
}
}
foreach ($container->findTaggedServiceIds('kernel.event_subscriber') as $id => $attributes) {
// We must assume that the class value has been correctly filled, even if the service is created by a factory
$class = $container->getDefinition($id)->getClass();
$refClass = new \ReflectionClass($class);
$interface = 'Symfony\Component\EventDispatcher\EventSubscriberInterface';
if (!$refClass->implementsInterface($interface)) {
throw new \InvalidArgumentException(sprintf('Service "%s" must implement interface "%s".', $id, $interface));
}
$definition->addMethodCall('addSubscriberService', array($id, $class));
}
}
}

View File

@@ -0,0 +1,60 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\DependencyInjection\Compiler;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
/**
* Register parser plugins. These plugins shouild be tagged thelia.parser.register_plugin
* in the configuration.
*
*
*/
class RegisterParserPluginPass implements CompilerPassInterface
{
/**
* You can modify the container here before it is dumped to PHP code.
*
* @param ContainerBuilder $container
*
* @api
*/
public function process(ContainerBuilder $container)
{
if (!$container->hasDefinition("thelia.parser")) {
return;
}
$smarty = $container->getDefinition("thelia.parser");
foreach ($container->findTaggedServiceIds("thelia.parser.register_plugin") as $id => $plugin) {
$smarty->addMethodCall("addPlugins", array(new Reference($id)));
}
$smarty->addMethodCall("registerPlugins");
}
}

View File

@@ -0,0 +1,368 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\DependencyInjection\Loader;
use Symfony\Component\Config\Resource\FileResource;
use Symfony\Component\Config\Util\XmlUtils;
use Symfony\Component\DependencyInjection\DefinitionDecorator;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\SimpleXMLElement;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Loader\FileLoader;
class XmlFileLoader extends FileLoader
{
/**
* Loads an XML file.
*
* @param mixed $file The resource
* @param string $type The resource type
*/
public function load($file, $type = null)
{
$path = $this->locator->locate($file);
$xml = $this->parseFile($path);
$xml->registerXPathNamespace('config', 'http://thelia.net/schema/dic/config');
$this->container->addResource(new FileResource($path));
$this->parseLoops($xml);
$this->parseFilters($xml);
$this->parseTemplateDirectives($xml);
$this->parseParameters($xml);
$this->parseCommands($xml);
$this->parseForms($xml);
$this->parseDefinitions($xml, $path);
}
protected function parseCommands(SimpleXMLElement $xml)
{
if (false === $commands = $xml->xpath('//config:commands/config:command')) {
return;
}
try {
$commandConfig = $this->container->getParameter("command.definition");
} catch (ParameterNotFoundException $e) {
$commandConfig = array();
}
foreach ($commands as $command) {
array_push($commandConfig, $command->getAttributeAsPhp("class"));
}
$this->container->setParameter("command.definition", $commandConfig);
}
/**
* Parses parameters
*
* @param SimpleXMLElement $xml
*/
protected function parseParameters(SimpleXMLElement $xml)
{
if (!$xml->parameters) {
return;
}
$this->container->getParameterBag()->add($xml->parameters->getArgumentsAsPhp('parameter'));
}
/**
*
* parse Loops property
*
* @param SimpleXMLElement $xml
*/
protected function parseLoops(SimpleXMLElement $xml)
{
if (false === $loops = $xml->xpath('//config:loops/config:loop')) {
return;
}
try {
$loopConfig = $this->container->getParameter("Thelia.parser.loops");
} catch (ParameterNotFoundException $e) {
$loopConfig = array();
}
foreach ($loops as $loop) {
$loopConfig[$loop->getAttributeAsPhp("name")] = $loop->getAttributeAsPhp("class");
}
$this->container->setParameter("Thelia.parser.loops", $loopConfig);
}
protected function parseForms(SimpleXMLElement $xml)
{
if (false === $forms = $xml->xpath('//config:forms/config:form')) {
return;
}
try {
$formConfig = $this->container->getParameter("Thelia.parser.forms");
} catch (ParameterNotFoundException $e) {
$formConfig = array();
}
foreach ($forms as $form) {
$formConfig[$form->getAttributeAsPhp('name')] = $form->getAttributeAsPhp('class');
}
$this->container->setParameter('Thelia.parser.forms', $formConfig);
}
/**
* parse Filters property
*
* @param SimpleXMLElement $xml
*/
protected function parseFilters(SimpleXMLElement $xml)
{
if (false === $filters = $xml->xpath('//config:filters/config:filter')) {
return;
}
try {
$filterConfig = $this->container->getParameter("Thelia.parser.filters");
} catch (ParameterNotFoundException $e) {
$filterConfig = array();
}
foreach ($filters as $filter) {
$filterConfig[$filter->getAttributeAsPhp("name")] = $filter->getAttributeAsPhp("class");
}
$this->container->setParameter("Thelia.parser.filters", $filterConfig);
}
/**
* parse BaseParams property
*
* @param SimpleXMLElement $xml
*/
protected function parseTemplateDirectives(SimpleXMLElement $xml)
{
if (false === $baseParams = $xml->xpath('//config:templateDirectives/config:templateDirective')) {
return;
}
try {
$baseParamConfig = $this->container->getParameter("Thelia.parser.templateDirectives");
} catch (ParameterNotFoundException $e) {
$baseParamConfig = array();
}
foreach ($baseParams as $baseParam) {
$baseParamConfig[$baseParam->getAttributeAsPhp("name")] = $baseParam->getAttributeAsPhp("class");
}
$this->container->setParameter("Thelia.parser.templateDirectives", $baseParamConfig);
}
/**
* Parses multiple definitions
*
* @param SimpleXMLElement $xml
* @param string $file
*/
protected function parseDefinitions(SimpleXMLElement $xml, $file)
{
if (false === $services = $xml->xpath('//config:services/config:service')) {
return;
}
foreach ($services as $service) {
$this->parseDefinition((string) $service['id'], $service, $file);
}
}
/**
* Parses an individual Definition
*
* @param string $id
* @param SimpleXMLElement $service
* @param string $file
*/
protected function parseDefinition($id, $service, $file)
{
if ((string) $service['alias']) {
$public = true;
if (isset($service['public'])) {
$public = $service->getAttributeAsPhp('public');
}
$this->container->setAlias($id, new Alias((string) $service['alias'], $public));
return;
}
if (isset($service['parent'])) {
$definition = new DefinitionDecorator((string) $service['parent']);
} else {
$definition = new Definition();
}
foreach (array('class', 'scope', 'public', 'factory-class', 'factory-method', 'factory-service', 'synthetic', 'abstract') as $key) {
if (isset($service[$key])) {
$method = 'set'.str_replace('-', '', $key);
$definition->$method((string) $service->getAttributeAsPhp($key));
}
}
if ($service->file) {
$definition->setFile((string) $service->file);
}
$definition->setArguments($service->getArgumentsAsPhp('argument'));
$definition->setProperties($service->getArgumentsAsPhp('property'));
if (isset($service->configurator)) {
if (isset($service->configurator['function'])) {
$definition->setConfigurator((string) $service->configurator['function']);
} else {
if (isset($service->configurator['service'])) {
$class = new Reference((string) $service->configurator['service'], ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE, false);
} else {
$class = (string) $service->configurator['class'];
}
$definition->setConfigurator(array($class, (string) $service->configurator['method']));
}
}
foreach ($service->call as $call) {
$definition->addMethodCall((string) $call['method'], $call->getArgumentsAsPhp('argument'));
}
foreach ($service->tag as $tag) {
$parameters = array();
foreach ($tag->attributes() as $name => $value) {
if ('name' === $name) {
continue;
}
$parameters[$name] = SimpleXMLElement::phpize($value);
}
$definition->addTag((string) $tag['name'], $parameters);
}
$this->container->setDefinition($id, $definition);
}
/**
* Parses a XML file.
*
* @param string $file Path to a file
*
* @return SimpleXMLElement
*
* @throws InvalidArgumentException When loading of XML file returns error
*/
protected function parseFile($file)
{
try {
$dom = XmlUtils::loadFile($file, array($this, 'validateSchema'));
} catch (\InvalidArgumentException $e) {
throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
}
return simplexml_import_dom($dom, 'Symfony\\Component\\DependencyInjection\\SimpleXMLElement');
}
/**
* Validates a documents XML schema.
*
* @param \DOMDocument $dom
*
* @return Boolean
*
* @throws RuntimeException When extension references a non-existent XSD file
*/
public function validateSchema(\DOMDocument $dom)
{
$schemaLocations = array('http://thelia.net/schema/dic/config' => str_replace('\\', '/',__DIR__.'/schema/dic/config/thelia-1.0.xsd'));
$tmpfiles = array();
$imports = '';
foreach ($schemaLocations as $namespace => $location) {
$parts = explode('/', $location);
if (0 === stripos($location, 'phar://')) {
$tmpfile = tempnam(sys_get_temp_dir(), 'sf2');
if ($tmpfile) {
copy($location, $tmpfile);
$tmpfiles[] = $tmpfile;
$parts = explode('/', str_replace('\\', '/', $tmpfile));
}
}
$drive = '\\' === DIRECTORY_SEPARATOR ? array_shift($parts).'/' : '';
$location = 'file:///'.$drive.implode('/', array_map('rawurlencode', $parts));
$imports .= sprintf(' <xsd:import namespace="%s" schemaLocation="%s" />'."\n", $namespace, $location);
}
$source = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<xsd:schema xmlns="http://symfony.com/schema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://symfony.com/schema"
elementFormDefault="qualified">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace"/>
$imports
</xsd:schema>
EOF
;
$valid = @$dom->schemaValidateSource($source);
foreach ($tmpfiles as $tmpfile) {
@unlink($tmpfile);
}
return $valid;
}
/**
* Returns true if this class supports the given resource.
*
* @param mixed $resource A resource
* @param string $type The resource type
*
* @return Boolean true if this class supports the given resource, false otherwise
*/
public function supports($resource, $type = null)
{
// TODO: Implement supports() method.
}
}

View File

@@ -0,0 +1,97 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Event;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\HttpFoundation\Request;
use Thelia\Form\BaseForm;
use Thelia\Core\Security\SecurityContext;
/**
*
* Class thrown on Thelia.action event
*
* call setAction if action match yours
*
*/
abstract class ActionEvent extends Event
{
/**
*
* @var Symfony\Component\HttpFoundation\Request
*/
protected $request;
/**
*
* @var string
*/
protected $action;
protected $errorForm = null;
/**
*
* @param \Symfony\Component\HttpFoundation\Request $request
* @param string $action
*/
public function __construct(Request $request, $action)
{
$this->request = $request;
$this->action = $action;
}
/**
*
* @return string
*/
public function getAction()
{
return $this->action;
}
/**
*
* @return \Symfony\Component\HttpFoundation\Request
*/
public function getRequest()
{
return $this->request;
}
public function setErrorForm(BaseForm $form) {
$this->errorForm = $form;
if ($form != null) $this->stopPropagation();
}
public function getErrorForm() {
return $this->errorForm;
}
public function hasErrorForm() {
return $this->errorForm != null ? true : false;
}
}

View File

@@ -0,0 +1,41 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Event;
use Thelia\Model\Cart;
class CartEvent extends InternalEvent {
public $cart;
public function __construct(Cart $cart)
{
$this->cart = $cart;
}
}

View File

@@ -0,0 +1,42 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Event;
use Thelia\Model\CartItem;
class CartItemEvent extends InternalEvent {
protected $cartItem;
public function __construct(CartItem $cartItem)
{
$this->cartItem = $cartItem;
}
public function getCartItem()
{
return $this->cartItem;
}
}

View File

@@ -0,0 +1,53 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Event;
use Symfony\Component\EventDispatcher\Event;
use Thelia\Model\Customer;
class CustomRefEvent extends Event {
protected $ref;
public $customer;
public function __construct(Customer $customer)
{
$this->customer = $customer;
}
public function hasRef()
{
return null !== $this->ref;
}
public function getRef()
{
return $this->ref;
}
public function setRef($ref)
{
$this->ref = $ref;
}
}

View File

@@ -0,0 +1,38 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Event;
use Thelia\Model\Customer;
class CustomerEvent extends InternalEvent {
public $customer;
public function __construct(Customer $customer)
{
$this->customer = $customer;
}
}

View File

@@ -0,0 +1,31 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Event;
use Thelia\Core\Event\ActionEvent;
class DefaultActionEvent extends ActionEvent
{
}

View File

@@ -0,0 +1,37 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Event;
use Symfony\Component\EventDispatcher\Event;
/**
* Base class used for internal event like creating new Customer, adding item to cart, etc
*
* Class InternalEvent
* @package Thelia\Core\Event
*/
abstract class InternalEvent extends Event {
}

View File

@@ -0,0 +1,106 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Event;
/**
*
* This class contains all Thelia events identifiers used by Thelia Core
*
* @author Manuel Raynaud <mraynaud@openstudio.fr>
*/
final class TheliaEvents
{
/**
* ACTION event
*
* Sent if no action are already present in Thelia action process ( see Thelia\Routing\Matcher\ActionMatcher)
*/
const ACTION = "thelia.action";
/**
* INCLUDE event
*
* Sent before starting thelia inclusion
*/
const INCLUSION = "thelia.include";
/**
* Sent before the logout of the customer.
*/
const CUSTOMER_LOGOUT = "action.customer_logout";
/**
* Sent once the customer is successfully logged in.
*/
const CUSTOMER_LOGIN = "action.customer_login";
/**
* Sent before the logout of the administrator.
*/
const ADMIN_LOGOUT = "action.admin_logout";
/**
* Sent once the administrator is successfully logged in.
*/
const ADMIN_LOGIN = "action.admin_login";
/**
* Sent once the customer creation form has been successfully validated, and before customer insertion in the database.
*/
const BEFORE_CREATECUSTOMER = "action.before_createcustomer";
/**
* Sent just after a successful insert of a new customer in the database.
*/
const AFTER_CREATECUSTOMER = "action.after_createcustomer";
/**
* Sent once the customer change form has been successfully validated, and before customer update in the database.
*/
const BEFORE_CHANGECUSTOMER = "action.before_changecustomer";
/**
* Sent just after a successful update of a customer in the database.
*/
const AFTER_CHANGECUSTOMER = "action.after_changecustomer";
/**
* Sent before customer insertion, to allow modules to create a custom customer reference.
*/
const CREATECUSTOMER_CUSTOMREF = "customer.creation.customref";
/**
* sent when a new existing cat id duplicated. This append when current customer is different from current cart
*/
const CART_DUPLICATE = "cart.duplicate";
/**
* sent when a new item is added to current cart
*/
const CART_ADDITEM = "cart.addItem";
/**
* sent when a cart item is modify
*/
const CART_MODIFYITEM = "cart.modifyItem";
}

View File

@@ -0,0 +1,76 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Thelia\Core\Factory\ActionEventFactory;
use Thelia\Core\Template\ParserContext;
/**
*
* Action are dispatched here.
*
* A factory is used for creating appropriate action object
*
* Class ControllerListener
* @package Thelia\Core\EventListener
*/
class ControllerListener implements EventSubscriberInterface
{
/**
* @var ParserContext the parser context
*/
protected $parserContext;
public function __construct(ParserContext $parserContext) {
$this->parserContext = $parserContext;
}
public function onKernelController(FilterControllerEvent $event)
{
$dispatcher = $event->getDispatcher();
$request = $event->getRequest();
if (false !== $action = $request->get("action")) {
//search corresponding action
$event = new ActionEventFactory($request, $action, $event->getKernel()->getContainer()->getParameter("thelia.actionEvent"));
$actionEvent = $event->createActionEvent();
$dispatcher->dispatch("action.".$action, $actionEvent);
// Process form errors
if ($actionEvent->hasErrorForm()) {
$this->parserContext->setErrorForm($actionEvent->getErrorForm());
}
}
}
public static function getSubscribedEvents()
{
return array(
KernelEvents::CONTROLLER => array('onKernelController', 0)
);
}
}

View File

@@ -0,0 +1,134 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Thelia\Core\Template\Exception\ResourceNotFoundException;
use Thelia\Core\Template\ParserInterface;
use Thelia\Tools\Redirect;
use Thelia\Tools\URL;
use Thelia\Core\Security\Exception\AuthenticationException;
/**
*
* ViewSubscriber Main class subscribing to view http response.
*
* @TODO Look if it's possible to block this definition in dependency-injection
*
* @author Manuel Raynaud <mraynaud@openstudio.fr>
*/
class ViewListener implements EventSubscriberInterface
{
/**
*
* @var Symfony\Component\DependencyInjection\ContainerInterface
*/
private $container;
/**
*
* @param \Thelia\Core\Template\ParserInterface $parser
*/
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
/**
*
* Launch the parser defined on the constructor and get the result.
*
* The result is transform id needed into a Response object
*
* @param \Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent $event
*/
public function onKernelView(GetResponseForControllerResultEvent $event)
{
$parser = $this->container->get('thelia.parser');
try {
$content = $parser->getContent();
if ($content instanceof Response) {
$event->setResponse($content);
} else {
$event->setResponse(new Response($content, $parser->getStatus() ?: 200));
}
}
catch (ResourceNotFoundException $e) {
$event->setResponse(new Response($e->getMessage(), 404));
}
catch (AuthenticationException $ex) {
// Redirect to the login template
$event->setResponse(Redirect::exec(URL::viewUrl($ex->getLoginTemplate())));
}
}
public function beforeKernelView(GetResponseForControllerResultEvent $event)
{
$request = $this->container->get('request');
if (!$view = $request->attributes->get('_view')) {
$request->attributes->set('_view', $this->findView($request));
}
}
public function findView(Request $request)
{
if (! $view = $request->query->get('view')) {
$view = "index";
if ($request->request->has('view')) {
$view = $request->request->get('view');
}
}
return $view;
}
/**
*
* Register the method to execute in this class for a specific event (here the kernel.view event)
*
* @return array The event names to listen to
*/
public static function getSubscribedEvents()
{
return array(
KernelEvents::VIEW =>array(
array('onKernelView', 0),
array('beforeKernelView', 5)
)
);
}
}

View File

@@ -0,0 +1,76 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Factory;
use Symfony\Component\HttpFoundation\Request;
class ActionEventFactory
{
/**
* @var \Symfony\Component\HttpFoundation\Request
*/
protected $request;
/**
* @var string
*/
protected $action;
/**
* array(
* "action.addCart" => "Thelia\Core\Event\CartAction"
* )
*
* @var array key are action name and value the Event class to dispatch
*/
protected $className;
protected $defaultClassName = "Thelia\Core\Event\DefaultActionEvent";
public function __construct(Request $request, $action, $className)
{
$this->request = $request;
$this->action = $action;
$this->className = $className;
}
public function createActionEvent()
{
if (array_key_exists($this->action, $this->className)) {
$class = new \ReflectionClass($this->className[$this->action]);
// return $class->newInstance($this->request, $this->action);
} else {
$class = new \ReflectionClass($this->defaultClassName);
}
if ($class->isSubclassOf("Thelia\Core\Event\ActionEvent") === false) {
throw new \RuntimeException("%s must be a subclass of Thelia\Core\Event\ActionEvent", $class->getName());
}
return $class->newInstance($this->request, $this->action);
}
}

View File

@@ -0,0 +1,51 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\HttpFoundation;
use Symfony\Component\HttpFoundation\Request as BaseRequest;
class Request extends BaseRequest{
public function getProductId()
{
return $this->get("product_id");
}
public function getUriAddingParameters(array $parameters = null)
{
$uri = $this->getUri();
$additionalQs = '';
foreach ($parameters as $key => $value) {
$additionalQs .= sprintf("&%s=%s", $key, $value);
}
if ('' == $this->getQueryString()) {
$additionalQs = '?'. ltrim($additionalQs, '&');
}
return $uri . $additionalQs;
}
}

View File

@@ -0,0 +1,167 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\HttpFoundation\Session;
use Symfony\Component\HttpFoundation\Session\Session as BaseSession;
use Thelia\Core\Security\User\UserInterface;
use Thelia\Exception\InvalidCartException;
use Thelia\Model\CartQuery;
use Thelia\Model\Cart;
use Thelia\Tools\URL;
class Session extends BaseSession
{
// -- Language ------------------------------------------------------------
public function getLocale()
{
return $this->get("locale", "en_US");
}
public function getLang()
{
return substr($this->getLocale(), 0, 2);
}
// -- Customer user --------------------------------------------------------
public function setCustomerUser(UserInterface $user)
{
$this->set('customer_user', $user);
}
public function getCustomerUser()
{
return $this->get('customer_user');
}
public function clearCustomerUser()
{
return $this->remove('customer_user');
}
// -- Admin user -----------------------------------------------------------
public function setAdminUser(UserInterface $user)
{
$this->set('admin_user', $user);
}
public function getAdminUser()
{
return $this->get('admin_user');
}
public function clearAdminUser()
{
return $this->remove('admin_user');
}
// -- Error form -----------------------------------------------------------
/**
* @param string $formName the form name
*/
public function setErrorFormName($formName)
{
$this->set('error_form', $formName);
}
public function getErrorFormName()
{
return $this->get('error_form', null);
}
public function clearErrorFormName()
{
return $this->remove('error_form');
}
// -- Return page ----------------------------------------------------------
public function setReturnToUrl($url)
{
$this->set('return_to_url', $url);
}
/**
*
* @return the return-to URL, or the index page if none is defined.
*/
public function getReturnToUrl()
{
return $this->get('return_to_url', URL::getIndexPage());
}
// -- Cart ------------------------------------------------------------------
/**
* return cart if exists and is valid (checking customer)
*
* @return \Thelia\Model\Cart|null
*/
public function getCart()
{
$cart_id = $this->get("cart_id");
$cart = null;
if ($cart_id) {
$cart = CartQuery::create()->findPk($cart_id);
try {
$this->verifyValidCart($cart);
} catch (InvalidCartException $e) {
$cart = null;
}
}
return $cart;
}
/**
*
*
* @param \Thelia\Model\Cart $cart
* @throws \Thelia\Exception\InvalidCartException
*/
protected function verifyValidCart(Cart $cart)
{
$customer = $this->getCustomerUser();
if ($customer && $cart->getCustomerId() != $customer->getId()) {
throw new InvalidCartException("customer in session and customer_id in cart are not the same");
} else if($customer === null && $cart->getCustomerId() !== null) {
throw new InvalidCartException("Customer exists in cart and not in session");
}
}
/**
* assign cart id in session
*
* @param $cart_id
*/
public function setCart($cart_id)
{
$this->set("cart_id", $cart_id);
}
}

View File

@@ -0,0 +1,43 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Security\Authentication;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Form;
use Thelia\Core\Security\UserProvider\AdminUserProvider;
use Thelia\Core\Security\Authentication\UsernamePasswordFormAuthenticator;
use Thelia\Form\AdminLogin;
class AdminUsernamePasswordFormAuthenticator extends UsernamePasswordFormAuthenticator {
public function __construct(Request $request, AdminLogin $loginForm) {
parent::__construct(
$request,
$loginForm,
new AdminUserProvider()
);
}
}

View File

@@ -0,0 +1,32 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Security\Authentication;
interface AuthenticatorInterface {
/**
* Returns a UserInterface instance, authentified using the authenticator specific method
*/
public function getAuthentifiedUser();
}

View File

@@ -0,0 +1,44 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Security\Authentication;
use Symfony\Component\HttpFoundation\Request;
use Thelia\Core\Security\Authentication\UsernamePasswordFormAuthenticator;
use Thelia\Form\CustomerLogin;
use Thelia\Core\Security\UserProvider\CustomerUserProvider;
class CustomerUsernamePasswordFormAuthenticator extends UsernamePasswordFormAuthenticator {
public function __construct(Request $request, CustomerLogin $loginForm) {
parent::__construct(
$request,
$loginForm,
new CustomerUserProvider(),
array(
'username_field_name' => 'email'
)
);
}
}

View File

@@ -0,0 +1,95 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Security\Authentication;
use Thelia\Core\Security\Authentication\AuthenticatorInterface;
use Symfony\Component\HttpFoundation\Request;
use Thelia\Core\Security\UserProvider\UserProviderInterface;
use Symfony\Component\Form\Form;
use Thelia\Core\Security\Exception\WrongPasswordException;
use Thelia\Core\Security\Exception\UsernameNotFoundException;
use Symfony\Component\Validator\Exception\ValidatorException;
use Thelia\Form\BaseForm;
class UsernamePasswordFormAuthenticator implements AuthenticatorInterface {
protected $request;
protected $loginForm;
protected $userProvider;
protected $options;
protected $baseLoginForm;
public function __construct(Request $request, BaseForm $loginForm, UserProviderInterface $userProvider, array $options = array()) {
$this->request = $request;
$this->baseLoginForm = $loginForm;
$this->loginForm = $this->baseLoginForm->getForm();
$this->userProvider = $userProvider;
$defaults = array(
'required_method' => 'POST',
'username_field_name' => 'username',
'password_field_name' => 'password'
);
$this->options = array_merge($defaults, $options);
$this->loginForm->bind($this->request);
}
/**
* @return string the username value
*/
public function getUsername() {
return $this->loginForm->get($this->options['username_field_name'])->getData();
}
/**
* @see \Thelia\Core\Security\Authentication\AuthenticatorInterface::getAuthentifiedUser()
*/
public function getAuthentifiedUser() {
if ($this->request->isMethod($this->options['required_method'])) {
if (! $this->loginForm->isValid()) throw new ValidatorException("Form is not valid.");
// Retreive user
$username = $this->getUsername();
$password = $this->loginForm->get($this->options['password_field_name'])->getData();
$user = $this->userProvider->getUser($username);
if ($user === null) throw new UsernameNotFoundException(sprintf("Username '%s' was not found.", $username));
// Check user password
$authOk = $user->checkPassword($password) === true;
if ($authOk !== true) throw new WrongPasswordException(sprintf("Wrong password for user '%s'.", $username));
return $user;
}
throw new \RuntimeException("Invalid method.");
}
}

View File

@@ -0,0 +1,49 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Security\Exception;
class AuthenticationException extends \Exception
{
/**
* @var string The login template name
*/
protected $loginTemplate = "login";
/**
* @return string the login template name
*/
public function getLoginTemplate() {
return $this->loginTemplate;
}
/**
* Set the login template name
*
* @param string $loginPath the login template name
*/
public function setLoginTemplate($loginTemplate) {
$this->loginTemplate = $loginTemplate;
}
}

View File

@@ -0,0 +1,29 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Security\Exception;
class UsernameNotFoundException extends AuthenticationException
{
}

View File

@@ -0,0 +1,29 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Security\Exception;
class WrongPasswordException extends AuthenticationException
{
}

View File

@@ -0,0 +1,46 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Thelia\Core\Security\Role;
/**
* Role is a simple implementation of a RoleInterface where the role is a
* string.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class Role implements RoleInterface
{
private $role;
/**
* Constructor.
*
* @param string $role The role name
*/
public function __construct($role)
{
$this->role = (string) $role;
}
/**
* {@inheritdoc}
*/
public function getRole()
{
return $this->role;
}
public function __toString() {
return $this->role;
}
}

View File

@@ -0,0 +1,35 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Thelia\Core\Security\Role;
/**
* RoleInterface represents a role granted to a user.
*
* A role must either have a string representation or it needs to be explicitly
* supported by at least one AccessDecisionManager.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface RoleInterface
{
/**
* Returns the role.
*
* This method returns a string representation whenever possible.
*
* When the role cannot be represented with sufficient precision by a
* string, it should return null.
*
* @return string|null A string representation of the role, or null
*/
public function getRole();
}

View File

@@ -0,0 +1,192 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Security;
use Thelia\Core\Security\Authentication\AuthenticationProviderInterface;
use Thelia\Core\Security\Exception\AuthenticationTokenNotFoundException;
use Thelia\Core\Security\Token\TokenInterface;
use Thelia\Core\Security\User\UserInterface;
use Thelia\Core\HttpFoundation\Request;
/**
* A simple security manager, in charge of checking user
*
* @author Franck Allimant <franck@cqfdev.fr>
*/
class SecurityContext {
const CONTEXT_FRONT_OFFICE = 'front';
const CONTEXT_BACK_OFFICE = 'admin';
private $request;
private $context;
public function __construct(Request $request) {
$this->request = $request;
$this->context = null;
}
public function setContext($context) {
if ($context !== self::CONTEXT_FRONT_OFFICE && $context !== self::CONTEXT_BACK_OFFICE) {
throw new \InvalidArgumentException(sprintf("Invalid or empty context identifier '%s'", $context));
}
$this->context = $context;
return $this;
}
public function getContext($exception_if_context_undefined = false) {
if (null === $this->context && $exception_if_context_undefined === true)
throw new \LogicException("No context defined. Please use setContext() first.");
return $this->context;
}
private function getSession() {
$session = $this->request->getSession();
if ($session === null)
throw new \LogicException("No session found.");
return $session;
}
/**
* Gets the currently authenticated user in the current context, or null if none is defined
*
* @return UserInterface|null A UserInterface instance or null if no user is available
*/
public function getUser() {
$context = $this->getContext(true);
if ($context === self::CONTEXT_FRONT_OFFICE)
$user = $this->getSession()->getCustomerUser();
else if ($context == self::CONTEXT_BACK_OFFICE)
$user = $this->getSession()->getAdminUser();
else
$user = null;
return $user;
}
final public function isAuthenticated()
{
if (null !== $this->getUser()) {
return true;
}
return false;
}
/**
* Checks if the current user is allowed
*
* @return Boolean
*/
final public function isGranted($roles, $permissions)
{
if ($this->isAuthenticated() === true) {
$user = $this->getUser();
// Check if user's roles matches required roles
$userRoles = $user->getRoles();
$roleFound = false;
foreach($userRoles as $role) {
if (in_array($role, $roles)) {
$roleFound = true;
break;
}
}
if ($roleFound) {
if (empty($permissions)) {
return true;
}
// Get permissions from profile
// $userPermissions = $user->getPermissions();
// TODO: Finalize permissions system !;
$userPermissions = array('*'); // FIXME !
$permissionsFound = true;
// User have all permissions ?
if (in_array('*', $userPermissions))
return true;
// Check that user's permissions matches required permissions
foreach($permissions as $permission) {
if (! in_array($permission, $userPermissions)) {
$permissionsFound = false;
break;
}
}
return $permissionsFound;
}
}
return false;
}
/**
* Sets the authenticated user.
*
* @param UserInterface $user A UserInterface, or null if no further user should be stored
*/
public function setUser(UserInterface $user)
{
$context = $this->getContext(true);
$user->eraseCredentials();
if ($context === self::CONTEXT_FRONT_OFFICE)
$this->getSession()->setCustomerUser($user);
else if ($context == self::CONTEXT_BACK_OFFICE)
$this->getSession()->setAdminUser($user);
}
/**
* Clear the user from the security context
*/
public function clear() {
$context = $this->getContext(true);
if ($context === self::CONTEXT_FRONT_OFFICE)
$this->getSession()->clearCustomerUser();
else if ($context == self::CONTEXT_BACK_OFFICE)
$this->getSession()->clearAdminUser();
}
}

View File

@@ -0,0 +1,51 @@
<?php
namespace Thelia\Core\Security\User;
/**
* This interface should be implemented by user classes
*
* @author Franck Allimant <franck@cqfdev.fr>
*
*/
interface UserInterface {
/**
* Return the user unique name
*/
public function getUsername();
/**
* Return the user encoded password
*/
public function getPassword();
/**
* Check a string against a the user password
*/
public function checkPassword($password);
/**
* Returns the roles granted to the user.
*
* <code>
* public function getRoles()
* {
* return array('USER');
* }
* </code>
*
* @return Role[] The user roles
*/
public function getRoles();
/**
* Removes sensitive data from the user.
*
* This is important if, at any given point, sensitive information like
* the plain-text password is stored on this object.
*
* @return void
*/
public function eraseCredentials();
}

View File

@@ -0,0 +1,17 @@
<?php
namespace Thelia\Core\Security\UserProvider;
use Thelia\Model\Admin;
use Thelia\Model\AdminQuery;
class AdminUserProvider implements UserProviderInterface {
public function getUser($key) {
$admin = AdminQuery::create()
->filterByLogin($key)
->findOne();
return $admin;
}
}

View File

@@ -0,0 +1,17 @@
<?php
namespace Thelia\Core\Security\UserProvider;
use Thelia\Action\Customer;
use Thelia\Model\CustomerQuery;
class CustomerUserProvider implements UserProviderInterface {
public function getUser($key) {
$customer = CustomerQuery::create()
->filterByEmail($key)
->findOne();
return $customer;
}
}

View File

@@ -0,0 +1,14 @@
<?php
namespace Thelia\Core\Security\UserProvider;
interface UserProviderInterface {
/**
* Returns a UserInterface instance
*
* @param $key the unique user key (username, email address, etc.)
* @return a UserInterface instance, or null if none was found.
*/
public function getUser($key);
}
?>

View File

@@ -0,0 +1,123 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Assets;
use Assetic\AssetManager;
use Assetic\FilterManager;
use Assetic\Filter;
use Assetic\Factory\AssetFactory;
use Assetic\Factory\Worker\CacheBustingWorker;
use Assetic\AssetWriter;
use Assetic\Asset\AssetCache;
use Assetic\Cache\FilesystemCache;
/**
* This class is a simple helper for generating assets using Assetic.
*
* @author Franck Allimant <franck@cqfdev.fr>
*/
class AsseticHelper
{
/**
* Generates assets from $asset_path in $output_path, using $filters.
*
* @param string $asset_path the full path to the asset file (or file collection)
* @param unknown $output_path the full disk path to the output directory (shoud be visible to web server)
* @param unknown $output_url the URL to the generated asset directory
* @param unknown $asset_type the asset type: css, js, ... The generated files will have this extension. Pass an empty string to use the asset source extension.
* @param unknown $filters a list of filters, as defined below (see switch($filter_name) ...)
* @param unknown $debug true / false
* @throws \InvalidArgumentException if an invalid filter name is found
* @return string The URL to the generated asset file.
*/
public function asseticize($asset_path, $output_path, $output_url, $asset_type, $filters, $debug)
{
$asset_name = basename($asset_path);
$asset_dir = dirname($asset_path);
$am = new AssetManager();
$fm = new FilterManager();
if (! empty($filters)) {
$filter_list = explode(',', $filters);
foreach ($filter_list as $filter_name) {
$filter_name = trim($filter_name);
switch ($filter_name) {
case 'less' :
$fm->set('less', new Filter\LessphpFilter());
break;
case 'sass' :
$fm->set('less', new Filter\Sass\SassFilter());
break;
case 'cssembed' :
$fm->set('cssembed', new Filter\PhpCssEmbedFilter());
break;
case 'cssrewrite':
$fm->set('cssrewrite', new Filter\CssRewriteFilter());
break;
case 'cssimport':
$fm->set('cssimport', new Filter\CssImportFilter());
break;
default :
throw new \InvalidArgumentException("Unsupported Assetic filter: '$filter_name'");
break;
}
}
} else {
$filter_list = array();
}
// Factory setup
$factory = new AssetFactory($asset_dir);
$factory->setAssetManager($am);
$factory->setFilterManager($fm);
$factory->setDefaultOutput('*'.(! empty($asset_type) ? '.' : '').$asset_type);
$factory->setDebug($debug);
$factory->addWorker(new CacheBustingWorker());
// Prepare the assets writer
$writer = new AssetWriter($output_path);
$asset = $factory->createAsset($asset_name, $filter_list);
$cache = new AssetCache($asset, new FilesystemCache($output_path));
$writer->writeAsset($cache);
return rtrim($output_url, '/').'/'.$asset->getTargetPath();
}
}

View File

@@ -0,0 +1,290 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Element;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Thelia\Core\Template\Loop\Argument\Argument;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Thelia\Core\Security\SecurityContext;
/**
*
* Class BaseLoop
* @package TThelia\Core\Template\Element
*/
abstract class BaseLoop
{
/**
* @var \Symfony\Component\HttpFoundation\Request
*/
protected $request;
/**
* @var \Symfony\Component\EventDispatcher\EventDispatcherInterface
*/
protected $dispatcher;
/**
* @var SecurityContext
*/
protected $securityContext;
protected $args;
/**
* Create a new Loop
*
* @param Request $request
* @param EventDispatcherInterface $dispatcher
* @param SecurityContext $securityContext
*/
public function __construct(Request $request, EventDispatcherInterface $dispatcher, SecurityContext $securityContext)
{
$this->request = $request;
$this->dispatcher = $dispatcher;
$this->securityContext = $securityContext;
$this->args = $this->getArgDefinitions()->addArguments($this->getDefaultArgs(), false);
}
/**
* Define common loop arguments
*
* @return Argument[]
*/
protected function getDefaultArgs()
{
return array(
Argument::createIntTypeArgument('offset', 0),
Argument::createIntTypeArgument('page'),
Argument::createIntTypeArgument('limit', 10),
);
}
/**
* Provides a getter to loop parameters
*
* @param string $name the methode name (only getArgname is supported)
* @param $arguments this parameter is ignored
*
* @return null
* @throws \InvalidArgumentException if the parameter is unknown or the method name is not supported.
*/
public function __call($name, $arguments) {
if (substr($name, 0, 3) == 'get') {
// camelCase to underscore: getNotEmpty -> not_empty
$argName = strtolower(preg_replace('/([^A-Z])([A-Z])/', "$1_$2", substr($name, 3)));
return $this->getArg($argName)->getValue();
}
throw new \InvalidArgumentException(sprintf("Unsupported magic method %s. only getArgname() is supported.", $name));
}
/**
* Initialize the loop arguments.
*
* @param array $nameValuePairs a array of name => value pairs. The name is the name of the argument.
*
* @throws \InvalidArgumentException if somùe argument values are missing, or invalid
*/
public function initializeArgs(array $nameValuePairs) {
$faultActor = array();
$faultDetails = array();
$loopType = isset($nameValuePairs['type']) ? $nameValuePairs['type'] : "undefined";
$loopName = isset($nameValuePairs['name']) ? $nameValuePairs['name'] : "undefined";
while (($argument = $this->args->current()) !== false) {
$this->args->next();
$value = isset($nameValuePairs[$argument->name]) ? $nameValuePairs[$argument->name] : null;
/* check if mandatory */
if($value === null && $argument->mandatory) {
$faultActor[] = $argument->name;
$faultDetails[] = sprintf('"%s" parameter is missing in loop type: %s, name: %s', $argument->name, $loopType, $loopName);
}
else if($value === '' && !$argument->empty) {
/* check if empty */
$faultActor[] = $argument->name;
$faultDetails[] = sprintf('"%s" parameter cannot be empty in loop type: %s, name: %s', $argument->name, $loopType, $loopName);
}
else if($value !== null && !$argument->type->isValid($value)) {
/* check type */
$faultActor[] = $argument->name;
$faultDetails[] = sprintf('Invalid value for "%s" argument in loop type: %s, name: %s', $argument->name, $loopType, $loopName);
}
else {
/* set default */
/* did it as last checking for we consider default value is acceptable no matter type or empty restriction */
if($value === null) {
$value = $argument->default;
}
$argument->setValue($value);
}
}
if (!empty($faultActor)) {
$complement = sprintf('[%s]', implode(', ', $faultDetails));
throw new \InvalidArgumentException($complement);
}
}
/**
* Return a loop argument
*
* @param string $argumentName the argument name
*
* @throws \InvalidArgumentException if argument is not found in loop argument list
* @return Argument the loop argument.
*/
public function getArg($argumentName) {
$arg = $this->args->get($argumentName);
if ($arg === null)
throw new \InvalidArgumentException("Undefined loop argument '$argumentName'");
return $arg;
}
/**
* Return a loop argument value
*
* @param string $argumentName the argument name
*
* @throws \InvalidArgumentException if argument is not found in loop argument list
* @return Argument the loop argument.
*/
public function getArgValue($argumentName) {
return $this->getArg($argumentName)->getValue();
}
/**
* @param \ModelCriteria $search
* @param null $pagination
*
* @return array|mixed|\PropelModelPager|\PropelObjectCollection
*/
public function search(ModelCriteria $search, &$pagination = null)
{
if($this->getArgValue('page') !== null) {
return $this->searchWithPagination($search, $pagination);
} else {
return $this->searchWithOffset($search);
}
}
/**
* @param \ModelCriteria $search
*
* @return array|mixed|\PropelObjectCollection
*/
public function searchWithOffset(ModelCriteria $search)
{
if($this->getArgValue('limit') >= 0) {
$search->limit($this->getArgValue('limit'));
}
$search->offset($this->getArgValue('offset'));
return $search->find();
}
/**
* @param \ModelCriteria $search
* @param $pagination
*
* @return array|\PropelModelPager
*/
public function searchWithPagination(ModelCriteria $search, &$pagination)
{
$pagination = $search->paginate($this->getArgValue('page'), $this->getArgValue('limit'));
if($this->getArgValue('page') > $pagination->getLastPage()) {
return array();
} else {
return $pagination;
}
}
/**
*
* this function have to be implement in your own loop class.
*
* All your parameters are defined in defineArgs() and can be accessible like a class property.
*
* example :
*
* public function defineArgs()
* {
* return array (
* "ref",
* "id" => "optional",
* "stock" => array(
* "optional",
* "default" => 10
* )
* );
* }
*
* you can retrieve ref value using $this->ref
*
* @param $pagination
*
* @return mixed
*/
abstract public function exec(&$pagination);
/**
*
* define all args used in your loop
*
* array key is your arg name.
*
* example :
*
* return array (
* "ref",
* "id" => "optional",
* "stock" => array(
* "optional",
* "default" => 10
* )
* );
*
* @return \Thelia\Core\Template\Loop\Argument\ArgumentCollection
*/
abstract protected function getArgDefinitions();
}

View File

@@ -0,0 +1,30 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Element\Exception;
class ElementNotFoundException extends \RuntimeException
{
}

View File

@@ -0,0 +1,30 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Element\Exception;
class InvalidElementException extends \RuntimeException
{
}

View File

@@ -0,0 +1,109 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Element;
use Thelia\Core\Template\Element\LoopResultRow;
class LoopResult implements \Iterator
{
private $position;
protected $collection = array();
public function __construct()
{
$this->position = 0;
}
public function isEmpty()
{
return count($this->collection) == 0;
}
public function addRow(LoopResultRow $row)
{
$this->collection[] = $row;
}
public function getCount()
{
return count($this->collection);
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Return the current element
* @link http://php.net/manual/en/iterator.current.php
* @return \Thelia\Core\Template\Element\LoopResultRow
*/
public function current()
{
return $this->collection[$this->position];
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Move forward to next element
* @link http://php.net/manual/en/iterator.next.php
* @return void Any returned value is ignored.
*/
public function next()
{
++$this->position;
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Return the key of the current element
* @link http://php.net/manual/en/iterator.key.php
* @return mixed scalar on success, or null on failure.
*/
public function key()
{
return $this->position;
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Checks if current position is valid
* @link http://php.net/manual/en/iterator.valid.php
* @return boolean The return value will be casted to boolean and then evaluated.
* Returns true on success or false on failure.
*/
public function valid()
{
return isset($this->collection[$this->position]);
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Rewind the Iterator to the first element
* @link http://php.net/manual/en/iterator.rewind.php
* @return void Any returned value is ignored.
*/
public function rewind()
{
$this->position = 0;
}
}

View File

@@ -0,0 +1,53 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Element;
class LoopResultRow
{
protected $substitution = array();
public function set($key, $value)
{
$this->substitution[$key] = $value === null ? '' : $value;
return $this;
}
public function get($key)
{
return $this->substitution[$key];
}
public function getVarVal()
{
return $this->substitution;
}
public function getVars()
{
return array_keys($this->substitution);
}
}

View File

@@ -0,0 +1,28 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Exception;
class ResourceNotFoundException extends \RuntimeException
{
}

View File

@@ -0,0 +1,120 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Loop;
use Thelia\Core\Template\Loop\Product;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\Join;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Log\Tlog;
use Thelia\Model\AccessoryQuery;
use Thelia\Model\ProductQuery;
use Thelia\Model\ConfigQuery;
use Thelia\Type\TypeCollection;
use Thelia\Type;
/**
*
* Accessory loop
*
*
* Class Accessory
* @package Thelia\Core\Template\Loop
* @author Etienne Roudeix <eroudeix@openstudio.fr>
*/
class Accessory extends Product
{
/**
* @return ArgumentCollection
*/
protected function getArgDefinitions()
{
$argumentCollection = parent::getArgDefinitions();
$argumentCollection->addArgument(
Argument::createIntTypeArgument('product', null, true)
);
$argumentCollection->get('order')->default = "accessory";
$argumentCollection->get('order')->type->getKey(0)->addValue('accessory');
$argumentCollection->get('order')->type->getKey(0)->addValue('accessory_reverse');
return $argumentCollection;
}
/**
* @param $pagination
*
* @return \Thelia\Core\Template\Element\LoopResult
*/
public function exec(&$pagination)
{
$search = AccessoryQuery::create();
$product = $this->getProduct();
$search->filterByProductId($product, Criteria::IN);
$order = $this->getOrder();
$orderByAccessory = array_search('accessory', $order);
$orderByAccessoryReverse = array_search('accessory_reverse', $order);
if($orderByAccessory !== false) {
$search->orderByPosition(Criteria::ASC);
$order[$orderByAccessory] = 'given_id';
$this->args->get('order')->setValue( implode(',', $order) );
}
if($orderByAccessoryReverse !== false) {
$search->orderByPosition(Criteria::DESC);
$order[$orderByAccessoryReverse] = 'given_id';
$this->args->get('order')->setValue( implode(',', $order) );
}
$accessories = $this->search($search);
$accessoryIdList = array(0);
foreach ($accessories as $accessory) {
array_push($accessoryIdList, $accessory->getAccessory());
}
$receivedIdList = $this->getId();
/* if an Id list is receive, loop will only match accessories from this list */
if($receivedIdList === null) {
$this->args->get('id')->setValue( implode(',', $accessoryIdList) );
} else {
$this->args->get('id')->setValue( implode(',', array_intersect($receivedIdList, $accessoryIdList)) );
}
return parent::exec($pagination);
}
}

View File

@@ -0,0 +1,141 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Loop;
use Propel\Runtime\ActiveQuery\Criteria;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Log\Tlog;
use Thelia\Model\AddressQuery;
use Thelia\Model\ConfigQuery;
use Thelia\Type\TypeCollection;
use Thelia\Type;
/**
*
* Address loop
*
*
* Class Address
* @package Thelia\Core\Template\Loop
* @author Etienne Roudeix <eroudeix@openstudio.fr>
*/
class Address extends BaseLoop
{
/**
* @return ArgumentCollection
*/
protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createIntListTypeArgument('id'),
new Argument(
'customer',
new TypeCollection(
new Type\IntType(),
new Type\EnumType(array('current'))
),
'current'
),
Argument::createBooleanTypeArgument('default'),
Argument::createIntListTypeArgument('exclude')
);
}
/**
* @param $pagination
*
* @return \Thelia\Core\Template\Element\LoopResult
*/
public function exec(&$pagination)
{
$search = AddressQuery::create();
$id = $this->getId();
if (null !== $id) {
$search->filterById($id, Criteria::IN);
}
$customer = $this->getCustomer();
if ($customer === 'current') {
$currentCustomer = $this->request->getSession()->getCustomerUser();
if($currentCustomer === null) {
return new LoopResult();
} else {
$search->filterByCustomerId($currentCustomer->getId(), Criteria::EQUAL);
}
} else {
$search->filterByCustomerId($customer, Criteria::EQUAL);
}
$default = $this->getDefault();
if ($default === true) {
$search->filterByIsDefault(1, Criteria::EQUAL);
} elseif($default === false) {
$search->filterByIsDefault(1, Criteria::NOT_EQUAL);
}
$exclude = $this->getExclude();
if (!is_null($exclude)) {
$search->filterById($exclude, Criteria::NOT_IN);
}
$addresses = $this->search($search, $pagination);
$loopResult = new LoopResult();
foreach ($addresses as $address) {
$loopResultRow = new LoopResultRow();
$loopResultRow->set("ID", $address->getId());
$loopResultRow->set("NAME", $address->getName());
$loopResultRow->set("CUSTOMER", $address->getCustomerId());
$loopResultRow->set("TITLE", $address->getTitleId());
$loopResultRow->set("COMPANY", $address->getCompany());
$loopResultRow->set("FIRSTNAME", $address->getFirstname());
$loopResultRow->set("LASTNAME", $address->getLastname());
$loopResultRow->set("ADDRESS1", $address->getAddress1());
$loopResultRow->set("ADDRESS2", $address->getAddress2());
$loopResultRow->set("ADDRESS3", $address->getAddress3());
$loopResultRow->set("ZIPCODE", $address->getZipcode());
$loopResultRow->set("CITY", $address->getCity());
$loopResultRow->set("COUNTRY", $address->getCountryId());
$loopResultRow->set("PHONE", $address->getPhone());
$loopResultRow->set("CELLPHONE", $address->getCellphone());
$loopResultRow->set("DEFAULT", $address->getIsDefault());
$loopResult->addRow($loopResultRow);
}
return $loopResult;
}
}

View File

@@ -0,0 +1,127 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Loop\Argument;
use Thelia\Type\TypeCollection;
use Thelia\Type;
/**
*
* @author Etienne Roudeix <eroudeix@openstudio.fr>
*
*/
class Argument
{
public $name;
public $type;
public $default;
public $mandatory;
public $empty;
private $value;
public function __construct($name, \Thelia\Type\TypeCollection $type, $default = null, $mandatory = false, $empty = true, $value = null)
{
$this->name = $name;
$this->type = $type;
$this->mandatory = $mandatory ? true : false;
$this->default = $default;
$this->empty = $empty;
$this->setValue($value);
}
public function getValue() {
return $this->type->getFormattedValue($this->value);
}
public function setValue($value) {
$this->value = $value === null ? null : (string)$value;
}
public static function createAnyTypeArgument($name, $default=null, $mandatory=false, $empty=true)
{
return new Argument(
$name,
new TypeCollection(
new Type\AnyType()
),
$default,
$mandatory,
$empty
);
}
public static function createIntTypeArgument($name, $default=null, $mandatory=false, $empty=true)
{
return new Argument(
$name,
new TypeCollection(
new Type\IntType()
),
$default,
$mandatory,
$empty
);
}
public static function createFloatTypeArgument($name, $default=null, $mandatory=false, $empty=true)
{
return new Argument(
$name,
new TypeCollection(
new Type\FloatType()
),
$default,
$mandatory,
$empty
);
}
public static function createBooleanTypeArgument($name, $default=null, $mandatory=false, $empty=true)
{
return new Argument(
$name,
new TypeCollection(
new Type\BooleanType()
),
$default,
$mandatory,
$empty
);
}
public static function createIntListTypeArgument($name, $default=null, $mandatory=false, $empty=true)
{
return new Argument(
$name,
new TypeCollection(
new Type\IntListType()
),
$default,
$mandatory,
$empty
);
}
}

View File

@@ -0,0 +1,146 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Loop\Argument;
/**
*
* @author Etienne Roudeix <eroudeix@openstudio.fr>
*
*/
class ArgumentCollection implements \Iterator
{
private $arguments = array();
public function __construct()
{
$this->addArguments(func_get_args(), true);
}
public function hasKey($key) {
return isset($this->arguments[$key]);
}
public function get($key) {
return $this->hasKey($key) ? $this->arguments[$key] : null;
}
public function isEmpty()
{
return count($this->arguments) == 0;
}
/**
* @param array $argumentList
* @param $force
*
* @return ArgumentCollection
*/
public function addArguments(array $argumentList, $force = true)
{
foreach($argumentList as $argument) {
$this->addArgument($argument, $force);
}
return $this;
}
/**
* @param Argument $argument
* @param $force
*
* @return ArgumentCollection
*/
public function addArgument(Argument $argument, $force = true)
{
if(isset($this->arguments[$argument->name]) && ! $force) {
return $this;
}
$this->arguments[$argument->name] = $argument;
return $this;
}
public function getCount()
{
return count($this->arguments);
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Return the current element
* @link http://php.net/manual/en/iterator.current.php
* @return Argument
*/
public function current()
{
return current($this->arguments);
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Move forward to next element
* @link http://php.net/manual/en/iterator.next.php
* @return void Any returned value is ignored.
*/
public function next()
{
next($this->arguments);
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Return the key of the current element
* @link http://php.net/manual/en/iterator.key.php
* @return mixed scalar on success, or null on failure.
*/
public function key()
{
return key($this->arguments);
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Checks if current position is valid
* @link http://php.net/manual/en/iterator.valid.php
* @return boolean The return value will be casted to boolean and then evaluated.
* Returns true on success or false on failure.
*/
public function valid()
{
return $this->key() !== null;
}
/**
* (PHP 5 &gt;= 5.0.0)<br/>
* Rewind the Iterator to the first element
* @link http://php.net/manual/en/iterator.rewind.php
* @return void Any returned value is ignored.
*/
public function rewind()
{
reset($this->arguments);
}
}

View File

@@ -0,0 +1,97 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Loop;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Type\TypeCollection;
use Thelia\Type;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
*
* @package Thelia\Core\Template\Loop
*
* @author Franck Allimant <franck@cqfdev.fr>
*/
class Auth extends BaseLoop
{
public function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createAnyTypeArgument('roles', null, true),
Argument::createAnyTypeArgument('permissions'),
Argument::createAnyTypeArgument('context', 'front', false)
);
}
private function _explode($commaSeparatedValues)
{
$array = explode(',', $commaSeparatedValues);
if (array_walk($array, function(&$item) {
$item = strtoupper(trim($item));
})) {
return $array;
}
return array();
}
/**
*
*
* @return \Thelia\Core\Template\Element\LoopResult
*/
public function exec(&$pagination)
{
$context = $this->getContext();
$roles = $this->_explode($this->getRoles());
$permissions = $this->_explode($this->getPermissions());
$loopResult = new LoopResult();
try {
$this->securityContext->setContext($context);
if (true === $this->securityContext->isGranted($roles, $permissions == null ? array() : $permissions)) {
// Create an empty row: loop is no longer empty :)
$loopResult->addRow(new LoopResultRow());
}
}
catch (\Exception $ex) {
// Not granted, loop is empty
}
return $loopResult;
}
}

View File

@@ -0,0 +1,71 @@
<?php
/**
* Created by JetBrains PhpStorm.
* User: manu
* Date: 08/08/13
* Time: 12:44
* To change this template use File | Settings | File Templates.
*/
namespace Thelia\Core\Template\Loop;
use Thelia\Core\Template\Element\BaseLoop;
class Cart extends BaseLoop {
/**
*
* this function have to be implement in your own loop class.
*
* All your parameters are defined in defineArgs() and can be accessible like a class property.
*
* example :
*
* public function defineArgs()
* {
* return array (
* "ref",
* "id" => "optional",
* "stock" => array(
* "optional",
* "default" => 10
* )
* );
* }
*
* you can retrieve ref value using $this->ref
*
* @param $pagination
*
* @return mixed
*/
public function exec(&$pagination)
{
// TODO: Implement exec() method.
}
/**
*
* define all args used in your loop
*
* array key is your arg name.
*
* example :
*
* return array (
* "ref",
* "id" => "optional",
* "stock" => array(
* "optional",
* "default" => 10
* )
* );
*
* @return \Thelia\Core\Template\Loop\Argument\ArgumentCollection
*/
protected function getArgDefinitions()
{
// TODO: Implement getArgDefinitions() method.
}
}

View File

@@ -0,0 +1,199 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Loop;
use Propel\Runtime\ActiveQuery\Criteria;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Log\Tlog;
use Thelia\Model\CategoryQuery;
use Thelia\Model\ConfigQuery;
use Thelia\Type\TypeCollection;
use Thelia\Type;
/**
*
* Category loop, all params available :
*
* - id : can be an id (eq : 3) or a "string list" (eg: 3, 4, 5)
* - parent : categories having this parent id
* - current : current id is used if you are on a category page
* - not_empty : if value is 1, category and subcategories must have at least 1 product
* - visible : default 1, if you want category not visible put 0
* - order : all value available : 'alpha', 'alpha_reverse', 'manual' (default), 'manual-reverse', 'random'
* - exclude : all category id you want to exclude (as for id, an integer or a "string list" can be used)
*
* example :
*
* <THELIA_cat type="category" parent="3" limit="4">
* #TITLE : #ID
* </THELIA_cat>
*
*
* Class Category
* @package Thelia\Core\Template\Loop
* @author Manuel Raynaud <mraynaud@openstudio.fr>
* @author Etienne Roudeix <eroudeix@openstudio.fr>
*/
class Category extends BaseLoop
{
/**
* @return ArgumentCollection
*/
protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createIntListTypeArgument('id'),
Argument::createIntTypeArgument('parent'),
Argument::createBooleanTypeArgument('current'),
Argument::createBooleanTypeArgument('not_empty', 0),
Argument::createBooleanTypeArgument('visible', 1),
new Argument(
'order',
new TypeCollection(
new Type\EnumListType(array('alpha', 'alpha_reverse', 'manual', 'manual-reverse', 'random'))
),
'manual'
),
Argument::createIntListTypeArgument('exclude')
);
}
/**
* @param $pagination
*
* @return \Thelia\Core\Template\Element\LoopResult
*/
public function exec(&$pagination)
{
$search = CategoryQuery::create();
$id = $this->getId();
if (!is_null($id)) {
$search->filterById($id, Criteria::IN);
}
$parent = $this->getParent();
if (!is_null($parent)) {
$search->filterByParent($parent);
}
$current = $this->getCurrent();
if ($current === true) {
$search->filterById($this->request->get("category_id"));
} elseif ($current === false) {
$search->filterById($this->request->get("category_id"), Criteria::NOT_IN);
}
$exclude = $this->getExclude();
if (!is_null($exclude)) {
$search->filterById($exclude, Criteria::NOT_IN);
}
$search->filterByVisible($this->getVisible() ? 1 : 0);
$orders = $this->getOrder();
foreach($orders as $order) {
switch ($order) {
case "alpha":
$search->addAscendingOrderByColumn(\Thelia\Model\Map\CategoryI18nTableMap::TITLE);
break;
case "alpha_reverse":
$search->addDescendingOrderByColumn(\Thelia\Model\Map\CategoryI18nTableMap::TITLE);
break;
case "manual-reverse":
$search->orderByPosition(Criteria::DESC);
break;
case "manual":
$search->orderByPosition(Criteria::ASC);
break;
case "random":
$search->clearOrderByColumns();
$search->addAscendingOrderByColumn('RAND()');
break(2);
break;
}
}
/**
* \Criteria::INNER_JOIN in second parameter for joinWithI18n exclude query without translation.
*
* @todo : verify here if we want results for row without translations.
*/
$search->joinWithI18n(
$this->request->getSession()->getLocale(),
(ConfigQuery::read("default_lang_without_translation", 1)) ? Criteria::LEFT_JOIN : Criteria::INNER_JOIN
);
$categories = $this->search($search, $pagination);
$notEmpty = $this->getNot_empty();
$loopResult = new LoopResult();
foreach ($categories as $category) {
if ($this->getNotEmpty() && $category->countAllProducts() == 0) continue;
$loopResultRow = new LoopResultRow();
$loopResultRow
->set("ID", $category->getId())
->set("TITLE",$category->getTitle())
->set("CHAPO", $category->getChapo())
->set("DESCRIPTION", $category->getDescription())
->set("POSTSCRIPTUM", $category->getPostscriptum())
->set("PARENT", $category->getParent())
->set("URL", $category->getUrl())
->set("PRODUCT_COUNT", $category->countChild())
->set("VISIBLE", $category->getVisible() ? "1" : "0")
->set("POSITION", $category->getPosition())
->set("CREATE_DATE", $category->getCreatedAt())
->set("UPDATE_DATE", $category->getUpdatedAt())
->set("VERSION", $category->getVersion())
->set("VERSION_DATE", $category->getVersionCreatedAt())
->set("VERSION_AUTHOR", $category->getVersionCreatedBy())
;
$loopResult->addRow($loopResultRow);
}
return $loopResult;
}
}

View File

@@ -0,0 +1,126 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Loop;
use Propel\Runtime\ActiveQuery\Criteria;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Log\Tlog;
use Thelia\Model\CategoryQuery;
use Thelia\Model\ConfigQuery;
use Thelia\Type\TypeCollection;
use Thelia\Type;
/**
*
* Category path loop, to get the path to a given category.
*
* - category is the category id
* - depth is the maximum depth to go, default unlimited
* - level is the exact level to return. Example: if level = 2 and the path is c1 -> c2 -> c3 -> c4, the loop will return c2
* - visible if true or missing, only visible categories will be displayed. If false, all categories (visible or not) are returned.
*
* example :
*
* <THELIA_cat type="category-path" category="3">
* <a href="#URL">#TITLE</a>
* </THELIA_cat>
*
*
* Class CategoryPath
* @package Thelia\Core\Template\Loop
* @author Franck Allimant <franck@cqfdev.fr>
*/
class CategoryPath extends BaseLoop
{
/**
* @return ArgumentCollection
*/
protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createIntTypeArgument('category', null, true),
Argument::createIntTypeArgument('depth'),
Argument::createIntTypeArgument('level'),
Argument::createBooleanTypeArgument('visible', true, false)
);
}
/**
* @param $pagination (ignored)
*
* @return \Thelia\Core\Template\Element\LoopResult
*/
public function exec(&$pagination)
{
$id = $this->getCategory();
$visible = $this->getVisible();
$search = CategoryQuery::create();
$search->filterById($id);
if ($visible == true) $search->filterByVisible($visible);
$results = array();
do {
$category = $search->findOne();
if ($category != null) {
$loopResultRow = new LoopResultRow();
$loopResultRow
->set("TITLE",$category->getTitle())
->set("URL", $category->getUrl())
->set("ID", $category->getId())
;
$results[] = $loopResultRow;
$parent = $category->getParent();
if ($parent > 0) {
$search = CategoryQuery::create();
$search->filterById($parent);
if ($visible == true) $search->filterByVisible($visible);
}
}
}
while ($category != null && $parent > 0);
// Reverse list and build the final result
$results = array_reverse($results);
$loopResult = new LoopResult();
foreach($results as $result) $loopResult->addRow($result);
return $loopResult;
}
}

View File

@@ -0,0 +1,239 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Loop;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\Join;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Log\Tlog;
use Thelia\Model\Base\FeatureContentQuery;
use Thelia\Model\FolderQuery;
use Thelia\Model\Map\ContentTableMap;
use Thelia\Model\ContentFolderQuery;
use Thelia\Model\ContentQuery;
use Thelia\Model\ConfigQuery;
use Thelia\Type\TypeCollection;
use Thelia\Type;
/**
*
* Content loop
*
*
* Class Content
* @package Thelia\Core\Template\Loop
* @author Etienne Roudeix <eroudeix@openstudio.fr>
*/
class Content extends BaseLoop
{
/**
* @return ArgumentCollection
*/
protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createIntListTypeArgument('id'),
Argument::createIntListTypeArgument('folder'),
Argument::createBooleanTypeArgument('current'),
Argument::createBooleanTypeArgument('current_folder'),
Argument::createIntTypeArgument('depth', 1),
Argument::createBooleanTypeArgument('visible', 1),
new Argument(
'order',
new TypeCollection(
new Type\EnumListType(array('alpha', 'alpha_reverse', 'manual', 'manual_reverse', 'random', 'given_id'))
),
'alpha'
),
Argument::createIntListTypeArgument('exclude'),
Argument::createIntListTypeArgument('exclude_folder')
);
}
/**
* @param $pagination
*
* @return LoopResult
* @throws \InvalidArgumentException
*/
public function exec(&$pagination)
{
$search = ContentQuery::create();
$id = $this->getId();
if (!is_null($id)) {
$search->filterById($id, Criteria::IN);
}
$folder = $this->getFolder();
if (!is_null($folder)) {
$folders = FolderQuery::create()->filterById($folder, Criteria::IN)->find();
$depth = $this->getDepth();
if(null !== $depth) {
foreach(FolderQuery::findAllChild($folder, $depth) as $subFolder) {
$folders->prepend($subFolder);
}
}
$search->filterByFolder(
$folders,
Criteria::IN
);
}
$current = $this->getCurrent();
if ($current === true) {
$search->filterById($this->request->get("content_id"));
} elseif($current === false) {
$search->filterById($this->request->get("content_id"), Criteria::NOT_IN);
}
$current_folder = $this->getCurrent_folder();
if ($current_folder === true) {
$search->filterByFolder(
FolderQuery::create()->filterByContent(
ContentFolderQuery::create()->filterByContentId(
$this->request->get("content_id"),
Criteria::EQUAL
)->find(),
Criteria::IN
)->find(),
Criteria::IN
);
} elseif($current_folder === false) {
$search->filterByFolder(
FolderQuery::create()->filterByContent(
ContentFolderQuery::create()->filterByContentId(
$this->request->get("content_id"),
Criteria::EQUAL
)->find(),
Criteria::IN
)->find(),
Criteria::NOT_IN
);
}
$visible = $this->getVisible();
$search->filterByVisible($visible);
$orders = $this->getOrder();
foreach($orders as $order) {
switch ($order) {
case "alpha":
$search->addAscendingOrderByColumn(\Thelia\Model\Map\ContentI18nTableMap::TITLE);
break;
case "alpha_reverse":
$search->addDescendingOrderByColumn(\Thelia\Model\Map\ContentI18nTableMap::TITLE);
break;
case "manual":
if(null === $folder || count($folder) != 1)
throw new \InvalidArgumentException('Manual order cannot be set without single folder argument');
$search->orderByPosition(Criteria::ASC);
break;
case "manual_reverse":
if(null === $folder || count($folder) != 1)
throw new \InvalidArgumentException('Manual order cannot be set without single folder argument');
$search->orderByPosition(Criteria::DESC);
break;
case "given_id":
if(null === $id)
throw new \InvalidArgumentException('Given_id order cannot be set without `id` argument');
foreach($id as $singleId) {
$givenIdMatched = 'given_id_matched_' . $singleId;
$search->withColumn(ContentTableMap::ID . "='$singleId'", $givenIdMatched);
$search->orderBy($givenIdMatched, Criteria::DESC);
}
break;
case "random":
$search->clearOrderByColumns();
$search->addAscendingOrderByColumn('RAND()');
break(2);
}
}
$exclude = $this->getExclude();
if (!is_null($exclude)) {
$search->filterById($exclude, Criteria::NOT_IN);
}
$exclude_folder = $this->getExclude_folder();
if (!is_null($exclude_folder)) {
$search->filterByFolder(
FolderQuery::create()->filterById($exclude_folder, Criteria::IN)->find(),
Criteria::NOT_IN
);
}
/**
* Criteria::INNER_JOIN in second parameter for joinWithI18n exclude query without translation.
*
* @todo : verify here if we want results for row without translations.
*/
$search->joinWithI18n(
$this->request->getSession()->getLocale(),
(ConfigQuery::read("default_lang_without_translation", 1)) ? Criteria::LEFT_JOIN : Criteria::INNER_JOIN
);
$search->groupBy(ContentTableMap::ID);
$contents = $this->search($search, $pagination);
$loopResult = new LoopResult();
foreach ($contents as $content) {
$loopResultRow = new LoopResultRow();
$loopResultRow->set("ID", $content->getId())
->set("TITLE",$content->getTitle())
->set("CHAPO", $content->getChapo())
->set("DESCRIPTION", $content->getDescription())
->set("POSTSCRIPTUM", $content->getPostscriptum())
->set("POSITION", $content->getPosition())
;
$loopResult->addRow($loopResultRow);
}
return $loopResult;
}
}

View File

@@ -0,0 +1,134 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Loop;
use Propel\Runtime\ActiveQuery\Criteria;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Log\Tlog;
use Thelia\Model\CountryQuery;
use Thelia\Model\ConfigQuery;
use Thelia\Type\TypeCollection;
use Thelia\Type;
/**
*
* Country loop
*
*
* Class Country
* @package Thelia\Core\Template\Loop
* @author Etienne Roudeix <eroudeix@openstudio.fr>
*/
class Country extends BaseLoop
{
/**
* @return ArgumentCollection
*/
protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createIntTypeArgument('limit', 500), // overwrite orginal param to increase the limit
Argument::createIntListTypeArgument('id'),
Argument::createIntListTypeArgument('area'),
Argument::createBooleanTypeArgument('with_area'),
Argument::createIntListTypeArgument('exclude')
);
}
/**
* @param $pagination
*
* @return \Thelia\Core\Template\Element\LoopResult
*/
public function exec(&$pagination)
{
$search = CountryQuery::create();
$id = $this->getId();
if (null !== $id) {
$search->filterById($id, Criteria::IN);
}
$area = $this->getArea();
if (null !== $area) {
$search->filterByAreaId($area, Criteria::IN);
}
$withArea = $this->getWith_area();
if (true === $withArea) {
$search->filterByAreaId(null, Criteria::ISNOTNULL);
} elseif (false == $withArea) {
$search->filterByAreaId(null, Criteria::ISNULL);
}
$exclude = $this->getExclude();
if (!is_null($exclude)) {
$search->filterById($exclude, Criteria::NOT_IN);
}
/**
* Criteria::INNER_JOIN in second parameter for joinWithI18n exclude query without translation.
*
* @todo : verify here if we want results for row without translations.
*/
$search->joinWithI18n(
$this->request->getSession()->getLocale(),
(ConfigQuery::read("default_lang_without_translation", 1)) ? Criteria::LEFT_JOIN : Criteria::INNER_JOIN
);
$search->addAscendingOrderByColumn(\Thelia\Model\Map\CountryI18nTableMap::TITLE);
$countries = $this->search($search, $pagination);
$loopResult = new LoopResult();
foreach ($countries as $country) {
$loopResultRow = new LoopResultRow();
$loopResultRow->set("ID", $country->getId());
$loopResultRow->set("AREA", $country->getAreaId());
$loopResultRow->set("TITLE", $country->getTitle());
$loopResultRow->set("CHAPO", $country->getChapo());
$loopResultRow->set("DESCRIPTION", $country->getDescription());
$loopResultRow->set("POSTSCRIPTUM", $country->getPostscriptum());
$loopResultRow->set("ISOCODE", $country->getIsocode());
$loopResultRow->set("ISOALPHA2", $country->getIsoalpha2());
$loopResultRow->set("ISOALPHA3", $country->getIsoalpha3());
$loopResult->addRow($loopResultRow);
}
return $loopResult;
}
}

View File

@@ -0,0 +1,137 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Loop;
use Propel\Runtime\ActiveQuery\Criteria;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Log\Tlog;
use Thelia\Model\CustomerQuery;
use Thelia\Model\ConfigQuery;
use Thelia\Type\TypeCollection;
use Thelia\Type;
/**
*
* Customer loop
*
*
* Class Customer
* @package Thelia\Core\Template\Loop
* @author Etienne Roudeix <eroudeix@openstudio.fr>
*/
class Customer extends BaseLoop
{
/**
* @return ArgumentCollection
*/
protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createBooleanTypeArgument('current', 1),
Argument::createIntListTypeArgument('id'),
new Argument(
'ref',
new TypeCollection(
new Type\AlphaNumStringListType()
)
),
Argument::createBooleanTypeArgument('reseller'),
Argument::createIntTypeArgument('sponsor')
);
}
/**
* @param $pagination
*
* @return \Thelia\Core\Template\Element\LoopResult
*/
public function exec(&$pagination)
{
$search = CustomerQuery::create();
$current = $this->getCurrent();
if ($current === true) {
$currentCustomer = $this->request->getSession()->getCustomerUser();
if($currentCustomer === null) {
return new LoopResult();
} else {
$search->filterById($currentCustomer->getId(), Criteria::EQUAL);
}
}
$id = $this->getId();
if (null !== $id) {
$search->filterById($id, Criteria::IN);
}
$ref = $this->getRef();
if (null !== $ref) {
$search->filterByRef($ref, Criteria::IN);
}
$reseller = $this->getReseller();
if ($reseller === true) {
$search->filterByReseller(1, Criteria::EQUAL);
} else if($reseller === false) {
$search->filterByReseller(0, Criteria::EQUAL);
}
$sponsor = $this->getSponsor();
if ($sponsor !== null) {
$search->filterBySponsor($sponsor, Criteria::EQUAL);
}
$customers = $this->search($search, $pagination);
$loopResult = new LoopResult();
foreach ($customers as $customer) {
$loopResultRow = new LoopResultRow();
$loopResultRow->set("ID", $customer->getId());
$loopResultRow->set("REF", $customer->getRef());
$loopResultRow->set("TITLE", $customer->getTitleId());
$loopResultRow->set("FIRSTNAME", $customer->getFirstname());
$loopResultRow->set("LASTNAME", $customer->getLastname());
$loopResultRow->set("EMAIL", $customer->getEmail());
$loopResultRow->set("RESELLER", $customer->getReseller());
$loopResultRow->set("SPONSOR", $customer->getSponsor());
$loopResultRow->set("DISCOUNT", $customer->getDiscount());
$loopResult->addRow($loopResultRow);
}
return $loopResult;
}
}

View File

@@ -0,0 +1,168 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Loop;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\Join;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Log\Tlog;
use Thelia\Model\Base\CategoryQuery;
use Thelia\Model\Base\ProductCategoryQuery;
use Thelia\Model\Base\FeatureQuery;
use Thelia\Model\ConfigQuery;
use Thelia\Model\Map\ProductCategoryTableMap;
use Thelia\Type\TypeCollection;
use Thelia\Type;
/**
*
* Feature loop
*
*
* Class Feature
* @package Thelia\Core\Template\Loop
* @author Etienne Roudeix <eroudeix@openstudio.fr>
*/
class Feature extends BaseLoop
{
/**
* @return ArgumentCollection
*/
protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createIntListTypeArgument('id'),
Argument::createIntListTypeArgument('product'),
Argument::createIntListTypeArgument('category'),
Argument::createBooleanTypeArgument('visible', 1),
Argument::createIntListTypeArgument('exclude'),
new Argument(
'order',
new TypeCollection(
new Type\EnumListType(array('alpha', 'alpha_reverse', 'manual', 'manual_reverse'))
),
'manual'
)
);
}
/**
* @param $pagination
*
* @return \Thelia\Core\Template\Element\LoopResult
*/
public function exec(&$pagination)
{
$search = FeatureQuery::create();
$id = $this->getId();
if (null !== $id) {
$search->filterById($id, Criteria::IN);
}
$exclude = $this->getExclude();
if (null !== $exclude) {
$search->filterById($exclude, Criteria::NOT_IN);
}
$visible = $this->getVisible();
$search->filterByVisible($visible);
$product = $this->getProduct();
$category = $this->getCategory();
if(null !== $product) {
$productCategories = ProductCategoryQuery::create()->select(array(ProductCategoryTableMap::CATEGORY_ID))->filterByProductId($product, Criteria::IN)->find()->getData();
if(null === $category) {
$category = $productCategories;
} else {
$category = array_merge($category, $productCategories);
}
}
if(null !== $category) {
$search->filterByCategory(
CategoryQuery::create()->filterById($category)->find(),
Criteria::IN
);
}
$orders = $this->getOrder();
foreach($orders as $order) {
switch ($order) {
case "alpha":
$search->addAscendingOrderByColumn(\Thelia\Model\Map\FeatureI18nTableMap::TITLE);
break;
case "alpha_reverse":
$search->addDescendingOrderByColumn(\Thelia\Model\Map\FeatureI18nTableMap::TITLE);
break;
case "manual":
$search->orderByPosition(Criteria::ASC);
break;
case "manual_reverse":
$search->orderByPosition(Criteria::DESC);
break;
}
}
/**
* Criteria::INNER_JOIN in second parameter for joinWithI18n exclude query without translation.
*
* @todo : verify here if we want results for row without translations.
*/
$search->joinWithI18n(
$this->request->getSession()->getLocale(),
(ConfigQuery::read("default_lang_without_translation", 1)) ? Criteria::LEFT_JOIN : Criteria::INNER_JOIN
);
$features = $this->search($search, $pagination);
$loopResult = new LoopResult();
foreach ($features as $feature) {
$loopResultRow = new LoopResultRow();
$loopResultRow->set("ID", $feature->getId());
$loopResultRow->set("TITLE",$feature->getTitle());
$loopResultRow->set("CHAPO", $feature->getChapo());
$loopResultRow->set("DESCRIPTION", $feature->getDescription());
$loopResultRow->set("POSTSCRIPTUM", $feature->getPostscriptum());
$loopResult->addRow($loopResultRow);
}
return $loopResult;
}
}

View File

@@ -0,0 +1,145 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Loop;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\Join;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Log\Tlog;
use Thelia\Model\Base\FeatureAvQuery;
use Thelia\Model\ConfigQuery;
use Thelia\Type\TypeCollection;
use Thelia\Type;
/**
*todo : to be finished
* FeatureAvailable loop
*
*
* Class FeatureAvailable
* @package Thelia\Core\Template\Loop
* @author Etienne Roudeix <eroudeix@openstudio.fr>
*/
class FeatureAvailable extends BaseLoop
{
/**
* @return ArgumentCollection
*/
protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createIntListTypeArgument('id'),
Argument::createIntListTypeArgument('feature'),
Argument::createIntListTypeArgument('exclude'),
new Argument(
'order',
new TypeCollection(
new Type\EnumListType(array('alpha', 'alpha_reverse', 'manual', 'manual_reverse'))
),
'manual'
)
);
}
/**
* @param $pagination
*
* @return \Thelia\Core\Template\Element\LoopResult
*/
public function exec(&$pagination)
{
$search = FeatureAvQuery::create();
$id = $this->getId();
if (null !== $id) {
$search->filterById($id, Criteria::IN);
}
$exclude = $this->getExclude();
if (null !== $exclude) {
$search->filterById($exclude, Criteria::NOT_IN);
}
$feature = $this->getFeature();
if(null !== $feature) {
$search->filterByFeatureId($feature, Criteria::IN);
}
$orders = $this->getOrder();
foreach($orders as $order) {
switch ($order) {
case "alpha":
$search->addAscendingOrderByColumn(\Thelia\Model\Map\FeatureAvI18nTableMap::TITLE);
break;
case "alpha_reverse":
$search->addDescendingOrderByColumn(\Thelia\Model\Map\FeatureAvI18nTableMap::TITLE);
break;
case "manual":
$search->orderByPosition(Criteria::ASC);
break;
case "manual_reverse":
$search->orderByPosition(Criteria::DESC);
break;
}
}
/**
* Criteria::INNER_JOIN in second parameter for joinWithI18n exclude query without translation.
*
* @todo : verify here if we want results for row without translations.
*/
$search->joinWithI18n(
$this->request->getSession()->getLocale(),
(ConfigQuery::read("default_lang_without_translation", 1)) ? Criteria::LEFT_JOIN : Criteria::INNER_JOIN
);
$featuresAv = $this->search($search, $pagination);
$loopResult = new LoopResult();
foreach ($featuresAv as $featureAv) {
$loopResultRow = new LoopResultRow();
$loopResultRow->set("ID", $featureAv->getId());
$loopResultRow->set("TITLE",$featureAv->getTitle());
$loopResultRow->set("CHAPO", $featureAv->getChapo());
$loopResultRow->set("DESCRIPTION", $featureAv->getDescription());
$loopResultRow->set("POSTSCRIPTUM", $featureAv->getPostscriptum());
$loopResult->addRow($loopResultRow);
}
return $loopResult;
}
}

View File

@@ -0,0 +1,153 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Loop;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\Join;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Log\Tlog;
use Thelia\Model\Base\FeatureProductQuery;
use Thelia\Model\ConfigQuery;
use Thelia\Type\TypeCollection;
use Thelia\Type;
/**
*
* FeatureValue loop
*
*
* Class FeatureValue
* @package Thelia\Core\Template\Loop
* @author Etienne Roudeix <eroudeix@openstudio.fr>
*/
class FeatureValue extends BaseLoop
{
/**
* @return ArgumentCollection
*/
protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createIntTypeArgument('feature', null, true),
Argument::createIntTypeArgument('product', null, true),
Argument::createIntListTypeArgument('feature_available'),
Argument::createBooleanTypeArgument('exclude_feature_available', 0),
Argument::createBooleanTypeArgument('exclude_default_values', 0),
new Argument(
'order',
new TypeCollection(
new Type\EnumListType(array('alpha', 'alpha_reverse', 'manual', 'manual_reverse'))
),
'manual'
)
);
}
/**
* @param $pagination
*
* @return \Thelia\Core\Template\Element\LoopResult
*/
public function exec(&$pagination)
{
$search = FeatureProductQuery::create();
$feature = $this->getFeature();
$search->filterByFeatureId($feature, Criteria::EQUAL);
$product = $this->getProduct();
$search->filterByProductId($product, Criteria::EQUAL);
$featureAvailable = $this->getFeature_available();
if (null !== $featureAvailable) {
$search->filterByFeatureAvId($featureAvailable, Criteria::IN);
}
$excludeFeatureAvailable = $this->getExclude_feature_available();
if($excludeFeatureAvailable == true) {
$search->filterByFeatureAvId(null, Criteria::NULL);
}
$excludeDefaultValues = $this->getExclude_default_values();
if($excludeDefaultValues == true) {
$search->filterByByDefault(null, Criteria::NULL);
}
$orders = $this->getOrder();
foreach($orders as $order) {
switch ($order) {
case "alpha":
$search->addAscendingOrderByColumn(\Thelia\Model\Map\FeatureI18nTableMap::TITLE);
break;
case "alpha_reverse":
$search->addDescendingOrderByColumn(\Thelia\Model\Map\FeatureI18nTableMap::TITLE);
break;
case "manual":
$search->orderByPosition(Criteria::ASC);
break;
case "manual_reverse":
$search->orderByPosition(Criteria::DESC);
break;
}
}
/**
* Criteria::INNER_JOIN in second parameter for joinWithI18n exclude query without translation.
*
* @todo : verify here if we want results for row without translations.
*/
/*$search->joinWithI18n(
$this->request->getSession()->getLocale(),
(ConfigQuery::read("default_lang_without_translation", 1)) ? Criteria::LEFT_JOIN : Criteria::INNER_JOIN
);*/
$featureValues = $this->search($search, $pagination);
$loopResult = new LoopResult();
foreach ($featureValues as $featureValue) {
$loopResultRow = new LoopResultRow();
$loopResultRow->set("ID", $featureValue->getId());
/*$loopResultRow->set("TITLE",$featureValue->getTitle());
$loopResultRow->set("CHAPO", $featureValue->getChapo());
$loopResultRow->set("DESCRIPTION", $featureValue->getDescription());
$loopResultRow->set("POSTSCRIPTUM", $featureValue->getPostscriptum());*/
$loopResult->addRow($loopResultRow);
}
return $loopResult;
}
}

View File

@@ -0,0 +1,106 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Loop;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Type\TypeCollection;
use Thelia\Type;
/**
*
* @package Thelia\Core\Template\Loop
*
* @author Franck Allimant <franck@cqfdev.fr>
*/
class Feed extends BaseLoop
{
public function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createAnyTypeArgument('url', null, true),
Argument::createIntTypeArgument('timeout', 10)
);
}
/**
*
*
* @return \Thelia\Core\Template\Element\LoopResult
*/
public function exec(&$pagination)
{
$cachedir = THELIA_ROOT . 'cache/feeds';
if (! is_dir($cachedir)) {
if (! mkdir($cachedir)) {
throw new \Exception(sprintf("Failed to create cache directory '%s'", $cachedir));
}
}
$feed = new \SimplePie($this->getUrl(), THELIA_ROOT . 'cache/feeds');
$feed->init();
$feed->handle_content_type();
$feed->set_timeout($this->getTimeout());
$items = $feed->get_items();
$limit = min(count($items), $this->getLimit());
$loopResult = new LoopResult();
for($idx = 0; $idx < $limit; $idx++) {
$item = $items[$idx];
$link = $item->get_permalink();
$title = $item->get_title();
$author = $item->get_author();
$description = $item->get_description();
$date = $item->get_date('d/m/Y');
$loopResultRow = new LoopResultRow();
$loopResultRow->set("URL", $item->get_permalink());
$loopResultRow->set("TITLE", $item->get_title());
$loopResultRow->set("AUTHOR", $item->get_author());
$loopResultRow->set("DESCRIPTION", $item->get_description());
$loopResultRow->set("DATE", $item->get_date('d/m/Y')); // FIXME - date format should be an intl parameter
$loopResult->addRow($loopResultRow);
}
return $loopResult;
}
}

View File

@@ -0,0 +1,179 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Loop;
use Propel\Runtime\ActiveQuery\Criteria;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Log\Tlog;
use Thelia\Model\FolderQuery;
use Thelia\Model\ConfigQuery;
use Thelia\Type\TypeCollection;
use Thelia\Type;
/**
* Class Folder
*
* @package Thelia\Core\Template\Loop
* @author Etienne Roudeix <eroudeix@openstudio.fr>
*/
class Folder extends BaseLoop
{
/**
* @return ArgumentCollection
*/
protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createIntListTypeArgument('id'),
Argument::createIntTypeArgument('parent'),
Argument::createBooleanTypeArgument('current'),
Argument::createBooleanTypeArgument('not_empty', 0),
Argument::createBooleanTypeArgument('visible', 1),
new Argument(
'order',
new TypeCollection(
new Type\EnumListType(array('alpha', 'alpha_reverse', 'manual', 'manual-reverse', 'random'))
),
'manual'
),
Argument::createIntListTypeArgument('exclude')
);
}
/**
* @param $pagination
*
* @return \Thelia\Core\Template\Element\LoopResult
*/
public function exec(&$pagination)
{
$search = FolderQuery::create();
$id = $this->getId();
if (!is_null($id)) {
$search->filterById($id, Criteria::IN);
}
$parent = $this->getParent();
if (!is_null($parent)) {
$search->filterByParent($parent);
}
$current = $this->getCurrent();
if ($current === true) {
$search->filterById($this->request->get("folder_id"));
} elseif ($current === false) {
$search->filterById($this->request->get("folder_id"), Criteria::NOT_IN);
}
$exclude = $this->getExclude();
if (!is_null($exclude)) {
$search->filterById($exclude, Criteria::NOT_IN);
}
$search->filterByVisible($this->getVisible() ? 1 : 0);
$orders = $this->getOrder();
foreach($orders as $order) {
switch ($order) {
case "alpha":
$search->addAscendingOrderByColumn(\Thelia\Model\Map\FolderI18nTableMap::TITLE);
break;
case "alpha_reverse":
$search->addDescendingOrderByColumn(\Thelia\Model\Map\FolderI18nTableMap::TITLE);
break;
case "manual-reverse":
$search->orderByPosition(Criteria::DESC);
break;
case "manual":
$search->orderByPosition(Criteria::ASC);
break;
case "random":
$search->clearOrderByColumns();
$search->addAscendingOrderByColumn('RAND()');
break(2);
break;
}
}
/**
* \Criteria::INNER_JOIN in second parameter for joinWithI18n exclude query without translation.
*
* @todo : verify here if we want results for row without translations.
*/
$search->joinWithI18n(
$this->request->getSession()->getLocale(),
(ConfigQuery::read("default_lang_without_translation", 1)) ? Criteria::LEFT_JOIN : Criteria::INNER_JOIN
);
$folders = $this->search($search, $pagination);
$notEmpty = $this->getNot_empty();
$loopResult = new LoopResult();
foreach ($folders as $folder) {
if ($notEmpty && $folder->countAllProducts() == 0) continue;
$loopResultRow = new LoopResultRow();
$loopResultRow
->set("ID", $folder->getId())
->set("TITLE",$folder->getTitle())
->set("CHAPO", $folder->getChapo())
->set("DESCRIPTION", $folder->getDescription())
->set("POSTSCRIPTUM", $folder->getPostscriptum())
->set("PARENT", $folder->getParent())
->set("CONTENT_COUNT", $folder->countChild())
->set("VISIBLE", $folder->getVisible() ? "1" : "0")
->set("POSITION", $folder->getPosition())
->set("CREATE_DATE", $folder->getCreatedAt())
->set("UPDATE_DATE", $folder->getUpdatedAt())
->set("VERSION", $folder->getVersion())
->set("VERSION_DATE", $folder->getVersionCreatedAt())
->set("VERSION_AUTHOR", $folder->getVersionCreatedBy())
;
$loopResult->addRow($loopResultRow);
}
return $loopResult;
}
}

View File

@@ -0,0 +1,59 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Loop;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Type\TypeCollection;
use Thelia\Type;
/**
*
* @package Thelia\Core\Template\Loop
*
* @author Franck Allimant <franck@cqfdev.fr>
*/
class Order extends BaseLoop
{
public function getArgDefinitions()
{
return new ArgumentCollection();
}
/**
*
*
* @return \Thelia\Core\Template\Element\LoopResult
*/
public function exec(&$pagination)
{
// TODO : a coder !
return new LoopResult();
}
}

View File

@@ -0,0 +1,59 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Loop;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Type\TypeCollection;
use Thelia\Type;
/**
*
* @package Thelia\Core\Template\Loop
*
* @author Franck Allimant <franck@cqfdev.fr>
*/
class OrderStatus extends BaseLoop
{
public function getArgDefinitions()
{
return new ArgumentCollection();
}
/**
*
*
* @return \Thelia\Core\Template\Element\LoopResult
*/
public function exec(&$pagination)
{
// TODO : a coder !
return new LoopResult();
}
}

View File

@@ -0,0 +1,421 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Loop;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\Join;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Log\Tlog;
use Thelia\Model\Base\FeatureProductQuery;
use Thelia\Model\CategoryQuery;
use Thelia\Model\FeatureAvQuery;
use Thelia\Model\FeatureQuery;
use Thelia\Model\Map\FeatureProductTableMap;
use Thelia\Model\Map\ProductTableMap;
use Thelia\Model\ProductCategoryQuery;
use Thelia\Model\ProductQuery;
use Thelia\Model\ConfigQuery;
use Thelia\Type\TypeCollection;
use Thelia\Type;
/**
*
* Product loop
*
*
* Class Product
* @package Thelia\Core\Template\Loop
* @author Etienne Roudeix <eroudeix@openstudio.fr>
*/
class Product extends BaseLoop
{
/**
* @return ArgumentCollection
*/
protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createIntListTypeArgument('id'),
new Argument(
'ref',
new TypeCollection(
new Type\AlphaNumStringListType()
)
),
Argument::createIntListTypeArgument('category'),
//Argument::createBooleanTypeArgument('new'),
//Argument::createBooleanTypeArgument('promo'),
//Argument::createFloatTypeArgument('min_price'),
//Argument::createFloatTypeArgument('max_price'),
//Argument::createIntTypeArgument('min_stock'),
//Argument::createFloatTypeArgument('min_weight'),
//Argument::createFloatTypeArgument('max_weight'),
Argument::createBooleanTypeArgument('current'),
Argument::createBooleanTypeArgument('current_category'),
Argument::createIntTypeArgument('depth', 1),
Argument::createBooleanTypeArgument('visible', 1),
new Argument(
'order',
new TypeCollection(
new Type\EnumListType(array('alpha', 'alpha_reverse', /*'min_price', 'max_price',*/ 'manual', 'manual_reverse', 'ref', /*'promo', 'new',*/ 'random', 'given_id'))
),
'alpha'
),
Argument::createIntListTypeArgument('exclude'),
Argument::createIntListTypeArgument('exclude_category'),
new Argument(
'feature_available',
new TypeCollection(
new Type\IntToCombinedIntsListType()
)
),
new Argument(
'feature_values',
new TypeCollection(
new Type\IntToCombinedStringsListType()
)
)
);
}
/**
* @param $pagination
*
* @return \Thelia\Core\Template\Element\LoopResult
* @throws \InvalidArgumentException
*/
public function exec(&$pagination)
{
$search = ProductQuery::create();
//$search->withColumn('CASE WHEN ' . ProductTableMap::PROMO . '=1 THEN ' . ProductTableMap::PRICE2 . ' ELSE ' . ProductTableMap::PRICE . ' END', 'real_price');
$id = $this->getId();
if (!is_null($id)) {
$search->filterById($id, Criteria::IN);
}
$ref = $this->getRef();
if (!is_null($ref)) {
$search->filterByRef($ref, Criteria::IN);
}
$category = $this->getCategory();
if (!is_null($category)) {
$categories = CategoryQuery::create()->filterById($category, Criteria::IN)->find();
$depth = $this->getDepth();
if(null !== $depth) {
foreach(CategoryQuery::findAllChild($category, $depth) as $subCategory) {
$categories->prepend($subCategory);
}
}
$search->filterByCategory(
$categories,
Criteria::IN
);
}
/*$new = $this->getNew();
if ($new === true) {
$search->filterByNewness(1, Criteria::EQUAL);
} else if($new === false) {
$search->filterByNewness(0, Criteria::EQUAL);
}
$promo = $this->getPromo();
if ($promo === true) {
$search->filterByPromo(1, Criteria::EQUAL);
} else if($promo === false) {
$search->filterByNewness(0, Criteria::EQUAL);
}
$min_stock = $this->getMin_stock();
if (null != $min_stock) {
$search->filterByQuantity($min_stock, Criteria::GREATER_EQUAL);
}
$min_price = $this->getMin_price();*/
//if(null !== $min_price) {
/**
* Following should work but does not :
*
* $search->filterBy('real_price', $max_price, Criteria::GREATER_EQUAL);
*/
/*$search->condition('in_promo', ProductTableMap::PROMO . Criteria::EQUAL . '1')
->condition('not_in_promo', ProductTableMap::PROMO . Criteria::NOT_EQUAL . '1')
->condition('min_price2', ProductTableMap::PRICE2 . Criteria::GREATER_EQUAL . '?', $min_price)
->condition('min_price', ProductTableMap::PRICE . Criteria::GREATER_EQUAL . '?', $min_price)
->combine(array('in_promo', 'min_price2'), Criteria::LOGICAL_AND, 'in_promo_min_price')
->combine(array('not_in_promo', 'min_price'), Criteria::LOGICAL_AND, 'not_in_promo_min_price')
->where(array('not_in_promo_min_price', 'in_promo_min_price'), Criteria::LOGICAL_OR);
}
$max_price = $this->getMax_price();*/
//if(null !== $max_price) {
/**
* Following should work but does not :
*
* $search->filterBy('real_price', $max_price, Criteria::LESS_EQUAL);
*/
/*$search->condition('in_promo', ProductTableMap::PROMO . Criteria::EQUAL . '1')
->condition('not_in_promo', ProductTableMap::PROMO . Criteria::NOT_EQUAL . '1')
->condition('max_price2', ProductTableMap::PRICE2 . Criteria::LESS_EQUAL . '?', $max_price)
->condition('max_price', ProductTableMap::PRICE . Criteria::LESS_EQUAL . '?', $max_price)
->combine(array('in_promo', 'max_price2'), Criteria::LOGICAL_AND, 'in_promo_max_price')
->combine(array('not_in_promo', 'max_price'), Criteria::LOGICAL_AND, 'not_in_promo_max_price')
->where(array('not_in_promo_max_price', 'in_promo_max_price'), Criteria::LOGICAL_OR);
}*/
/*$min_weight = $this->getMin_weight();
if(null !== $min_weight) {
$search->filterByWeight($min_weight, Criteria::GREATER_EQUAL);
}
$max_weight = $this->getMax_weight();
if(null !== $max_weight) {
$search->filterByWeight($max_weight, Criteria::LESS_EQUAL);
}*/
$current = $this->getCurrent();
if ($current === true) {
$search->filterById($this->request->get("product_id"));
} elseif($current === false) {
$search->filterById($this->request->get("product_id"), Criteria::NOT_IN);
}
$current_category = $this->getCurrent_category();
if ($current_category === true) {
$search->filterByCategory(
CategoryQuery::create()->filterByProduct(
ProductCategoryQuery::create()->filterByProductId(
$this->request->get("product_id"),
Criteria::EQUAL
)->find(),
Criteria::IN
)->find(),
Criteria::IN
);
} elseif($current_category === false) {
$search->filterByCategory(
CategoryQuery::create()->filterByProduct(
ProductCategoryQuery::create()->filterByProductId(
$this->request->get("product_id"),
Criteria::EQUAL
)->find(),
Criteria::IN
)->find(),
Criteria::NOT_IN
);
}
$visible = $this->getVisible();
$search->filterByVisible($visible);
$orders = $this->getOrder();
foreach($orders as $order) {
switch ($order) {
case "alpha":
$search->addAscendingOrderByColumn(\Thelia\Model\Map\ProductI18nTableMap::TITLE);
break;
case "alpha_reverse":
$search->addDescendingOrderByColumn(\Thelia\Model\Map\ProductI18nTableMap::TITLE);
break;
/*case "min_price":
$search->orderBy('real_price', Criteria::ASC);
break;
case "max_price":
$search->orderBy('real_price', Criteria::DESC);
break;*/
case "manual":
if(null === $category || count($category) != 1)
throw new \InvalidArgumentException('Manual order cannot be set without single category argument');
$search->orderByPosition(Criteria::ASC);
break;
case "manual_reverse":
if(null === $category || count($category) != 1)
throw new \InvalidArgumentException('Manual order cannot be set without single category argument');
$search->orderByPosition(Criteria::DESC);
break;
case "ref":
$search->orderByRef(Criteria::ASC);
break;
/*case "promo":
$search->orderByPromo(Criteria::DESC);
break;
case "new":
$search->orderByNewness(Criteria::DESC);
break;*/
case "given_id":
if(null === $id)
throw new \InvalidArgumentException('Given_id order cannot be set without `id` argument');
foreach($id as $singleId) {
$givenIdMatched = 'given_id_matched_' . $singleId;
$search->withColumn(ProductTableMap::ID . "='$singleId'", $givenIdMatched);
$search->orderBy($givenIdMatched, Criteria::DESC);
}
break;
case "random":
$search->clearOrderByColumns();
$search->addAscendingOrderByColumn('RAND()');
break(2);
}
}
$exclude = $this->getExclude();
if (!is_null($exclude)) {
$search->filterById($exclude, Criteria::NOT_IN);
}
$exclude_category = $this->getExclude_category();
if (!is_null($exclude_category)) {
$search->filterByCategory(
CategoryQuery::create()->filterById($exclude_category, Criteria::IN)->find(),
Criteria::NOT_IN
);
}
$feature_available = $this->getFeature_available();
if(null !== $feature_available) {
foreach($feature_available as $feature => $feature_choice) {
foreach($feature_choice['values'] as $feature_av) {
$featureAlias = 'fa_' . $feature;
if($feature_av != '*')
$featureAlias .= '_' . $feature_av;
$search->joinFeatureProduct($featureAlias, Criteria::LEFT_JOIN)
->addJoinCondition($featureAlias, "`$featureAlias`.FEATURE_ID = ?", $feature, null, \PDO::PARAM_INT);
if($feature_av != '*')
$search->addJoinCondition($featureAlias, "`$featureAlias`.FEATURE_AV_ID = ?", $feature_av, null, \PDO::PARAM_INT);
}
/* format for mysql */
$sqlWhereString = $feature_choice['expression'];
if($sqlWhereString == '*') {
$sqlWhereString = 'NOT ISNULL(`fa_' . $feature . '`.ID)';
} else {
$sqlWhereString = preg_replace('#([0-9]+)#', 'NOT ISNULL(`fa_' . $feature . '_' . '\1`.ID)', $sqlWhereString);
$sqlWhereString = str_replace('&', ' AND ', $sqlWhereString);
$sqlWhereString = str_replace('|', ' OR ', $sqlWhereString);
}
$search->where("(" . $sqlWhereString . ")");
}
}
$feature_values = $this->getFeature_values();
if(null !== $feature_values) {
foreach($feature_values as $feature => $feature_choice) {
foreach($feature_choice['values'] as $feature_value) {
$featureAlias = 'fv_' . $feature;
if($feature_value != '*')
$featureAlias .= '_' . $feature_value;
$search->joinFeatureProduct($featureAlias, Criteria::LEFT_JOIN)
->addJoinCondition($featureAlias, "`$featureAlias`.FEATURE_ID = ?", $feature, null, \PDO::PARAM_INT);
if($feature_value != '*')
$search->addJoinCondition($featureAlias, "`$featureAlias`.BY_DEFAULT = ?", $feature_value, null, \PDO::PARAM_STR);
}
/* format for mysql */
$sqlWhereString = $feature_choice['expression'];
if($sqlWhereString == '*') {
$sqlWhereString = 'NOT ISNULL(`fv_' . $feature . '`.ID)';
} else {
$sqlWhereString = preg_replace('#([a-zA-Z0-9_\-]+)#', 'NOT ISNULL(`fv_' . $feature . '_' . '\1`.ID)', $sqlWhereString);
$sqlWhereString = str_replace('&', ' AND ', $sqlWhereString);
$sqlWhereString = str_replace('|', ' OR ', $sqlWhereString);
}
$search->where("(" . $sqlWhereString . ")");
}
}
/**
* Criteria::INNER_JOIN in second parameter for joinWithI18n exclude query without translation.
*
* @todo : verify here if we want results for row without translations.
*/
$search->joinWithI18n(
$this->request->getSession()->getLocale(),
(ConfigQuery::read("default_lang_without_translation", 1)) ? Criteria::LEFT_JOIN : Criteria::INNER_JOIN
);
$search->groupBy(ProductTableMap::ID);
$products = $this->search($search, $pagination);
$loopResult = new LoopResult();
foreach ($products as $product) {
$loopResultRow = new LoopResultRow();
$loopResultRow->set("ID", $product->getId())
->set("REF",$product->getRef())
->set("TITLE",$product->getTitle())
->set("CHAPO", $product->getChapo())
->set("DESCRIPTION", $product->getDescription())
->set("POSTSCRIPTUM", $product->getPostscriptum())
//->set("PRICE", $product->getPrice())
//->set("PROMO_PRICE", $product->getPrice2())
//->set("WEIGHT", $product->getWeight())
//->set("PROMO", $product->getPromo())
//->set("NEW", $product->getNewness())
->set("POSITION", $product->getPosition())
;
$loopResult->addRow($loopResultRow);
}
return $loopResult;
}
}

View File

@@ -0,0 +1,105 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Loop;
use Propel\Runtime\ActiveQuery\Criteria;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Log\Tlog;
use Thelia\Model\CustomerTitleQuery;
use Thelia\Model\ConfigQuery;
use Thelia\Type\TypeCollection;
use Thelia\Type;
/**
*
* Title loop
*
*
* Class Title
* @package Thelia\Core\Template\Loop
* @author Etienne Roudeix <eroudeix@openstudio.fr>
*/
class Title extends BaseLoop
{
/**
* @return ArgumentCollection
*/
protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createIntListTypeArgument('id')
);
}
/**
* @param $pagination
*
* @return \Thelia\Core\Template\Element\LoopResult
*/
public function exec(&$pagination)
{
$search = CustomerTitleQuery::create();
$id = $this->getId();
if (null !== $id) {
$search->filterById($id, Criteria::IN);
}
/**
* Criteria::INNER_JOIN in second parameter for joinWithI18n exclude query without translation.
*
* @todo : verify here if we want results for row without translations.
*/
$search->joinWithI18n(
$this->request->getSession()->getLocale(),
(ConfigQuery::read("default_lang_without_translation", 1)) ? Criteria::LEFT_JOIN : Criteria::INNER_JOIN
);
$search->orderByPosition();
$titles = $this->search($search, $pagination);
$loopResult = new LoopResult();
foreach ($titles as $title) {
$loopResultRow = new LoopResultRow();
$loopResultRow->set("ID", $title->getId());
$loopResultRow->set("DEFAULT", $title->getByDefault());
$loopResultRow->set("SHORT", $title->getShort());
$loopResultRow->set("LONG", $title->getLong());
$loopResult->addRow($loopResultRow);
}
return $loopResult;
}
}

View File

@@ -0,0 +1,97 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template;
use Thelia\Model\ConfigQuery;
use Thelia\Core\HttpFoundation\Request;
use Thelia\Tools\URL;
use Thelia\Form\BaseForm;
/**
* The parser context is an application-wide context, which stores var-value pairs.
* Theses pairs are injected in the parser and becomes available to the templates.
*
* @author Franck Allimant <franck@cqfdev.fr>
*/
class ParserContext implements \IteratorAggregate
{
private $store = array();
public function __construct(Request $request) {
// Setup basic variables
$this
->set('BASE_URL' , ConfigQuery::read('base_url', '/'))
->set('INDEX_PAGE' , URL::getIndexPage())
->set('RETURN_TO_URL' , URL::absoluteUrl($request->getSession()->getReturnToUrl()))
->set('THELIA_VERSION' , ConfigQuery::read('thelia_version', 'undefined'))
;
}
// -- Error form -----------------------------------------------------------
/**
* @param BaseForm $form the errored form
*/
public function setErrorForm(BaseForm $form)
{
$this->set('error_form', $form);
}
public function getErrorForm()
{
return $this->get('error_form', null);
}
public function clearErrorForm()
{
return $this->remove('error_form');
}
// -- Internal table manipulation ------------------------------------------
public function set($name, $value)
{
$this->store[$name] = $value;
return $this;
}
public function remove($name)
{
unset($this->store[$name]);
return $this;
}
public function get($name, $default = null)
{
return isset($this->store[$name]) ? $this->store[$name] : $default;
}
public function getIterator()
{
return new \ArrayIterator( $this->store );
}
}

View File

@@ -0,0 +1,44 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template;
/**
*
* @author Manuel Raynaud <mraynaud@openstudio.fr>
*
*/
interface ParserInterface
{
/**
*
*/
public function getContent();
public function setContent($content);
public function getStatus();
public function setStatus($status);
}

View File

@@ -0,0 +1,101 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Smarty;
/**
*
* The class all Smarty Thelia plugin shoud extend
*
* Class AbstractSmartyPlugin
* @package Thelia\Core\Template\Smarty
*/
abstract class AbstractSmartyPlugin
{
/**
* Explode a comma separated list in a array, trimming all array elements
*
* @param unknown $commaSeparatedValues
* @return multitype:
*/
protected function _explode($commaSeparatedValues)
{
$array = explode(',', $commaSeparatedValues);
if (array_walk($array, function(&$item) {
$item = strtoupper(trim($item));
})) {
return $array;
}
return array();
}
/**
* Get a function or block parameter value, and normalize it, trimming balnks and
* making it lowercase
*
* @param array $params the parameters array
* @param mixed $name as single parameter name, or an array of names. In this case, the first defined parameter is returned. Use this for aliases (context, ctx, c)
* @param mixed $default the defaut value if parameter is missing (default to null)
* @return mixed the parameter value, or the default value if it is not found.
*/
public function getNormalizedParam($params, $name, $default = null)
{
$value = $this->getParam($params, $name, $default);
if (is_string($value)) $value = strtolower(trim($value));
return $value;
}
/**
* Get a function or block parameter value
*
* @param array $params the parameters array
* @param mixed $name as single parameter name, or an array of names. In this case, the first defined parameter is returned. Use this for aliases (context, ctx, c)
* @param mixed $default the defaut value if parameter is missing (default to null)
* @return mixed the parameter value, or the default value if it is not found.
*/
public function getParam($params, $name, $default = null)
{
if (is_array($name)) {
foreach($name as $test) {
if (isset($params[$test])) {
return $params[$test];
}
}
}
else if (isset($params[$name])) {
return $params[$name];
}
return $default;
}
/**
* @return an array of SmartyPluginDescriptor
*/
public abstract function getPluginDescriptors();
}

View File

@@ -0,0 +1,95 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Smarty\Assets;
use Thelia\Core\Template\Assets\AsseticHelper;
use Thelia\Model\ConfigQuery;
use Thelia\Tools\URL;
class SmartyAssetsManager
{
const ASSET_TYPE_AUTO = '';
private $assetic_manager;
private $web_root;
private $path_relative_to_web_root;
/**
* Creates a new SmartyAssetsManager instance
*
* @param string $web_root the disk path to the web root
* @param string $path_relative_to_web_root the path (relative to web root) where the assets will be generated
*/
public function __construct($web_root, $path_relative_to_web_root)
{
$this->web_root = $web_root;
$this->path_relative_to_web_root = $path_relative_to_web_root;
$this->assetic_manager = new AsseticHelper();
}
public function computeAssetUrl($assetType, $params, \Smarty_Internal_Template $template) {
$file = $params['file'];
$filters = isset($params['filters']) ? $params['filters'] : '';
$debug = isset($params['debug']) ? trim(strtolower($params['debug'])) == 'true' : false;
// Get template base path
$tpl_path = $template->source->filepath;
// Get basedir
$tpl_dir = dirname($tpl_path);
// Create absolute dir path
$asset_dir = realpath($tpl_dir.'/'.dirname($file));
$asset_file = basename($file);
if ($asset_dir === false) throw new \Exception("Failed to get real path of '".$tpl_dir.'/'.dirname($file)."'");
$url = $this->assetic_manager->asseticize(
$asset_dir.'/'.$asset_file,
$this->web_root."/".$this->path_relative_to_web_root,
URL::absoluteUrl($this->path_relative_to_web_root, array(), true /* path only */),
$assetType,
$filters,
$debug
);
return $url;
}
public function processSmartyPluginCall($assetType, $params, $content, \Smarty_Internal_Template $template, &$repeat)
{
// Opening tag (first call only)
if ($repeat) {
$url = $this->computeAssetUrl($assetType, $params, $template);
$template->assign('asset_url', $url);
} elseif (isset($content)) {
return $content;
}
}
}

View File

@@ -0,0 +1,79 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Smarty\Plugins;
use Thelia\Core\Template\Smarty\SmartyPluginDescriptor;
use Thelia\Core\Template\Smarty\AbstractSmartyPlugin;
use Thelia\Core\Template\Smarty\Assets\SmartyAssetsManager;
use Thelia\Model\ConfigQuery;
class Assetic extends AbstractSmartyPlugin
{
public $assetManager;
public function __construct()
{
$web_root = THELIA_WEB_DIR;
$asset_dir_from_web_root = ConfigQuery::read('asset_dir_from_web_root', 'assets');
$this->assetManager = new SmartyAssetsManager($web_root, $asset_dir_from_web_root);
}
public function blockJavascripts($params, $content, \Smarty_Internal_Template $template, &$repeat)
{
return $this->assetManager->processSmartyPluginCall('js', $params, $content, $template, $repeat);
}
public function blockImages($params, $content, \Smarty_Internal_Template $template, &$repeat)
{
return $this->assetManager->processSmartyPluginCall(SmartyAssetsManager::ASSET_TYPE_AUTO, $params, $content, $template, $repeat);
}
public function blockStylesheets($params, $content, \Smarty_Internal_Template $template, &$repeat)
{
return $this->assetManager->processSmartyPluginCall('css', $params, $content, $template, $repeat);
}
public function functionImage($params, \Smarty_Internal_Template $template)
{
return $this->assetManager->computeAssetUrl(SmartyAssetsManager::ASSET_TYPE_AUTO, $params, $template);
}
/**
* Define the various smarty plugins hendled by this class
*
* @return an array of smarty plugin descriptors
*/
public function getPluginDescriptors()
{
return array(
new SmartyPluginDescriptor('block' , 'stylesheets', $this, 'blockStylesheets'),
new SmartyPluginDescriptor('block' , 'javascripts', $this, 'blockJavascripts'),
new SmartyPluginDescriptor('block' , 'images' , $this, 'blockImages'),
new SmartyPluginDescriptor('function', 'image' , $this, 'functionImage')
);
}
}

View File

@@ -0,0 +1,113 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Smarty\Plugins;
use Thelia\Core\Template\Smarty\AbstractSmartyPlugin;
use Thelia\Core\Security\SecurityContext;
use Thelia\Core\Template\ParserContext;
use Thelia\Core\Template\Smarty\SmartyPluginDescriptor;
/**
* Implementation of data access to main Thelia objects (users, cart, etc.)
*
* @author Franck Allimant <franck@cqfdev.fr>
*
*/
class DataAccessFunctions extends AbstractSmartyPlugin
{
private $securityContext;
protected $parserContext;
public function __construct(SecurityContext $securityContext, ParserContext $parserContext)
{
$this->securityContext = $securityContext;
}
/**
* Provides access to the current logged administrator attributes using the accessors.
*
* @param array $params
* @param unknown $smarty
* @return string the value of the requested attribute
*/
public function adminDataAccess($params, &$smarty)
{
return $this->userDataAccess("Admin User", SecurityContext::CONTEXT_BACK_OFFICE, $params);
}
/**
* Provides access to the current logged customer attributes throught the accessor
*
* @param array $params
* @param unknown $smarty
* @return string the value of the requested attribute
*/
public function customerDataAccess($params, &$smarty)
{
return $this->userDataAccess("Customer User", SecurityContext::CONTEXT_FRONT_OFFICE, $params);
}
/**
* Provides access to user attributes using the accessors.
*
* @param array $params
* @param unknown $smarty
* @return string the value of the requested attribute
* @throws InvalidArgumentException if the object does not have the requested attribute.
*/
protected function userDataAccess($objectLabel, $context, $params)
{
$attribute = $this->getNormalizedParam($params, array('attribute', 'attrib', 'attr'));
if (! empty($attribute)) {
$user = $this->securityContext->setContext($context)->getUser();
if (null != $user) {
$getter = sprintf("get%s", ucfirst($attribute));
if (method_exists($user, $getter)) {
return $user->$getter();
}
throw new \InvalidArgumentException(sprintf("%s has no '%s' attribute", $objectLabel, $attribute));
}
}
return '';
}
/**
* Define the various smarty plugins hendled by this class
*
* @return an array of smarty plugin descriptors
*/
public function getPluginDescriptors()
{
return array(
new SmartyPluginDescriptor('function', 'admin', $this, 'adminDataAccess'),
new SmartyPluginDescriptor('function', 'customer', $this, 'customerDataAccess')
);
}
}

View File

@@ -0,0 +1,273 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Smarty\Plugins;
use Symfony\Component\Form\FormView;
use Thelia\Form\BaseForm;
use Thelia\Core\Template\Element\Exception\ElementNotFoundException;
use Symfony\Component\HttpFoundation\Request;
use Thelia\Core\Template\Smarty\SmartyPluginDescriptor;
use Thelia\Core\Template\Smarty\AbstractSmartyPlugin;
use Thelia\Log\Tlog;
use Thelia\Core\Template\ParserContext;
/**
*
* Plugin for smarty defining blocks and functions for using Form display.
*
* blocks :
* - {form name="myForm"} ... {/form} => find form named myForm,
* create an instance and assign this instanciation into smarty variable. Form must be declare into
* config using <forms> tag
*
* - {form_field form=$form.fieldName} {/form_field} This block find info into the Form field containing by
* the form paramter. This field must be an instance of FormView. fieldName is the name of your field. This block
* can output these info :
* * $name => name of yout input
* * $value => value for your input
* * $label => label for your input
* * $error => boolean for know if there is error for this field
* * $attr => all your attribute for your input (define when you construct programmatically you form)
*
* - {form_error form=$form.fieldName} ... {/form_error} Display this block if there are errors on this field.
* fieldName is the name of your field
*
* Class Form
* @package Thelia\Core\Template\Smarty\Plugins
*/
class Form extends AbstractSmartyPlugin
{
protected $request;
protected $parserContext;
protected $formDefinition = array();
public function __construct(Request $request, ParserContext $parserContext)
{
$this->request = $request;
$this->parserContext = $parserContext;
}
public function setFormDefinition($formDefinition)
{
foreach ($formDefinition as $name => $className) {
if (array_key_exists($name, $this->formDefinition)) {
throw new \InvalidArgumentException(sprintf("%s form name already exists for %s class", $name,
$className));
}
$this->formDefinition[$name] = $className;
}
}
public function generateForm($params, $content, \Smarty_Internal_Template $template, &$repeat)
{
if ($repeat) {
$name = $this->getParam($params, 'name');
if (null == $name) {
throw new \InvalidArgumentException("Missing 'name' parameter in form arguments");
}
$instance = $this->createInstance($name);
// Check if parser context contains our form
$errorForm = $this->parserContext->getErrorForm();
if (null != $errorForm && $errorForm->getName() == $instance->getName()) {
// Re-use the errored form
$instance = $errorForm;
$this->parserContext->clearErrorForm();
}
$instance->createView();
$template->assign("form", $instance);
$template->assign("form_error", $instance->hasError() ? true : false);
$template->assign("form_error_message", $instance->getErrorMessage());
}
else {
return $content;
}
}
public function renderFormField($params, $content, \Smarty_Internal_Template $template, &$repeat)
{
if ($repeat) {
$formFieldView = $this->getFormFieldView($params);
$template->assign("options", $formFieldView->vars);
$template->assign("name", $formFieldView->vars["full_name"]);
$template->assign("value", $formFieldView->vars["value"]);
$template->assign("label", $formFieldView->vars["label"]);
$errors = $formFieldView->vars["errors"];
$template->assign("error", empty($errors) ? false : true);
if (! empty($errors)) {
$this->assignFieldErrorVars($template, $errors);
}
$attr = array();
foreach ($formFieldView->vars["attr"] as $key => $value) {
$attr[] = sprintf('%s="%s"', $key, $value);
}
$template->assign("attr", implode(" ", $attr));
$formFieldView->setRendered();
}
else {
return $content;
}
}
public function renderHiddenFormField($params, \Smarty_Internal_Template $template)
{
$field = '<input type="hidden" name="%s" value="%s">';
$instance = $this->getInstanceFromParams($params);
$formView = $instance->getView();
$return = "";
foreach ($formView->getIterator() as $row) {
if ($this->isHidden($row) && $row->isRendered() === false) {
$return .= sprintf($field, $row->vars["full_name"], $row->vars["value"]);
}
}
return $return;
}
public function formEnctype($params, \Smarty_Internal_Template $template)
{
$instance = $this->getInstanceFromParams($params);
$formView = $instance->getForm();
if ($formView->vars["multipart"]) {
return sprintf('%s="%s"',"enctype", "multipart/form-data");
}
}
public function formError($params, $content, \Smarty_Internal_Template $template, &$repeat)
{
$formFieldView = $this->getFormFieldView($params);
$errors = $formFieldView->vars["errors"];
if (empty($errors)) {
return "";
}
if ($repeat) {
$this->assignFieldErrorVars($template, $errors);
}
else {
return $content;
}
}
protected function assignFieldErrorVars(\Smarty_Internal_Template $template, array $errors)
{
$template->assign("message", $errors[0]->getMessage());
$template->assign("parameters", $errors[0]->getMessageParameters());
$template->assign("pluralization", $errors[0]->getMessagePluralization());
}
protected function isHidden(FormView $formView)
{
return array_search("hidden", $formView->vars["block_prefixes"]);
}
protected function getFormFieldView($params) {
$instance = $this->getInstanceFromParams($params);
$fieldName = $this->getParam($params, 'field');
if (null == $fieldName)
throw new \InvalidArgumentException("'field' parameter is missing");
if (empty($instance->getView()[$fieldName]))
throw new \InvalidArgumentException(sprintf("Field name '%s' not found in form %s", $fieldName, $instance->getName()));
return $instance->getView()[$fieldName];
}
protected function getInstanceFromParams($params) {
$instance = $this->getParam($params, 'form');
if (null == $instance) {
throw new \InvalidArgumentException("Missing 'form' parameter in form arguments");
}
if (! $instance instanceof \Thelia\Form\BaseForm) {
throw new \InvalidArgumentException(sprintf("form parameter in form_field block must be an instance of
\Thelia\Form\BaseForm, instance of %s found", get_class($instance)));
}
return $instance;
}
protected function createInstance($name)
{
if (!isset($this->formDefinition[$name])) {
throw new ElementNotFoundException(sprintf("%s form does not exists", $name));
}
$class = new \ReflectionClass($this->formDefinition[$name]);
return $class->newInstance(
$this->request,
"form"
);
}
/**
* @return an array of SmartyPluginDescriptor
*/
public function getPluginDescriptors()
{
return array(
new SmartyPluginDescriptor("block", "form", $this, "generateForm"),
new SmartyPluginDescriptor("block", "form_field", $this, "renderFormField"),
new SmartyPluginDescriptor("function", "form_hidden_fields", $this, "renderHiddenFormField"),
new SmartyPluginDescriptor("function", "form_enctype", $this, "formEnctype"),
new SmartyPluginDescriptor("block", "form_error", $this, "formError")
);
}
}

View File

@@ -0,0 +1,56 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Smarty\Plugins;
use Thelia\Core\Template\Smarty\SmartyPluginDescriptor;
use Thelia\Core\Template\Smarty\AbstractSmartyPlugin;
class Module extends AbstractSmartyPlugin
{
/**
* Process theliaModule template inclusion function
*
* @param unknown $params
* @param unknown $smarty
* @return string
*/
public function theliaModule($params, &$smarty)
{
// TODO
return "";
}
/**
* Define the various smarty plugins hendled by this class
*
* @return an array of smarty plugin descriptors
*/
public function getPluginDescriptors()
{
return array(
new SmartyPluginDescriptor('function', 'module_include', $this, 'theliaModule'),
);
}
}

View File

@@ -0,0 +1,90 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Smarty\Plugins;
use Thelia\Core\Template\Smarty\SmartyPluginDescriptor;
use Thelia\Core\Template\Smarty\AbstractSmartyPlugin;
use Thelia\Core\Template\Smarty\Assets\SmartyAssetsManager;
use Thelia\Core\Security\SecurityContext;
use Thelia\Core\Security\Exception\AuthenticationException;
class Security extends AbstractSmartyPlugin
{
private $securityContext;
public function __construct(SecurityContext $securityContext)
{
$this->securityContext = $securityContext;
}
/**
* Process security check function
*
* @param array $params
* @param unknown $smarty
* @return string no text is returned.
*/
public function checkAuthFunction($params, &$smarty)
{
// Context: 'front' or 'admin'
$context = $this->getNormalizedParam($params, 'context');
$this->securityContext->setContext($context);
$roles = $this->_explode($this->getParam($params, 'roles'));
$permissions = $this->_explode($this->getParam($params, 'permissions'));
if (! $this->securityContext->isGranted($roles, $permissions)) {
$ex = new AuthenticationException(
sprintf("User not granted for roles '%s', permissions '%s' in context '%s'.",
implode(',', $roles), implode(',', $permissions), $context
)
);
$loginTpl = $this->getParam($params, 'login_tpl');
if (null != $loginTpl) {
$ex->setLoginTemplate($loginTpl);
}
throw $ex;
}
return '';
}
/**
* Define the various smarty plugins handled by this class
*
* @return an array of smarty plugin descriptors
*/
public function getPluginDescriptors()
{
return array(
new SmartyPluginDescriptor('function', 'check_auth', $this, 'checkAuthFunction')
);
}
}

View File

@@ -0,0 +1,378 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Smarty\Plugins;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Smarty\AbstractSmartyPlugin;
use Thelia\Core\Template\Smarty\SmartyPluginDescriptor;
use Thelia\Core\Template\Element\Exception\ElementNotFoundException;
use Thelia\Core\Template\Element\Exception\InvalidElementException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Thelia\Core\Security\SecurityContext;
class TheliaLoop extends AbstractSmartyPlugin
{
protected static $pagination = null;
protected $loopDefinition = array();
protected $request;
protected $dispatcher;
protected $securityContext;
protected $loopstack = array();
protected $varstack = array();
public function __construct(Request $request, EventDispatcherInterface $dispatcher, SecurityContext $securityContext)
{
$this->request = $request;
$this->dispatcher = $dispatcher;
$this->securityContext = $securityContext;
}
/**
* @param $loopId
*
* @return \PropelModelPager
*/
public static function getPagination($loopId)
{
if(!empty(self::$pagination[$loopId])) {
return self::$pagination[$loopId];
} else {
return null;
}
}
/**
* Process the count function: executes a loop and return the number of items found
*/
public function theliaCount($params, $template)
{
$type = $this->getParam($params, 'type');
if (null == $type)
throw new \InvalidArgumentException("Missing 'type' parameter in count arguments");
$loop = $this->createLoopInstance($params);
$dummy = null;
$loopResults = $loop->exec($dummy);
return $loopResults->valid() ? $loopResults->getCount() : 0;
}
/**
* Process {loop name="loop name" type="loop type" ... } ... {/loop} block
*
* @param unknown $params
* @param unknown $content
* @param unknown $template
* @param unknown $repeat
* @throws \InvalidArgumentException
* @return string
*/
public function theliaLoop($params, $content, $template, &$repeat)
{
$name = $this->getParam($params, 'name');
if (null == $name)
throw new \InvalidArgumentException("Missing 'name' parameter in loop arguments");
$type = $this->getParam($params, 'type');
if (null == $type)
throw new \InvalidArgumentException("Missing 'type' parameter in loop arguments");
if ($content === null) {
// Check if a loop with the same name exists in the current scope, and abort if it's the case.
if (array_key_exists($name, $this->varstack)) {
throw new \InvalidArgumentException("A loop named '$name' already exists in the current scope.");
}
$loop = $this->createLoopInstance($params);
self::$pagination[$name] = null;
$loopResults = $loop->exec(self::$pagination[$name]);
$this->loopstack[$name] = $loopResults;
// Pas de résultat ? la boucle est terminée, ne pas évaluer le contenu.
if ($loopResults->isEmpty()) $repeat = false;
} else {
$loopResults = $this->loopstack[$name];
$loopResults->next();
}
if ($loopResults->valid()) {
$loopResultRow = $loopResults->current();
// On first iteration, save variables that may be overwritten by this loop
if (! isset($this->varstack[$name])) {
$saved_vars = array();
$varlist = $loopResultRow->getVars();
$varlist[] = 'LOOP_COUNT';
$varlist[] = 'LOOP_TOTAL';
foreach($varlist as $var) {
$saved_vars[$var] = $template->getTemplateVars($var);
}
$this->varstack[$name] = $saved_vars;
}
foreach($loopResultRow->getVarVal() as $var => $val) {
$template->assign($var, $val);
}
$repeat = true;
}
// Assign meta information
$template->assign('LOOP_COUNT', 1 + $loopResults->key());
$template->assign('LOOP_TOTAL', $loopResults->getCount());
// Loop is terminated. Cleanup.
if (! $repeat) {
// Restore previous variables values before terminating
if (isset($this->varstack[$name])) {
foreach($this->varstack[$name] as $var => $value) {
$template->assign($var, $value);
}
unset($this->varstack[$name]);
}
}
if ($content !== null) {
if ($loopResults->isEmpty()) {
$content = "";
}
return $content;
}
}
/**
* Process {elseloop rel="loopname"} ... {/elseloop} block
*
* @param unknown $params
* @param unknown $content
* @param unknown $template
* @param unknown $repeat
* @return Ambigous <string, unknown>
*/
public function theliaElseloop($params, $content, $template, &$repeat)
{
// When encoutering close tag, check if loop has results.
if ($repeat === false) {
return $this->checkEmptyLoop($params, $template) ? $content : '';
}
}
/**
* Process {ifloop rel="loopname"} ... {/ifloop} block
*
* @param unknown $params
* @param unknown $content
* @param unknown $template
* @param unknown $repeat
* @return Ambigous <string, unknown>
*/
public function theliaIfLoop($params, $content, $template, &$repeat)
{
// When encountering close tag, check if loop has results.
if ($repeat === false) {
return $this->checkEmptyLoop($params, $template) ? '' : $content;
}
}
/**
* Process {pageloop rel="loopname"} ... {/pageloop} block
*
* @param $params
* @param $content
* @param $template
* @param $repeat
*
* @return string
* @throws \InvalidArgumentException
*/
public function theliaPageLoop($params, $content, $template, &$repeat)
{
$loopName = $this->getParam($params, 'rel');
if (null == $loopName)
throw new \InvalidArgumentException("Missing 'rel' parameter in page loop");
// Find loop results in the current template vars
/* $loopResults = $template->getTemplateVars($loopName);
if (empty($loopResults)) {
throw new \InvalidArgumentException("Loop $loopName is not defined.");
}*/
// Find pagination
$pagination = self::getPagination($loopName);
if ($pagination === null) {
throw new \InvalidArgumentException("Loop $loopName is not defined");
}
if($pagination->getNbResults() == 0) {
return '';
}
if ($content === null) {
$page = 1;
} else {
$page = $template->getTemplateVars('PAGE');
$page++;
}
if ($page <= $pagination->getLastPage()) {
$template->assign('PAGE', $page);
$template->assign('CURRENT', $pagination->getPage());
$template->assign('LAST', $pagination->getLastPage());
$repeat = true;
}
if ($content !== null) {
return $content;
}
}
/**
* Check if a loop has returned results. The loop shoud have been executed before, or an
* InvalidArgumentException is thrown
*
* @param unknown $params
* @param unknown $template
* @throws \InvalidArgumentException
*/
protected function checkEmptyLoop($params, $template)
{
$loopName = $this->getParam($params, 'rel');
if (null == $loopName)
throw new \InvalidArgumentException("Missing 'rel' parameter in ifloop/elseloop arguments");
if (! isset($this->loopstack[$loopName])) {
throw new \InvalidArgumentException("Loop $loopName is not defined.");
}
return $this->loopstack[$loopName]->isEmpty();
}
/**
*
* find the loop class with his name and construct an instance of this class
*
* @param string $name
* @return \Thelia\Core\Template\Element\BaseLoop
* @throws InvalidElementException
* @throws ElementNotFoundException
*/
protected function createLoopInstance($smartyParams)
{
$type = strtolower($smartyParams['type']);
if (! isset($this->loopDefinition[$type])) {
throw new ElementNotFoundException(sprintf("%s loop does not exists", $type));
}
$class = new \ReflectionClass($this->loopDefinition[$type]);
if ($class->isSubclassOf("Thelia\Core\Template\Element\BaseLoop") === false) {
throw new InvalidElementException(sprintf("%s Loop class have to extends Thelia\Core\Template\Element\BaseLoop",
$type));
}
$loop = $class->newInstance(
$this->request,
$this->dispatcher,
$this->securityContext
);
$loop->initializeArgs($smartyParams);
return $loop;
}
/**
*
* Injects an associative array containing information for loop execution
*
* key is loop name
* value is the class implementing/extending base loop classes
*
* ex :
*
* $loop = array(
* "product" => "Thelia\Loop\Product",
* "category" => "Thelia\Loop\Category",
* "myLoop" => "My\Own\Loop"
* );
*
* @param array $loopDefinition
* @throws \InvalidArgumentException if loop name already exists
*/
public function setLoopList(array $loopDefinition)
{
foreach ($loopDefinition as $name => $className) {
if (array_key_exists($name, $this->loopDefinition)) {
throw new \InvalidArgumentException(sprintf("%s loop name already exists for %s class name", $name, $className));
}
$this->loopDefinition[$name] = $className;
}
}
/**
* Defines the various smarty plugins hendled by this class
*
* @return an array of smarty plugin descriptors
*/
public function getPluginDescriptors()
{
return array(
new SmartyPluginDescriptor('function', 'count' , $this, 'theliaCount'),
new SmartyPluginDescriptor('block' , 'loop' , $this, 'theliaLoop'),
new SmartyPluginDescriptor('block' , 'elseloop' , $this, 'theliaElseloop'),
new SmartyPluginDescriptor('block' , 'ifloop' , $this, 'theliaIfLoop'),
new SmartyPluginDescriptor('block' , 'pageloop' , $this, 'theliaPageLoop'),
);
}
}

View File

@@ -0,0 +1,55 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Smarty\Plugins;
use Thelia\Core\Template\Smarty\SmartyPluginDescriptor;
use Thelia\Core\Template\Smarty\AbstractSmartyPlugin;
/**
* Class TheliaSyntax
* @package Thelia\Core\Template\Smarty\Plugins
*
* @author Etienne Roudeix <eroudeix@openstudio.fr>
*/
class TheliaSyntax extends AbstractSmartyPlugin
{
public function dieseCancel($value, $diese)
{
if($value === null) {
return $diese;
}
return $value;
}
/**
* @return SmartyPluginDescriptor[]
*/
public function getPluginDescriptors()
{
return array(
new SmartyPluginDescriptor("modifier", "dieseCanceller", $this, "dieseCancel")
);
}
}

View File

@@ -0,0 +1,70 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Smarty\Plugins;
use Thelia\Core\Template\Smarty\SmartyPluginDescriptor;
use Thelia\Core\Template\Smarty\AbstractSmartyPlugin;
use Symfony\Component\Translation\TranslatorInterface;
class Translation extends AbstractSmartyPlugin
{
protected $translator;
public function __construct(TranslatorInterface $translator) {
$this->translator = $translator;
}
/**
* Process translate function
*
* @param unknown $params
* @param unknown $smarty
* @return string
*/
public function translate($params, &$smarty)
{
// All parameters other than 'l' are supposed to be variables. Build an array of var => value pairs
// and pass it to the translator
$vars = array();
foreach($params as $name => $value) {
if ($name != 'l') $vars["%$name"] = $value;
}
return $this->translator->trans($this->getParam($params, 'l'), $vars);
}
/**
* Define the various smarty plugins hendled by this class
*
* @return an array of smarty plugin descriptors
*/
public function getPluginDescriptors()
{
return array(
new SmartyPluginDescriptor('function', 'intl', $this, 'translate'),
);
}
}

View File

@@ -0,0 +1,122 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Smarty\Plugins;
use Thelia\Core\Template\Smarty\SmartyPluginDescriptor;
use Thelia\Core\Template\Smarty\AbstractSmartyPlugin;
use Thelia\Tools\URL;
use Thelia\Core\HttpFoundation\Request;
class UrlGenerator extends AbstractSmartyPlugin
{
protected $request;
public function __construct(Request $request)
{
$this->request = $request;
}
/**
* Process url generator function
*
* @param array $params
* @param unknown $smarty
* @return string no text is returned.
*/
public function generateUrlFunction($params, &$smarty)
{
// the path to process
$path = $this->getParam($params, 'path');
return URL::absoluteUrl($path, $this->getArgsFromParam($params));
}
/**
* Process view url generator function
*
* @param array $params
* @param unknown $smarty
* @return string no text is returned.
*/
public function generateFrontViewUrlFunction($params, &$smarty)
{
return $this->generateViewUrlFunction($params, false);
}
/**
* Process administration view url generator function
*
* @param array $params
* @param unknown $smarty
* @return string no text is returned.
*/
public function generateAdminViewUrlFunction($params, &$smarty)
{
return $this->generateViewUrlFunction($params, true);
}
protected function generateViewUrlFunction($params, $forAdmin)
{
// the view name (without .html)
$view = $this->getParam($params,'view');
// the related action (optionale)
$action = $this->getParam($params, 'action');
$args = $this->getArgsFromParam($params);
if (! empty($action)) $args['action'] = $action;
return $forAdmin ? URL::adminViewUrl($view, $args) : URL::viewUrl($view, $args);
}
/**
* Get URL parameters array from a comma separated list or arguments in the
* parameters.
*
* @param array $params Smarty function params
* @return array the parameters array (either emply, of valued)
*/
private function getArgsFromParam($params) {
$args = $this->getParam($params, array('arguments', 'args'));
return $args !== null ? explode($args, ',') : array();
}
/**
* Define the various smarty plugins handled by this class
*
* @return an array of smarty plugin descriptors
*/
public function getPluginDescriptors()
{
return array(
new SmartyPluginDescriptor('function', 'url', $this, 'generateUrlFunction'),
new SmartyPluginDescriptor('function', 'viewurl', $this, 'generateFrontViewUrlFunction'),
new SmartyPluginDescriptor('function', 'admin_viewurl', $this, 'generateAdminViewUrlFunction')
);
}
}

View File

@@ -0,0 +1,230 @@
<?php
namespace Thelia\Core\Template\Smarty;
use \Symfony\Component\HttpFoundation\Request;
use \Symfony\Component\EventDispatcher\EventDispatcherInterface;
use \Smarty;
use Symfony\Component\HttpFoundation\Response;
use Thelia\Core\Template\ParserInterface;
use Thelia\Core\Template\Smarty\AbstractSmartyPlugin;
use Thelia\Core\Template\Exception\ResourceNotFoundException;
use Thelia\Core\Template\ParserContext;
use Thelia\Model\ConfigQuery;
/**
*
* @author Franck Allimant <franck@cqfdev.fr>
* @author Etienne Roudeix <eroudeix@openstudio.fr>
*/
class SmartyParser extends Smarty implements ParserInterface
{
public $plugins = array();
protected $request;
protected $dispatcher;
protected $parserContext;
protected $template = "";
protected $status = 200;
/**
* @param Request $request
* @param EventDispatcherInterface $dispatcher
* @param bool $template
* @param string $env
* @param bool $debug
*/
public function __construct(
Request $request, EventDispatcherInterface $dispatcher, ParserContext $parserContext,
$template = false, $env = "prod", $debug = false)
{
parent::__construct();
$this->request = $request;
$this->dispatcher = $dispatcher;
$this->parserContext = $parserContext;
// Configure basic Smarty parameters
$compile_dir = THELIA_ROOT . 'cache/'. $env .'/smarty/compile';
if (! is_dir($compile_dir)) @mkdir($compile_dir, 0777, true);
$cache_dir = THELIA_ROOT . 'cache/'. $env .'/smarty/cache';
if (! is_dir($cache_dir)) @mkdir($cache_dir, 0777, true);
$this->setCompileDir($compile_dir);
$this->setCacheDir($cache_dir);
$this->setTemplate($template ?: ConfigQuery::read('active-template', 'default'));
$this->debugging = $debug;
// Prevent smarty ErrorException: Notice: Undefined index bla bla bla...
$this->error_reporting = E_ALL ^ E_NOTICE;
// Si on n'est pas en mode debug, activer le cache, avec une lifetime de 15mn, et en vérifiant que les templates sources n'ont pas été modifiés.
if($debug === false) {
$this->caching = Smarty::CACHING_LIFETIME_CURRENT;
$this->cache_lifetime = 300;
$this->compile_check = true;
} else {
$this->caching = Smarty::CACHING_OFF;
$this->force_compile = true;
}
// The default HTTP status
$this->status = 200;
$this->registerFilter('pre', array($this, "preThelia"));
$this->registerFilter('output', array($this, "removeBlankLines"));
}
public function preThelia($tpl_source, \Smarty_Internal_Template $template)
{
$new_source = preg_replace('`{#([a-zA-Z][a-zA-Z0-9\-_]*)(.*)}`', '{\$$1$2}', $tpl_source);
$new_source = preg_replace('`#([a-zA-Z][a-zA-Z0-9\-_]*)`', '{\$$1|dieseCanceller:\'#$1\'}', $new_source);
return $new_source;
}
public function removeBlankLines($tpl_source, \Smarty_Internal_Template $template)
{
return preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $tpl_source);
}
public function setTemplate($template_path_from_template_base)
{
$this->template = $template_path_from_template_base;
$this->setTemplateDir(THELIA_TEMPLATE_DIR.$this->template);
}
public function getTemplate()
{
return $this->template;
}
/**
* Return a rendered template file
*
* @param string $realTemplateName the template name (from the template directory)
* @param array $parameters an associative array of names / value pairs
* @return string the rendered template text
*/
public function render($realTemplateName, array $parameters = array())
{
// Assign the parserContext variables
foreach($this->parserContext as $var => $value) {
$this->assign($var, $value);
}
$this->assign($parameters);
return $this->fetch($realTemplateName);
}
/**
*
* This method must return a Symfony\Component\HttpFoudation\Response instance or the content of the response
*
*/
public function getContent()
{
try {
$templateFile = $this->getTemplateFilePath();
}
catch(\RuntimeException $e) {
return new Response($e->getMessage(), "404");
}
return $this->render($templateFile);
}
/**
*
* set $content with the body of the response or the Response object directly
*
* @param string|Symfony\Component\HttpFoundation\Response $content
*/
public function setContent($content)
{
$this->content = $content;
}
/**
*
* @return type the status of the response
*/
public function getStatus()
{
return $this->status;
}
/**
*
* status HTTP of the response
*
* @param int $status
*/
public function setStatus($status)
{
$this->status = $status;
}
public function addPlugins(AbstractSmartyPlugin $plugin)
{
$this->plugins[] = $plugin;
}
public function registerPlugins()
{
foreach ($this->plugins as $register_plugin) {
$plugins = $register_plugin->getPluginDescriptors();
if (!is_array($plugins)) {
$plugins = array($plugins);
}
foreach ($plugins as $plugin) {
$this->registerPlugin(
$plugin->getType(),
$plugin->getName(),
array(
$plugin->getClass(),
$plugin->getMethod()
)
);
}
}
}
protected function getTemplateFilePath()
{
$file = $this->request->attributes->get('_view');
$fileName = THELIA_TEMPLATE_DIR . rtrim($this->template, "/") . "/" . $file;
$pathFileName = realpath(dirname(THELIA_TEMPLATE_DIR . rtrim($this->template, "/") . "/" . $file));
$templateDir = realpath(THELIA_TEMPLATE_DIR . rtrim($this->template, "/") . "/");
if (strpos($pathFileName, $templateDir) !== 0) {
throw new ResourceNotFoundException(sprintf("%s view does not exists", $file));
}
if (!file_exists($fileName)) {
$fileName .= ".html";
if(!file_exists($fileName)) {
throw new ResourceNotFoundException(sprintf("%s file not found in %s template", $file, $this->template));
}
}
return $fileName;
}
}

View File

@@ -0,0 +1,102 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core\Template\Smarty;
/**
* Class allowing to describe a smarty plugin
*
* Class SmartyPluginDescriptor
* @package Thelia\Core\Template\Smarty
*/
class SmartyPluginDescriptor
{
/**
* @var string Smarty plugin type (block, function, etc.)
*/
protected $type;
/**
* @var string Smarty plugin name. This name will be used in Smarty templates.
*/
protected $name;
/**
* @var AbstractSmartyPlugin plugin implmentation class
*/
protected $class;
/**
* @var string plugin implmentation method in $class
*/
protected $method;
public function __construct($type, $name, $class, $method)
{
$this->type = $type;
$this->name = $name;
$this->class = $class;
$this->method = $method;
}
public function setType($type)
{
$this->type = $type;
}
public function getType()
{
return $this->type;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function setClass($class)
{
$this->class = $class;
}
public function getClass()
{
return $this->class;
}
public function setMethod($method)
{
$this->method = $method;
}
public function getMethod()
{
return $this->method;
}
}

View File

@@ -0,0 +1,244 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core;
/**
* Root class of Thelia
*
* It extends Symfony\Component\HttpKernel\Kernel for changing some fonctionnality
*
*
* @author Manuel Raynaud <mraynaud@openstudio.fr>
*/
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\Yaml\Yaml;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Thelia\Core\Bundle;
use Thelia\Log\Tlog;
use Thelia\Config\DatabaseConfiguration;
use Thelia\Config\DefinePropel;
use Thelia\Core\TheliaContainerBuilder;
use Thelia\Core\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\Config\FileLocator;
use Propel\Runtime\Propel;
use Propel\Runtime\Connection\ConnectionManagerSingle;
class Thelia extends Kernel
{
const THELIA_VERSION = 0.1;
protected $tpexConfig;
public function init()
{
parent::init();
if ($this->debug) {
ini_set('display_errors', 1);
}
$this->initPropel();
}
protected function initPropel()
{
if (file_exists(THELIA_ROOT . '/local/config/database.yml') === false) {
return ;
}
$definePropel = new DefinePropel(new DatabaseConfiguration(),
Yaml::parse(THELIA_ROOT . '/local/config/database.yml'));
$propelConfig = $definePropel->getConfig();
$serviceContainer = Propel::getServiceContainer();
$serviceContainer->setAdapterClass('thelia', 'mysql');
$manager = new ConnectionManagerSingle();
$manager->setConfiguration($definePropel->getConfig());
$serviceContainer->setConnectionManager('thelia', $manager);
if ($this->isDebug()) {
$serviceContainer->setLogger('defaultLogger', Tlog::getInstance());
$con = Propel::getConnection(\Thelia\Model\Map\ProductTableMap::DATABASE_NAME);
$con->useDebug(true);
}
}
/**
*
* Load some configuration
* Initialize all plugins
*
*/
protected function loadConfiguration(ContainerBuilder $container)
{
$loader = new XmlFileLoader($container, new FileLocator(THELIA_ROOT . "/core/lib/Thelia/Config/Resources"));
$loader->load("config.xml");
$loader->load("routing.xml");
$loader->load("action.xml");
if (defined("THELIA_INSTALL_MODE") === false) {
$modules = \Thelia\Model\ModuleQuery::getActivated();
foreach ($modules as $module) {
try {
$loader = new XmlFileLoader($container, new FileLocator(THELIA_MODULE_DIR . "/" . ucfirst($module->getCode()) . "/Config"));
$loader->load("config.xml");
} catch (\InvalidArgumentException $e) {
// FIXME: process module configuration exception
}
}
}
}
/**
*
* initialize session in Request object
*
* All param must be change in Config table
*
* @param \Symfony\Component\HttpFoundation\Request $request
*/
/**
* Gets a new ContainerBuilder instance used to build the service container.
*
* @return ContainerBuilder
*/
protected function getContainerBuilder()
{
return new TheliaContainerBuilder(new ParameterBag($this->getKernelParameters()));
}
/**
* Builds the service container.
*
* @return ContainerBuilder The compiled service container
*
* @throws \RuntimeException
*/
protected function buildContainer()
{
$container = parent::buildContainer();
$this->loadConfiguration($container);
$container->customCompile();
return $container;
}
/**
* Gets the cache directory.
*
* @return string The cache directory
*
* @api
*/
public function getCacheDir()
{
if (defined('THELIA_ROOT')) {
return THELIA_ROOT.'cache/'.$this->environment;
} else {
return parent::getCacheDir();
}
}
/**
* Gets the log directory.
*
* @return string The log directory
*
* @api
*/
public function getLogDir()
{
if (defined('THELIA_ROOT')) {
return THELIA_ROOT.'log/';
} else {
return parent::getLogDir();
}
}
/**
* Returns the kernel parameters.
*
* @return array An array of kernel parameters
*/
protected function getKernelParameters()
{
$parameters = parent::getKernelParameters();
$parameters["thelia.root_dir"] = THELIA_ROOT;
$parameters["thelia.core_dir"] = THELIA_ROOT . "core/lib/Thelia";
return $parameters;
}
/**
* return available bundle
*
* Part of Symfony\Component\HttpKernel\KernelInterface
*
* @return array An array of bundle instances.
*
*/
public function registerBundles()
{
$bundles = array(
/* TheliaBundle contain all the dependency injection description */
new Bundle\TheliaBundle(),
);
/**
* OTHER CORE BUNDLE CAN BE DECLARE HERE AND INITIALIZE WITH SPECIFIC CONFIGURATION
*
* HOW TO DECLARE OTHER BUNDLE ? ETC
*/
return $bundles;
}
/**
* Loads the container configuration
*
* part of Symfony\Component\HttpKernel\KernelInterface
*
* @param LoaderInterface $loader A LoaderInterface instance
*
* @api
*/
public function registerContainerConfiguration(LoaderInterface $loader)
{
//Nothing is load here but it's possible to load container configuration here.
//exemple in sf2 : $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
}
}

View File

@@ -0,0 +1,39 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class TheliaContainerBuilder extends ContainerBuilder
{
public function compile(){}
public function customCompile()
{
parent::compile();
}
}

View File

@@ -0,0 +1,208 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Core;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Session;
use Thelia\Model;
/**
*
* @author Manuel Raynaud <mraynaud@openstudio.fr>
*/
class TheliaHttpKernel extends HttpKernel
{
protected $container;
public function __construct(EventDispatcherInterface $dispatcher, ContainerInterface $container, ControllerResolverInterface $controllerResolver)
{
parent::__construct($dispatcher, $controllerResolver);
$this->container = $container;
}
public function getContainer()
{
return $this->container;
}
/**
* Handles a Request to convert it to a Response.
*
* When $catch is true, the implementation must catch all exceptions
* and do its best to convert them to a Response instance.
*
* @param Request $request A Request instance
* @param integer $type The type of the request
* (one of HttpKernelInterface::MASTER_REQUEST or HttpKernelInterface::SUB_REQUEST)
* @param Boolean $catch Whether to catch exceptions or not
*
* @return Response A Response instance
*
* @throws \Exception When an Exception occurs during processing
*
* @api
*
*/
public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
{
//$request->headers->set('X-Php-Ob-Level', ob_get_level());
$request = $this->initSession($request);
$this->initParam($request);
$this->container->enterScope('request');
$this->container->set('request', $request, 'request');
try {
$response = parent::handle($request, $type, $catch);
} catch (\Exception $e) {
$this->container->leaveScope('request');
throw $e;
}
$this->container->leaveScope('request');
return $response;
}
/*
* @TODO define here all needed parameters like locale, currency, etc :
*
*
* LOCALE :
* define locale with this order :
* 1) locale define into plugins
* 2) locale paramter in request
* 3) current locale <-> locale
* 4) locale in session
* 5) default locale
*
* $lang déjà défini par un plugin
* 2) paramètre 'lang' dans l'URL courante
* 3) Correspondance URL courante <-> langue
* 4) Langue précédemment stockée en session
* 5) Defaut
* put this locale into session with keyname "locale"
*
*
*
*
*
*/
protected function initParam(Request $request)
{
$lang = $this->detectLang($request);
if ($lang) {
$request->getSession()->set("lang", $lang->getCode());
$request->getSession()->set("locale", $lang->getLocale());
}
}
/**
* @param Request $request
* @return null|\Thelia\Model\Lang
*/
protected function detectLang(Request $request)
{
$lang = null;
//first priority => lang parameter present in request (get or post)
if($request->query->has("lang")) {
$lang = Model\LangQuery::create()->findOneByCode($request->query->get("lang"));
if(is_null($lang)) {
return;
}
//if each lang had is own domain, we redirect the user to the good one.
if (Model\ConfigQuery::read("one_domain_foreach_lang", false) == 1) {
//if lang domain is different from actuel domain, redirect to the good one
if (rtrim($lang->getUrl(), "/") != $request->getSchemeAndHttpHost()) {
// TODO : search if http status 302 is the good one.
$redirect = new RedirectResponse($lang->getUrl(), 302);
$redirect->send();
exit;
} else {
//the user is actually on the good domain, nothing to change
return null;
}
} else {
//one domain for all languages, the lang is set into session
return $lang;
}
}
//check if lang is not defined. If not we have to search the good one.
if (null === $request->getSession()->get("lang")) {
if (Model\ConfigQuery::read("one_domain_foreach_lang", false) == 1) {
//find lang with domain
return Model\LangQuery::create()->filterByUrl($request->getSchemeAndHttpHost(), ModelCriteria::LIKE)->findOne();
}
//find default lang
return Model\LangQuery::create()->findOneByByDefault(1);
}
}
protected function initSession(Request $request)
{
$storage = new Session\Storage\NativeSessionStorage();
if (Model\ConfigQuery::read("session_config.default")) {
$storage->setSaveHandler(new Session\Storage\Handler\NativeFileSessionHandler(Model\ConfigQuery::read("session_config.save_path", THELIA_ROOT . '/local/session/')));
} else {
$handlerString = Model\ConfigQuery::read("session_config.handlers");
$handler = new $handlerString;
$storage->setSaveHandler($handler);
}
if (Model\ConfigQuery::read("session_config.config", null)) {
$storage->setOptions(json_decode(Model\ConfigQuery::read("session_config.config")));
}
$session = new \Thelia\Core\HttpFoundation\Session\Session($storage);
$session->start();
$request->setSession($session);
return $request;
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace Thelia\Core\Translation;
use Symfony\Component\Translation\Translator as BaseTranslator;
class Translator extends BaseTranslator {
/**
* {@inheritdoc}
*
* @api
*/
public function trans($id, array $parameters = array(), $domain = 'messages', $locale = null)
{
if (null === $locale) {
$locale = $this->getLocale();
}
if (!isset($this->catalogues[$locale])) {
$this->loadCatalogue($locale);
}
if ($this->catalogues[$locale]->has((string) $id, $domain))
return parent::trans($id, $parameters, $domain = 'messages', $locale = null);
else
return strtr($id, $parameters);
}
}