Merge branch 'modules'

This commit is contained in:
Manuel Raynaud
2013-12-20 14:57:14 +01:00
360 changed files with 4433 additions and 3914 deletions

View File

@@ -22,7 +22,7 @@ Requirements
* gd * gd
* curl * curl
* safe_mode off * safe_mode off
* memory_limit at least 128M, preferably 256. * memory_limit at least 150M, preferably 256.
* post_max_size 20M * post_max_size 20M
* upload_max_filesize 2M * upload_max_filesize 2M
* apache 2 * apache 2
@@ -44,8 +44,10 @@ Installation
------------ ------------
``` bash ``` bash
$ git clone https://github.com/thelia/thelia.git
$ cd thelia
$ curl -sS https://getcomposer.org/installer | php $ curl -sS https://getcomposer.org/installer | php
$ php composer.phar create-project thelia/thelia path/ dev-master $ php composer.phar install --prefer-dist --optimize-autoloader
``` ```
Finish the installation using cli tools : Finish the installation using cli tools :
@@ -56,14 +58,6 @@ $ php Thelia thelia:install
You just have to follow all instructions. You just have to follow all instructions.
Documentation
-------------
Thelia documentation is available at http://doc.thelia.net
The documentation is also in beta version and some part can be obsolete cause to some refactor.
Contribute Contribute
---------- ----------

View File

@@ -30,6 +30,7 @@ use Thelia\Core\Event\UpdateSeoEvent;
use Thelia\Exception\UrlRewritingException; use Thelia\Exception\UrlRewritingException;
use Thelia\Form\Exception\FormValidationException; use Thelia\Form\Exception\FormValidationException;
use \Thelia\Model\Tools\UrlRewritingTrait;
class BaseAction class BaseAction
{ {
@@ -81,8 +82,8 @@ class BaseAction
/** /**
* Changes SEO Fields for an object. * Changes SEO Fields for an object.
* *
* @param ModelCriteria $query * @param ModelCriteria $query
* @param UpdateSeoEvent $event * @param UpdateSeoEvent $event
* *
* @return mixed * @return mixed
*/ */
@@ -104,7 +105,7 @@ class BaseAction
// Update the rewritten URL, if required // Update the rewritten URL, if required
try { try {
$object->setRewrittenUrl($event->getLocale(), $event->getUrl()); $object->setRewrittenUrl($event->getLocale(), $event->getUrl());
} catch (UrlRewritingException $e) { } catch(UrlRewritingException $e) {
throw new FormValidationException($e->getMessage(), $e->getCode()); throw new FormValidationException($e->getMessage(), $e->getCode());
} }

View File

@@ -28,7 +28,6 @@ use Thelia\Condition\ConditionFactory;
use Thelia\Condition\Implementation\ConditionInterface; use Thelia\Condition\Implementation\ConditionInterface;
use Thelia\Core\Event\Coupon\CouponConsumeEvent; use Thelia\Core\Event\Coupon\CouponConsumeEvent;
use Thelia\Core\Event\Coupon\CouponCreateOrUpdateEvent; use Thelia\Core\Event\Coupon\CouponCreateOrUpdateEvent;
use Thelia\Core\Event\Order\OrderEvent;
use Thelia\Core\Event\TheliaEvents; use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\HttpFoundation\Request; use Thelia\Core\HttpFoundation\Request;
use Thelia\Coupon\CouponFactory; use Thelia\Coupon\CouponFactory;
@@ -37,7 +36,6 @@ use Thelia\Condition\ConditionCollection;
use Thelia\Coupon\Type\CouponInterface; use Thelia\Coupon\Type\CouponInterface;
use Thelia\Model\Coupon as CouponModel; use Thelia\Model\Coupon as CouponModel;
use Thelia\Model\CouponQuery; use Thelia\Model\CouponQuery;
use Thelia\Model\OrderCoupon;
/** /**
* Created by JetBrains PhpStorm. * Created by JetBrains PhpStorm.
@@ -124,20 +122,23 @@ class Coupon extends BaseAction implements EventSubscriberInterface
$request->getSession()->setConsumedCoupons($consumedCoupons); $request->getSession()->setConsumedCoupons($consumedCoupons);
$totalDiscount = $couponManager->getDiscount(); $totalDiscount = $couponManager->getDiscount();
// @todo insert false product in cart with the name of the coupon and the discount as negative price
// Decrement coupon quantity
// @todo move this part in after order event
$couponQuery = CouponQuery::create();
$couponModel = $couponQuery->findOneByCode($coupon->getCode());
$couponManager->decrementQuantity($couponModel);
$request $request
->getSession() ->getSession()
->getCart() ->getCart()
->setDiscount($totalDiscount) ->setDiscount($totalDiscount)
->save(); ->save();
$request
->getSession()
->getOrder()
->setDiscount($totalDiscount)
->save();
} }
} }
$event->setIsValid($isValid); $event->setIsValid($isValid);
$event->setDiscount($totalDiscount); $event->setDiscount($totalDiscount);
} }
@@ -206,68 +207,6 @@ class Coupon extends BaseAction implements EventSubscriberInterface
$event->setCouponModel($coupon); $event->setCouponModel($coupon);
} }
/**
* @param \Thelia\Core\Event\Order\OrderEvent $event
*/
public function testFreePostage(OrderEvent $event)
{
/** @var CouponManager $couponManager */
$couponManager = $this->container->get('thelia.coupon.manager');
if($couponManager->isCouponRemovingPostage()) {
$order = $event->getOrder();
$order->setPostage(0);
$event->setOrder($order);
$event->stopPropagation();
}
}
/**
* @param \Thelia\Core\Event\Order\OrderEvent $event
*/
public function afterOrder(OrderEvent $event)
{
$request = $this->container->get('request');
/** @var CouponManager $couponManager */
$couponManager = $this->container->get('thelia.coupon.manager');
$consumedCoupons = $request->getSession()->getConsumedCoupons();
if (is_array($consumedCoupons)) {
foreach($consumedCoupons as $couponCode) {
$couponQuery = CouponQuery::create();
$couponModel = $couponQuery->findOneByCode($couponCode);
$couponModel->setLocale($request->getSession()->getLang()->getLocale());
/* decrease coupon quantity */
$couponManager->decrementQuantity($couponModel);
/* memorize coupon */
$orderCoupon = new OrderCoupon();
$orderCoupon->setOrder($event->getOrder())
->setCode($couponModel->getCode())
->setType($couponModel->getType())
->setAmount($couponModel->getAmount())
->setTitle($couponModel->getTitle())
->setShortDescription($couponModel->getShortDescription())
->setDescription($couponModel->getDescription())
->setExpirationDate($couponModel->getExpirationDate())
->setIsCumulative($couponModel->getIsCumulative())
->setIsRemovingPostage($couponModel->getIsRemovingPostage())
->setIsAvailableOnSpecialOffers($couponModel->getIsAvailableOnSpecialOffers())
->setSerializedConditions($couponModel->getSerializedConditions())
;
$orderCoupon->save();
}
}
}
/** /**
* Returns an array of event names this subscriber listens to. * Returns an array of event names this subscriber listens to.
* *
@@ -294,9 +233,7 @@ class Coupon extends BaseAction implements EventSubscriberInterface
TheliaEvents::COUPON_CREATE => array("create", 128), TheliaEvents::COUPON_CREATE => array("create", 128),
TheliaEvents::COUPON_UPDATE => array("update", 128), TheliaEvents::COUPON_UPDATE => array("update", 128),
TheliaEvents::COUPON_CONSUME => array("consume", 128), TheliaEvents::COUPON_CONSUME => array("consume", 128),
TheliaEvents::COUPON_CONDITION_UPDATE => array("updateCondition", 128), TheliaEvents::COUPON_CONDITION_UPDATE => array("updateCondition", 128)
TheliaEvents::ORDER_SET_POSTAGE => array("testFreePostage", 256),
TheliaEvents::ORDER_BEFORE_PAYMENT => array("afterOrder", 128),
); );
} }
} }

View File

@@ -56,7 +56,7 @@ class HttpException extends BaseAction implements EventSubscriberInterface
$parser = $this->container->get("thelia.parser"); $parser = $this->container->get("thelia.parser");
// Define the template thant shoud be used // Define the template thant shoud be used
$parser->setTemplate(TemplateHelper::getInstance()->getActiveFrontTemplate()); $parser->setTemplateDefinition(TemplateHelper::getInstance()->getActiveFrontTemplate());
//$event->getRequest()->attributes->set('_view', ConfigQuery::getPageNotFoundView()); //$event->getRequest()->attributes->set('_view', ConfigQuery::getPageNotFoundView());

View File

@@ -35,7 +35,7 @@ class MailingSystem extends BaseAction implements EventSubscriberInterface
*/ */
public function update(MailingSystemEvent $event) public function update(MailingSystemEvent $event)
{ {
if ($event->getEnabled()) { if($event->getEnabled()) {
ConfigQuery::enableSmtp(); ConfigQuery::enableSmtp();
} else { } else {
ConfigQuery::disableSmtp(); ConfigQuery::disableSmtp();

View File

@@ -33,6 +33,7 @@ use Thelia\Core\Event\TheliaEvents;
use Thelia\Model\Map\ModuleTableMap; use Thelia\Model\Map\ModuleTableMap;
use Thelia\Model\ModuleQuery; use Thelia\Model\ModuleQuery;
use Thelia\Module\BaseModule; use Thelia\Module\BaseModule;
use Thelia\Core\Event\UpdatePositionEvent;
/** /**
* Class Module * Class Module
@@ -122,6 +123,16 @@ class Module extends BaseAction implements EventSubscriberInterface
} }
} }
/**
* Changes position, selecting absolute ou relative change.
*
* @param CategoryChangePositionEvent $event
*/
public function updatePosition(UpdatePositionEvent $event)
{
return $this->genericUpdatePosition(ModuleQuery::create(), $event);
}
protected function cacheClear() protected function cacheClear()
{ {
$cacheEvent = new CacheEvent($this->container->getParameter('kernel.cache_dir')); $cacheEvent = new CacheEvent($this->container->getParameter('kernel.cache_dir'));
@@ -153,6 +164,7 @@ class Module extends BaseAction implements EventSubscriberInterface
{ {
return array( return array(
TheliaEvents::MODULE_TOGGLE_ACTIVATION => array('toggleActivation', 128), TheliaEvents::MODULE_TOGGLE_ACTIVATION => array('toggleActivation', 128),
TheliaEvents::MODULE_UPDATE_POSITION => array('updatePosition', 128),
TheliaEvents::MODULE_DELETE => array('delete', 128), TheliaEvents::MODULE_DELETE => array('delete', 128),
TheliaEvents::MODULE_UPDATE => array('update', 128), TheliaEvents::MODULE_UPDATE => array('update', 128),
); );

View File

@@ -30,7 +30,6 @@ use Thelia\Core\Event\Cart\CartEvent;
use Thelia\Core\Event\Order\OrderAddressEvent; use Thelia\Core\Event\Order\OrderAddressEvent;
use Thelia\Core\Event\Order\OrderEvent; use Thelia\Core\Event\Order\OrderEvent;
use Thelia\Core\Event\TheliaEvents; use Thelia\Core\Event\TheliaEvents;
use Thelia\Coupon\CouponManager;
use Thelia\Exception\TheliaProcessException; use Thelia\Exception\TheliaProcessException;
use Thelia\Model\AddressQuery; use Thelia\Model\AddressQuery;
use Thelia\Model\ConfigQuery; use Thelia\Model\ConfigQuery;
@@ -74,17 +73,6 @@ class Order extends BaseAction implements EventSubscriberInterface
$order = $event->getOrder(); $order = $event->getOrder();
$order->setDeliveryModuleId($event->getDeliveryModule()); $order->setDeliveryModuleId($event->getDeliveryModule());
$event->setOrder($order);
}
/**
* @param \Thelia\Core\Event\Order\OrderEvent $event
*/
public function setPostage(OrderEvent $event)
{
$order = $event->getOrder();
$order->setPostage($event->getPostage()); $order->setPostage($event->getPostage());
$event->setOrder($order); $event->setOrder($order);
@@ -190,11 +178,6 @@ class Order extends BaseAction implements EventSubscriberInterface
OrderStatusQuery::create()->findOneByCode(OrderStatus::CODE_NOT_PAID)->getId() OrderStatusQuery::create()->findOneByCode(OrderStatus::CODE_NOT_PAID)->getId()
); );
/* memorize discount */
$placedOrder->setDiscount(
$cart->getDiscount()
);
$placedOrder->save($con); $placedOrder->save($con);
/* fulfill order_products and decrease stock */ /* fulfill order_products and decrease stock */
@@ -279,6 +262,8 @@ class Order extends BaseAction implements EventSubscriberInterface
} }
} }
/* discount @todo */
$con->commit(); $con->commit();
$this->getDispatcher()->dispatch(TheliaEvents::ORDER_BEFORE_PAYMENT, new OrderEvent($placedOrder)); $this->getDispatcher()->dispatch(TheliaEvents::ORDER_BEFORE_PAYMENT, new OrderEvent($placedOrder));
@@ -288,7 +273,7 @@ class Order extends BaseAction implements EventSubscriberInterface
$sessionOrder = new \Thelia\Model\Order(); $sessionOrder = new \Thelia\Model\Order();
$event->setOrder($sessionOrder); $event->setOrder($sessionOrder);
$event->setPlacedOrder($placedOrder); $event->setPlacedOrder($placedOrder);
$this->getSession()->setOrder($placedOrder); $this->getSession()->setOrder($sessionOrder);
/* empty cart */ /* empty cart */
$this->getDispatcher()->dispatch(TheliaEvents::CART_CLEAR, new CartEvent($this->getCart($this->getRequest()))); $this->getDispatcher()->dispatch(TheliaEvents::CART_CLEAR, new CartEvent($this->getCart($this->getRequest())));
@@ -305,7 +290,7 @@ class Order extends BaseAction implements EventSubscriberInterface
{ {
$contact_email = ConfigQuery::read('contact_email'); $contact_email = ConfigQuery::read('contact_email');
if ($contact_email) { if($contact_email) {
$message = MessageQuery::create() $message = MessageQuery::create()
->filterByName('order_confirmation') ->filterByName('order_confirmation')
@@ -427,7 +412,6 @@ class Order extends BaseAction implements EventSubscriberInterface
return array( return array(
TheliaEvents::ORDER_SET_DELIVERY_ADDRESS => array("setDeliveryAddress", 128), TheliaEvents::ORDER_SET_DELIVERY_ADDRESS => array("setDeliveryAddress", 128),
TheliaEvents::ORDER_SET_DELIVERY_MODULE => array("setDeliveryModule", 128), TheliaEvents::ORDER_SET_DELIVERY_MODULE => array("setDeliveryModule", 128),
TheliaEvents::ORDER_SET_POSTAGE => array("setPostage", 128),
TheliaEvents::ORDER_SET_INVOICE_ADDRESS => array("setInvoiceAddress", 128), TheliaEvents::ORDER_SET_INVOICE_ADDRESS => array("setInvoiceAddress", 128),
TheliaEvents::ORDER_SET_PAYMENT_MODULE => array("setPaymentModule", 128), TheliaEvents::ORDER_SET_PAYMENT_MODULE => array("setPaymentModule", 128),
TheliaEvents::ORDER_PAY => array("create", 128), TheliaEvents::ORDER_PAY => array("create", 128),

View File

@@ -131,6 +131,7 @@ class Product extends BaseAction implements EventSubscriberInterface
return $this->genericUpdateSeo(ProductQuery::create(), $event); return $this->genericUpdateSeo(ProductQuery::create(), $event);
} }
/** /**
* Delete a product entry * Delete a product entry
* *

View File

@@ -209,7 +209,8 @@ class ProductSaleElement extends BaseAction implements EventSubscriberInterface
if ($product->countSaleElements() <= 0) { if ($product->countSaleElements() <= 0) {
// If we just deleted the last PSE, create a default one // If we just deleted the last PSE, create a default one
$product->createProductSaleElement($con, 0, 0, 0, $event->getCurrencyId(), true); $product->createProductSaleElement($con, 0, 0, 0, $event->getCurrencyId(), true);
} elseif ($pse->getIsDefault()) { }
elseif ($pse->getIsDefault()) {
// If we deleted the default PSE, make the last created one the default // If we deleted the default PSE, make the last created one the default
$pse = ProductSaleElementsQuery::create() $pse = ProductSaleElementsQuery::create()
@@ -237,8 +238,8 @@ class ProductSaleElement extends BaseAction implements EventSubscriberInterface
* *
* @param ProductCombinationGenerationEvent $event * @param ProductCombinationGenerationEvent $event
*/ */
public function generateCombinations(ProductCombinationGenerationEvent $event) public function generateCombinations(ProductCombinationGenerationEvent $event) {
{
$con = Propel::getWriteConnection(ProductSaleElementsTableMap::DATABASE_NAME); $con = Propel::getWriteConnection(ProductSaleElementsTableMap::DATABASE_NAME);
$con->beginTransaction(); $con->beginTransaction();
@@ -251,7 +252,7 @@ class ProductSaleElement extends BaseAction implements EventSubscriberInterface
$isDefault = true; $isDefault = true;
// Create all combinations // Create all combinations
foreach ($event->getCombinations() as $combinationAttributesAvIds) { foreach($event->getCombinations() as $combinationAttributesAvIds) {
// Create the PSE // Create the PSE
$saleElement = $event->getProduct()->createProductSaleElement( $saleElement = $event->getProduct()->createProductSaleElement(
@@ -275,7 +276,8 @@ class ProductSaleElement extends BaseAction implements EventSubscriberInterface
// Store all the stuff ! // Store all the stuff !
$con->commit(); $con->commit();
} catch (\Exception $ex) { }
catch (\Exception $ex) {
$con->rollback(); $con->rollback();
@@ -286,9 +288,9 @@ class ProductSaleElement extends BaseAction implements EventSubscriberInterface
/** /**
* Create a combination for a given product sale element * Create a combination for a given product sale element
* *
* @param ConnectionInterface $con the Propel connection * @param ConnectionInterface $con the Propel connection
* @param ProductSaleElement $salesElement the product sale element * @param ProductSaleElement $salesElement the product sale element
* @param unknown $combinationAttributes an array oif attributes av IDs * @param unknown $combinationAttributes an array oif attributes av IDs
*/ */
protected function createCombination(ConnectionInterface $con, ProductSaleElements $salesElement, $combinationAttributes) protected function createCombination(ConnectionInterface $con, ProductSaleElements $salesElement, $combinationAttributes)
{ {

View File

@@ -32,6 +32,7 @@ use Thelia\Core\Event\TheliaEvents;
use Thelia\Model\AdminQuery; use Thelia\Model\AdminQuery;
use Thelia\Tools\Password; use Thelia\Tools\Password;
/** /**
* command line for updating admin password * command line for updating admin password
* *
@@ -71,15 +72,18 @@ class AdminUpdatePasswordCommand extends ContainerAwareCommand
{ {
$login = $input->getArgument('login'); $login = $input->getArgument('login');
if (null === $admin = AdminQuery::create()->filterByLogin($login)->findOne()) { if (null === $admin = AdminQuery::create()->filterByLogin($login)->findOne()) {
throw new \RuntimeException(sprintf('Admin with login %s does not exists', $login)); throw new \RuntimeException(sprintf('Admin with login %s does not exists', $login));
} }
$password = $input->getOption('password') ?: Password::generateRandom(); $password = $input->getOption('password') ?: Password::generateRandom();
$event = new AdministratorUpdatePasswordEvent($admin); $event = new AdministratorUpdatePasswordEvent($admin);
$event->setPassword($password); $event->setPassword($password);
$this-> $this->
getContainer() getContainer()
->get('event_dispatcher') ->get('event_dispatcher')
@@ -95,3 +99,4 @@ class AdminUpdatePasswordCommand extends ContainerAwareCommand
} }
} }

View File

@@ -1,14 +1,14 @@
<?php <?php
return array( return array(
'Delivery module' => 'Delivery module', 'Delivery module' => 'Delivery module',
'Quantity' => 'Quantity', 'Quantity' => 'Quantity',
'Product' => 'Product', 'Product' => 'Product',
'Unit. price' => 'Unit. price', 'Unit. price' => 'Unit. price',
'Tax' => 'Tax', 'Tax' => 'Tax',
'Unit taxed price' => 'Unit taxed price', 'Unit taxed price' => 'Unit taxed price',
'Taxed total' => 'Taxed total', 'Taxed total' => 'Taxed total',
'Payment module' => 'Payment module', 'Payment module' => 'Payment module',
'Postage' => 'Postage', 'Postage' => 'Postage',
'Total' => 'Total', 'Total' => 'Total',
); );

View File

@@ -1,36 +1,36 @@
<?php <?php
return array( return array(
'Combination builder' => 'Combination builder', 'Combination builder' => 'Combination builder',
'Title' => 'Title', 'Title' => 'Title',
'City' => 'City', 'City' => 'City',
'Zip code' => 'Zip code', 'Zip code' => 'Zip code',
'Country' => 'Country', 'Country' => 'Country',
'Phone' => 'Phone', 'Phone' => 'Phone',
'Login' => 'Login', 'Login' => 'Login',
'Password' => 'Password', 'Password' => 'Password',
'Profile' => 'Profile', 'Profile' => 'Profile',
'Postage' => 'Postage', 'Postage' => 'Postage',
'Add to all product templates' => 'Add to all product templates', 'Add to all product templates' => 'Add to all product templates',
'Quantity' => 'Quantity', 'Quantity' => 'Quantity',
'Name' => 'Name', 'Name' => 'Name',
'Value' => 'Value', 'Value' => 'Value',
'Subject' => 'Subject', 'Subject' => 'Subject',
'Company' => 'Company', 'Company' => 'Company',
'Description' => 'Description', 'Description' => 'Description',
'Language name' => 'Language name', 'Language name' => 'Language name',
'ISO 639 Code' => 'ISO 639 Code', 'ISO 639 Code' => 'ISO 639 Code',
'If a translation is missing or incomplete :' => 'If a translation is missing or incomplete :', 'If a translation is missing or incomplete :' => 'If a translation is missing or incomplete :',
'Host' => 'Host', 'Host' => 'Host',
'Port' => 'Port', 'Port' => 'Port',
'Encryption' => 'Encryption', 'Encryption' => 'Encryption',
'Username' => 'Username', 'Username' => 'Username',
'Timeout' => 'Timeout', 'Timeout' => 'Timeout',
'Source IP' => 'Source IP', 'Source IP' => 'Source IP',
'Email address' => 'Email address', 'Email address' => 'Email address',
'Firstname' => 'Firstname', 'Firstname' => 'Firstname',
'Lastname' => 'Lastname', 'Lastname' => 'Lastname',
'Additional address' => 'Additional address', 'Additional address' => 'Additional address',
'Reference' => 'Reference', 'Reference' => 'Reference',
'EAN Code' => 'EAN Code', 'EAN Code' => 'EAN Code',
); );

View File

@@ -23,4 +23,4 @@
return array( return array(
); );

View File

@@ -23,4 +23,4 @@
return array( return array(
); );

View File

@@ -28,7 +28,6 @@
<loop class="Thelia\Core\Template\Loop\Order" name="order"/> <loop class="Thelia\Core\Template\Loop\Order" name="order"/>
<loop class="Thelia\Core\Template\Loop\OrderAddress" name="order_address"/> <loop class="Thelia\Core\Template\Loop\OrderAddress" name="order_address"/>
<loop class="Thelia\Core\Template\Loop\OrderProduct" name="order_product"/> <loop class="Thelia\Core\Template\Loop\OrderProduct" name="order_product"/>
<loop class="Thelia\Core\Template\Loop\OrderCoupon" name="order_coupon"/>
<loop class="Thelia\Core\Template\Loop\OrderProductAttributeCombination" name="order_product_attribute_combination"/> <loop class="Thelia\Core\Template\Loop\OrderProductAttributeCombination" name="order_product_attribute_combination"/>
<loop class="Thelia\Core\Template\Loop\OrderStatus" name="order-status"/> <loop class="Thelia\Core\Template\Loop\OrderStatus" name="order-status"/>
<loop class="Thelia\Core\Template\Loop\CategoryPath" name="category-path"/> <loop class="Thelia\Core\Template\Loop\CategoryPath" name="category-path"/>

View File

@@ -980,6 +980,10 @@
<default key="_controller">Thelia\Controller\Admin\ModuleController::deleteAction</default> <default key="_controller">Thelia\Controller\Admin\ModuleController::deleteAction</default>
</route> </route>
<route id="admin.module.delete" path="/admin/module/update-position">
<default key="_controller">Thelia\Controller\Admin\ModuleController::updatePositionAction</default>
</route>
<!-- <!--
Generic module route. Generic module route.
Will be use if module route is not define in module own config file. Will be use if module route is not define in module own config file.

View File

@@ -443,6 +443,7 @@ abstract class AbstractCrudController extends BaseAdminController
$ex $ex
); );
//return $this->renderEditionTemplate(); //return $this->renderEditionTemplate();
} }

View File

@@ -53,7 +53,7 @@ abstract class AbstractSeoCrudController extends AbstractCrudController
* *
* @param string $visibilityToggleEventIdentifier the dispatched visibility toggle TheliaEvent identifier, or null if the object has no visible options. Example: TheliaEvents::MESSAGE_TOGGLE_VISIBILITY * @param string $visibilityToggleEventIdentifier the dispatched visibility toggle TheliaEvent identifier, or null if the object has no visible options. Example: TheliaEvents::MESSAGE_TOGGLE_VISIBILITY
* @param string $changePositionEventIdentifier the dispatched position change TheliaEvent identifier, or null if the object has no position. Example: TheliaEvents::MESSAGE_UPDATE_POSITION * @param string $changePositionEventIdentifier the dispatched position change TheliaEvent identifier, or null if the object has no position. Example: TheliaEvents::MESSAGE_UPDATE_POSITION
* @param string $updateSeoEventIdentifier the dispatched update SEO change TheliaEvent identifier, or null if the object has no SEO. Example: TheliaEvents::MESSAGE_UPDATE_SEO * @param string $updateSeoEventIdentifier the dispatched update SEO change TheliaEvent identifier, or null if the object has no SEO. Example: TheliaEvents::MESSAGE_UPDATE_SEO
*/ */
public function __construct( public function __construct(
$objectName, $objectName,
@@ -134,8 +134,7 @@ abstract class AbstractSeoCrudController extends AbstractCrudController
* *
* @param unknown $object * @param unknown $object
*/ */
protected function hydrateSeoForm($object) protected function hydrateSeoForm($object){
{
// The "SEO" tab form // The "SEO" tab form
$locale = $object->getLocale(); $locale = $object->getLocale();
$data = array( $data = array(
@@ -228,6 +227,8 @@ abstract class AbstractSeoCrudController extends AbstractCrudController
$ex $ex
); );
// At this point, the form has errors, and should be redisplayed. // At this point, the form has errors, and should be redisplayed.
return $this->renderEditionTemplate(); return $this->renderEditionTemplate();
} }

View File

@@ -98,7 +98,7 @@ class AddressController extends AbstractCrudController
/** /**
* Fills in the form data array * Fills in the form data array
* *
* @param unknown $object * @param unknown $object
* @return multitype:NULL * @return multitype:NULL
*/ */
protected function createFormDataArray($object) protected function createFormDataArray($object)
@@ -309,8 +309,7 @@ class AddressController extends AbstractCrudController
$this->redirectToEditionTemplate(); $this->redirectToEditionTemplate();
} }
protected function getCustomerId() protected function getCustomerId() {
{
if (null !== $address = $this->getExistingObject()) if (null !== $address = $this->getExistingObject())
return $address->getCustomerId(); return $address->getCustomerId();
else else

View File

@@ -34,6 +34,7 @@ use Thelia\Form\AttributeModificationForm;
use Thelia\Form\AttributeCreationForm; use Thelia\Form\AttributeCreationForm;
use Thelia\Core\Event\UpdatePositionEvent; use Thelia\Core\Event\UpdatePositionEvent;
use Thelia\Model\AttributeAv; use Thelia\Model\AttributeAv;
use Thelia\Model\AttributeAvQuery;
use Thelia\Core\Event\Attribute\AttributeAvUpdateEvent; use Thelia\Core\Event\Attribute\AttributeAvUpdateEvent;
use Thelia\Core\Event\Attribute\AttributeEvent; use Thelia\Core\Event\Attribute\AttributeEvent;

View File

@@ -201,7 +201,7 @@ class BaseAdminController extends BaseController
$parser = $this->container->get("thelia.parser"); $parser = $this->container->get("thelia.parser");
// Define the template that should be used // Define the template that should be used
$parser->setTemplate($template ?: TemplateHelper::getInstance()->getActiveAdminTemplate()); $parser->setTemplateDefinition($template ?: TemplateHelper::getInstance()->getActiveAdminTemplate());
return $parser; return $parser;
} }
@@ -309,7 +309,6 @@ class BaseAdminController extends BaseController
{ {
// Check if the functionality is activated // Check if the functionality is activated
if(!ConfigQuery::read("one_domain_foreach_lang", false)) if(!ConfigQuery::read("one_domain_foreach_lang", false))
return; return;
// If we don't have a locale value, use the locale value in the session // If we don't have a locale value, use the locale value in the session
@@ -391,8 +390,8 @@ class BaseAdminController extends BaseController
* Render the given template, and returns the result as an Http Response. * Render the given template, and returns the result as an Http Response.
* *
* @param $templateName the complete template name, with extension * @param $templateName the complete template name, with extension
* @param array $args the template arguments * @param array $args the template arguments
* @param int $status http code status * @param int $status http code status
* @return \Thelia\Core\HttpFoundation\Response * @return \Thelia\Core\HttpFoundation\Response
*/ */
protected function render($templateName, $args = array(), $status = 200) protected function render($templateName, $args = array(), $status = 200)

View File

@@ -201,12 +201,15 @@ class CategoryController extends AbstractSeoCrudController
protected function redirectToListTemplateWithId($category_id) protected function redirectToListTemplateWithId($category_id)
{ {
if ($category_id > 0) { if($category_id > 0)
{
$this->redirectToRoute( $this->redirectToRoute(
'admin.categories.default', 'admin.categories.default',
array('category_id' => $category_id) array('category_id' => $category_id)
); );
} else { }
else
{
$this->redirectToRoute( $this->redirectToRoute(
'admin.catalog' 'admin.catalog'
); );

View File

@@ -23,9 +23,11 @@
namespace Thelia\Controller\Admin; namespace Thelia\Controller\Admin;
use Thelia\Core\Security\Resource\AdminResources; use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Core\Security\AccessManager; use Thelia\Core\Security\AccessManager;
use Thelia\Form\ConfigStoreForm; use Thelia\Form\ConfigStoreForm;
use Thelia\Log\Tlog;
use Thelia\Model\ConfigQuery; use Thelia\Model\ConfigQuery;
/** /**
* Class ConfigStoreController * Class ConfigStoreController
@@ -78,7 +80,7 @@ class ConfigStoreController extends BaseAdminController
$data = $form->getData(); $data = $form->getData();
// Update store // Update store
foreach ($data as $name => $value) { foreach($data as $name => $value) {
if(! in_array($name , array('success_url', 'error_message'))) if(! in_array($name , array('success_url', 'error_message')))
ConfigQuery::write($name, $value, false); ConfigQuery::write($name, $value, false);
} }

View File

@@ -23,14 +23,19 @@
namespace Thelia\Controller\Admin; namespace Thelia\Controller\Admin;
use Propel\Runtime\Exception\PropelException;
use Thelia\Core\Security\Resource\AdminResources; use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Core\Event\Customer\CustomerCreateOrUpdateEvent; use Thelia\Core\Event\Customer\CustomerCreateOrUpdateEvent;
use Thelia\Core\Event\Customer\CustomerEvent; use Thelia\Core\Event\Customer\CustomerEvent;
use Thelia\Core\Event\TheliaEvents; use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Security\AccessManager;
use Thelia\Form\CustomerCreateForm; use Thelia\Form\CustomerCreateForm;
use Thelia\Form\CustomerUpdateForm; use Thelia\Form\CustomerUpdateForm;
use Thelia\Form\Exception\FormValidationException;
use Thelia\Model\CustomerQuery; use Thelia\Model\CustomerQuery;
use Thelia\Core\Translation\Translator;
use Thelia\Tools\Password; use Thelia\Tools\Password;
use Thelia\Model\AddressQuery;
use Thelia\Model\Address; use Thelia\Model\Address;
/** /**
@@ -203,4 +208,4 @@ class CustomerController extends AbstractCrudController
{ {
$this->redirectToRoute("admin.customer.update.view", $this->getEditionArguments()); $this->redirectToRoute("admin.customer.update.view", $this->getEditionArguments());
} }
} }

View File

@@ -34,6 +34,7 @@ use Thelia\Form\FeatureModificationForm;
use Thelia\Form\FeatureCreationForm; use Thelia\Form\FeatureCreationForm;
use Thelia\Core\Event\UpdatePositionEvent; use Thelia\Core\Event\UpdatePositionEvent;
use Thelia\Model\FeatureAv; use Thelia\Model\FeatureAv;
use Thelia\Model\FeatureAvQuery;
use Thelia\Core\Event\Feature\FeatureAvUpdateEvent; use Thelia\Core\Event\Feature\FeatureAvUpdateEvent;
use Thelia\Core\Event\Feature\FeatureEvent; use Thelia\Core\Event\Feature\FeatureEvent;

View File

@@ -584,7 +584,7 @@ class FileController extends BaseAdminController
); );
} }
if (null === $message) { if(null === $message) {
$message = $this->getTranslator() $message = $this->getTranslator()
->trans( ->trans(
'Images deleted successfully', 'Images deleted successfully',
@@ -638,7 +638,7 @@ class FileController extends BaseAdminController
) . $e->getMessage(); ) . $e->getMessage();
} }
if (null === $message) { if(null === $message) {
$message = $this->getTranslator() $message = $this->getTranslator()
->trans( ->trans(
'Image position updated', 'Image position updated',
@@ -692,7 +692,7 @@ class FileController extends BaseAdminController
) . $e->getMessage(); ) . $e->getMessage();
} }
if (null === $message) { if(null === $message) {
$message = $this->getTranslator() $message = $this->getTranslator()
->trans( ->trans(
'Document position updated', 'Document position updated',

View File

@@ -42,7 +42,7 @@ class HomeController extends BaseAdminController
public function loadStatsAjaxAction() public function loadStatsAjaxAction()
{ {
if (null !== $response = $this->checkAuth(self::RESOURCE_CODE, array(), AccessManager::VIEW)) return $response; if (null !== $response = $this->checkAuth(self::RESOURCE_CODE, array(), AccessManager::VIEW)) return $response;
$data = new \stdClass(); $data = new \stdClass();
$data->title = "Stats on " . $this->getRequest()->query->get('month', date('m')) . "/" . $this->getRequest()->query->get('year', date('Y')); $data->title = "Stats on " . $this->getRequest()->query->get('month', date('m')) . "/" . $this->getRequest()->query->get('year', date('Y'));
@@ -88,6 +88,7 @@ class HomeController extends BaseAdminController
array(5) array(5)
); );
$data->series = array( $data->series = array(
$saleSeries, $saleSeries,
$newCustomerSeries, $newCustomerSeries,

View File

@@ -31,6 +31,7 @@ use Thelia\Model\MessageQuery;
use Thelia\Form\MessageModificationForm; use Thelia\Form\MessageModificationForm;
use Thelia\Form\MessageCreationForm; use Thelia\Form\MessageCreationForm;
use Symfony\Component\Finder\Finder; use Symfony\Component\Finder\Finder;
use Thelia\Model\ConfigQuery;
use Thelia\Core\Template\TemplateHelper; use Thelia\Core\Template\TemplateHelper;
/** /**
@@ -163,8 +164,8 @@ class MessageController extends AbstractCrudController
return $this->render('messages'); return $this->render('messages');
} }
protected function listDirectoryContent($requiredExtension) protected function listDirectoryContent($requiredExtension) {
{
$list = array(); $list = array();
$dir = TemplateHelper::getInstance()->getActiveMailTemplate()->getAbsolutePath(); $dir = TemplateHelper::getInstance()->getActiveMailTemplate()->getAbsolutePath();

View File

@@ -33,6 +33,7 @@ use Thelia\Core\Security\AccessManager;
use Thelia\Form\ModuleModificationForm; use Thelia\Form\ModuleModificationForm;
use Thelia\Model\ModuleQuery; use Thelia\Model\ModuleQuery;
use Thelia\Module\ModuleManagement; use Thelia\Module\ModuleManagement;
use Thelia\Core\Event\UpdatePositionEvent;
/** /**
* Class ModuleController * Class ModuleController
@@ -45,14 +46,30 @@ class ModuleController extends AbstractCrudController
{ {
parent::__construct( parent::__construct(
'module', 'module',
null, 'manual',
null, 'module_order',
AdminResources::MODULE, AdminResources::MODULE,
null, null,
TheliaEvents::MODULE_UPDATE, TheliaEvents::MODULE_UPDATE,
null null,
null,
TheliaEvents::MODULE_UPDATE_POSITION
/*
$objectName,
$defaultListOrder = null,
$orderRequestParameterName = null,
$resourceCode,
$createEventIdentifier,
$updateEventIdentifier,
$deleteEventIdentifier,
$visibilityToggleEventIdentifier = null,
$changePositionEventIdentifier = null
*/
); );
} }
@@ -90,6 +107,15 @@ class ModuleController extends AbstractCrudController
return null; return null;
} }
protected function createUpdatePositionEvent($positionChangeMode, $positionValue)
{
return new UpdatePositionEvent(
$this->getRequest()->get('module_id', null),
$positionChangeMode,
$positionValue
);
}
protected function eventContainsObject($event) protected function eventContainsObject($event)
{ {
return $event->hasModule(); return $event->hasModule();
@@ -123,6 +149,7 @@ class ModuleController extends AbstractCrudController
->findOneById($this->getRequest()->get('module_id')); ->findOneById($this->getRequest()->get('module_id'));
} }
protected function getObjectLabel($object) protected function getObjectLabel($object)
{ {
return $object->getTitle(); return $object->getTitle();
@@ -150,7 +177,7 @@ class ModuleController extends AbstractCrudController
// We always return to the feature edition form // We always return to the feature edition form
return $this->render( return $this->render(
'modules', 'modules',
array() array('module_order' => $currentOrder)
); );
} }
@@ -184,18 +211,19 @@ class ModuleController extends AbstractCrudController
$moduleManagement = new ModuleManagement(); $moduleManagement = new ModuleManagement();
$moduleManagement->updateModules(); $moduleManagement->updateModules();
return $this->render("modules"); return $this->renderList();
} }
public function configureAction($module_code) public function configureAction($module_code)
{ {
$module = ModuleQuery::create()->findOneByCode($module_code); $module = ModuleQuery::create()->findOneByCode($module_code);
if (null === $module) { if(null === $module) {
throw new \InvalidArgumentException(sprintf("Module `%s` does not exists", $module_code)); throw new \InvalidArgumentException(sprintf("Module `%s` does not exists", $module_code));
} }
if (null !== $response = $this->checkAuth(array(), $module_code, AccessManager::VIEW)) return $response; if (null !== $response = $this->checkAuth(array(), $module_code, AccessManager::VIEW)) return $response;
return $this->render( return $this->render(
"module-configure", "module-configure",
array( array(

View File

@@ -27,6 +27,7 @@ use Thelia\Core\HttpFoundation\Response;
use Thelia\Core\Security\Resource\AdminResources; use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Core\Event\Order\OrderAddressEvent; use Thelia\Core\Event\Order\OrderAddressEvent;
use Thelia\Core\Event\Order\OrderEvent; use Thelia\Core\Event\Order\OrderEvent;
use Thelia\Core\Event\PdfEvent;
use Thelia\Core\Event\TheliaEvents; use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Security\AccessManager; use Thelia\Core\Security\AccessManager;
use Thelia\Form\OrderUpdateAddress; use Thelia\Form\OrderUpdateAddress;
@@ -35,6 +36,7 @@ use Thelia\Model\Base\OrderAddressQuery;
use Thelia\Model\OrderQuery; use Thelia\Model\OrderQuery;
use Thelia\Model\OrderStatusQuery; use Thelia\Model\OrderStatusQuery;
use Thelia\Tools\URL; use Thelia\Tools\URL;
use Thelia\Core\Template\TemplateHelper;
/** /**
* Class OrderController * Class OrderController
@@ -201,18 +203,20 @@ class OrderController extends BaseAdminController
public function generateInvoicePdf($order_id) public function generateInvoicePdf($order_id)
{ {
if (null !== $response = $this->checkAuth(AdminResources::ORDER, array(), AccessManager::UPDATE)) return $response; if (null !== $response = $this->checkAuth(AdminResources::ORDER, array(), AccessManager::UPDATE)) return $response;
return $this->generateBackOfficeOrderPdf($order_id, ConfigQuery::read('pdf_invoice_file', 'invoice')); return $this->generateBackOfficeOrderPdf($order_id, ConfigQuery::read('pdf_invoice_file', 'invoice'));
} }
public function generateDeliveryPdf($order_id) public function generateDeliveryPdf($order_id)
{ {
if (null !== $response = $this->checkAuth(AdminResources::ORDER, array(), AccessManager::UPDATE)) return $response; if (null !== $response = $this->checkAuth(AdminResources::ORDER, array(), AccessManager::UPDATE)) return $response;
return $this->generateBackOfficeOrderPdf($order_id, ConfigQuery::read('pdf_delivery_file', 'delivery')); return $this->generateBackOfficeOrderPdf($order_id, ConfigQuery::read('pdf_delivery_file', 'delivery'));
} }
private function generateBackOfficeOrderPdf($order_id, $fileName) private function generateBackOfficeOrderPdf($order_id, $fileName)
{ {
if (null === $response = $this->generateOrderPdf($order_id, $fileName)) { if(null === $response = $this->generateOrderPdf($order_id, $fileName)){
$this->redirect(URL::getInstance()->absoluteUrl($this->getRoute("admin.order.update.view", array( $this->redirect(URL::getInstance()->absoluteUrl($this->getRoute("admin.order.update.view", array(
'order_id' => $order_id 'order_id' => $order_id
)))); ))));
@@ -221,4 +225,5 @@ class OrderController extends BaseAdminController
return $response; return $response;
} }
} }

View File

@@ -72,6 +72,7 @@ use Thelia\Form\ProductCombinationGenerationForm;
use Thelia\TaxEngine\Calculator; use Thelia\TaxEngine\Calculator;
use Thelia\Tools\NumberFormat; use Thelia\Tools\NumberFormat;
/** /**
* Manages products * Manages products
* *
@@ -1036,18 +1037,17 @@ class ProductController extends AbstractSeoCrudController
} }
// Create combinations // Create combinations
protected function combine($input, &$output, &$tmp) protected function combine($input, &$output, &$tmp) {
{
$current = array_shift($input); $current = array_shift($input);
if (count($input) > 0) { if (count($input) > 0) {
foreach ($current as $element) { foreach($current as $element) {
$tmp[] = $element; $tmp[] = $element;
$this->combine($input, $output, $tmp); $this->combine($input, $output, $tmp);
array_pop($tmp); array_pop($tmp);
} }
} else { } else {
foreach ($current as $element) { foreach($current as $element) {
$tmp[] = $element; $tmp[] = $element;
$output[] = $tmp; $output[] = $tmp;
array_pop($tmp); array_pop($tmp);
@@ -1058,8 +1058,8 @@ class ProductController extends AbstractSeoCrudController
/** /**
* Build combinations from the combination output builder * Build combinations from the combination output builder
*/ */
public function buildCombinationsAction() public function buildCombinationsAction() {
{
// Check current user authorization // Check current user authorization
if (null !== $response = $this->checkAuth($this->resourceCode, array(), AccessManager::UPDATE)) return $response; if (null !== $response = $this->checkAuth($this->resourceCode, array(), AccessManager::UPDATE)) return $response;
@@ -1082,7 +1082,7 @@ class ProductController extends AbstractSeoCrudController
// from the list of attribute_id:attributes_av ID from the form. // from the list of attribute_id:attributes_av ID from the form.
$combinations = $attributes_av_list = array(); $combinations = $attributes_av_list = array();
foreach ($data['attribute_av'] as $item) { foreach($data['attribute_av'] as $item) {
list($attribute_id, $attribute_av_id) = explode(':', $item); list($attribute_id, $attribute_av_id) = explode(':', $item);
if (! isset($attributes_av_list[$attribute_id])) if (! isset($attributes_av_list[$attribute_id]))
@@ -1118,7 +1118,7 @@ class ProductController extends AbstractSeoCrudController
$this->dispatch(TheliaEvents::PRODUCT_COMBINATION_GENERATION, $event); $this->dispatch(TheliaEvents::PRODUCT_COMBINATION_GENERATION, $event);
// Log object modification // Log object modification
$this->adminLogAppend(sprintf("Combination generation for product reference %s", $event->getProduct()->getRef())); $this->adminLogAppend($this->resourceCode, AccessManager::CREATE, sprintf("Combination generation for product reference %s", $event->getProduct()->getRef()));
// Redirect to the success URL // Redirect to the success URL
$this->redirect($changeForm->getSuccessUrl()); $this->redirect($changeForm->getSuccessUrl());

View File

@@ -23,6 +23,7 @@
namespace Thelia\Controller\Admin; namespace Thelia\Controller\Admin;
use Thelia\Core\Security\Resource\AdminResources; use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Core\Security\AccessManager; use Thelia\Core\Security\AccessManager;
use Thelia\Form\SystemLogConfigurationForm; use Thelia\Form\SystemLogConfigurationForm;
@@ -42,7 +43,7 @@ class SystemLogController extends BaseAdminController
$destination_directories = Tlog::getInstance()->getDestinationsDirectories(); $destination_directories = Tlog::getInstance()->getDestinationsDirectories();
foreach ($destination_directories as $dir) { foreach($destination_directories as $dir) {
$this->loadDefinedDestinations($dir, $destinations); $this->loadDefinedDestinations($dir, $destinations);
} }
@@ -57,8 +58,8 @@ class SystemLogController extends BaseAdminController
); );
} }
protected function loadDefinedDestinations($directory, &$destinations) protected function loadDefinedDestinations($directory, &$destinations) {
{
try { try {
foreach (new \DirectoryIterator($directory) as $fileInfo) { foreach (new \DirectoryIterator($directory) as $fileInfo) {
@@ -143,7 +144,7 @@ class SystemLogController extends BaseAdminController
$active_destinations = array(); $active_destinations = array();
foreach ($destinations as $classname => $destination) { foreach($destinations as $classname => $destination) {
if (isset($destination['active'])) { if (isset($destination['active'])) {
$active_destinations[] = $destination['classname']; $active_destinations[] = $destination['classname'];
@@ -152,7 +153,7 @@ class SystemLogController extends BaseAdminController
if (isset($configs[$classname])) { if (isset($configs[$classname])) {
// Update destinations configuration // Update destinations configuration
foreach ($configs[$classname] as $var => $value) { foreach($configs[$classname] as $var => $value) {
ConfigQuery::write($var, $value, true, true); ConfigQuery::write($var, $value, true, true);
} }
} }

View File

@@ -23,8 +23,12 @@
namespace Thelia\Controller\Admin; namespace Thelia\Controller\Admin;
use Thelia\Core\Security\Resource\AdminResources; use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Core\Security\AccessManager; use Thelia\Core\Security\AccessManager;
use Thelia\Form\SystemLogConfigurationForm;
use Thelia\Log\Tlog;
use Thelia\Model\ConfigQuery;
use Thelia\Model\ModuleQuery; use Thelia\Model\ModuleQuery;
use Thelia\Core\Template\TemplateHelper; use Thelia\Core\Template\TemplateHelper;
use Thelia\Core\Template\TemplateDefinition; use Thelia\Core\Template\TemplateDefinition;
@@ -63,7 +67,7 @@ class TranslationsController extends BaseAdminController
if (! empty($item_id) || $item_to_translate == 'co') { if (! empty($item_id) || $item_to_translate == 'co') {
switch ($item_to_translate) { switch($item_to_translate) {
case 'mo' : case 'mo' :
if (null !== $module = ModuleQuery::create()->findPk($item_id)) { if (null !== $module = ModuleQuery::create()->findPk($item_id)) {
@@ -145,7 +149,8 @@ class TranslationsController extends BaseAdminController
$templateArguments['max_input_vars_warning'] = true; $templateArguments['max_input_vars_warning'] = true;
$templateArguments['required_max_input_vars'] = $stringsCount; $templateArguments['required_max_input_vars'] = $stringsCount;
$templateArguments['current_max_input_vars'] = ini_get('max_input_vars'); $templateArguments['current_max_input_vars'] = ini_get('max_input_vars');
} else { }
else {
$templateArguments['all_strings'] = $all_strings; $templateArguments['all_strings'] = $all_strings;
} }
} }
@@ -157,12 +162,14 @@ class TranslationsController extends BaseAdminController
public function defaultAction() public function defaultAction()
{ {
if (null !== $response = $this->checkAuth(AdminResources::TRANSLATIONS, array(), AccessManager::VIEW)) return $response; if (null !== $response = $this->checkAuth(AdminResources::TRANSLATIONS, array(), AccessManager::VIEW)) return $response;
return $this->renderTemplate(); return $this->renderTemplate();
} }
public function updateAction() public function updateAction()
{ {
if (null !== $response = $this->checkAuth(AdminResources::LANGUAGE, array(), AccessManager::UPDATE)) return $response; if (null !== $response = $this->checkAuth(AdminResources::LANGUAGE, array(), AccessManager::UPDATE)) return $response;
return $this->renderTemplate(); return $this->renderTemplate();
} }
} }

View File

@@ -61,7 +61,7 @@ abstract class BaseController extends ContainerAware
/** /**
* Return an empty response (after an ajax request, for example) * Return an empty response (after an ajax request, for example)
* @param int $status * @param int $status
* @return \Thelia\Core\HttpFoundation\Response * @return \Thelia\Core\HttpFoundation\Response
*/ */
protected function nullResponse($status = 200) protected function nullResponse($status = 200)
@@ -252,6 +252,7 @@ abstract class BaseController extends ContainerAware
} }
} }
/** /**
@@ -366,8 +367,8 @@ abstract class BaseController extends ContainerAware
* Render the given template, and returns the result as an Http Response. * Render the given template, and returns the result as an Http Response.
* *
* @param $templateName the complete template name, with extension * @param $templateName the complete template name, with extension
* @param array $args the template arguments * @param array $args the template arguments
* @param int $status http code status * @param int $status http code status
* @return \Thelia\Core\HttpFoundation\Response * @return \Thelia\Core\HttpFoundation\Response
*/ */
abstract protected function render($templateName, $args = array(), $status = 200); abstract protected function render($templateName, $args = array(), $status = 200);

View File

@@ -25,8 +25,10 @@ namespace Thelia\Controller\Front;
use Symfony\Component\Routing\Router; use Symfony\Component\Routing\Router;
use Thelia\Controller\BaseController; use Thelia\Controller\BaseController;
use Thelia\Core\HttpFoundation\Response; use Thelia\Core\HttpFoundation\Response;
use Thelia\Core\Security\Exception\AuthenticationException;
use Thelia\Core\Template\TemplateHelper; use Thelia\Core\Template\TemplateHelper;
use Thelia\Model\AddressQuery; use Thelia\Model\AddressQuery;
use Thelia\Model\ConfigQuery;
use Thelia\Model\ModuleQuery; use Thelia\Model\ModuleQuery;
use Thelia\Tools\Redirect; use Thelia\Tools\Redirect;
use Thelia\Tools\URL; use Thelia\Tools\URL;
@@ -95,7 +97,7 @@ class BaseFrontController extends BaseController
$parser = $this->container->get("thelia.parser"); $parser = $this->container->get("thelia.parser");
// Define the template that should be used // Define the template that should be used
$parser->setTemplate($template ?: TemplateHelper::getInstance()->getActiveFrontTemplate()); $parser->setTemplateDefinition($template ?: TemplateHelper::getInstance()->getActiveFrontTemplate());
return $parser; return $parser;
} }
@@ -104,8 +106,8 @@ class BaseFrontController extends BaseController
* Render the given template, and returns the result as an Http Response. * Render the given template, and returns the result as an Http Response.
* *
* @param $templateName the complete template name, with extension * @param $templateName the complete template name, with extension
* @param array $args the template arguments * @param array $args the template arguments
* @param int $status http code status * @param int $status http code status
* @return \Thelia\Core\HttpFoundation\Response * @return \Thelia\Core\HttpFoundation\Response
*/ */
protected function render($templateName, $args = array(), $status = 200) protected function render($templateName, $args = array(), $status = 200)

View File

@@ -26,6 +26,7 @@ use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Reference;
/** /**
* Class TranslatorPass * Class TranslatorPass
* @package Thelia\Core\DependencyInjection\Compiler * @package Thelia\Core\DependencyInjection\Compiler
@@ -49,11 +50,11 @@ class TranslatorPass implements CompilerPassInterface
$translator = $container->getDefinition('thelia.translator'); $translator = $container->getDefinition('thelia.translator');
foreach ($container->findTaggedServiceIds('translation.loader') as $id => $attributes) { foreach($container->findTaggedServiceIds('translation.loader') as $id => $attributes) {
$translator->addMethodCall('addLoader', array($attributes[0]['alias'], new Reference($id))); $translator->addMethodCall('addLoader', array($attributes[0]['alias'], new Reference($id)));
if (isset($attributes[0]['legacy-alias'])) { if (isset($attributes[0]['legacy-alias'])) {
$translator->addMethodCall('addLoader', array($attributes[0]['legacy-alias'], new Reference($id))); $translator->addMethodCall('addLoader', array($attributes[0]['legacy-alias'], new Reference($id)));
} }
} }
} }
} }

View File

@@ -25,6 +25,7 @@ namespace Thelia\Core\Event\Administrator;
use Thelia\Core\Event\ActionEvent; use Thelia\Core\Event\ActionEvent;
use Thelia\Model\Admin; use Thelia\Model\Admin;
/** /**
* Class AdministratorUpdatePasswordEvent * Class AdministratorUpdatePasswordEvent
* @package Thelia\Core\Event\Administrator * @package Thelia\Core\Event\Administrator
@@ -81,3 +82,4 @@ class AdministratorUpdatePasswordEvent extends ActionEvent
} }
} }

View File

@@ -23,6 +23,7 @@
namespace Thelia\Core\Event\Customer; namespace Thelia\Core\Event\Customer;
use Symfony\Component\EventDispatcher\Event; use Symfony\Component\EventDispatcher\Event;
use Thelia\Core\Event\ActionEvent;
use Thelia\Model\Customer; use Thelia\Model\Customer;
/** /**

View File

@@ -23,6 +23,7 @@
namespace Thelia\Core\Event\Customer; namespace Thelia\Core\Event\Customer;
use Thelia\Core\Event\ActionEvent;
use Thelia\Model\Customer; use Thelia\Model\Customer;
class CustomerLoginEvent extends CustomerEvent class CustomerLoginEvent extends CustomerEvent

View File

@@ -138,4 +138,4 @@ class MessageUpdateEvent extends MessageCreateEvent
return $this; return $this;
} }
} }

View File

@@ -65,7 +65,6 @@ class ProductCombinationGenerationEvent extends ProductEvent
public function setReference($reference) public function setReference($reference)
{ {
$this->reference = $reference; $this->reference = $reference;
return $this; return $this;
} }
@@ -77,7 +76,6 @@ class ProductCombinationGenerationEvent extends ProductEvent
public function setPrice($price) public function setPrice($price)
{ {
$this->price = $price; $this->price = $price;
return $this; return $this;
} }
@@ -89,7 +87,6 @@ class ProductCombinationGenerationEvent extends ProductEvent
public function setWeight($weight) public function setWeight($weight)
{ {
$this->weight = $weight; $this->weight = $weight;
return $this; return $this;
} }
@@ -101,7 +98,6 @@ class ProductCombinationGenerationEvent extends ProductEvent
public function setQuantity($quantity) public function setQuantity($quantity)
{ {
$this->quantity = $quantity; $this->quantity = $quantity;
return $this; return $this;
} }
@@ -113,7 +109,6 @@ class ProductCombinationGenerationEvent extends ProductEvent
public function setSalePrice($sale_price) public function setSalePrice($sale_price)
{ {
$this->sale_price = $sale_price; $this->sale_price = $sale_price;
return $this; return $this;
} }
@@ -125,7 +120,6 @@ class ProductCombinationGenerationEvent extends ProductEvent
public function setOnsale($onsale) public function setOnsale($onsale)
{ {
$this->onsale = $onsale; $this->onsale = $onsale;
return $this; return $this;
} }
@@ -137,7 +131,6 @@ class ProductCombinationGenerationEvent extends ProductEvent
public function setIsnew($isnew) public function setIsnew($isnew)
{ {
$this->isnew = $isnew; $this->isnew = $isnew;
return $this; return $this;
} }
@@ -149,7 +142,6 @@ class ProductCombinationGenerationEvent extends ProductEvent
public function setEanCode($ean_code) public function setEanCode($ean_code)
{ {
$this->ean_code = $ean_code; $this->ean_code = $ean_code;
return $this; return $this;
return $this; return $this;
} }
@@ -162,7 +154,6 @@ class ProductCombinationGenerationEvent extends ProductEvent
public function setCombinations($combinations) public function setCombinations($combinations)
{ {
$this->combinations = $combinations; $this->combinations = $combinations;
return $this; return $this;
} }
} }

View File

@@ -60,4 +60,4 @@ class ProductSetTemplateEvent extends ProductEvent
return $this; return $this;
} }
} }

View File

@@ -22,6 +22,7 @@
/*************************************************************************************/ /*************************************************************************************/
namespace Thelia\Core\Event\ProductSaleElement; namespace Thelia\Core\Event\ProductSaleElement;
use Thelia\Model\Product;
class ProductSaleElementDeleteEvent extends ProductSaleElementEvent class ProductSaleElementDeleteEvent extends ProductSaleElementEvent
{ {

View File

@@ -370,7 +370,6 @@ final class TheliaEvents
*/ */
const ORDER_SET_DELIVERY_ADDRESS = "action.order.setDeliveryAddress"; const ORDER_SET_DELIVERY_ADDRESS = "action.order.setDeliveryAddress";
const ORDER_SET_DELIVERY_MODULE = "action.order.setDeliveryModule"; const ORDER_SET_DELIVERY_MODULE = "action.order.setDeliveryModule";
const ORDER_SET_POSTAGE = "action.order.setPostage";
const ORDER_SET_INVOICE_ADDRESS = "action.order.setInvoiceAddress"; const ORDER_SET_INVOICE_ADDRESS = "action.order.setInvoiceAddress";
const ORDER_SET_PAYMENT_MODULE = "action.order.setPaymentModule"; const ORDER_SET_PAYMENT_MODULE = "action.order.setPaymentModule";
const ORDER_PAY = "action.order.pay"; const ORDER_PAY = "action.order.pay";
@@ -692,9 +691,15 @@ final class TheliaEvents
*/ */
const MODULE_TOGGLE_ACTIVATION = 'thelia.module.toggleActivation'; const MODULE_TOGGLE_ACTIVATION = 'thelia.module.toggleActivation';
/**
* sent when module position is changed
*/
const MODULE_UPDATE_POSITION = 'thelia.module.action.updatePosition';
/** /**
* module * module
*/ */
const MODULE_CREATE = 'thelia.module.create';
const MODULE_UPDATE = 'thelia.module.update'; const MODULE_UPDATE = 'thelia.module.update';
const MODULE_DELETE = 'thelia.module.delete'; const MODULE_DELETE = 'thelia.module.delete';

View File

@@ -184,4 +184,5 @@ class UpdateSeoEvent extends ActionEvent
return $this->object; return $this->object;
} }
} }

View File

@@ -30,10 +30,12 @@ use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Thelia\Core\HttpFoundation\Response; use Thelia\Core\HttpFoundation\Response;
use Symfony\Component\Routing\Router; use Symfony\Component\Routing\Router;
use Thelia\Core\HttpKernel\Exception\NotFountHttpException;
use Thelia\Core\Template\Exception\ResourceNotFoundException; use Thelia\Core\Template\Exception\ResourceNotFoundException;
use Thelia\Core\Template\ParserInterface; use Thelia\Core\Template\ParserInterface;
use Thelia\Core\Template\TemplateHelper; use Thelia\Core\Template\TemplateHelper;
use Thelia\Exception\OrderException; use Thelia\Exception\OrderException;
use Thelia\Model\ConfigQuery;
use Thelia\Tools\Redirect; use Thelia\Tools\Redirect;
use Thelia\Tools\URL; use Thelia\Tools\URL;
use Thelia\Core\Security\Exception\AuthenticationException; use Thelia\Core\Security\Exception\AuthenticationException;
@@ -76,7 +78,7 @@ class ViewListener implements EventSubscriberInterface
{ {
$parser = $this->container->get('thelia.parser'); $parser = $this->container->get('thelia.parser');
$parser->setTemplate(TemplateHelper::getInstance()->getActiveFrontTemplate()); $parser->setTemplateDefinition(TemplateHelper::getInstance()->getActiveFrontTemplate());
$request = $this->container->get('request'); $request = $this->container->get('request');
try { try {

View File

@@ -39,8 +39,8 @@ class Response extends BaseResponse
* *
* @see \Thelia\Core\HttpFoundation\Response::sendContent() * @see \Thelia\Core\HttpFoundation\Response::sendContent()
*/ */
public function sendContent() public function sendContent() {
{
Tlog::getInstance()->write($this->content); Tlog::getInstance()->write($this->content);
parent::sendContent(); parent::sendContent();

View File

@@ -65,8 +65,7 @@ class HttpCache extends BaseHttpCache implements HttpKernelInterface
$request->getContent() $request->getContent()
); );
} }
return parent::handle($request, $type, $catch); return parent::handle($request, $type, $catch);
} }
} }

View File

@@ -177,7 +177,7 @@ class SecurityContext
continue; continue;
} }
if (!array_key_exists('module', $userPermissions)) { if(!array_key_exists('module', $userPermissions)) {
return false; return false;
} }

View File

@@ -23,32 +23,45 @@
namespace Thelia\Core\Template\Assets; namespace Thelia\Core\Template\Assets;
interface AssetManagerInterface interface AssetManagerInterface {
{
/** /**
* Prepare an asset directory. * Prepare an asset directory by checking that no changes occured in
* the source directory. If any change is detected, the whole asset directory
* is copied in the web space.
*
* @param string $sourceAssetsDirectory the full path to the source asstes directory
* @param string $webAssetsDirectoryBase the base directory of the web based asset directory
* @param $webAssetsTemplate
* @param string $webAssetsKey the assets key : module name or 0 for base template
* *
* @param string $source_assets_directory the full path to the source asstes directory
* @param string $web_assets_directory_base the base directory of the web based asset directory
* @throws \RuntimeException if something goes wrong. * @throws \RuntimeException if something goes wrong.
*
* @internal param string $source_assets_directory the full path to the source asstes directory
* @internal param string $web_assets_directory_base the base directory of the web based asset directory
* @internal param string $key the assets key : module name or 0 for base template
*/ */
public function prepareAssets($source_assets_directory, $web_assets_directory_base); public function prepareAssets($sourceAssetsDirectory, $webAssetsDirectoryBase, $webAssetsTemplate, $webAssetsKey);
/** /**
* Generates assets from $asset_path in $output_path, using $filters. * Generates assets from $asset_path in $output_path, using $filters.
* *
* @param string $asset_path the full path to the asset file (or file collection, e.g. *.less) * @param $assetSource
* @param $assetDirectoryBase
* @param string $webAssetsDirectoryBase the full path to the asset file (or file collection, e.g. *.less)
* *
* @param string $web_assets_directory_base the full disk path to the base assets output directory in the web space * @param string $webAssetsTemplate the full disk path to the base assets output directory in the web space
* @param string $output_url the URL to the base assets output directory in the web space * @param $webAssetsKey
* @param string $outputUrl the URL to the base assets output directory in the web space
* *
* @param string $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 string $assetType the asset type: css, js, ... The generated files will have this extension. Pass an empty string to use the asset source extension.
* @param array $filters a list of filters, as defined below (see switch($filter_name) ...) * @param array $filters a list of filters, as defined below (see switch($filter_name) ...)
* *
* @param boolean $debug the debug mode, true or false * @param boolean $debug true / false
* *
* @throws \InvalidArgumentException if an invalid filter name is found * @internal param string $web_assets_directory_base the full disk path to the base assets output directory in the web space
* @return string The URL to the generated asset file. * @internal param string $output_url the URL to the base assets output directory in the web space
*
* @return string The URL to the generated asset file.
*/ */
public function processAsset($asset_path, $web_assets_directory_base, $output_url, $asset_type, $filters, $debug); public function processAsset($assetSource, $assetDirectoryBase, $webAssetsDirectoryBase, $webAssetsTemplate, $webAssetsKey, $outputUrl, $assetType, $filters, $debug);
} }

View File

@@ -31,7 +31,6 @@ use Assetic\AssetWriter;
use Thelia\Model\ConfigQuery; use Thelia\Model\ConfigQuery;
use Thelia\Log\Tlog; use Thelia\Log\Tlog;
use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Exception\IOException;
/** /**
* This class is a simple helper for generating assets using Assetic. * This class is a simple helper for generating assets using Assetic.
@@ -52,7 +51,7 @@ class AsseticAssetManager implements AssetManagerInterface
/** /**
* Create a stamp form the modification time of the content of the given directory and all of its subdirectories * Create a stamp form the modification time of the content of the given directory and all of its subdirectories
* *
* @param string $directory ther directory name * @param string $directory ther directory name
* @return string the stamp of this directory * @return string the stamp of this directory
*/ */
protected function getStamp($directory) protected function getStamp($directory)
@@ -73,19 +72,21 @@ class AsseticAssetManager implements AssetManagerInterface
/** /**
* Check if a file is a source asset file * Check if a file is a source asset file
* *
* @param \DirectoryIterator $fileInfo * @param \SplFileInfo $fileInfo
*
* @return bool
*/ */
protected function isSourceFile(\SplFileInfo $fileInfo) protected function isSourceFile(\SplFileInfo $fileInfo) {
{
return in_array($fileInfo->getExtension(), $this->source_file_extensions); return in_array($fileInfo->getExtension(), $this->source_file_extensions);
} }
/** /**
* Recursively copy assets from the source directory to the destination * Recursively copy assets from the source directory to the destination
* directory in the web space, ommiting source files. * directory in the web space, omitting source files.
* *
* @param string $from_directory the source * @param Filesystem $fs
* @param string $to_directory the destination * @param string $from_directory the source
* @param string $to_directory the destination
* @throws \RuntimeException if a problem occurs. * @throws \RuntimeException if a problem occurs.
*/ */
protected function copyAssets(Filesystem $fs, $from_directory, $to_directory) protected function copyAssets(Filesystem $fs, $from_directory, $to_directory)
@@ -122,38 +123,21 @@ class AsseticAssetManager implements AssetManagerInterface
} }
} }
/**
* Compite the assets path relative to the base template directory
*
* @param string $source_assets_directory the source directory
* @param string $web_assets_directory_base base directory of the web assets
* @return the full path of the destination directory
*/
protected function getRelativeDirectoryPath($source_assets_directory, $web_assets_directory_base)
{
$source_assets_directory = realpath($source_assets_directory);
// Remove base path from asset source path to get a path relative to the template base
// and use it to create the destination path.
return str_replace(
realpath(THELIA_ROOT),
'',
$source_assets_directory
);
}
/** /**
* Compute the destination directory path, from the source directory and the * Compute the destination directory path, from the source directory and the
* base directory of the web assets * base directory of the web assets
* *
* @param string $source_assets_directory the source directory * @param string $webAssetsDirectoryBase base directory of the web assets
* @param string $web_assets_directory_base base directory of the web assets * @param $webAssetsTemplate
* @return the full path of the destination directory * @param string $webAssetsKey the assests key : module name or 0 for base template
*
* @internal param string $source_assets_directory the source directory
* @return the full path of the destination directory
*/ */
protected function getDestinationDirectory($source_assets_directory, $web_assets_directory_base) protected function getDestinationDirectory($webAssetsDirectoryBase, $webAssetsTemplate, $webAssetsKey)
{ {
// Compute the absolute path of the output directory // Compute the absolute path of the output directory
return $web_assets_directory_base . $this->getRelativeDirectoryPath($source_assets_directory, $web_assets_directory_base); return $webAssetsDirectoryBase . DS . $webAssetsTemplate . DS . $webAssetsKey;
} }
/** /**
@@ -161,14 +145,17 @@ class AsseticAssetManager implements AssetManagerInterface
* the source directory. If any change is detected, the whole asset directory * the source directory. If any change is detected, the whole asset directory
* is copied in the web space. * is copied in the web space.
* *
* @param string $source_assets_directory the full path to the source asstes directory * @param string $sourceAssetsDirectory the full path to the source asstes directory
* @param string $web_assets_directory_base the base directory of the web based asset directory * @param string $webAssetsDirectoryBase the base directory of the web based asset directory
* @param $webAssetsTemplate
* @param string $webAssetsKey the assets key : module name or 0 for base template
*
* @throws \RuntimeException if something goes wrong. * @throws \RuntimeException if something goes wrong.
*/ */
public function prepareAssets($source_assets_directory, $web_assets_directory_base) public function prepareAssets($sourceAssetsDirectory, $webAssetsDirectoryBase, $webAssetsTemplate, $webAssetsKey)
{ {
// Compute the absolute path of the output directory // Compute the absolute path of the output directory
$to_directory = $this->getDestinationDirectory($source_assets_directory, $web_assets_directory_base); $to_directory = $this->getDestinationDirectory($webAssetsDirectoryBase, $webAssetsTemplate, $webAssetsKey);
// Get a path to the stamp file // Get a path to the stamp file
$stamp_file_path = $to_directory . DS . '.source-stamp'; $stamp_file_path = $to_directory . DS . '.source-stamp';
@@ -177,7 +164,7 @@ class AsseticAssetManager implements AssetManagerInterface
$prev_stamp = @file_get_contents($stamp_file_path); $prev_stamp = @file_get_contents($stamp_file_path);
// Get the current stamp of the source directory // Get the current stamp of the source directory
$curr_stamp = $this->getStamp($source_assets_directory); $curr_stamp = $this->getStamp($sourceAssetsDirectory);
if ($prev_stamp !== $curr_stamp) { if ($prev_stamp !== $curr_stamp) {
@@ -198,7 +185,7 @@ class AsseticAssetManager implements AssetManagerInterface
$fs->remove($tmp_dir); $fs->remove($tmp_dir);
// Copy the whole source dir in a temp directory // Copy the whole source dir in a temp directory
$this->copyAssets($fs, $source_assets_directory, $tmp_dir); $this->copyAssets($fs, $sourceAssetsDirectory, $tmp_dir);
// Remove existing directory // Remove existing directory
if ($fs->exists($to_directory)) $fs->remove($to_directory); if ($fs->exists($to_directory)) $fs->remove($to_directory);
@@ -218,7 +205,8 @@ class AsseticAssetManager implements AssetManagerInterface
throw new \RuntimeException( throw new \RuntimeException(
"Failed to create asset stamp file $stamp_file_path. Please check that your web server has the proper access rights to do that."); "Failed to create asset stamp file $stamp_file_path. Please check that your web server has the proper access rights to do that.");
} }
/* } else { /* }
else {
@fclose($fp); @fclose($fp);
} }
*/ */
@@ -228,13 +216,13 @@ class AsseticAssetManager implements AssetManagerInterface
/** /**
* Decode the filters names, and initialize the Assetic FilterManager * Decode the filters names, and initialize the Assetic FilterManager
* *
* @param FilterManager $filterManager the Assetic filter manager * @param FilterManager $filterManager the Assetic filter manager
* @param string $filters a comma separated list of filter names * @param string $filters a comma separated list of filter names
* @throws \InvalidArgumentException if a wrong filter is passed * @throws \InvalidArgumentException if a wrong filter is passed
* @return an array of filter names * @return an array of filter names
*/ */
protected function decodeAsseticFilters(FilterManager $filterManager, $filters) protected function decodeAsseticFilters(FilterManager $filterManager, $filters) {
{
if (!empty($filters)) { if (!empty($filters)) {
$filter_list = explode(',', $filters); $filter_list = explode(',', $filters);
@@ -273,7 +261,8 @@ class AsseticAssetManager implements AssetManagerInterface
break; break;
} }
} }
} else { }
else {
$filter_list = array(); $filter_list = array();
} }
@@ -283,67 +272,73 @@ class AsseticAssetManager implements AssetManagerInterface
/** /**
* Generates assets from $asset_path in $output_path, using $filters. * Generates assets from $asset_path in $output_path, using $filters.
* *
* @param string $asset_path the full path to the asset file (or file collection, e.g. *.less) * @param $assetSource
* @param $assetDirectoryBase
* @param string $webAssetsDirectoryBase the full path to the asset file (or file collection, e.g. *.less)
* *
* @param string $web_assets_directory_base the full disk path to the base assets output directory in the web space * @param string $webAssetsTemplate the full disk path to the base assets output directory in the web space
* @param string $output_url the URL to the base assets output directory in the web space * @param $webAssetsKey
* @param string $outputUrl the URL to the base assets output directory in the web space
* *
* @param string $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 string $assetType the asset type: css, js, ... The generated files will have this extension. Pass an empty string to use the asset source extension.
* @param array $filters a list of filters, as defined below (see switch($filter_name) ...) * @param array $filters a list of filters, as defined below (see switch($filter_name) ...)
* *
* @param boolean $debug true / false * @param boolean $debug true / false
* @throws \InvalidArgumentException if an invalid filter name is found *
* @return string The URL to the generated asset file. * @return string The URL to the generated asset file.
*/ */
public function processAsset($asset_path, $web_assets_directory_base, $output_url, $asset_type, $filters, $debug) public function processAsset($assetSource, $assetDirectoryBase, $webAssetsDirectoryBase, $webAssetsTemplate, $webAssetsKey, $outputUrl, $assetType, $filters, $debug)
{ {
$asset_name = basename($asset_path); $assetName = basename($assetSource);
$input_directory = realpath(dirname($asset_path)); $inputDirectory = realpath(dirname($assetSource));
$assetFileDirectoryInAssetDirectory = trim(str_replace(array($assetDirectoryBase, $assetName), '', $assetSource), DS);
$am = new AssetManager(); $am = new AssetManager();
$fm = new FilterManager(); $fm = new FilterManager();
// Get the filter list // Get the filter list
$filter_list = $this->decodeAsseticFilters($fm, $filters); $filterList = $this->decodeAsseticFilters($fm, $filters);
// Factory setup // Factory setup
$factory = new AssetFactory($input_directory); $factory = new AssetFactory($inputDirectory);
$factory->setAssetManager($am); $factory->setAssetManager($am);
$factory->setFilterManager($fm); $factory->setFilterManager($fm);
$factory->setDefaultOutput('*' . (!empty($asset_type) ? '.' : '') . $asset_type); $factory->setDefaultOutput('*' . (!empty($assetType) ? '.' : '') . $assetType);
$factory->setDebug($debug); $factory->setDebug($debug);
$asset = $factory->createAsset($asset_name, $filter_list); $asset = $factory->createAsset($assetName, $filterList);
$input_directory = realpath(dirname($asset_path)); $outputDirectory = $this->getDestinationDirectory($webAssetsDirectoryBase, $webAssetsTemplate, $webAssetsKey);
$output_directory = $this->getDestinationDirectory($input_directory, $web_assets_directory_base);
// Get the URL part from the relative path // Get the URL part from the relative path
$output_relative_path = $this->getRelativeDirectoryPath($input_directory, $web_assets_directory_base); $outputRelativePath = $webAssetsTemplate . DS . $webAssetsKey;
$output_relative_web_path = rtrim(str_replace('\\', '/', $output_relative_path), '/') . '/'; $outputRelativeWebPath = rtrim(str_replace('\\', '/', $outputRelativePath), '/') . '/';
$asset_target_filename = $asset->getTargetPath(); $assetTargetFilename = $asset->getTargetPath();
// This is the final name of the generated asset /*
$asset_destination_path = $output_directory . DS . $asset_target_filename; * This is the final name of the generated asset
* We preserve file structure intending to keep - for example - relative css links working
*/
$assetDestinationPath = $outputDirectory . DS . $assetFileDirectoryInAssetDirectory . DS . $assetTargetFilename;
Tlog::getInstance()->addDebug("Asset destination full path: $asset_destination_path"); Tlog::getInstance()->addDebug("Asset destination full path: $assetDestinationPath");
// We generate an asset only if it does not exists, or if the asset processing is forced in development mode // We generate an asset only if it does not exists, or if the asset processing is forced in development mode
if (! file_exists($asset_destination_path) || ($this->debugMode && ConfigQuery::read('process_assets', true)) ) { if (! file_exists($assetDestinationPath) || ($this->debugMode && ConfigQuery::read('process_assets', true)) ) {
$writer = new AssetWriter($output_directory); $writer = new AssetWriter($outputDirectory . DS . $assetFileDirectoryInAssetDirectory);
Tlog::getInstance()->addDebug("Writing asset to $output_directory"); Tlog::getInstance()->addDebug("Writing asset to $outputDirectory . DS . $assetFileDirectoryInAssetDirectory");
$writer->writeAsset($asset); $writer->writeAsset($asset);
} }
return rtrim($output_url, '/') . '/' . ltrim($output_relative_web_path, '/') . $asset_target_filename; return rtrim($outputUrl, '/') . '/' . trim($outputRelativeWebPath, '/') . '/' . trim($assetFileDirectoryInAssetDirectory, '/') . '/' . ltrim($assetTargetFilename, '/');
} }
} }

View File

@@ -277,6 +277,7 @@ abstract class BaseLoop
} }
} }
protected function searchArray(array $search, &$pagination = null) protected function searchArray(array $search, &$pagination = null)
{ {
if (false === $this->countable) { if (false === $this->countable) {
@@ -285,7 +286,7 @@ abstract class BaseLoop
if ($this->getArgValue('page') !== null) { if ($this->getArgValue('page') !== null) {
$nbPage = ceil(count($search)/$this->getArgValue('limit')); $nbPage = ceil(count($search)/$this->getArgValue('limit'));
if ($this->getArgValue('page') > $nbPage || $this->getArgValue('page') <= 0) { if($this->getArgValue('page') > $nbPage || $this->getArgValue('page') <= 0) {
return array(); return array();
} }
@@ -337,9 +338,9 @@ abstract class BaseLoop
*/ */
public function exec(&$pagination) public function exec(&$pagination)
{ {
if ($this instanceof PropelSearchLoopInterface) { if($this instanceof PropelSearchLoopInterface) {
$searchModelCriteria = $this->buildModelCriteria(); $searchModelCriteria = $this->buildModelCriteria();
if (null === $searchModelCriteria) { if(null === $searchModelCriteria) {
$results = array(); $results = array();
} else { } else {
$results = $this->search( $results = $this->search(
@@ -349,7 +350,7 @@ abstract class BaseLoop
} }
} elseif ($this instanceof ArraySearchLoopInterface) { } elseif ($this instanceof ArraySearchLoopInterface) {
$searchArray = $this->buildArray(); $searchArray = $this->buildArray();
if (null === $searchArray) { if(null === $searchArray) {
$results = array(); $results = array();
} else { } else {
$results = $this->searchArray( $results = $this->searchArray(
@@ -361,13 +362,13 @@ abstract class BaseLoop
$loopResult = new LoopResult($results); $loopResult = new LoopResult($results);
if (true === $this->countable) { if(true === $this->countable) {
$loopResult->setCountable(); $loopResult->setCountable();
} }
if (true === $this->timestampable) { if(true === $this->timestampable) {
$loopResult->setTimestamped(); $loopResult->setTimestamped();
} }
if (true === $this->versionable) { if(true === $this->versionable) {
$loopResult->setVersioned(); $loopResult->setVersioned();
} }
@@ -381,29 +382,29 @@ abstract class BaseLoop
* - ArraySearchLoopInterface * - ArraySearchLoopInterface
*/ */
$searchInterface = false; $searchInterface = false;
if ($this instanceof PropelSearchLoopInterface) { if($this instanceof PropelSearchLoopInterface) {
if (true === $searchInterface) { if(true === $searchInterface) {
throw new LoopException('Loop cannot implements multiple Search Interfaces : `PropelSearchLoopInterface`, `ArraySearchLoopInterface`', LoopException::MULTIPLE_SEARCH_INTERFACE); throw new LoopException('Loop cannot implements multiple Search Interfaces : `PropelSearchLoopInterface`, `ArraySearchLoopInterface`', LoopException::MULTIPLE_SEARCH_INTERFACE);
} }
$searchInterface = true; $searchInterface = true;
} }
if ($this instanceof ArraySearchLoopInterface) { if($this instanceof ArraySearchLoopInterface) {
if (true === $searchInterface) { if(true === $searchInterface) {
throw new LoopException('Loop cannot implements multiple Search Interfaces : `PropelSearchLoopInterface`, `ArraySearchLoopInterface`', LoopException::MULTIPLE_SEARCH_INTERFACE); throw new LoopException('Loop cannot implements multiple Search Interfaces : `PropelSearchLoopInterface`, `ArraySearchLoopInterface`', LoopException::MULTIPLE_SEARCH_INTERFACE);
} }
$searchInterface = true; $searchInterface = true;
} }
if (false === $searchInterface) { if(false === $searchInterface) {
throw new LoopException('Loop must implements one of the following interfaces : `PropelSearchLoopInterface`, `ArraySearchLoopInterface`', LoopException::SEARCH_INTERFACE_NOT_FOUND); throw new LoopException('Loop must implements one of the following interfaces : `PropelSearchLoopInterface`, `ArraySearchLoopInterface`', LoopException::SEARCH_INTERFACE_NOT_FOUND);
} }
/* Only PropelSearch allows timestamp and version */ /* Only PropelSearch allows timestamp and version */
if (!$this instanceof PropelSearchLoopInterface) { if(!$this instanceof PropelSearchLoopInterface) {
if (true === $this->timestampable) { if(true === $this->timestampable) {
throw new LoopException("Loop must implements 'PropelSearchLoopInterface' to be timestampable", LoopException::NOT_TIMESTAMPED); throw new LoopException("Loop must implements 'PropelSearchLoopInterface' to be timestampable", LoopException::NOT_TIMESTAMPED);
} }
if (true === $this->versionable) { if(true === $this->versionable) {
throw new LoopException("Loop must implements 'PropelSearchLoopInterface' to be versionable", LoopException::NOT_VERSIONED); throw new LoopException("Loop must implements 'PropelSearchLoopInterface' to be versionable", LoopException::NOT_VERSIONED);
} }
} }

View File

@@ -33,6 +33,7 @@ use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument; use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Model\AdminQuery; use Thelia\Model\AdminQuery;
use Thelia\Type;
/** /**
* *

View File

@@ -48,7 +48,7 @@ class AssociatedContent extends Content
{ {
protected $contentId; protected $contentId;
protected $contentPosition; protected $contentPosition;
/** /**
* @return ArgumentCollection * @return ArgumentCollection
*/ */

View File

@@ -88,7 +88,7 @@ class Auth extends BaseLoop implements ArraySearchLoopInterface
$module = $this->getModule(); $module = $this->getModule();
$access = $this->getAccess(); $access = $this->getAccess();
if (null !== $module) { if(null !== $module) {
$in = true; $in = true;
} }

View File

@@ -24,6 +24,7 @@
namespace Thelia\Core\Template\Loop; namespace Thelia\Core\Template\Loop;
use Propel\Runtime\ActiveQuery\Criteria; use Propel\Runtime\ActiveQuery\Criteria;
use Thelia\Core\Template\Element\BaseI18nLoop; use Thelia\Core\Template\Element\BaseI18nLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\PropelSearchLoopInterface; use Thelia\Core\Template\Element\PropelSearchLoopInterface;
use Thelia\Core\Template\Loop\Argument\Argument; use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Core\Template\Loop\Argument\ArgumentCollection;

View File

@@ -16,6 +16,7 @@ use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\Argument; use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Model\CountryQuery; use Thelia\Model\CountryQuery;
use Thelia\TaxEngine\TaxEngine;
use Thelia\Type; use Thelia\Type;
class Cart extends BaseLoop implements ArraySearchLoopInterface class Cart extends BaseLoop implements ArraySearchLoopInterface
@@ -57,7 +58,7 @@ class Cart extends BaseLoop implements ArraySearchLoopInterface
{ {
$cart = $this->getCart($this->request); $cart = $this->getCart($this->request);
if (null === $cart) { if(null === $cart) {
return array(); return array();
} }
@@ -78,9 +79,9 @@ class Cart extends BaseLoop implements ArraySearchLoopInterface
public function parseResults(LoopResult $loopResult) public function parseResults(LoopResult $loopResult)
{ {
$taxCountry = CountryQuery::create()->findPk(64); // @TODO : make it magic; $taxCountry = TaxEngine::getInstance($this->request->getSession())->getDeliveryCountry();
foreach ($loopResult->getResultDataCollection() as $cartItem) { foreach($loopResult->getResultDataCollection() as $cartItem) {
$product = $cartItem->getProduct(); $product = $cartItem->getProduct();
$productSaleElement = $cartItem->getProductSaleElements(); $productSaleElement = $cartItem->getProductSaleElements();

View File

@@ -125,9 +125,9 @@ class CategoryPath extends BaseI18nLoop implements ArraySearchLoopInterface
public function parseResults(LoopResult $loopResult) public function parseResults(LoopResult $loopResult)
{ {
foreach ($loopResult->getResultDataCollection() as $result) { foreach($loopResult->getResultDataCollection() as $result) {
$loopResultRow = new LoopResultRow($result); $loopResultRow = new LoopResultRow($result);
foreach ($result as $output => $outputValue) { foreach($result as $output => $outputValue) {
$loopResultRow->set($output, $outputValue); $loopResultRow->set($output, $outputValue);
} }
$loopResult->addRow($loopResultRow); $loopResult->addRow($loopResultRow);

View File

@@ -99,9 +99,9 @@ class CategoryTree extends BaseI18nLoop implements ArraySearchLoopInterface
public function parseResults(LoopResult $loopResult) public function parseResults(LoopResult $loopResult)
{ {
foreach ($loopResult->getResultDataCollection() as $result) { foreach($loopResult->getResultDataCollection() as $result) {
$loopResultRow = new LoopResultRow($result); $loopResultRow = new LoopResultRow($result);
foreach ($result as $output => $outputValue) { foreach($result as $output => $outputValue) {
$loopResultRow->set($output, $outputValue); $loopResultRow->set($output, $outputValue);
} }
$loopResult->addRow($loopResultRow); $loopResult->addRow($loopResultRow);

View File

@@ -24,6 +24,7 @@
namespace Thelia\Core\Template\Loop; namespace Thelia\Core\Template\Loop;
use Propel\Runtime\ActiveQuery\Criteria; use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\Util\PropelModelPager;
use Thelia\Condition\ConditionFactory; use Thelia\Condition\ConditionFactory;
use Thelia\Condition\Implementation\ConditionInterface; use Thelia\Condition\Implementation\ConditionInterface;
use Thelia\Core\HttpFoundation\Request; use Thelia\Core\HttpFoundation\Request;

View File

@@ -158,7 +158,6 @@ class Currency extends BaseI18nLoop implements PropelSearchLoopInterface
} }
/* perform search */ /* perform search */
return $search; return $search;
} }

View File

@@ -36,6 +36,9 @@ use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Model\CustomerQuery; use Thelia\Model\CustomerQuery;
use Thelia\Type\TypeCollection; use Thelia\Type\TypeCollection;
use Thelia\Type; use Thelia\Type;
use Thelia\Model\OrderQuery;
use Thelia\Model\Map\OrderAddressTableMap;
use Thelia\Model\Map\OrderTableMap;
/** /**
* *
@@ -205,6 +208,7 @@ class Customer extends BaseLoop implements SearchLoopInterface, PropelSearchLoop
$search->orderByCreatedAt(Criteria::DESC); $search->orderByCreatedAt(Criteria::DESC);
break; break;
} }
} }

View File

@@ -29,6 +29,7 @@ use Thelia\Exception\OrderException;
use Thelia\Model\CountryQuery; use Thelia\Model\CountryQuery;
use Thelia\Module\BaseModule; use Thelia\Module\BaseModule;
use Thelia\Module\DeliveryModuleInterface; use Thelia\Module\DeliveryModuleInterface;
use Thelia\TaxEngine\TaxEngine;
/** /**
* Class Delivery * Class Delivery
@@ -59,7 +60,7 @@ class Delivery extends BaseSpecificModule
throw new \InvalidArgumentException('Cannot found country id: `' . $countryId . '` in delivery loop'); throw new \InvalidArgumentException('Cannot found country id: `' . $countryId . '` in delivery loop');
} }
} else { } else {
$country = CountryQuery::create()->findOneByByDefault(1); $country = TaxEngine::getInstance($this->request->getSession())->getDeliveryCountry();
} }
foreach ($loopResult->getResultDataCollection() as $deliveryModule) { foreach ($loopResult->getResultDataCollection() as $deliveryModule) {
@@ -73,8 +74,8 @@ class Delivery extends BaseSpecificModule
try { try {
$postage = $moduleInstance->getPostage($country); $postage = $moduleInstance->getPostage($country);
} catch (OrderException $e) { } catch(OrderException $e) {
switch ($e->getCode()) { switch($e->getCode()) {
case OrderException::DELIVERY_MODULE_UNAVAILABLE: case OrderException::DELIVERY_MODULE_UNAVAILABLE:
/* do not show this delivery module */ /* do not show this delivery module */
continue(2); continue(2);

View File

@@ -126,6 +126,7 @@ class Folder extends BaseI18nLoop implements PropelSearchLoopInterface
if ($visible !== BooleanOrBothType::ANY) $search->filterByVisible($visible ? 1 : 0); if ($visible !== BooleanOrBothType::ANY) $search->filterByVisible($visible ? 1 : 0);
$orders = $this->getOrder(); $orders = $this->getOrder();
foreach ($orders as $order) { foreach ($orders as $order) {

View File

@@ -135,9 +135,9 @@ class FolderPath extends BaseI18nLoop implements ArraySearchLoopInterface
public function parseResults(LoopResult $loopResult) public function parseResults(LoopResult $loopResult)
{ {
foreach ($loopResult->getResultDataCollection() as $result) { foreach($loopResult->getResultDataCollection() as $result) {
$loopResultRow = new LoopResultRow($result); $loopResultRow = new LoopResultRow($result);
foreach ($result as $output => $outputValue) { foreach($result as $output => $outputValue) {
$loopResultRow->set($output, $outputValue); $loopResultRow->set($output, $outputValue);
} }
$loopResult->addRow($loopResultRow); $loopResult->addRow($loopResultRow);

View File

@@ -100,9 +100,9 @@ class FolderTree extends BaseI18nLoop implements ArraySearchLoopInterface
public function parseResults(LoopResult $loopResult) public function parseResults(LoopResult $loopResult)
{ {
foreach ($loopResult->getResultDataCollection() as $result) { foreach($loopResult->getResultDataCollection() as $result) {
$loopResultRow = new LoopResultRow($result); $loopResultRow = new LoopResultRow($result);
foreach ($result as $output => $outputValue) { foreach($result as $output => $outputValue) {
$loopResultRow->set($output, $outputValue); $loopResultRow->set($output, $outputValue);
} }
$loopResult->addRow($loopResultRow); $loopResult->addRow($loopResultRow);

View File

@@ -236,6 +236,7 @@ class Image extends BaseI18nLoop implements PropelSearchLoopInterface
$search->filterById($exclude, Criteria::NOT_IN); $search->filterById($exclude, Criteria::NOT_IN);
// echo "sql=".$search->toString(); // echo "sql=".$search->toString();
return $search; return $search;
} }

View File

@@ -38,6 +38,7 @@ use Thelia\Model\ModuleQuery;
use Thelia\Module\BaseModule; use Thelia\Module\BaseModule;
use Thelia\Type; use Thelia\Type;
use Thelia\Type\TypeCollection;
/** /**
* *
@@ -76,6 +77,13 @@ class Module extends BaseI18nLoop implements PropelSearchLoopInterface
)) ))
) )
), ),
new Argument(
'order',
new TypeCollection(
new Type\EnumListType(array('id', 'id_reverse', 'code', 'code_reverse', 'alpha', 'alpha_reverse', 'manual', 'manual_reverse', 'enabled', 'enabled_reverse'))
),
'manual'
),
Argument::createIntListTypeArgument('exclude'), Argument::createIntListTypeArgument('exclude'),
Argument::createBooleanOrBothTypeArgument('active', Type\BooleanOrBothType::ANY) Argument::createBooleanOrBothTypeArgument('active', Type\BooleanOrBothType::ANY)
); );
@@ -126,7 +134,42 @@ class Module extends BaseI18nLoop implements PropelSearchLoopInterface
$search->filterByActivate($active ? 1 : 0, Criteria::EQUAL); $search->filterByActivate($active ? 1 : 0, Criteria::EQUAL);
} }
$search->orderByPosition(); $orders = $this->getOrder();
foreach ($orders as $order) {
switch ($order) {
case "id":
$search->orderById(Criteria::ASC);
break;
case "id_reverse":
$search->orderById(Criteria::DESC);
break;
case "alpha":
$search->addAscendingOrderByColumn('i18n_TITLE');
break;
case "alpha_reverse":
$search->addDescendingOrderByColumn('i18n_TITLE');
break;
case "code":
$search->orderByCode(Criteria::ASC);
break;
case "code_reverse":
$search->orderByCode(Criteria::DESC);
break;
case "manual":
$search->orderByPosition(Criteria::ASC);
break;
case "manual_reverse":
$search->orderByPosition(Criteria::DESC);
break;
case "enabled":
$search->orderByActivate(Criteria::ASC);
break;
case "enabled_reverse":
$search->orderByActivate(Criteria::DESC);
break;
}
}
return $search; return $search;
@@ -153,19 +196,19 @@ class Module extends BaseI18nLoop implements PropelSearchLoopInterface
/* first test if module defines it's own config route */ /* first test if module defines it's own config route */
$routerId = "router." . $module->getBaseDir(); $routerId = "router." . $module->getBaseDir();
if ($this->container->has($routerId)) { if($this->container->has($routerId)) {
try { try {
if ($this->container->get($routerId)->match('/admin/module/' . $module->getCode())) { if($this->container->get($routerId)->match('/admin/module/' . $module->getCode())) {
$hasConfigurationInterface = true; $hasConfigurationInterface = true;
} }
} catch (ResourceNotFoundException $e) { } catch(ResourceNotFoundException $e) {
/* $hasConfigurationInterface stays false */ /* $hasConfigurationInterface stays false */
} }
} }
/* if not ; test if it uses admin inclusion : module_configuration.html */ /* if not ; test if it uses admin inclusion : module_configuration.html */
if (false === $hasConfigurationInterface) { if(false === $hasConfigurationInterface) {
if (file_exists( sprintf("%s/AdminIncludes/%s.html", $module->getAbsoluteBaseDir(), "module_configuration"))) { if(file_exists( sprintf("%s/AdminIncludes/%s.html", $module->getAbsoluteBaseDir(), "module_configuration"))) {
$hasConfigurationInterface = true; $hasConfigurationInterface = true;
} }
} }

View File

@@ -46,7 +46,7 @@ use Thelia\Type;
*/ */
class Order extends BaseLoop implements SearchLoopInterface, PropelSearchLoopInterface class Order extends BaseLoop implements SearchLoopInterface, PropelSearchLoopInterface
{ {
protected $countable = true; protected $countable = true;
protected $timestampable = true; protected $timestampable = true;
protected $versionable = false; protected $versionable = false;
@@ -175,6 +175,7 @@ class Order extends BaseLoop implements SearchLoopInterface, PropelSearchLoopInt
} }
return $search; return $search;
} }
public function parseResults(LoopResult $loopResult) public function parseResults(LoopResult $loopResult)
@@ -201,7 +202,6 @@ class Order extends BaseLoop implements SearchLoopInterface, PropelSearchLoopInt
->set("STATUS", $order->getStatusId()) ->set("STATUS", $order->getStatusId())
->set("LANG", $order->getLangId()) ->set("LANG", $order->getLangId())
->set("POSTAGE", $order->getPostage()) ->set("POSTAGE", $order->getPostage())
->set("DISCOUNT", $order->getDiscount())
->set("TOTAL_TAX", $tax) ->set("TOTAL_TAX", $tax)
->set("TOTAL_AMOUNT", $amount - $tax) ->set("TOTAL_AMOUNT", $amount - $tax)
->set("TOTAL_TAXED_AMOUNT", $amount) ->set("TOTAL_TAXED_AMOUNT", $amount)

View File

@@ -1,116 +0,0 @@
<?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\Condition\ConditionFactory;
use Thelia\Condition\Implementation\ConditionInterface;
use Thelia\Core\HttpFoundation\Request;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Element\PropelSearchLoopInterface;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Model\OrderCouponQuery;
use Thelia\Model\OrderQuery;
use Thelia\Type;
/**
*
* OrderCoupon loop
*
*
* Class OrderCoupon
* @package Thelia\Core\Template\Loop
* @author Etienne Roudeix <eroudeix@openstudio.fr>
*/
class OrderCoupon extends BaseLoop implements PropelSearchLoopInterface
{
/**
* Define all args used in your loop
*
* @return ArgumentCollection
*/
protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createIntTypeArgument('order', null, true)
);
}
public function buildModelCriteria()
{
$search = OrderCouponQuery::create();
$order = $this->getOrder();
$search->filterByOrderId($order, Criteria::EQUAL);
$search->orderById(Criteria::ASC);
return $search;
}
public function parseResults(LoopResult $loopResult)
{
$conditionFactory = $this->container->get('thelia.condition.factory');
/** @var OrderCoupon $orderCoupon */
foreach ($loopResult->getResultDataCollection() as $orderCoupon) {
$loopResultRow = new LoopResultRow($orderCoupon);
$conditions = $conditionFactory->unserializeConditionCollection(
$orderCoupon->getSerializedConditions()
);
$now = time();
$datediff = $orderCoupon->getExpirationDate()->getTimestamp() - $now;
$daysLeftBeforeExpiration = floor($datediff/(60*60*24));
$cleanedConditions = array();
foreach ($conditions->getConditions() as $condition) {
$cleanedConditions[] = $condition->getToolTip();
}
$loopResultRow->set("ID", $orderCoupon->getId())
->set("CODE", $orderCoupon->getCode())
->set("TITLE", $orderCoupon->getTitle())
->set("SHORT_DESCRIPTION", $orderCoupon->getShortDescription())
->set("DESCRIPTION", $orderCoupon->getDescription())
->set("EXPIRATION_DATE", $orderCoupon->getExpirationDate( OrderQuery::create()->findPk($this->getOrder())->getLangId() ))
->set("USAGE_LEFT", $orderCoupon->getMaxUsage())
->set("IS_CUMULATIVE", $orderCoupon->getIsCumulative())
->set("IS_REMOVING_POSTAGE", $orderCoupon->getIsRemovingPostage())
->set("IS_AVAILABLE_ON_SPECIAL_OFFERS", $orderCoupon->getIsAvailableOnSpecialOffers())
->set("AMOUNT", $orderCoupon->getAmount())
->set("APPLICATION_CONDITIONS", $cleanedConditions)
->set("DAY_LEFT_BEFORE_EXPIRATION", $daysLeftBeforeExpiration)
;
$loopResult->addRow($loopResultRow);
}
return $loopResult;
}
}

View File

@@ -72,7 +72,7 @@ class OrderProduct extends BaseLoop implements PropelSearchLoopInterface
$search->orderById(Criteria::ASC); $search->orderById(Criteria::ASC);
return $search; return $search;
} }
public function parseResults(LoopResult $loopResult) public function parseResults(LoopResult $loopResult)

View File

@@ -87,7 +87,7 @@ class OrderProductAttributeCombination extends BaseI18nLoop implements PropelSea
} }
return $search; return $search;
} }
public function parseResults(LoopResult $loopResult) public function parseResults(LoopResult $loopResult)

View File

@@ -42,6 +42,7 @@ use Thelia\Model\Map\ProductPriceTableMap;
use Thelia\Model\Map\ProductSaleElementsTableMap; use Thelia\Model\Map\ProductSaleElementsTableMap;
use Thelia\Model\Map\ProductTableMap; use Thelia\Model\Map\ProductTableMap;
use Thelia\Model\ProductQuery; use Thelia\Model\ProductQuery;
use Thelia\TaxEngine\TaxEngine;
use Thelia\Type\TypeCollection; use Thelia\Type\TypeCollection;
use Thelia\Type; use Thelia\Type;
@@ -464,7 +465,7 @@ class Product extends BaseI18nLoop implements PropelSearchLoopInterface, SearchL
return $this->parseComplex($loopResult); return $this->parseComplex($loopResult);
} }
$taxCountry = CountryQuery::create()->findPk(64); // @TODO : make it magic $taxCountry = TaxEngine::getInstance($this->request->getSession())->getDeliveryCountry();
foreach ($loopResult->getResultDataCollection() as $product) { foreach ($loopResult->getResultDataCollection() as $product) {
@@ -982,7 +983,7 @@ class Product extends BaseI18nLoop implements PropelSearchLoopInterface, SearchL
{ {
$loopResult = new LoopResult($results); $loopResult = new LoopResult($results);
$taxCountry = CountryQuery::create()->findPk(64); // @TODO : make it magic $taxCountry = TaxEngine::getInstance($this->request->getSession())->getDeliveryCountry();
foreach ($loopResult->getResultDataCollection() as $product) { foreach ($loopResult->getResultDataCollection() as $product) {

View File

@@ -37,6 +37,7 @@ use Thelia\Model\Base\ProductSaleElementsQuery;
use Thelia\Model\CountryQuery; use Thelia\Model\CountryQuery;
use Thelia\Model\CurrencyQuery; use Thelia\Model\CurrencyQuery;
use Thelia\Model\Map\ProductSaleElementsTableMap; use Thelia\Model\Map\ProductSaleElementsTableMap;
use Thelia\TaxEngine\TaxEngine;
use Thelia\Type\TypeCollection; use Thelia\Type\TypeCollection;
use Thelia\Type; use Thelia\Type;
@@ -145,7 +146,7 @@ class ProductSaleElements extends BaseLoop implements PropelSearchLoopInterface
public function parseResults(LoopResult $loopResult) public function parseResults(LoopResult $loopResult)
{ {
$taxCountry = CountryQuery::create()->findPk(64); // @TODO : make it magic $taxCountry = TaxEngine::getInstance($this->request->getSession())->getDeliveryCountry();
foreach ($loopResult->getResultDataCollection() as $PSEValue) { foreach ($loopResult->getResultDataCollection() as $PSEValue) {
$loopResultRow = new LoopResultRow($PSEValue); $loopResultRow = new LoopResultRow($PSEValue);

View File

@@ -103,4 +103,4 @@ class ProductTemplate extends BaseI18nLoop implements PropelSearchLoopInterface
return $loopResult; return $loopResult;
} }
} }

View File

@@ -33,6 +33,7 @@ use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument; use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Model\ProfileQuery; use Thelia\Model\ProfileQuery;
use Thelia\Type;
/** /**
* *

View File

@@ -23,12 +23,19 @@
namespace Thelia\Core\Template\Loop; namespace Thelia\Core\Template\Loop;
use Propel\Runtime\ActiveQuery\Criteria;
use Thelia\Core\Security\AccessManager;
use Thelia\Core\Template\Element\BaseI18nLoop;
use Thelia\Core\Template\Element\LoopResult; use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow; use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Element\PropelSearchLoopInterface;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection; use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument; use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Model\ModuleQuery;
use Thelia\Module\BaseModule;
use Thelia\Type; use Thelia\Type;
use Thelia\Core\Template\TemplateHelper; use Thelia\Core\Template\TemplateHelper;
use Thelia\Core\Template\TemplateDefinition; use Thelia\Core\Template\TemplateDefinition;
@@ -52,9 +59,9 @@ class Template extends BaseLoop implements ArraySearchLoopInterface
{ {
return new ArgumentCollection( return new ArgumentCollection(
new Argument( new Argument(
'template_type', 'template-type',
new Type\TypeCollection( new Type\TypeCollection(
new Type\EnumListType(array( new Type\EnumType(array(
'front-office', 'front-office',
'back-office', 'back-office',
'pdf', 'pdf',
@@ -65,9 +72,8 @@ class Template extends BaseLoop implements ArraySearchLoopInterface
); );
} }
public function buildArray() public function buildArray() {
{ $type = $this->getArg('template-type')->getValue();
$type = $this->getArg(template_type);
if ($type == 'front-office') if ($type == 'front-office')
$templateType = TemplateDefinition::FRONT_OFFICE; $templateType = TemplateDefinition::FRONT_OFFICE;

View File

@@ -30,9 +30,6 @@ namespace Thelia\Core\Template;
interface ParserInterface interface ParserInterface
{ {
/**
*
*/
public function render($realTemplateName, array $parameters = array()); public function render($realTemplateName, array $parameters = array());
public function setContent($content); public function setContent($content);
@@ -40,4 +37,26 @@ interface ParserInterface
public function getStatus(); public function getStatus();
public function setStatus($status); public function setStatus($status);
}
/**
* Add a template directory to the current template list
*
* @param unknown $templateType the template type (
*
* @param string $templateName the template name
* @param string $templateDirectory path to the template dirtectory
* @param unknown $key ???
* @param string $unshift ??? Etienne ?
*/
public function addTemplateDirectory($templateType, $templateName, $templateDirectory, $key, $unshift = false);
/**
* Return the registeted template directories for a givent template type
*
* @param unknown $templateType
* @throws InvalidArgumentException if the tempmateType is not defined
* @return array: an array of defined templates directories for the given template type
*/
public function getTemplateDirectories($templateType);
}

View File

@@ -23,6 +23,8 @@
namespace Thelia\Core\Template\Smarty\Assets; namespace Thelia\Core\Template\Smarty\Assets;
use Thelia\Core\Template\Assets\AsseticHelper;
use Thelia\Core\Template\TemplateDefinition;
use Thelia\Tools\URL; use Thelia\Tools\URL;
use Thelia\Core\Template\Assets\AssetManagerInterface; use Thelia\Core\Template\Assets\AssetManagerInterface;
@@ -35,12 +37,14 @@ class SmartyAssetsManager
private $web_root; private $web_root;
private $path_relative_to_web_root; private $path_relative_to_web_root;
static private $assetsDirectory = null;
/** /**
* Creates a new SmartyAssetsManager instance * Creates a new SmartyAssetsManager instance
* *
* @param AssetManagerInterface $assetsManager an asset manager instance * @param AssetManagerInterface $assetsManager an asset manager instance
* @param string $web_root the disk path to the web root (with final /) * @param string $web_root the disk path to the web root (with final /)
* @param string $path_relative_to_web_root the path (relative to web root) where the assets will be generated * @param string $path_relative_to_web_root the path (relative to web root) where the assets will be generated
*/ */
public function __construct(AssetManagerInterface $assetsManager, $web_root, $path_relative_to_web_root) public function __construct(AssetManagerInterface $assetsManager, $web_root, $path_relative_to_web_root)
{ {
@@ -52,46 +56,73 @@ class SmartyAssetsManager
public function prepareAssets($assets_directory, \Smarty_Internal_Template $template) public function prepareAssets($assets_directory, \Smarty_Internal_Template $template)
{ {
$tpl_dir = dirname($template->source->filepath); self::$assetsDirectory = $assets_directory;
$asset_dir_absolute_path = realpath($tpl_dir . DS . $assets_directory); $smartyParser = $template->smarty;
$templateDefinition = $smartyParser->getTemplateDefinition();
if ($asset_dir_absolute_path === false) throw new \Exception("Failed to get real path of '".$tpl_dir . DS . $assets_directory."'"); // Get the registered template directories for the current template path
$templateDirectories = $smartyParser->getTemplateDirectories($templateDefinition->getType());
$this->assetsManager->prepareAssets( if (isset($templateDirectories[$templateDefinition->getName()])) {
$asset_dir_absolute_path,
$this->web_root . $this->path_relative_to_web_root /* create assets foreach registered directory : main @ modules */
); foreach($templateDirectories[$templateDefinition->getName()] as $key => $directory) {
$tpl_path = $directory . DS . self::$assetsDirectory;
$asset_dir_absolute_path = realpath($tpl_path);
if (false !== $asset_dir_absolute_path) {
$this->assetsManager->prepareAssets(
$asset_dir_absolute_path,
$this->web_root . $this->path_relative_to_web_root,
$templateDefinition->getPath(),
$key
);
}
}
}
} }
public function computeAssetUrl($assetType, $params, \Smarty_Internal_Template $template) public function computeAssetUrl($assetType, $params, \Smarty_Internal_Template $template)
{ {
$file = $params['file']; $file = $params['file'];
$filters = isset($params['filters']) ? $params['filters'] : ''; $assetOrigin = isset($params['source']) ? $params['source'] : "0";
$debug = isset($params['debug']) ? trim(strtolower($params['debug'])) == 'true' : false; $filters = isset($params['filters']) ? $params['filters'] : '';
$debug = isset($params['debug']) ? trim(strtolower($params['debug'])) == 'true' : false;
// Get template base path /* we trick here relative thinking for file attribute */
$tpl_path = $template->source->filepath; $file = ltrim($file, '/');
while(substr($file, 0, 3) == '../') {
$file = substr($file, 3);
}
// Get basedir $smartyParser = $template->smarty;
$tpl_dir = dirname($tpl_path); $templateDefinition = $smartyParser->getTemplateDefinition();
// Create absolute dir path $templateDirectories = $smartyParser->getTemplateDirectories($templateDefinition->getType());
$asset_dir = realpath($tpl_dir) . DS . dirname($file);
$asset_file = basename($file);
if ($asset_dir === false) throw new \Exception("Failed to get real path of '".$tpl_dir.'/'.dirname($file)."'"); if (! isset($templateDirectories[$templateDefinition->getName()][$assetOrigin])) {
throw new \Exception("Failed to get real path of '/".dirname($file)."'");
}
$url = $this->assetsManager->processAsset( $assetSource = $templateDirectories[$templateDefinition->getName()][$assetOrigin];
$asset_dir . DS . $asset_file,
$this->web_root . $this->path_relative_to_web_root,
URL::getInstance()->absoluteUrl($this->path_relative_to_web_root, null, URL::PATH_TO_FILE /* path only */),
$assetType,
$filters,
$debug
);
return $url; $url = $this->assetsManager->processAsset(
$assetSource . DS . $file,
$assetSource . DS . self::$assetsDirectory,
$this->web_root . $this->path_relative_to_web_root,
$templateDefinition->getPath(),
$assetOrigin,
URL::getInstance()->absoluteUrl($this->path_relative_to_web_root, null, URL::PATH_TO_FILE /* path only */),
$assetType,
$filters,
$debug
);
return $url;
} }
public function processSmartyPluginCall($assetType, $params, $content, \Smarty_Internal_Template $template, &$repeat) public function processSmartyPluginCall($assetType, $params, $content, \Smarty_Internal_Template $template, &$repeat)

View File

@@ -27,6 +27,8 @@ use Thelia\Core\Template\Smarty\SmartyPluginDescriptor;
use Thelia\Core\Template\Smarty\AbstractSmartyPlugin; use Thelia\Core\Template\Smarty\AbstractSmartyPlugin;
use Thelia\Tools\URL; use Thelia\Tools\URL;
use Thelia\Core\Security\SecurityContext; use Thelia\Core\Security\SecurityContext;
use Thelia\Model\Config;
use Thelia\Model\ConfigQuery;
use Thelia\Core\Template\TemplateHelper; use Thelia\Core\Template\TemplateHelper;
/** /**
@@ -43,8 +45,8 @@ class AdminUtilities extends AbstractSmartyPlugin
$this->securityContext = $securityContext; $this->securityContext = $securityContext;
} }
protected function fetch_snippet($smarty, $templateName, $variablesArray) protected function fetch_snippet($smarty, $templateName, $variablesArray) {
{
$data = ''; $data = '';
$snippet_path = sprintf('%s/%s/%s.html', $snippet_path = sprintf('%s/%s/%s.html',
@@ -97,6 +99,7 @@ class AdminUtilities extends AbstractSmartyPlugin
$module === null ? array() : array($module), $module === null ? array() : array($module),
array($access)) array($access))
) { ) {
return $this->fetch_snippet($smarty, 'includes/admin-utilities-position-block', array( return $this->fetch_snippet($smarty, 'includes/admin-utilities-position-block', array(
'admin_utilities_go_up_url' => URL::getInstance()->absoluteUrl($path, array('mode' => 'up', $url_parameter => $id)), 'admin_utilities_go_up_url' => URL::getInstance()->absoluteUrl($path, array('mode' => 'up', $url_parameter => $id)),
'admin_utilities_in_place_edit_class' => $in_place_edit_class, 'admin_utilities_in_place_edit_class' => $in_place_edit_class,

View File

@@ -56,11 +56,10 @@ class Assets extends AbstractSmartyPlugin
{ {
try { try {
return $this->assetManager->processSmartyPluginCall('js', $params, $content, $template, $repeat); return $this->assetManager->processSmartyPluginCall('js', $params, $content, $template, $repeat);
} catch (\Exception $e) { } catch(\Exception $e) {
$catchException = $this->getNormalizedParam($params, array('catchException')); $catchException = $this->getNormalizedParam($params, array('catchException'));
if ($catchException == "true") { if($catchException == "true") {
$repeat = false; $repeat = false;
return null; return null;
} else { } else {
throw $e; throw $e;

View File

@@ -40,6 +40,7 @@ use Thelia\Model\OrderQuery;
use Thelia\Model\Product; use Thelia\Model\Product;
use Thelia\Model\ProductQuery; use Thelia\Model\ProductQuery;
use Thelia\Model\Tools\ModelCriteriaTools; use Thelia\Model\Tools\ModelCriteriaTools;
use Thelia\TaxEngine\TaxEngine;
use Thelia\Tools\DateTimeFormat; use Thelia\Tools\DateTimeFormat;
use Thelia\Cart\CartTrait; use Thelia\Cart\CartTrait;
@@ -181,10 +182,10 @@ class DataAccessFunctions extends AbstractSmartyPlugin
public function cartDataAccess($params, $smarty) public function cartDataAccess($params, $smarty)
{ {
if (array_key_exists('currentCountry', self::$dataAccessCache)) { if (array_key_exists('currentCountry', self::$dataAccessCache)) {
$currentCountry = self::$dataAccessCache['currentCountry']; $taxCountry = self::$dataAccessCache['currentCountry'];
} else { } else {
$currentCountry = CountryQuery::create()->findOneById(64); // @TODO : make it magic $taxCountry = TaxEngine::getInstance($this->request->getSession())->getDeliveryCountry();
self::$dataAccessCache['currentCountry'] = $currentCountry; self::$dataAccessCache['currentCountry'] = $taxCountry;
} }
$cart = $this->getCart($this->request); $cart = $this->getCart($this->request);
@@ -197,7 +198,7 @@ class DataAccessFunctions extends AbstractSmartyPlugin
$result = $cart->getTotalAmount(); $result = $cart->getTotalAmount();
break; break;
case "total_taxed_price": case "total_taxed_price":
$result = $cart->getTaxedAmount($currentCountry); $result = $cart->getTaxedAmount($taxCountry);
break; break;
} }
@@ -211,8 +212,6 @@ class DataAccessFunctions extends AbstractSmartyPlugin
switch ($attribute) { switch ($attribute) {
case 'postage': case 'postage':
return $order->getPostage(); return $order->getPostage();
case 'discount':
return $order->getDiscount();
case 'delivery_address': case 'delivery_address':
return $order->chosenDeliveryAddress; return $order->chosenDeliveryAddress;
case 'invoice_address': case 'invoice_address':
@@ -268,69 +267,69 @@ class DataAccessFunctions extends AbstractSmartyPlugin
$includeShipping = true; $includeShipping = true;
} }
if ($params['startDate'] == 'today') { if($params['startDate'] == 'today') {
$startDate = new \DateTime(); $startDate = new \DateTime();
$startDate->setTime(0, 0, 0); $startDate->setTime(0, 0, 0);
} elseif ($params['startDate'] == 'yesterday') { } elseif($params['startDate'] == 'yesterday') {
$startDate = new \DateTime(); $startDate = new \DateTime();
$startDate->setTime(0, 0, 0); $startDate->setTime(0, 0, 0);
$startDate->modify('-1 day'); $startDate->modify('-1 day');
} elseif ($params['startDate'] == 'this_month') { } elseif($params['startDate'] == 'this_month') {
$startDate = new \DateTime(); $startDate = new \DateTime();
$startDate->modify('first day of this month'); $startDate->modify('first day of this month');
$startDate->setTime(0, 0, 0); $startDate->setTime(0, 0, 0);
} elseif ($params['startDate'] == 'last_month') { } elseif($params['startDate'] == 'last_month') {
$startDate = new \DateTime(); $startDate = new \DateTime();
$startDate->modify('first day of last month'); $startDate->modify('first day of last month');
$startDate->setTime(0, 0, 0); $startDate->setTime(0, 0, 0);
} elseif ($params['startDate'] == 'this_year') { } elseif($params['startDate'] == 'this_year') {
$startDate = new \DateTime(); $startDate = new \DateTime();
$startDate->modify('first day of January this year'); $startDate->modify('first day of January this year');
$startDate->setTime(0, 0, 0); $startDate->setTime(0, 0, 0);
} elseif ($params['startDate'] == 'last_year') { } elseif($params['startDate'] == 'last_year') {
$startDate = new \DateTime(); $startDate = new \DateTime();
$startDate->modify('first day of December last year'); $startDate->modify('first day of December last year');
$startDate->setTime(0, 0, 0); $startDate->setTime(0, 0, 0);
} else { } else {
try { try {
$startDate = new \DateTime($params['startDate']); $startDate = new \DateTime($params['startDate']);
} catch (\Exception $e) { } catch(\Exception $e) {
throw new \InvalidArgumentException(sprintf("invalid startDate attribute '%s' in stats access function", $params['startDate'])); throw new \InvalidArgumentException(sprintf("invalid startDate attribute '%s' in stats access function", $params['startDate']));
} }
} }
if ($params['endDate'] == 'today') { if($params['endDate'] == 'today') {
$endDate = new \DateTime(); $endDate = new \DateTime();
$endDate->setTime(0, 0, 0); $endDate->setTime(0, 0, 0);
} elseif ($params['endDate'] == 'yesterday') { } elseif($params['endDate'] == 'yesterday') {
$endDate = new \DateTime(); $endDate = new \DateTime();
$endDate->setTime(0, 0, 0); $endDate->setTime(0, 0, 0);
$endDate->modify('-1 day'); $endDate->modify('-1 day');
} elseif ($params['endDate'] == 'this_month') { } elseif($params['endDate'] == 'this_month') {
$endDate = new \DateTime(); $endDate = new \DateTime();
$endDate->modify('last day of this month'); $endDate->modify('last day of this month');
$endDate->setTime(0, 0, 0); $endDate->setTime(0, 0, 0);
} elseif ($params['endDate'] == 'last_month') { } elseif($params['endDate'] == 'last_month') {
$endDate = new \DateTime(); $endDate = new \DateTime();
$endDate->modify('last day of last month'); $endDate->modify('last day of last month');
$endDate->setTime(0, 0, 0); $endDate->setTime(0, 0, 0);
} elseif ($params['endDate'] == 'this_year') { } elseif($params['endDate'] == 'this_year') {
$endDate = new \DateTime(); $endDate = new \DateTime();
$endDate->modify('last day of December this year'); $endDate->modify('last day of December this year');
$endDate->setTime(0, 0, 0); $endDate->setTime(0, 0, 0);
} elseif ($params['endDate'] == 'last_year') { } elseif($params['endDate'] == 'last_year') {
$endDate = new \DateTime(); $endDate = new \DateTime();
$endDate->modify('last day of January last year'); $endDate->modify('last day of January last year');
$endDate->setTime(0, 0, 0); $endDate->setTime(0, 0, 0);
} else { } else {
try { try {
$endDate = new \DateTime($params['endDate']); $endDate = new \DateTime($params['endDate']);
} catch (\Exception $e) { } catch(\Exception $e) {
throw new \InvalidArgumentException(sprintf("invalid endDate attribute '%s' in stats access function", $params['endDate'])); throw new \InvalidArgumentException(sprintf("invalid endDate attribute '%s' in stats access function", $params['endDate']));
} }
} }
switch ($params['key']) { switch( $params['key'] ) {
case 'sales' : case 'sales' :
return OrderQuery::getSaleStats($startDate, $endDate, $includeShipping); return OrderQuery::getSaleStats($startDate, $endDate, $includeShipping);
case 'orders' : case 'orders' :

View File

@@ -28,6 +28,7 @@ use Thelia\Core\Template\Smarty\AbstractSmartyPlugin;
use Thelia\Core\Template\Smarty\an; use Thelia\Core\Template\Smarty\an;
use Thelia\Core\Template\Smarty\SmartyPluginDescriptor; use Thelia\Core\Template\Smarty\SmartyPluginDescriptor;
/** /**
* Class Esi * Class Esi
* @package Thelia\Core\Template\Smarty\Plugins * @package Thelia\Core\Template\Smarty\Plugins
@@ -52,7 +53,7 @@ class Esi extends AbstractSmartyPlugin
$ignore_errors = $this->getParam($params, 'ignore_errors'); $ignore_errors = $this->getParam($params, 'ignore_errors');
$comment = $this->getParam($params, 'comment'); $comment = $this->getParam($params, 'comment');
if (null === $path) { if(null === $path) {
return; return;
} }
@@ -78,4 +79,4 @@ class Esi extends AbstractSmartyPlugin
new SmartyPluginDescriptor('function', 'render_esi', $this, 'renderEsi') new SmartyPluginDescriptor('function', 'render_esi', $this, 'renderEsi')
); );
} }
} }

View File

@@ -48,7 +48,7 @@ class Module extends AbstractSmartyPlugin
/** /**
* Process theliaModule template inclusion function * Process theliaModule template inclusion function
* *
* @param unknown $params * @param unknown $params
* @param \Smarty_Internal_Template $template * @param \Smarty_Internal_Template $template
* @internal param \Thelia\Core\Template\Smarty\Plugins\unknown $smarty * @internal param \Thelia\Core\Template\Smarty\Plugins\unknown $smarty
* *
@@ -60,7 +60,7 @@ class Module extends AbstractSmartyPlugin
if (false !== $location = $this->getParam($params, 'location', false)) { if (false !== $location = $this->getParam($params, 'location', false)) {
if ($this->debug === true && $this->request->get('SHOW_INCLUDE')) { if($this->debug === true && $this->request->get('SHOW_INCLUDE')) {
echo sprintf('<div style="background-color: #C82D26; border-color: #000000; border: solid;">%s</div>', $location); echo sprintf('<div style="background-color: #C82D26; border-color: #000000; border: solid;">%s</div>', $location);
} }
@@ -70,7 +70,7 @@ class Module extends AbstractSmartyPlugin
foreach ($modules as $module) { foreach ($modules as $module) {
if (null !== $moduleLimit && $moduleLimit != $module->getCode()) { if(null !== $moduleLimit && $moduleLimit != $module->getCode()) {
continue; continue;
} }

View File

@@ -14,6 +14,9 @@ use Thelia\Core\Template\Smarty\AbstractSmartyPlugin;
use Thelia\Core\Template\Exception\ResourceNotFoundException; use Thelia\Core\Template\Exception\ResourceNotFoundException;
use Thelia\Core\Template\ParserContext; use Thelia\Core\Template\ParserContext;
use Thelia\Core\Template\TemplateDefinition; use Thelia\Core\Template\TemplateDefinition;
use Thelia\Model\ConfigQuery;
use Thelia\Core\Template\TemplateHelper;
use Imagine\Exception\InvalidArgumentException;
use Thelia\Core\Translation\Translator; use Thelia\Core\Translation\Translator;
/** /**
@@ -32,7 +35,12 @@ class SmartyParser extends Smarty implements ParserInterface
protected $backOfficeTemplateDirectories = array(); protected $backOfficeTemplateDirectories = array();
protected $frontOfficeTemplateDirectories = array(); protected $frontOfficeTemplateDirectories = array();
protected $template = ""; protected $templateDirectories = array();
/**
* @var TemplateDefinition
*/
protected $templateDefinition = "";
protected $status = 200; protected $status = 200;
@@ -64,6 +72,7 @@ class SmartyParser extends Smarty implements ParserInterface
$this->setCompileDir($compile_dir); $this->setCompileDir($compile_dir);
$this->setCacheDir($cache_dir); $this->setCacheDir($cache_dir);
$this->debugging = $debug; $this->debugging = $debug;
// Prevent smarty ErrorException: Notice: Undefined index bla bla bla... // Prevent smarty ErrorException: Notice: Undefined index bla bla bla...
@@ -71,7 +80,7 @@ class SmartyParser extends Smarty implements ParserInterface
// 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. // 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) { if($debug) {
$this->setCaching(Smarty::CACHING_OFF); $this->setCaching(Smarty::CACHING_OFF);
$this->setForceCompile(true); $this->setForceCompile(true);
} else { } else {
@@ -80,6 +89,7 @@ class SmartyParser extends Smarty implements ParserInterface
//$this->enableSecurity(); //$this->enableSecurity();
// The default HTTP status // The default HTTP status
$this->status = 200; $this->status = 200;
@@ -87,6 +97,46 @@ class SmartyParser extends Smarty implements ParserInterface
$this->registerFilter('variable', array(__CLASS__, "theliaEscape")); $this->registerFilter('variable', array(__CLASS__, "theliaEscape"));
} }
/**
* Add a template directory to the current template list
*
* @param unknown $templateType the template type (a TemplateDefinition type constant)
* @param string $templateName the template name
* @param string $templateDirectory path to the template dirtectory
* @param unknown $key ???
* @param string $unshift ??? Etienne ?
*/
public function addTemplateDirectory($templateType, $templateName, $templateDirectory, $key, $unshift = false) {
if(true === $unshift && isset($this->templateDirectories[$templateType][$templateName])) {
$this->templateDirectories[$templateType][$templateName] = array_merge(
array(
$key => $templateDirectory,
),
$this->templateDirectories[$templateType][$templateName]
);
} else {
$this->templateDirectories[$templateType][$templateName][$key] = $templateDirectory;
}
}
/**
* Return the registeted template directories for a givent template type
*
* @param unknown $templateType
* @throws InvalidArgumentException
* @return multitype:
*/
public function getTemplateDirectories($templateType)
{
if (! isset($this->templateDirectories[$templateType])) {
throw new InvalidArgumentException("Failed to get template type %", $templateType);
}
return $this->templateDirectories[$templateType];
}
public function removeBlankLines($tpl_source, \Smarty_Internal_Template $template) public function removeBlankLines($tpl_source, \Smarty_Internal_Template $template)
{ {
return preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $tpl_source); return preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $tpl_source);
@@ -101,72 +151,52 @@ class SmartyParser extends Smarty implements ParserInterface
} }
} }
public function addBackOfficeTemplateDirectory($templateName, $templateDirectory, $key)
{
$this->backOfficeTemplateDirectories[$templateName][$key] = $templateDirectory;
}
public function addFrontOfficeTemplateDirectory($templateName, $templateDirectory, $key)
{
$this->frontOfficeTemplateDirectories[$templateName][$key] = $templateDirectory;
}
/** /**
* @param TemplateDefinition $templateDefinition * @param TemplateDefinition $templateDefinition
*/ */
public function setTemplate(TemplateDefinition $templateDefinition) public function setTemplateDefinition(TemplateDefinition $templateDefinition)
{ {
$this->template = $templateDefinition->getPath(); $this->templateDefinition = $templateDefinition;
/* init template directories */ /* init template directories */
$this->setTemplateDir(array()); $this->setTemplateDir(array());
/* add main template directory */
$this->addTemplateDir($templateDefinition->getAbsolutePath(), 0);
/* define config directory */ /* define config directory */
$configDirectory = $templateDefinition->getAbsoluteConfigPath(); $configDirectory = THELIA_TEMPLATE_DIR . $this->getTemplate() . '/configs';
$this->setConfigDir($configDirectory); $this->setConfigDir($configDirectory);
/* add modules template directories */ /* add modules template directories */
switch ($templateDefinition->getType()) { $this->addTemplateDirectory(
case TemplateDefinition::FRONT_OFFICE: $templateDefinition->getType(),
/* do not pass array directly to addTemplateDir since we cant control on keys */ $templateDefinition->getName(),
if (isset($this->frontOfficeTemplateDirectories[$templateDefinition->getName()])) { THELIA_TEMPLATE_DIR . $this->getTemplate(),
foreach ($this->frontOfficeTemplateDirectories[$templateDefinition->getName()] as $key => $directory) { '0',
$this->addTemplateDir($directory, $key); true
} );
}
break;
case TemplateDefinition::BACK_OFFICE: /* do not pass array directly to addTemplateDir since we cant control on keys */
/* do not pass array directly to addTemplateDir since we cant control on keys */ if (isset($this->templateDirectories[$templateDefinition->getType()][$templateDefinition->getName()])) {
if (isset($this->backOfficeTemplateDirectories[$templateDefinition->getName()])) { foreach($this->templateDirectories[$templateDefinition->getType()][$templateDefinition->getName()] as $key => $directory) {
foreach ($this->backOfficeTemplateDirectories[$templateDefinition->getName()] as $key => $directory) { $this->addTemplateDir($directory, $key);
$this->addTemplateDir($directory, $key); }
}
}
break;
case TemplateDefinition::PDF:
break;
default:
break;
} }
} }
public function getTemplateDefinition()
{
return $this->templateDefinition;
}
public function getTemplate() public function getTemplate()
{ {
return $this->template; return $this->templateDefinition->getPath();
} }
/** /**
* Return a rendered template, either from file or ftom a string * Return a rendered template, either from file or ftom a string
* *
* @param string $resourceType either 'string' (rendering from a string) or 'file' (rendering a file) * @param string $resourceType either 'string' (rendering from a string) or 'file' (rendering a file)
* @param string $resourceContent the resource content (a text, or a template file name) * @param string $resourceContent the resource content (a text, or a template file name)
* @param array $parameters an associative array of names / value pairs * @param array $parameters an associative array of names / value pairs
* *
* @return string the rendered template text * @return string the rendered template text
*/ */
@@ -185,8 +215,8 @@ class SmartyParser extends Smarty implements ParserInterface
/** /**
* Return a rendered template file * Return a rendered template file
* *
* @param string $realTemplateName the template name (from the template directory) * @param string $realTemplateName the template name (from the template directory)
* @param array $parameters an associative array of names / value pairs * @param array $parameters an associative array of names / value pairs
* @return string the rendered template text * @return string the rendered template text
*/ */
public function render($realTemplateName, array $parameters = array()) public function render($realTemplateName, array $parameters = array())
@@ -201,8 +231,8 @@ class SmartyParser extends Smarty implements ParserInterface
/** /**
* Return a rendered template text * Return a rendered template text
* *
* @param string $templateText the template text * @param string $templateText the template text
* @param array $parameters an associative array of names / value pairs * @param array $parameters an associative array of names / value pairs
* @return string the rendered template text * @return string the rendered template text
*/ */
public function renderString($templateText, array $parameters = array()) public function renderString($templateText, array $parameters = array())

View File

@@ -35,6 +35,13 @@ class TemplateDefinition
const PDF_SUBDIR = 'pdf/'; const PDF_SUBDIR = 'pdf/';
const EMAIL_SUBDIR = 'email/'; const EMAIL_SUBDIR = 'email/';
protected static $standardTemplatesSubdirs = array(
self::FRONT_OFFICE => self::FRONT_OFFICE_SUBDIR,
self::BACK_OFFICE => self::BACK_OFFICE_SUBDIR,
self::PDF => self::PDF_SUBDIR,
self::EMAIL => self::EMAIL_SUBDIR,
);
/** /**
* @var the template directory name (e.g. 'default') * @var the template directory name (e.g. 'default')
*/ */
@@ -50,12 +57,13 @@ class TemplateDefinition
*/ */
protected $type; protected $type;
public function __construct($name, $type) public function __construct($name, $type)
{ {
$this->name = $name; $this->name = $name;
$this->type = $type; $this->type = $type;
switch ($type) { switch($type) {
case TemplateDefinition::FRONT_OFFICE: case TemplateDefinition::FRONT_OFFICE:
$this->path = self::FRONT_OFFICE_SUBDIR . $name; $this->path = self::FRONT_OFFICE_SUBDIR . $name;
break; break;
@@ -82,17 +90,14 @@ class TemplateDefinition
public function setName($name) public function setName($name)
{ {
$this->name = $name; $this->name = $name;
return $this; return $this;
} }
public function getI18nPath() public function getI18nPath() {
{
return $this->getPath() . DS . 'I18n'; return $this->getPath() . DS . 'I18n';
} }
public function getAbsoluteI18nPath() public function getAbsoluteI18nPath() {
{
return THELIA_TEMPLATE_DIR . $this->getI18nPath(); return THELIA_TEMPLATE_DIR . $this->getI18nPath();
} }
@@ -101,8 +106,7 @@ class TemplateDefinition
return $this->path; return $this->path;
} }
public function getAbsolutePath() public function getAbsolutePath() {
{
return THELIA_TEMPLATE_DIR . $this->getPath(); return THELIA_TEMPLATE_DIR . $this->getPath();
} }
@@ -111,15 +115,13 @@ class TemplateDefinition
return $this->getPath() . DS . 'configs'; return $this->getPath() . DS . 'configs';
} }
public function getAbsoluteConfigPath() public function getAbsoluteConfigPath() {
{
return THELIA_TEMPLATE_DIR . $this->getConfigPath(); return THELIA_TEMPLATE_DIR . $this->getConfigPath();
} }
public function setPath($path) public function setPath($path)
{ {
$this->path = $path; $this->path = $path;
return $this; return $this;
} }
@@ -131,7 +133,13 @@ class TemplateDefinition
public function setType($type) public function setType($type)
{ {
$this->type = $type; $this->type = $type;
return $this; return $this;
} }
/**
* Returns an iterator on the standard templates subdir names
*/
public static function getStandardTemplatesSubdirsIterator() {
return new \ArrayIterator(self::$standardTemplatesSubdirs);
}
} }

View File

@@ -40,17 +40,16 @@ class TemplateHelper
private function __construct() {} private function __construct() {}
public static function getInstance() public static function getInstance() {
{
if (self::$instance == null) self::$instance = new TemplateHelper(); if (self::$instance == null) self::$instance = new TemplateHelper();
return self::$instance; return self::$instance;
} }
/** /**
* @return TemplateDefinition * @return TemplateDefinition
*/ */
public function getActiveMailTemplate() public function getActiveMailTemplate() {
{
return new TemplateDefinition( return new TemplateDefinition(
ConfigQuery::read('active-mail-template', 'default'), ConfigQuery::read('active-mail-template', 'default'),
TemplateDefinition::EMAIL TemplateDefinition::EMAIL
@@ -60,8 +59,7 @@ class TemplateHelper
/** /**
* @return TemplateDefinition * @return TemplateDefinition
*/ */
public function getActivePdfTemplate() public function getActivePdfTemplate() {
{
return new TemplateDefinition( return new TemplateDefinition(
ConfigQuery::read('active-pdf-template', 'default'), ConfigQuery::read('active-pdf-template', 'default'),
TemplateDefinition::PDF TemplateDefinition::PDF
@@ -71,8 +69,7 @@ class TemplateHelper
/** /**
* @return TemplateDefinition * @return TemplateDefinition
*/ */
public function getActiveAdminTemplate() public function getActiveAdminTemplate() {
{
return new TemplateDefinition( return new TemplateDefinition(
ConfigQuery::read('active-admin-template', 'default'), ConfigQuery::read('active-admin-template', 'default'),
TemplateDefinition::BACK_OFFICE TemplateDefinition::BACK_OFFICE
@@ -82,44 +79,62 @@ class TemplateHelper
/** /**
* @return TemplateDefinition * @return TemplateDefinition
*/ */
public function getActiveFrontTemplate() public function getActiveFrontTemplate() {
{
return new TemplateDefinition( return new TemplateDefinition(
ConfigQuery::read('active-front-template', 'default'), ConfigQuery::read('active-front-template', 'default'),
TemplateDefinition::FRONT_OFFICE TemplateDefinition::FRONT_OFFICE
); );
} }
public function getList($templateType) /**
{ * Returns an array which contains all standard template definitions
*/
public function getStandardTemplateDefinitions() {
return array(
$this->getActiveFrontTemplate(),
$this->getActiveAdminTemplate(),
$this->getActivePdfTemplate(),
$this->getActiveMailTemplate(),
);
}
/**
* Return a list of existing templates for a given template type
*
* @param int $templateType the template type
* @return An array of \Thelia\Core\Template\TemplateDefinition
*/
public function getList($templateType) {
$list = $exclude = array(); $list = $exclude = array();
if ($templateType == TemplateDefinition::BACK_OFFICE) { $tplIterator = TemplateDefinition::getStandardTemplatesSubdirsIterator();
$baseDir = THELIA_TEMPLATE_DIR.TemplateDefinition::BACK_OFFICE_SUBDIR;
} elseif ($templateType == TemplateDefinition::PDF) {
$baseDir = THELIA_TEMPLATE_DIR.TemplateDefinition::PDF_SUBDIR;
} else {
$baseDir = THELIA_TEMPLATE_DIR.TemplateDefinition::FRONT_OFFICE_SUBDIR;
$exclude = array(TemplateDefinition::BACK_OFFICE_SUBDIR, TemplateDefinition::PDF_SUBDIR); foreach($tplIterator as $type => $subdir) {
if ($templateType == $type) {
$baseDir = THELIA_TEMPLATE_DIR.$subdir;
// Every subdir of the basedir is supposed to be a template.
$di = new \DirectoryIterator($baseDir);
foreach ($di as $file) {
// Ignore 'dot' elements
if ($file->isDot() || ! $file->isDir()) continue;
// Ignore reserved directory names
if (in_array($file->getFilename()."/", $exclude)) continue;
$list[] = new TemplateDefinition($file->getFilename(), $templateType);
}
return $list;
}
} }
// Every subdir of the basedir is supposed to be a template.
$di = new \DirectoryIterator($baseDir);
foreach ($di as $file) {
// Ignore 'dot' elements
if ($file->isDot() || ! $file->isDir()) continue;
// Ignore reserved directory names
if (in_array($file->getFilename()."/", $exclude)) continue;
$list[] = new TemplateDefinition($file->getFilename(), $templateType);
}
return $list;
} }
protected function normalize_path($path) protected function normalize_path($path)
{ {
$path = str_replace( $path = str_replace(
@@ -140,27 +155,28 @@ class TemplateHelper
* 'translation' => the text translation, or an empty string if none available. * 'translation' => the text translation, or an empty string if none available.
* 'dollar' => true if the translatable text contains a $ * 'dollar' => true if the translatable text contains a $
* *
* @param string $directory the path to the directory to examine * @param string $directory the path to the directory to examine
* @param string $walkMode type of file scanning: WALK_MODE_PHP or WALK_MODE_TEMPLATE * @param string $walkMode type of file scanning: WALK_MODE_PHP or WALK_MODE_TEMPLATE
* @param \Thelia\Core\Translation\Translator $translator the current translator * @param \Thelia\Core\Translation\Translator $translator the current translator
* @param string $currentLocale the current locale * @param string $currentLocale the current locale
* @param array $strings the list of strings * @param array $strings the list of strings
* @throws \InvalidArgumentException if $walkMode contains an invalid value * @throws \InvalidArgumentException if $walkMode contains an invalid value
* @return number the total number of translatable texts * @return number the total number of translatable texts
*/ */
public function walkDir($directory, $walkMode, Translator $translator, $currentLocale, &$strings) public function walkDir($directory, $walkMode, Translator $translator, $currentLocale, &$strings) {
{
$num_texts = 0; $num_texts = 0;
if ($walkMode == self::WALK_MODE_PHP) { if ($walkMode == self::WALK_MODE_PHP) {
$prefix = '\-\>[\s]*trans[\s]*\('; $prefix = '\-\>[\s]*trans[\s]*\(';
$allowed_exts = array('php'); $allowed_exts = array('php');
} elseif ($walkMode == self::WALK_MODE_TEMPLATE) { } else if ($walkMode == self::WALK_MODE_TEMPLATE) {
$prefix = '\{intl[\s]l='; $prefix = '\{intl[\s]l=';
$allowed_exts = array('html', 'tpl', 'xml'); $allowed_exts = array('html', 'tpl', 'xml');
} else { }
else {
throw new \InvalidArgumentException( throw new \InvalidArgumentException(
Translator::getInstance()->trans('Invalid value for walkMode parameter: %value', array('%value' => $walkMode)) Translator::getInstance()->trans('Invalid value for walkMode parameter: %value', array('%value' => $walkMode))
); );
@@ -194,15 +210,18 @@ class TemplateHelper
Tlog::getInstance()->debug("Strings found: ", $matches[2]); Tlog::getInstance()->debug("Strings found: ", $matches[2]);
foreach ($matches[2] as $match) { foreach($matches[2] as $match) {
$hash = md5($match); $hash = md5($match);
if (isset($strings[$hash])) { if (isset($strings[$hash]))
if (! in_array($short_path, $strings[$hash]['files'])) { {
if (! in_array($short_path, $strings[$hash]['files']))
{
$strings[$hash]['files'][] = $short_path; $strings[$hash]['files'][] = $short_path;
} }
} else { }
else {
$num_texts++; $num_texts++;
// remove \' // remove \'
@@ -254,7 +273,9 @@ class TemplateHelper
fwrite($fp, ");\n"); fwrite($fp, ");\n");
@fclose($fp); @fclose($fp);
} else { }
else
{
throw new \RuntimeException( throw new \RuntimeException(
Translator::getInstance()->trans( Translator::getInstance()->trans(
'Failed to open translation file %file. Please be sure that this file is writable by your Web server', 'Failed to open translation file %file. Please be sure that this file is writable by your Web server',

View File

@@ -49,11 +49,13 @@ use Thelia\Config\DefinePropel;
use Thelia\Core\Template\TemplateDefinition; use Thelia\Core\Template\TemplateDefinition;
use Thelia\Core\TheliaContainerBuilder; use Thelia\Core\TheliaContainerBuilder;
use Thelia\Core\DependencyInjection\Loader\XmlFileLoader; use Thelia\Core\DependencyInjection\Loader\XmlFileLoader;
use Thelia\Model\ConfigQuery;
use Symfony\Component\Config\FileLocator; use Symfony\Component\Config\FileLocator;
use Propel\Runtime\Propel; use Propel\Runtime\Propel;
use Propel\Runtime\Connection\ConnectionManagerSingle; use Propel\Runtime\Connection\ConnectionManagerSingle;
use Thelia\Core\Template\TemplateHelper; use Thelia\Core\Template\TemplateHelper;
use Thelia\Log\Tlog;
class Thelia extends Kernel class Thelia extends Kernel
{ {
@@ -104,6 +106,61 @@ class Thelia extends Kernel
} }
/**
* Add all module's standard templates to the parser environment
*
* @param TheliaParser $parser the parser
* @param Module $module the Module.
*/
protected function addStandardModuleTemplatesToParserEnvironment($parser, $module) {
$stdTpls = TemplateDefinition::getStandardTemplatesSubdirsIterator();
foreach($stdTpls as $templateType => $templateSubdirName) {
$this->addModuleTemplateToParserEnvironment($parser, $module, $templateType, $templateSubdirName);
}
}
/**
* Add a module template directory to the parser environment
*
* @param TheliaParser $parser the parser
* @param Module $module the Module.
* @param string $templateType the template type (one of the TemplateDefinition type constants)
* @param string $templateSubdirName the template subdirectory name (one of the TemplateDefinition::XXX_SUBDIR constants)
*/
protected function addModuleTemplateToParserEnvironment($parser, $module, $templateType, $templateSubdirName) {
// Get template path
$templateDirectory = $module->getAbsoluteTemplateDirectoryPath($templateSubdirName);
try {
$templateDirBrowser = new \DirectoryIterator($templateDirectory);
$code = ucfirst($module->getCode());
/* browse the directory */
foreach ($templateDirBrowser as $templateDirContent) {
/* is it a directory which is not . or .. ? */
if ($templateDirContent->isDir() && ! $templateDirContent->isDot()) {
$parser->addMethodCall(
'addTemplateDirectory',
array(
$templateType,
$templateDirContent->getFilename(),
$templateDirContent->getPathName(),
$code
)
);
}
}
}
catch (\UnexpectedValueException $ex) {
// The directory does not exists, ignore it.
}
}
/** /**
* *
* Load some configuration * Load some configuration
@@ -119,7 +176,7 @@ class Thelia extends Kernel
->depth(0) ->depth(0)
->in(THELIA_ROOT . "/core/lib/Thelia/Config/Resources"); ->in(THELIA_ROOT . "/core/lib/Thelia/Config/Resources");
foreach ($finder as $file) { foreach($finder as $file) {
$loader->load($file->getBaseName()); $loader->load($file->getBaseName());
} }
@@ -128,21 +185,19 @@ class Thelia extends Kernel
$translationDirs = array(); $translationDirs = array();
$parser = $container->getDefinition('thelia.parser'); $parser = $container->getDefinition('thelia.parser');
foreach ($modules as $module) { foreach ($modules as $module) {
try { try {
$definition = new Definition();
$defintion = new Definition(); $definition->setClass($module->getFullNamespace());
$defintion->setClass($module->getFullNamespace()); $definition->addMethodCall("setContainer", array(new Reference('service_container')));
$defintion->addMethodCall("setContainer", array(new Reference('service_container')));
$container->setDefinition( $container->setDefinition(
"module.".$module->getCode(), "module.".$module->getCode(),
$defintion $definition
); );
$code = ucfirst($module->getCode());
$loader = new XmlFileLoader($container, new FileLocator($module->getAbsoluteConfigPath())); $loader = new XmlFileLoader($container, new FileLocator($module->getAbsoluteConfigPath()));
$loader->load("config.xml"); $loader->load("config.xml");
@@ -150,79 +205,24 @@ class Thelia extends Kernel
$translationDirs[] = $dir; $translationDirs[] = $dir;
} }
/* is there a front-office template directory ? */ $this->addStandardModuleTemplatesToParserEnvironment($parser, $module);
$frontOfficeModuleTemplateDirectory = sprintf("%s%stemplates%s%s", $module->getAbsoluteBaseDir(), DS, DS, TemplateDefinition::FRONT_OFFICE_SUBDIR);
if (is_dir($frontOfficeModuleTemplateDirectory)) {
try {
$moduleFrontOfficeTemplateBrowser = new \DirectoryIterator($frontOfficeModuleTemplateDirectory);
} catch (\UnexpectedValueException $e) {
throw $e;
}
/* browse the directory */
foreach ($moduleFrontOfficeTemplateBrowser as $moduleFrontOfficeTemplateContent) {
/* is it a directory which is not . or .. ? */
if ($moduleFrontOfficeTemplateContent->isDir() && !$moduleFrontOfficeTemplateContent->isDot()) {
$parser->addMethodCall(
'addFrontOfficeTemplateDirectory',
array(
$moduleFrontOfficeTemplateContent->getFilename(),
$moduleFrontOfficeTemplateContent->getPathName(),
$code,
)
);
}
}
}
/* is there a back-office template directory ? */
$backOfficeModuleTemplateDirectory = sprintf("%s%stemplates%s%s", $module->getAbsoluteBaseDir(), DS, DS, TemplateDefinition::BACK_OFFICE_SUBDIR);
if (is_dir($backOfficeModuleTemplateDirectory)) {
try {
$moduleBackOfficeTemplateBrowser = new \DirectoryIterator($backOfficeModuleTemplateDirectory);
} catch (\UnexpectedValueException $e) {
throw $e;
}
/* browse the directory */
foreach ($moduleBackOfficeTemplateBrowser as $moduleBackOfficeTemplateContent) {
/* is it a directory which is not . or .. ? */
if ($moduleBackOfficeTemplateContent->isDir() && !$moduleBackOfficeTemplateContent->isDot()) {
$parser->addMethodCall(
'addBackOfficeTemplateDirectory',
array(
$moduleBackOfficeTemplateContent->getFilename(),
$moduleBackOfficeTemplateContent->getPathName(),
$code,
)
);
}
}
}
} catch (\InvalidArgumentException $e) { } catch (\InvalidArgumentException $e) {
// TODO: process module configuration exception Tlog::getInstance()->addError(sprintf("Failed to load module %s: %s", $module->getCode(), $e->getMessage()), $e);
} }
} }
// Load translation from templates // Load translation from templates
//core translation // core translation
$translationDirs[] = THELIA_ROOT . "core/lib/Thelia/Config/I18n"; $translationDirs[] = THELIA_ROOT . "core/lib/Thelia/Config/I18n";
// Standard templates (front, back, pdf, mail)
$th = TemplateHelper::getInstance(); $th = TemplateHelper::getInstance();
// admin template foreach($th->getStandardTemplateDefinitions() as $templateDefinition) {
if (is_dir($dir = $th->getActiveAdminTemplate()->getAbsoluteI18nPath())) { if (is_dir($dir = $templateDefinition->getAbsoluteI18nPath())) {
$translationDirs[] = $dir; $translationDirs[] = $dir;
} }
// front template
if (is_dir($dir = $th->getActiveFrontTemplate()->getAbsoluteI18nPath())) {
$translationDirs[] = $dir;
}
// PDF template
if (is_dir($dir = $th->getActivePdfTemplate()->getAbsoluteI18nPath())) {
$translationDirs[] = $dir;
} }
if ($translationDirs) { if ($translationDirs) {
@@ -370,5 +370,4 @@ class Thelia extends Kernel
//Nothing is load here but it's possible to load container configuration here. //Nothing is load here but it's possible to load container configuration here.
//exemple in sf2 : $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml'); //exemple in sf2 : $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
} }
} }

View File

@@ -215,7 +215,7 @@ class TheliaHttpKernel extends HttpKernel
protected function initSession(Request $request) protected function initSession(Request $request)
{ {
if (null === self::$session) { if(null === self::$session) {
$storage = new Session\Storage\NativeSessionStorage(); $storage = new Session\Storage\NativeSessionStorage();
if (Model\ConfigQuery::read("session_config.default")) { if (Model\ConfigQuery::read("session_config.default")) {

View File

@@ -40,7 +40,7 @@ class Translator extends BaseTranslator
public function getLocale() public function getLocale()
{ {
if ($this->container->isScopeActive('request') && $this->container->has('request')) { if($this->container->isScopeActive('request') && $this->container->has('request')) {
return $this->container->get('request')->getSession()->getLang()->getLocale(); return $this->container->get('request')->getSession()->getLang()->getLocale();
} }

View File

@@ -82,8 +82,15 @@ class CouponManager
if (count($this->coupons) > 0) { if (count($this->coupons) > 0) {
$couponsKept = $this->sortCoupons($this->coupons); $couponsKept = $this->sortCoupons($this->coupons);
$isRemovingPostage = $this->isCouponRemovingPostage($couponsKept);
$discount = $this->getEffect($couponsKept); $discount = $this->getEffect($couponsKept);
if ($isRemovingPostage) {
$postage = $this->facade->getCheckoutPostagePrice();
$discount += $postage;
}
// Just In Case test // Just In Case test
$checkoutTotalPrice = $this->facade->getCartTotalPrice(); $checkoutTotalPrice = $this->facade->getCartTotalPrice();
if ($discount >= $checkoutTotalPrice) { if ($discount >= $checkoutTotalPrice) {
@@ -96,24 +103,23 @@ class CouponManager
/** /**
* Check if there is a Coupon removing Postage * Check if there is a Coupon removing Postage
*
* @param array $couponsKept Array of CouponInterface sorted
*
* @return bool * @return bool
*/ */
public function isCouponRemovingPostage() protected function isCouponRemovingPostage(array $couponsKept)
{ {
if (count($this->coupons) == 0) { $isRemovingPostage = false;
return false;
}
$couponsKept = $this->sortCoupons($this->coupons);
/** @var CouponInterface $coupon */ /** @var CouponInterface $coupon */
foreach ($couponsKept as $coupon) { foreach ($couponsKept as $coupon) {
if ($coupon->isRemovingPostage()) { if ($coupon->isRemovingPostage()) {
return true; $isRemovingPostage = true;
} }
} }
return false; return $isRemovingPostage;
} }
/** /**

View File

@@ -23,6 +23,7 @@
namespace Thelia\Form; namespace Thelia\Form;
use Symfony\Component\Validator\ExecutionContextInterface; use Symfony\Component\Validator\ExecutionContextInterface;
use Thelia\Core\Translation\Translator;
use Thelia\Model\CustomerQuery; use Thelia\Model\CustomerQuery;
/** /**

View File

@@ -23,6 +23,7 @@
namespace Thelia\Form; namespace Thelia\Form;
use Symfony\Component\Validator\Constraints; use Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\ExecutionContextInterface; use Symfony\Component\Validator\ExecutionContextInterface;
use Thelia\Core\Translation\Translator; use Thelia\Core\Translation\Translator;
use Thelia\Model\ProfileQuery; use Thelia\Model\ProfileQuery;

View File

@@ -23,6 +23,7 @@
namespace Thelia\Form; namespace Thelia\Form;
use Symfony\Component\Validator\Constraints\GreaterThan; use Symfony\Component\Validator\Constraints\GreaterThan;
use Symfony\Component\Validator\Constraints\NotBlank;
use Thelia\Model\Currency; use Thelia\Model\Currency;
use Thelia\Core\Translation\Translator; use Thelia\Core\Translation\Translator;
@@ -87,4 +88,4 @@ class ProductCombinationGenerationForm extends BaseForm
{ {
return 'thelia_product_combination_generation_form'; return 'thelia_product_combination_generation_form';
} }
} }

View File

@@ -25,6 +25,7 @@ namespace Thelia\Form;
use Symfony\Component\Validator\Constraints\GreaterThan; use Symfony\Component\Validator\Constraints\GreaterThan;
use Thelia\Core\Translation\Translator; use Thelia\Core\Translation\Translator;
class ProductModificationForm extends ProductCreationForm class ProductModificationForm extends ProductCreationForm
{ {
use StandardDescriptionFieldsTrait; use StandardDescriptionFieldsTrait;

View File

@@ -35,7 +35,7 @@ trait SeoFieldsTrait
/** /**
* Add seo meta title, meta description and meta keywords fields * Add seo meta title, meta description and meta keywords fields
* *
* @param array $exclude name of the fields that should not be added to the form * @param array $exclude name of the fields that should not be added to the form
*/ */
protected function addSeoFields($exclude = array()) protected function addSeoFields($exclude = array())
{ {

View File

@@ -23,6 +23,8 @@
namespace Thelia\Form; namespace Thelia\Form;
use Symfony\Component\Validator\Constraints; use Symfony\Component\Validator\Constraints;
use Thelia\Model\ConfigQuery;
use Symfony\Component\Validator\ExecutionContextInterface;
use Thelia\Log\Tlog; use Thelia\Log\Tlog;
use Thelia\Core\Translation\Translator; use Thelia\Core\Translation\Translator;

View File

@@ -58,7 +58,7 @@ class CheckPermission extends BaseInstall
/** @var array Minimum server configuration necessary */ /** @var array Minimum server configuration necessary */
protected $minServerConfigurationNecessary = array( protected $minServerConfigurationNecessary = array(
'memory_limit' => 134217728, 'memory_limit' => 157286400,
'post_max_size' => 20971520, 'post_max_size' => 20971520,
'upload_max_filesize' => 2097152 'upload_max_filesize' => 2097152
); );

View File

@@ -138,4 +138,4 @@ class TlogDestinationFile extends AbstractTlogDestination
$this->fh = false; $this->fh = false;
} }
} }

View File

@@ -25,29 +25,27 @@ namespace Thelia\Log\Destination;
use Thelia\Log\AbstractTlogDestination; use Thelia\Log\AbstractTlogDestination;
class TlogDestinationJavascriptConsole extends AbstractTlogDestination class TlogDestinationJavascriptConsole extends AbstractTlogDestination {
{
public function getTitle()
{
return "Browser's Javascript console";
}
public function getDescription() public function getTitle() {
{ return "Browser's Javascript console";
return "The Thelia logs are displayed in your browser's Javascript console."; }
}
public function write(&$res) public function getDescription() {
{ return "The Thelia logs are displayed in your browser's Javascript console.";
$content = '<script>try {'."\n"; }
foreach ($this->_logs as $line) { public function write(&$res) {
$content .= "console.log('".str_replace("'", "\\'", str_replace(array("\r\n", "\r", "\n"), '\\n', $line))."');\n";
}
$content .= '} catch (ex) { alert("Les logs Thelia ne peuvent être affichés dans la console javascript:" + ex); }</script>'."\n"; $content = '<script>try {'."\n";
if (preg_match("|</body>|i", $res)) foreach($this->_logs as $line) {
$res = preg_replace("|</body>|i", "$content</html>", $res); $content .= "console.log('".str_replace("'", "\\'", str_replace(array("\r\n", "\r", "\n"), '\\n', $line))."');\n";
}
$content .= '} catch(ex) { alert("Les logs Thelia ne peuvent être affichés dans la console javascript:" + ex); }</script>'."\n";
if (preg_match("|</body>|i", $res))
$res = preg_replace("|</body>|i", "$content</html>", $res);
} }
} }

Some files were not shown because too many files have changed in this diff Show More