diff --git a/Adapter/Adapter_AddressFactory.php b/Adapter/Adapter_AddressFactory.php index 927f2be0..b76ce74d 100644 --- a/Adapter/Adapter_AddressFactory.php +++ b/Adapter/Adapter_AddressFactory.php @@ -26,25 +26,25 @@ class Adapter_AddressFactory { - /** - * Initilize an address corresponding to the specified id address or if empty to the - * default shop configuration - * @param null $id_address - * @param bool $with_geoloc - * @return Address - */ - public function findOrCreate($id_address = null, $with_geoloc = false) + /** + * Initilize an address corresponding to the specified id address or if empty to the + * default shop configuration + * @param null $id_address + * @param bool $with_geoloc + * @return Address + */ + public function findOrCreate($id_address = null, $with_geoloc = false) { $func_args = func_get_args(); return call_user_func_array(array('Address', 'initialize'), $func_args); } - /** - * Check if an address exists depending on given $id_address - * @param $id_address - * @return bool - */ - public function addressExists($id_address) + /** + * Check if an address exists depending on given $id_address + * @param $id_address + * @return bool + */ + public function addressExists($id_address) { return Address::addressExists($id_address); } diff --git a/Adapter/Adapter_CacheManager.php b/Adapter/Adapter_CacheManager.php new file mode 100644 index 00000000..9bd57f52 --- /dev/null +++ b/Adapter/Adapter_CacheManager.php @@ -0,0 +1,38 @@ + + * @copyright 2007-2015 PrestaShop SA + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * International Registered Trademark & Property of PrestaShop SA + */ + +class Adapter_CacheManager +{ + /** + * Cleans the cache for specific cache key. + * + * @param $key + */ + public function clean($key) + { + Cache::clean($key); + } +} diff --git a/Adapter/Adapter_Configuration.php b/Adapter/Adapter_Configuration.php index bcc3aebb..7e7c3ec8 100644 --- a/Adapter/Adapter_Configuration.php +++ b/Adapter/Adapter_Configuration.php @@ -26,14 +26,13 @@ class Adapter_Configuration implements Core_Business_ConfigurationInterface { - - /** - * Returns constant defined by given $key if exists or check directly into PrestaShop - * Configuration - * @param $key - * @return mixed - */ - public function get($key) + /** + * Returns constant defined by given $key if exists or check directly into PrestaShop + * Configuration + * @param $key + * @return mixed + */ + public function get($key) { if (defined($key)) { return constant($key); diff --git a/Adapter/Adapter_Database.php b/Adapter/Adapter_Database.php index 53d74def..2d95f721 100644 --- a/Adapter/Adapter_Database.php +++ b/Adapter/Adapter_Database.php @@ -26,23 +26,23 @@ class Adapter_Database implements Core_Foundation_Database_DatabaseInterface { - /** - * Perform a SELECT sql statement - * @param $sqlString - * @return array|false - * @throws PrestaShopDatabaseException - */ - public function select($sqlString) + /** + * Perform a SELECT sql statement + * @param $sqlString + * @return array|false + * @throws PrestaShopDatabaseException + */ + public function select($sqlString) { return Db::getInstance()->executeS($sqlString); } - /** - * Escape $unsafe to be used into a SQL statement - * @param $unsafeData - * @return string - */ - public function escape($unsafeData) + /** + * Escape $unsafe to be used into a SQL statement + * @param $unsafeData + * @return string + */ + public function escape($unsafeData) { // Prepare required params $html_ok = true; diff --git a/Adapter/Adapter_EntityMapper.php b/Adapter/Adapter_EntityMapper.php index ffa0a44c..b677edca 100644 --- a/Adapter/Adapter_EntityMapper.php +++ b/Adapter/Adapter_EntityMapper.php @@ -24,84 +24,81 @@ * International Registered Trademark & Property of PrestaShop SA */ -class Adapter_EntityMapper { +class Adapter_EntityMapper +{ + /** + * Load ObjectModel + * @param $id + * @param $id_lang + * @param $entity ObjectModel + * @param $entity_defs + * @param $id_shop + * @param $should_cache_objects + * @throws PrestaShopDatabaseException + */ + public function load($id, $id_lang, $entity, $entity_defs, $id_shop, $should_cache_objects) + { + // Load object from database if object id is present + $cache_id = 'objectmodel_' . $entity_defs['classname'] . '_' . (int)$id . '_' . (int)$id_shop . '_' . (int)$id_lang; + if (!$should_cache_objects || !Cache::isStored($cache_id)) { + $sql = new DbQuery(); + $sql->from($entity_defs['table'], 'a'); + $sql->where('a.`' . bqSQL($entity_defs['primary']) . '` = ' . (int)$id); - /** - * Load ObjectModel - * @param $id - * @param $id_lang - * @param $entity ObjectModel - * @param $entity_defs - * @param $id_shop - * @param $should_cache_objects - * @throws PrestaShopDatabaseException - */ - public function load($id, $id_lang, $entity, $entity_defs, $id_shop, $should_cache_objects) - { - // Load object from database if object id is present - $cache_id = 'objectmodel_' . $entity_defs['classname'] . '_' . (int)$id . '_' . (int)$id_shop . '_' . (int)$id_lang; - if (!$should_cache_objects || !Cache::isStored($cache_id)) { - $sql = new DbQuery(); - $sql->from($entity_defs['table'], 'a'); - $sql->where('a.`' . bqSQL($entity_defs['primary']) . '` = ' . (int)$id); + // Get lang informations + if ($id_lang && isset($entity_defs['multilang']) && $entity_defs['multilang']) { + $sql->leftJoin($entity_defs['table'] . '_lang', 'b', 'a.`' . bqSQL($entity_defs['primary']) . '` = b.`' . bqSQL($entity_defs['primary']) . '` AND b.`id_lang` = ' . (int)$id_lang); + if ($id_shop && !empty($entity_defs['multilang_shop'])) { + $sql->where('b.`id_shop` = ' . (int)$id_shop); + } + } - // Get lang informations - if ($id_lang && isset($entity_defs['multilang']) && $entity_defs['multilang']) { + // Get shop informations + if (Shop::isTableAssociated($entity_defs['table'])) { + $sql->leftJoin($entity_defs['table'] . '_shop', 'c', 'a.`' . bqSQL($entity_defs['primary']) . '` = c.`' . bqSQL($entity_defs['primary']) . '` AND c.`id_shop` = ' . (int)$id_shop); + } - $sql->leftJoin($entity_defs['table'] . '_lang', 'b', 'a.`' . bqSQL($entity_defs['primary']) . '` = b.`' . bqSQL($entity_defs['primary']) . '` AND b.`id_lang` = ' . (int)$id_lang); - if ($id_shop && !empty($entity_defs['multilang_shop'])) { - $sql->where('b.`id_shop` = ' . (int)$id_shop); - } - } - - // Get shop informations - if (Shop::isTableAssociated($entity_defs['table'])) { - $sql->leftJoin($entity_defs['table'] . '_shop', 'c', 'a.`' . bqSQL($entity_defs['primary']) . '` = c.`' . bqSQL($entity_defs['primary']) . '` AND c.`id_shop` = ' . (int)$id_shop); - } - - if ($object_datas = Db::getInstance()->getRow($sql)) { - if (!$id_lang && isset($entity_defs['multilang']) && $entity_defs['multilang']) { - - $sql = 'SELECT * + if ($object_datas = Db::getInstance()->getRow($sql)) { + if (!$id_lang && isset($entity_defs['multilang']) && $entity_defs['multilang']) { + $sql = 'SELECT * FROM `' . bqSQL(_DB_PREFIX_ . $entity_defs['table']) . '_lang` WHERE `' . bqSQL($entity_defs['primary']) . '` = ' . (int)$id - .(($id_shop && $entity->isLangMultishop()) ? ' AND `id_shop` = ' . (int)$id_shop : ''); + .(($id_shop && $entity->isLangMultishop()) ? ' AND `id_shop` = ' . (int)$id_shop : ''); - if ($object_datas_lang = Db::getInstance()->executeS($sql)) { - - foreach ($object_datas_lang as $row) { - foreach ($row as $key => $value) { - if ($key != $entity_defs['primary'] && array_key_exists($key, $entity)) { - if (!isset($object_datas[$key]) || !is_array($object_datas[$key])) - $object_datas[$key] = array(); - - $object_datas[$key][$row['id_lang']] = $value; - } - } - } - } - } - $entity->id = (int)$id; - foreach ($object_datas as $key => $value) { - if (array_key_exists($key, $entity)) { - $entity->{$key} = $value; - } else { - unset($object_datas[$key]); - } - } - if ($should_cache_objects) { - Cache::store($cache_id, $object_datas); - } - } - } else { - $object_datas = Cache::retrieve($cache_id); - if ($object_datas) { - $entity->id = (int)$id; - foreach ($object_datas as $key => $value) { - $entity->{$key} = $value; - } - } - } - } + if ($object_datas_lang = Db::getInstance()->executeS($sql)) { + foreach ($object_datas_lang as $row) { + foreach ($row as $key => $value) { + if ($key != $entity_defs['primary'] && array_key_exists($key, $entity)) { + if (!isset($object_datas[$key]) || !is_array($object_datas[$key])) { + $object_datas[$key] = array(); + } + $object_datas[$key][$row['id_lang']] = $value; + } + } + } + } + } + $entity->id = (int)$id; + foreach ($object_datas as $key => $value) { + if (array_key_exists($key, $entity)) { + $entity->{$key} = $value; + } else { + unset($object_datas[$key]); + } + } + if ($should_cache_objects) { + Cache::store($cache_id, $object_datas); + } + } + } else { + $object_datas = Cache::retrieve($cache_id); + if ($object_datas) { + $entity->id = (int)$id; + foreach ($object_datas as $key => $value) { + $entity->{$key} = $value; + } + } + } + } } diff --git a/Adapter/Adapter_Exception.php b/Adapter/Adapter_Exception.php index e8108f42..3472d628 100644 --- a/Adapter/Adapter_Exception.php +++ b/Adapter/Adapter_Exception.php @@ -26,4 +26,4 @@ class Adapter_Exception extends Core_Foundation_Exception_Exception { -} \ No newline at end of file +} diff --git a/Adapter/Adapter_HookManager.php b/Adapter/Adapter_HookManager.php new file mode 100644 index 00000000..1817d55d --- /dev/null +++ b/Adapter/Adapter_HookManager.php @@ -0,0 +1,54 @@ + + * @copyright 2007-2015 PrestaShop SA + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * International Registered Trademark & Property of PrestaShop SA + */ + +class Adapter_HookManager +{ + /** + * Execute modules for specified hook + * + * @param string $hook_name Hook Name + * @param array $hook_args Parameters for the functions + * @param int $id_module Execute hook for this module only + * @param bool $array_return If specified, module output will be set by name in an array + * @param bool $check_exceptions Check permission exceptions + * @param bool $use_push Force change to be refreshed on Dashboard widgets + * @param int $id_shop If specified, hook will be execute the shop with this ID + * + * @throws PrestaShopException + * + * @return string/array modules output + */ + public function exec($hook_name, + $hook_args = array(), + $id_module = null, + $array_return = false, + $check_exceptions = true, + $use_push = false, + $id_shop = null) + { + return Hook::exec($hook_name, $hook_args, $id_module, $array_return, $check_exceptions, $use_push, $id_shop); + } +} diff --git a/Adapter/Adapter_PackItemsManager.php b/Adapter/Adapter_PackItemsManager.php new file mode 100644 index 00000000..e535d84d --- /dev/null +++ b/Adapter/Adapter_PackItemsManager.php @@ -0,0 +1,87 @@ + + * @copyright 2007-2015 PrestaShop SA + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * International Registered Trademark & Property of PrestaShop SA + */ + +class Adapter_PackItemsManager +{ + /** + * Get the Products contained in the given Pack. + * + * @param Pack $pack + * @param integer $id_lang Optional + * @return Array[Product] The products contained in this Pack, with special dynamic attributes [pack_quantity, id_pack_product_attribute] + */ + public function getPackItems($pack, $id_lang = false) + { + if ($id_lang === false) { + $configuration = Adapter_ServiceLocator::get('Core_Business_ConfigurationInterface'); + $id_lang = (int)$configuration->get('PS_LANG_DEFAULT'); + } + return Pack::getItems($pack->id, $id_lang); + } + + /** + * Get all Packs that contains the given item in the corresponding declination. + * + * @param Product $item + * @param integer $item_attribute_id + * @param integer $id_lang Optional + * @return Array[Pack] The packs that contains the given item, with special dynamic attribute [pack_item_quantity] + */ + public function getPacksContainingItem($item, $item_attribute_id, $id_lang = false) + { + if ($id_lang === false) { + $configuration = Adapter_ServiceLocator::get('Core_Business_ConfigurationInterface'); + $id_lang = (int)$configuration->get('PS_LANG_DEFAULT'); + } + return Pack::getPacksContainingItem($item->id, $item_attribute_id, $id_lang); + } + + /** + * Is this product a pack? + * + * @param Product $product + * @return boolean + */ + public function isPack($product) + { + return Pack::isPack($product->id); + } + + /** + * Is this product in a pack? + * If $id_product_attribute specified, then will restrict search on the given combination, + * else this method will match a product if at least one of all its combination is in a pack. + * + * @param Product $product + * @param integer $id_product_attribute Optional combination of the product + * @return boolean + */ + public function isPacked($product, $id_product_attribute = false) + { + return Pack::isPacked($product->id, $id_product_attribute); + } + +} diff --git a/Adapter/Adapter_ProductPriceCalculator.php b/Adapter/Adapter_ProductPriceCalculator.php index 53676297..e87335f4 100644 --- a/Adapter/Adapter_ProductPriceCalculator.php +++ b/Adapter/Adapter_ProductPriceCalculator.php @@ -32,20 +32,19 @@ class Adapter_ProductPriceCalculator $id_product_attribute = null, $decimals = 6, $divisor = null, - $only_reduc = false, + $only_reduc = false, $usereduc = true, $quantity = 1, $force_associated_tax = false, $id_customer = null, $id_cart = null, - $id_address = null, + $id_address = null, &$specific_price_output = null, $with_ecotax = true, $use_group_reduction = true, Context $context = null, - $use_customer_price = true - ) - { + $use_customer_price = true + ) { return Product::getPriceStatic( $id_product, $usetax, diff --git a/Adapter/Adapter_ServiceLocator.php b/Adapter/Adapter_ServiceLocator.php index ba3ced50..2807eaca 100644 --- a/Adapter/Adapter_ServiceLocator.php +++ b/Adapter/Adapter_ServiceLocator.php @@ -26,29 +26,29 @@ class Adapter_ServiceLocator { - /** - * Set a service container Instance - * @var Core_Foundation_IoC_Container - */ - private static $service_container; + /** + * Set a service container Instance + * @var Core_Foundation_IoC_Container + */ + private static $service_container; - public static function setServiceContainerInstance(Core_Foundation_IoC_Container $container) - { - self::$service_container = $container; - } + public static function setServiceContainerInstance(Core_Foundation_IoC_Container $container) + { + self::$service_container = $container; + } - /** - * Get a service depending on its given $serviceName - * @param $serviceName - * @return mixed|object - * @throws Adapter_Exception - */ - public static function get($serviceName) - { - if (empty(self::$service_container) || is_null(self::$service_container)) { - throw new Adapter_Exception('Service container is not set.'); - } + /** + * Get a service depending on its given $serviceName + * @param $serviceName + * @return mixed|object + * @throws Adapter_Exception + */ + public static function get($serviceName) + { + if (empty(self::$service_container) || is_null(self::$service_container)) { + throw new Adapter_Exception('Service container is not set.'); + } - return self::$service_container->make($serviceName); - } + return self::$service_container->make($serviceName); + } } diff --git a/Adapter/Adapter_StockManager.php b/Adapter/Adapter_StockManager.php new file mode 100644 index 00000000..8fb21e33 --- /dev/null +++ b/Adapter/Adapter_StockManager.php @@ -0,0 +1,34 @@ + + * @copyright 2007-2015 PrestaShop SA + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * International Registered Trademark & Property of PrestaShop SA + */ + +class Adapter_StockManager +{ + + public function getStockAvailableByProduct($product, $id_product_attribute = null, $id_shop = null) + { + return new StockAvailable(StockAvailable::getStockAvailableIdByProductId($product->id, $id_product_attribute, $id_shop)); + } +} diff --git a/Core/Business/CMS/Core_Business_CMS_CMSRepository.php b/Core/Business/CMS/Core_Business_CMS_CMSRepository.php index 28bbec31..a7ea3a88 100644 --- a/Core/Business/CMS/Core_Business_CMS_CMSRepository.php +++ b/Core/Business/CMS/Core_Business_CMS_CMSRepository.php @@ -26,24 +26,24 @@ class Core_Business_CMS_CMSRepository extends Core_Foundation_Database_EntityRepository { - /** - * Return CMSRepository lang associative table name - * @return string - */ - private function getLanguageTableNameWithPrefix() - { - return $this->getTableNameWithPrefix() . '_lang'; - } + /** + * Return CMSRepository lang associative table name + * @return string + */ + private function getLanguageTableNameWithPrefix() + { + return $this->getTableNameWithPrefix() . '_lang'; + } - /** - * Return all CMSRepositories depending on $id_lang/$id_shop tuple - * @param $id_lang - * @param $id_shop - * @return array|null - */ - public function i10nFindAll($id_lang, $id_shop) - { - $sql = ' + /** + * Return all CMSRepositories depending on $id_lang/$id_shop tuple + * @param $id_lang + * @param $id_shop + * @return array|null + */ + public function i10nFindAll($id_lang, $id_shop) + { + $sql = ' SELECT * FROM `'.$this->getTableNameWithPrefix().'` c JOIN `'.$this->getPrefix().'cms_lang` cl ON c.`id_cms`= cl.`id_cms` @@ -52,20 +52,20 @@ class Core_Business_CMS_CMSRepository extends Core_Foundation_Database_EntityRep '; - return $this->hydrateMany($this->db->select($sql)); - } + return $this->hydrateMany($this->db->select($sql)); + } - /** - * Return all CMSRepositories depending on $id_lang/$id_shop tuple - * @param $id_cms - * @param $id_lang - * @param $id_shop - * @return CMS|null - * @throws Core_Foundation_Database_Exception - */ - public function i10nFindOneById($id_cms, $id_lang, $id_shop) - { - $sql = ' + /** + * Return all CMSRepositories depending on $id_lang/$id_shop tuple + * @param $id_cms + * @param $id_lang + * @param $id_shop + * @return CMS|null + * @throws Core_Foundation_Database_Exception + */ + public function i10nFindOneById($id_cms, $id_lang, $id_shop) + { + $sql = ' SELECT * FROM `'.$this->getTableNameWithPrefix().'` c JOIN `'.$this->getPrefix().'cms_lang` cl ON c.`id_cms`= cl.`id_cms` @@ -75,6 +75,6 @@ class Core_Business_CMS_CMSRepository extends Core_Foundation_Database_EntityRep LIMIT 0 , 1 '; - return $this->hydrateOne($this->db->select($sql)); - } + return $this->hydrateOne($this->db->select($sql)); + } } diff --git a/Core/Business/CMS/Core_Business_CMS_CMSRoleRepository.php b/Core/Business/CMS/Core_Business_CMS_CMSRoleRepository.php index 454f59e7..0d5e4bb8 100644 --- a/Core/Business/CMS/Core_Business_CMS_CMSRoleRepository.php +++ b/Core/Business/CMS/Core_Business_CMS_CMSRoleRepository.php @@ -26,19 +26,17 @@ class Core_Business_CMS_CMSRoleRepository extends Core_Foundation_Database_EntityRepository { - /** - * Return all CMSRoles which are already associated - * @return array|null - */ - public function getCMSRolesAssociated() - { - $sql = ' + /** + * Return all CMSRoles which are already associated + * @return array|null + */ + public function getCMSRolesAssociated() + { + $sql = ' SELECT * FROM `'.$this->getTableNameWithPrefix().'` WHERE `id_cms` != 0'; - return $this->hydrateMany($this->db->select($sql)); - } - - -} \ No newline at end of file + return $this->hydrateMany($this->db->select($sql)); + } +} diff --git a/Core/Business/Core_Business_ContainerBuilder.php b/Core/Business/Core_Business_ContainerBuilder.php index 9d624598..86e0f132 100644 --- a/Core/Business/Core_Business_ContainerBuilder.php +++ b/Core/Business/Core_Business_ContainerBuilder.php @@ -26,12 +26,12 @@ class Core_Business_ContainerBuilder { - /** - * Construct PrestaShop Core Service container - * @return Core_Foundation_IoC_Container - * @throws Core_Foundation_IoC_Exception - */ - public function build() + /** + * Construct PrestaShop Core Service container + * @return Core_Foundation_IoC_Container + * @throws Core_Foundation_IoC_Exception + */ + public function build() { $container = new Core_Foundation_IoC_Container; diff --git a/Core/Business/Email/Core_Business_Email_EmailLister.php b/Core/Business/Email/Core_Business_Email_EmailLister.php index 7aabfcff..7c5911e7 100644 --- a/Core/Business/Email/Core_Business_Email_EmailLister.php +++ b/Core/Business/Email/Core_Business_Email_EmailLister.php @@ -26,67 +26,66 @@ class Core_Business_Email_EmailLister { - private $filesystem; + private $filesystem; - public function __construct(Core_Foundation_FileSystem_FileSystem $fs) - { - // Register dependencies - $this->filesystem = $fs; - } + public function __construct(Core_Foundation_FileSystem_FileSystem $fs) + { + // Register dependencies + $this->filesystem = $fs; + } - /** - * Return the list of available mails - * @param null $lang - * @param null $dir - * @return array|null - */ - public function getAvailableMails($dir) - { - if (!is_dir($dir)) { - return null; - } + /** + * Return the list of available mails + * @param null $lang + * @param null $dir + * @return array|null + */ + public function getAvailableMails($dir) + { + if (!is_dir($dir)) { + return null; + } - $mail_directory = $this->filesystem->listEntriesRecursively($dir); - $mail_list = array(); + $mail_directory = $this->filesystem->listEntriesRecursively($dir); + $mail_list = array(); - // Remove unwanted .html / .txt / .tpl / .php / . / .. - foreach ($mail_directory as $mail) { + // Remove unwanted .html / .txt / .tpl / .php / . / .. + foreach ($mail_directory as $mail) { + if (strpos($mail->getFilename(), '.') !== false) { + $tmp = explode('.', $mail->getFilename()); - if (strpos($mail->getFilename(), '.') !== false) { - $tmp = explode('.', $mail->getFilename()); + // Check for filename existence (left part) and if extension is html (right part) + if (($tmp === false || !isset($tmp[0])) || (isset($tmp[1]) && $tmp[1] !== 'html')) { + continue; + } - // Check for filename existence (left part) and if extension is html (right part) - if ( ($tmp === false || !isset($tmp[0])) || (isset($tmp[1]) && $tmp[1] !== 'html')) { - continue; - } + $mail_name_no_ext = $tmp[0]; + if (!in_array($mail_name_no_ext, $mail_list)) { + $mail_list[] = $mail_name_no_ext; + } + } + } - $mail_name_no_ext = $tmp[0]; - if (!in_array($mail_name_no_ext, $mail_list)) { - $mail_list[] = $mail_name_no_ext; - } - } - } - - return $mail_list; - } + return $mail_list; + } - /** - * Give in input getAvailableMails(), will output a human readable and proper string name - * @return string - */ - public function getCleanedMailName($mail_name) - { - if (strpos($mail_name, '.') !== false) { - $tmp = explode('.', $mail_name); + /** + * Give in input getAvailableMails(), will output a human readable and proper string name + * @return string + */ + public function getCleanedMailName($mail_name) + { + if (strpos($mail_name, '.') !== false) { + $tmp = explode('.', $mail_name); - if ($tmp === false || !isset($tmp[0])) { - return $mail_name; - } + if ($tmp === false || !isset($tmp[0])) { + return $mail_name; + } - $mail_name = $tmp[0]; - } + $mail_name = $tmp[0]; + } - return ucfirst(str_replace(array('_', '-'), ' ', $mail_name)); - } -} \ No newline at end of file + return ucfirst(str_replace(array('_', '-'), ' ', $mail_name)); + } +} diff --git a/Core/Business/Payment/Core_Business_Payment_PaymentOption.php b/Core/Business/Payment/Core_Business_Payment_PaymentOption.php index 5c75f3ad..5f7b564a 100644 --- a/Core/Business/Payment/Core_Business_Payment_PaymentOption.php +++ b/Core/Business/Payment/Core_Business_Payment_PaymentOption.php @@ -26,189 +26,189 @@ class Core_Business_Payment_PaymentOption { - private $callToActionText; - private $logo; - private $action; - private $method; - private $inputs; - private $form; - private $moduleName; + private $callToActionText; + private $logo; + private $action; + private $method; + private $inputs; + private $form; + private $moduleName; - /** - * Return Call to Action Text - * @return string - */ - public function getCallToActionText() - { - return $this->callToActionText; - } + /** + * Return Call to Action Text + * @return string + */ + public function getCallToActionText() + { + return $this->callToActionText; + } - /** - * Set Call To Action Text - * @param $callToActionText - * @return $this - */ - public function setCallToActionText($callToActionText) - { - $this->callToActionText = $callToActionText; - return $this; - } + /** + * Set Call To Action Text + * @param $callToActionText + * @return $this + */ + public function setCallToActionText($callToActionText) + { + $this->callToActionText = $callToActionText; + return $this; + } - /** - * Return logo path - * @return string - */ - public function getLogo() - { - return $this->logo; - } + /** + * Return logo path + * @return string + */ + public function getLogo() + { + return $this->logo; + } - /** - * Set logo path - * @param $logo - * @return $this - */ - public function setLogo($logo) - { - $this->logo = $logo; - return $this; - } + /** + * Set logo path + * @param $logo + * @return $this + */ + public function setLogo($logo) + { + $this->logo = $logo; + return $this; + } - /** - * Return action to perform (POST/GET) - * @return string - */ - public function getAction() - { - return $this->action; - } + /** + * Return action to perform (POST/GET) + * @return string + */ + public function getAction() + { + return $this->action; + } - /** - * Set action to be performed by this option - * @param $action - * @return $this - */ - public function setAction($action) - { - $this->action = $action; - return $this; - } + /** + * Set action to be performed by this option + * @param $action + * @return $this + */ + public function setAction($action) + { + $this->action = $action; + return $this; + } - public function getMethod() - { - return $this->method; - } + public function getMethod() + { + return $this->method; + } - public function setMethod($method) - { - $this->method = $method; - return $this; - } + public function setMethod($method) + { + $this->method = $method; + return $this; + } - /** - * Return inputs contained in this payment option - * @return mixed - */ - public function getInputs() - { - return $this->inputs; - } + /** + * Return inputs contained in this payment option + * @return mixed + */ + public function getInputs() + { + return $this->inputs; + } - /** - * Set inputs for this payment option - * @param $inputs - * @return $this - */ - public function setInputs($inputs) - { - $this->inputs = $inputs; - return $this; - } + /** + * Set inputs for this payment option + * @param $inputs + * @return $this + */ + public function setInputs($inputs) + { + $this->inputs = $inputs; + return $this; + } - /** - * Get payment option form - * @return mixed - */ - public function getForm() - { - return $this->form; - } + /** + * Get payment option form + * @return mixed + */ + public function getForm() + { + return $this->form; + } - /** - * Set payment option form - * @param $form - * @return $this - */ - public function setForm($form) - { - $this->form = $form; - return $this; - } + /** + * Set payment option form + * @param $form + * @return $this + */ + public function setForm($form) + { + $this->form = $form; + return $this; + } - /** - * Get related module name to this payment option - * @return string - */ - public function getModuleName() - { - return $this->moduleName; - } + /** + * Get related module name to this payment option + * @return string + */ + public function getModuleName() + { + return $this->moduleName; + } - /** - * Set related module name to this payment option - * @param $moduleName - * @return $this - */ - public function setModuleName($moduleName) - { - $this->moduleName = $moduleName; - return $this; - } + /** + * Set related module name to this payment option + * @param $moduleName + * @return $this + */ + public function setModuleName($moduleName) + { + $this->moduleName = $moduleName; + return $this; + } - /** - * Legacy options were specified this way: - * - either an array with a top level property 'cta_text' - * and then the other properties - * - or a numerically indexed array or arrays as described above - * Since this was a mess, this method is provided to convert them. - * It takes as input a legacy option (in either form) and always - * returns an array of instances of Core_Business_Payment_PaymentOption - */ - public static function convertLegacyOption(array $legacyOption) - { - if (!$legacyOption) - return; + /** + * Legacy options were specified this way: + * - either an array with a top level property 'cta_text' + * and then the other properties + * - or a numerically indexed array or arrays as described above + * Since this was a mess, this method is provided to convert them. + * It takes as input a legacy option (in either form) and always + * returns an array of instances of Core_Business_Payment_PaymentOption + */ + public static function convertLegacyOption(array $legacyOption) + { + if (!$legacyOption) { + return; + } - if (array_key_exists('cta_text', $legacyOption)) { - $legacyOption = array($legacyOption); - } + if (array_key_exists('cta_text', $legacyOption)) { + $legacyOption = array($legacyOption); + } - $newOptions = array(); + $newOptions = array(); - $defaults = array( - 'action' => null, - 'form' => null, - 'method' => null, - 'inputs' => array(), - 'logo' => null - ); + $defaults = array( + 'action' => null, + 'form' => null, + 'method' => null, + 'inputs' => array(), + 'logo' => null + ); - foreach ($legacyOption as $option) { + foreach ($legacyOption as $option) { + $option = array_merge($defaults, $option); - $option = array_merge($defaults, $option); + $newOption = new Core_Business_Payment_PaymentOption(); + $newOption->setCallToActionText($option['cta_text']) + ->setAction($option['action']) + ->setForm($option['form']) + ->setInputs($option['inputs']) + ->setLogo($option['logo']) + ->setMethod($option['method']); - $newOption = new Core_Business_Payment_PaymentOption(); - $newOption->setCallToActionText($option['cta_text']) - ->setAction($option['action']) - ->setForm($option['form']) - ->setInputs($option['inputs']) - ->setLogo($option['logo']) - ->setMethod($option['method']); + $newOptions[] = $newOption; + } - $newOptions[] = $newOption; - } - - return $newOptions; - } + return $newOptions; + } } diff --git a/Core/Business/Stock/Core_Business_Stock_StockManager.php b/Core/Business/Stock/Core_Business_Stock_StockManager.php new file mode 100644 index 00000000..3e17f046 --- /dev/null +++ b/Core/Business/Stock/Core_Business_Stock_StockManager.php @@ -0,0 +1,150 @@ + + * @copyright 2007-2015 PrestaShop SA + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * International Registered Trademark & Property of PrestaShop SA + */ + +class Core_Business_Stock_StockManager +{ + /** + * This will update a Pack quantity and will decrease the quantity of containing Products if needed. + * + * @param Product $product A product pack object to update its quantity + * @param StockAvailable $stock_available the stock of the product to fix with correct quantity + * @param integer $delta_quantity The movement of the stock (negative for a decrease) + * @param integer|null $id_shop Opional shop ID + */ + public function updatePackQuantity($product, $stock_available, $delta_quantity, $id_shop = null) + { + $configuration = Adapter_ServiceLocator::get('Core_Business_ConfigurationInterface'); + if ($product->pack_stock_type == 1 || $product->pack_stock_type == 2 || ($product->pack_stock_type == 3 && $configuration->get('PS_PACK_STOCK_TYPE') > 0)) { + $packItemsManager = Adapter_ServiceLocator::get('Adapter_PackItemsManager'); + $products_pack = $packItemsManager->getPackItems($product); + $stockAvailable = new Core_Business_Stock_StockManager(); + $stockManager = Adapter_ServiceLocator::get('Adapter_StockManager'); + $cacheManager = Adapter_ServiceLocator::get('Adapter_CacheManager'); + foreach ($products_pack as $product_pack) { + $productStockAvailable = $stockManager->getStockAvailableByProduct($product_pack, $product_pack->id_pack_product_attribute, $id_shop); + $productStockAvailable->quantity = $productStockAvailable->quantity + ($delta_quantity * $product_pack->pack_quantity); + $productStockAvailable->update(); + + $cacheManager->clean('StockAvailable::getQuantityAvailableByProduct_'.(int)$product_pack->id.'*'); + } + } + + $stock_available->quantity = $stock_available->quantity + $delta_quantity; + + if ($product->pack_stock_type == 0 || $product->pack_stock_type == 2 || + ($product->pack_stock_type == 3 && ($configuration->get('PS_PACK_STOCK_TYPE') == 0 || $configuration->get('PS_PACK_STOCK_TYPE') == 2))) { + $stock_available->update(); + } + } + + /** + * This will decrease (if needed) Packs containing this product + * (with the right declinaison) if there is not enough product in stocks. + * + * @param Product $product A product object to update its quantity + * @param integer $id_product_attribute The product attribute to update + * @param StockAvailable $stock_available the stock of the product to fix with correct quantity + * @param integer|null $id_shop Opional shop ID + */ + public function updatePacksQuantityContainingProduct($product, $id_product_attribute, $stock_available, $id_shop = null) + { + $configuration = Adapter_ServiceLocator::get('Core_Business_ConfigurationInterface'); + $packItemsManager = Adapter_ServiceLocator::get('Adapter_PackItemsManager'); + $stockManager = Adapter_ServiceLocator::get('Adapter_StockManager'); + $cacheManager = Adapter_ServiceLocator::get('Adapter_CacheManager'); + $packs = $packItemsManager->getPacksContainingItem($product, $id_product_attribute); + foreach($packs as $pack) { + // Decrease stocks of the pack only if pack is in linked stock mode (option called 'Decrement both') + if (!((int)$pack->pack_stock_type == 2) && + !((int)$pack->pack_stock_type == 3 && $configuration->get('PS_PACK_STOCK_TYPE') == 2) + ) { + continue; + } + + // Decrease stocks of the pack only if there is not enough items to constituate the actual pack stocks. + + // How many packs can be constituated with the remaining product stocks + $quantity_by_pack = $pack->pack_item_quantity; + $max_pack_quantity = max(array(0, floor($stock_available->quantity / $quantity_by_pack))); + + $stock_available_pack = $stockManager->getStockAvailableByProduct($pack, null, $id_shop); + if ($stock_available_pack->quantity > $max_pack_quantity) { + $stock_available_pack->quantity = $max_pack_quantity; + $stock_available_pack->update(); + + $cacheManager->clean('StockAvailable::getQuantityAvailableByProduct_'.(int)$pack->id.'*'); + } + } + } + + /** + * Will update Product available stock int he given declinaison. If product is a Pack, could decrease the sub products. + * If Product is contained in a Pack, Pack could be decreased or not (only if sub product stocks become not sufficient). + * + * @param Product $product The product to update its stockAvailable + * @param integer $id_product_attribute The declinaison to update (null if not) + * @param integer $delta_quantity The quantity change (positive or negative) + * @param integer|null $id_shop Optional + */ + public function updateQuantity($product, $id_product_attribute, $delta_quantity, $id_shop = null) + { + $stockManager = Adapter_ServiceLocator::get('Adapter_StockManager'); + $stockAvailable = $stockManager->getStockAvailableByProduct($product, $id_product_attribute, $id_shop); + $packItemsManager = Adapter_ServiceLocator::get('Adapter_PackItemsManager'); + $cacheManager = Adapter_ServiceLocator::get('Adapter_CacheManager'); + $hookManager = Adapter_ServiceLocator::get('Adapter_HookManager'); + + // Update quantity of the pack products + if ($packItemsManager->isPack($product)) { + // The product is a pack + $this->updatePackQuantity($product, $stockAvailable, $delta_quantity, $id_shop); + } else { + // The product is not a pack + $stockAvailable->quantity = $stockAvailable->quantity + $delta_quantity; + $stockAvailable->update(); + + // Decrease case only: the stock of linked packs should be decreased too. + if ($delta_quantity < 0) { + // The product is not a pack, but the product combination is part of a pack (use of isPacked, not isPack) + if ($packItemsManager->isPacked($product, $id_product_attribute)) { + $this->updatePacksQuantityContainingProduct($product, $id_product_attribute, $stockAvailable, $id_shop); + } + } + } + + $cacheManager->clean('StockAvailable::getQuantityAvailableByProduct_'.(int)$product->id.'*'); + + $hookManager->exec('actionUpdateQuantity', + array( + 'id_product' => $product->id, + 'id_product_attribute' => $id_product_attribute, + 'quantity' => $stockAvailable->quantity + ) + ); + } + + +} diff --git a/Core/Foundation/Database/Core_Foundation_Database_EntityInterface.php b/Core/Foundation/Database/Core_Foundation_Database_EntityInterface.php index b489c421..aab6cf87 100644 --- a/Core/Foundation/Database/Core_Foundation_Database_EntityInterface.php +++ b/Core/Foundation/Database/Core_Foundation_Database_EntityInterface.php @@ -26,17 +26,17 @@ interface Core_Foundation_Database_EntityInterface { - /** - * Returns the name of the repository class for this entity. - * If unspecified, a generic repository will be used for the entity. - * - * @return string or falsey value - */ - public static function getRepositoryClassName(); + /** + * Returns the name of the repository class for this entity. + * If unspecified, a generic repository will be used for the entity. + * + * @return string or falsey value + */ + public static function getRepositoryClassName(); - public function save(); + public function save(); - public function delete(); + public function delete(); - public function hydrate(array $keyValueData); + public function hydrate(array $keyValueData); } diff --git a/Core/Foundation/Database/Core_Foundation_Database_EntityManager.php b/Core/Foundation/Database/Core_Foundation_Database_EntityManager.php index 44d7b767..b63151e6 100644 --- a/Core/Foundation/Database/Core_Foundation_Database_EntityManager.php +++ b/Core/Foundation/Database/Core_Foundation_Database_EntityManager.php @@ -26,90 +26,89 @@ class Core_Foundation_Database_EntityManager { - private $db; - private $configuration; + private $db; + private $configuration; - private $entityMetaData = array(); + private $entityMetaData = array(); - public function __construct( + public function __construct( Core_Foundation_Database_DatabaseInterface $db, Core_Business_ConfigurationInterface $configuration - ) - { - $this->db = $db; - $this->configuration = $configuration; + ) { + $this->db = $db; + $this->configuration = $configuration; } - /** - * Return current database object used - * @return Core_Foundation_Database_DatabaseInterface - */ - public function getDatabase() - { - return $this->db; - } + /** + * Return current database object used + * @return Core_Foundation_Database_DatabaseInterface + */ + public function getDatabase() + { + return $this->db; + } - /** - * Return current repository used - * @param $className - * @return mixed - */ - public function getRepository($className) - { + /** + * Return current repository used + * @param $className + * @return mixed + */ + public function getRepository($className) + { if (is_callable(array($className, 'getRepositoryClassName'))) { $repositoryClass = call_user_func(array($className, 'getRepositoryClassName')); } else { $repositoryClass = null; } - if (!$repositoryClass) { - $repositoryClass = 'Core_Foundation_Database_EntityRepository'; - } + if (!$repositoryClass) { + $repositoryClass = 'Core_Foundation_Database_EntityRepository'; + } $repository = new $repositoryClass( - $this, - $this->configuration->get('_DB_PREFIX_'), - $this->getEntityMetaData($className) - ); + $this, + $this->configuration->get('_DB_PREFIX_'), + $this->getEntityMetaData($className) + ); - return $repository; - } + return $repository; + } - /** - * Return entity's meta data - * @param $className - * @return mixed - * @throws Adapter_Exception - */ - public function getEntityMetaData($className) - { - if (!array_key_exists($className, $this->entityMetaData)) { - $metaDataRetriever = new Adapter_EntityMetaDataRetriever; - $this->entityMetaData[$className] = $metaDataRetriever->getEntityMetaData($className); - } + /** + * Return entity's meta data + * @param $className + * @return mixed + * @throws Adapter_Exception + */ + public function getEntityMetaData($className) + { + if (!array_key_exists($className, $this->entityMetaData)) { + $metaDataRetriever = new Adapter_EntityMetaDataRetriever; + $this->entityMetaData[$className] = $metaDataRetriever->getEntityMetaData($className); + } - return $this->entityMetaData[$className]; - } + return $this->entityMetaData[$className]; + } - /** - * Flush entity to DB - * @param Core_Foundation_Database_EntityInterface $entity - * @return $this - */ - public function save(Core_Foundation_Database_EntityInterface $entity) - { - $entity->save(); - return $this; - } + /** + * Flush entity to DB + * @param Core_Foundation_Database_EntityInterface $entity + * @return $this + */ + public function save(Core_Foundation_Database_EntityInterface $entity) + { + $entity->save(); + return $this; + } - /** - * DElete entity from DB - * @param Core_Foundation_Database_EntityInterface $entity - * @return $this - */ - public function delete(Core_Foundation_Database_EntityInterface $entity) - { - $entity->delete(); - return $this; - } + /** + * DElete entity from DB + * @param Core_Foundation_Database_EntityInterface $entity + * @return $this + */ + public function delete(Core_Foundation_Database_EntityInterface $entity) + { + $entity->delete(); + return $this; + } } diff --git a/Core/Foundation/Database/Core_Foundation_Database_EntityRepository.php b/Core/Foundation/Database/Core_Foundation_Database_EntityRepository.php index 22b6b7d5..30ab5d5e 100644 --- a/Core/Foundation/Database/Core_Foundation_Database_EntityRepository.php +++ b/Core/Foundation/Database/Core_Foundation_Database_EntityRepository.php @@ -26,99 +26,98 @@ class Core_Foundation_Database_EntityRepository { - protected $entityManager; - protected $db; - protected $tablesPrefix; - protected $entityMetaData; - protected $queryBuilder; + protected $entityManager; + protected $db; + protected $tablesPrefix; + protected $entityMetaData; + protected $queryBuilder; - public function __construct( - Core_Foundation_Database_EntityManager $entityManager, - $tablesPrefix, - Core_Foundation_Database_EntityMetaData $entityMetaData - ) - { - $this->entityManager = $entityManager; - $this->db = $this->entityManager->getDatabase(); - $this->tablesPrefix = $tablesPrefix; - $this->entityMetaData = $entityMetaData; - $this->queryBuilder = new Core_Foundation_Database_EntityManager_QueryBuilder($this->db); - } + public function __construct( + Core_Foundation_Database_EntityManager $entityManager, + $tablesPrefix, + Core_Foundation_Database_EntityMetaData $entityMetaData + ) { + $this->entityManager = $entityManager; + $this->db = $this->entityManager->getDatabase(); + $this->tablesPrefix = $tablesPrefix; + $this->entityMetaData = $entityMetaData; + $this->queryBuilder = new Core_Foundation_Database_EntityManager_QueryBuilder($this->db); + } - public function __call($method, $arguments) - { - if (0 === strpos($method, 'findOneBy')) { - $one = true; - $by = substr($method, 9); - } else if (0 === strpos($method, 'findBy')) { - $one = false; - $by = substr($method, 6); - } else { - throw new Core_Foundation_Database_Exception(sprintf('Undefind method %s.', $method)); - } + public function __call($method, $arguments) + { + if (0 === strpos($method, 'findOneBy')) { + $one = true; + $by = substr($method, 9); + } elseif (0 === strpos($method, 'findBy')) { + $one = false; + $by = substr($method, 6); + } else { + throw new Core_Foundation_Database_Exception(sprintf('Undefind method %s.', $method)); + } - if (count($arguments) !== 1) { - throw new Core_Foundation_Database_Exception(sprintf('Method %s takes exactly one argument.', $method)); - } + if (count($arguments) !== 1) { + throw new Core_Foundation_Database_Exception(sprintf('Method %s takes exactly one argument.', $method)); + } - if (!$by) { - $where = $arguments[0]; - } else { - $where = array(); - $by = $this->convertToDbFieldName($by); - $where[$by] = $arguments[0]; - } + if (!$by) { + $where = $arguments[0]; + } else { + $where = array(); + $by = $this->convertToDbFieldName($by); + $where[$by] = $arguments[0]; + } - return $this->doFind($one, $where); - } + return $this->doFind($one, $where); + } - /** - * Convert a camelCase field name to a snakeCase one - * e.g.: findAllByIdCMS => id_cms - * @param $camel_case_field_name - * @return string - */ - private function convertToDbFieldName($camel_case_field_name) - { - return strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $camel_case_field_name)); - } + /** + * Convert a camelCase field name to a snakeCase one + * e.g.: findAllByIdCMS => id_cms + * @param $camel_case_field_name + * @return string + */ + private function convertToDbFieldName($camel_case_field_name) + { + return strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $camel_case_field_name)); + } - /** - * Return ID field name - * @return mixed - * @throws Core_Foundation_Database_Exception - */ - protected function getIdFieldName() - { - $primary = $this->entityMetaData->getPrimaryKeyFieldnames(); + /** + * Return ID field name + * @return mixed + * @throws Core_Foundation_Database_Exception + */ + protected function getIdFieldName() + { + $primary = $this->entityMetaData->getPrimaryKeyFieldnames(); - if (count($primary) === 0) { - throw new Core_Foundation_Database_Exception( - sprintf( - 'No primary key defined in entity `%s`.', - $this->entityMetaData->getEntityClassName() - ) - ); - } else if (count($primary) > 1) { - throw new Core_Foundation_Database_Exception( - sprintf( - 'Entity `%s` has a composite primary key, which is not supported by entity repositories.', - $this->entityMetaData->getEntityClassName() - ) - ); - } + if (count($primary) === 0) { + throw new Core_Foundation_Database_Exception( + sprintf( + 'No primary key defined in entity `%s`.', + $this->entityMetaData->getEntityClassName() + ) + ); + } elseif (count($primary) > 1) { + throw new Core_Foundation_Database_Exception( + sprintf( + 'Entity `%s` has a composite primary key, which is not supported by entity repositories.', + $this->entityMetaData->getEntityClassName() + ) + ); + } - return $primary[0]; - } + return $primary[0]; + } - /** - * Returns escaped+prefixed current table name - * @return mixed - */ - protected function getTableNameWithPrefix() - { - return $this->db->escape($this->tablesPrefix . $this->entityMetaData->getTableName()); - } + /** + * Returns escaped+prefixed current table name + * @return mixed + */ + protected function getTableNameWithPrefix() + { + return $this->db->escape($this->tablesPrefix . $this->entityMetaData->getTableName()); + } /** * Returns escaped DB table prefix @@ -129,93 +128,93 @@ class Core_Foundation_Database_EntityRepository return $this->db->escape($this->tablesPrefix); } - /** - * Return a new empty Entity depending on current Repository selected - * @return mixed - */ - public function getNewEntity() - { - $entityClassName = $this->entityMetaData->getEntityClassName(); - return new $entityClassName; - } + /** + * Return a new empty Entity depending on current Repository selected + * @return mixed + */ + public function getNewEntity() + { + $entityClassName = $this->entityMetaData->getEntityClassName(); + return new $entityClassName; + } - /** - * This function takes an array of database rows as input - * and returns an hydrated entity if there is one row only. - * - * Null is returned when there are no rows, and an exception is thrown - * if there are too many rows. - * - * @param array $rows Database rows - */ - protected function hydrateOne(array $rows) - { - if (count($rows) === 0) { - return null; - } else if (count($rows) > 1) { - throw new Core_Foundation_Database_Exception('Too many rows returned.'); - } else { - $data = $rows[0]; - $entity = $this-> getNewEntity(); - $entity->hydrate($data); - return $entity; - } - } + /** + * This function takes an array of database rows as input + * and returns an hydrated entity if there is one row only. + * + * Null is returned when there are no rows, and an exception is thrown + * if there are too many rows. + * + * @param array $rows Database rows + */ + protected function hydrateOne(array $rows) + { + if (count($rows) === 0) { + return null; + } elseif (count($rows) > 1) { + throw new Core_Foundation_Database_Exception('Too many rows returned.'); + } else { + $data = $rows[0]; + $entity = $this-> getNewEntity(); + $entity->hydrate($data); + return $entity; + } + } - protected function hydrateMany(array $rows) - { - $entities = array(); - foreach ($rows as $row) { - $entity = $this->getNewEntity(); - $entity->hydrate($row); - $entities[] = $entity; - } - return $entities; - } + protected function hydrateMany(array $rows) + { + $entities = array(); + foreach ($rows as $row) { + $entity = $this->getNewEntity(); + $entity->hydrate($row); + $entities[] = $entity; + } + return $entities; + } - /** - * Constructs and performs 'SELECT' in DB - * @param $one - * @param array $cumulativeConditions - * @return array|mixed|null - * @throws Core_Foundation_Database_Exception - */ - private function doFind($one, array $cumulativeConditions) - { - $whereClause = $this->queryBuilder->buildWhereConditions('AND', $cumulativeConditions); + /** + * Constructs and performs 'SELECT' in DB + * @param $one + * @param array $cumulativeConditions + * @return array|mixed|null + * @throws Core_Foundation_Database_Exception + */ + private function doFind($one, array $cumulativeConditions) + { + $whereClause = $this->queryBuilder->buildWhereConditions('AND', $cumulativeConditions); - $sql = 'SELECT * FROM ' . $this->getTableNameWithPrefix() . ' WHERE ' . $whereClause; + $sql = 'SELECT * FROM ' . $this->getTableNameWithPrefix() . ' WHERE ' . $whereClause; - $rows = $this->db->select($sql); + $rows = $this->db->select($sql); - if ($one) { - return $this->hydrateOne($rows); - } else { - return $this->hydrateMany($rows); - } - } + if ($one) { + return $this->hydrateOne($rows); + } else { + return $this->hydrateMany($rows); + } + } - /** - * Find one entity in DB - * @param $id - * @return array|mixed|null - * @throws Core_Foundation_Database_Exception - */ - public function findOne($id) - { - $conditions = array(); - $conditions[$this->getIdFieldName()] = $id; + /** + * Find one entity in DB + * @param $id + * @return array|mixed|null + * @throws Core_Foundation_Database_Exception + */ + public function findOne($id) + { + $conditions = array(); + $conditions[$this->getIdFieldName()] = $id; - return $this->doFind(true, $conditions); - } + return $this->doFind(true, $conditions); + } - /** - * Find all entities in DB - * @return array - */ - public function findAll() - { - $sql = 'SELECT * FROM ' . $this->getTableNameWithPrefix(); - return $this->hydrateMany($this->db->select($sql)); - } + /** + * Find all entities in DB + * @return array + */ + public function findAll() + { + $sql = 'SELECT * FROM ' . $this->getTableNameWithPrefix(); + return $this->hydrateMany($this->db->select($sql)); + } } diff --git a/Core/Foundation/Database/Core_Foundation_Database_Exception.php b/Core/Foundation/Database/Core_Foundation_Database_Exception.php index cd13c0e9..e19c0832 100644 --- a/Core/Foundation/Database/Core_Foundation_Database_Exception.php +++ b/Core/Foundation/Database/Core_Foundation_Database_Exception.php @@ -26,4 +26,4 @@ class Core_Foundation_Database_Exception extends Core_Foundation_Exception_Exception { -} \ No newline at end of file +} diff --git a/Core/Foundation/Exception/Core_Foundation_Exception_Exception.php b/Core/Foundation/Exception/Core_Foundation_Exception_Exception.php index 81f28457..942aa5b2 100644 --- a/Core/Foundation/Exception/Core_Foundation_Exception_Exception.php +++ b/Core/Foundation/Exception/Core_Foundation_Exception_Exception.php @@ -26,8 +26,8 @@ class Core_Foundation_Exception_Exception extends Exception { - public function __construct($message = null, $code = 0, Exception $previous = null) - { - parent::__construct($message, $code, $previous); - } -} \ No newline at end of file + public function __construct($message = null, $code = 0, Exception $previous = null) + { + parent::__construct($message, $code, $previous); + } +} diff --git a/Core/Foundation/Filesystem/Core_Foundation_FileSystem_Exception.php b/Core/Foundation/Filesystem/Core_Foundation_FileSystem_Exception.php index ececb41f..bcc82d61 100644 --- a/Core/Foundation/Filesystem/Core_Foundation_FileSystem_Exception.php +++ b/Core/Foundation/Filesystem/Core_Foundation_FileSystem_Exception.php @@ -26,4 +26,4 @@ class Core_Foundation_FileSystem_Exception extends Core_Foundation_Exception_Exception { -} \ No newline at end of file +} diff --git a/Core/Foundation/Filesystem/Core_Foundation_FileSystem_FileSystem.php b/Core/Foundation/Filesystem/Core_Foundation_FileSystem_FileSystem.php index 314a75e1..3afaf4ea 100644 --- a/Core/Foundation/Filesystem/Core_Foundation_FileSystem_FileSystem.php +++ b/Core/Foundation/Filesystem/Core_Foundation_FileSystem_FileSystem.php @@ -26,109 +26,116 @@ class Core_Foundation_FileSystem_FileSystem { - /** - * Replaces directory separators with the system's native one - * and trims the trailing separator. - */ - public function normalizePath($path) - { - return rtrim( - str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path), - DIRECTORY_SEPARATOR - ); - } + /** + * Replaces directory separators with the system's native one + * and trims the trailing separator. + */ + public function normalizePath($path) + { + return rtrim( + str_replace(array('/', '\\'), DIRECTORY_SEPARATOR, $path), + DIRECTORY_SEPARATOR + ); + } - private function joinTwoPaths($a, $b) - { - return $this->normalizePath($a) . DIRECTORY_SEPARATOR . $this->normalizePath($b); - } + private function joinTwoPaths($a, $b) + { + return $this->normalizePath($a) . DIRECTORY_SEPARATOR . $this->normalizePath($b); + } - /** - * Joins an arbitrary number of paths, normalizing them along the way. - */ - public function joinPaths() - { - if (func_num_args() < 2) { - throw new Core_Foundation_FileSystem_Exception('joinPaths requires at least 2 arguments.'); - } else if (func_num_args() === 2) { - return $this->joinTwoPaths(func_get_arg(0), func_get_arg(1)); - } else if (func_num_args() > 2) { - return $this->joinPaths( - func_get_arg(0), - call_user_func_array( - array($this, 'joinPaths'), - array_slice(func_get_args(), 1) - ) - ); - } - } + /** + * Joins an arbitrary number of paths, normalizing them along the way. + */ + public function joinPaths() + { + if (func_num_args() < 2) { + throw new Core_Foundation_FileSystem_Exception('joinPaths requires at least 2 arguments.'); + } else if (func_num_args() === 2) { + $arg_O = func_get_arg(0); + $arg_1 = func_get_arg(1); - /** - * Performs a depth first listing of directory entries. - * Throws exception if $path is not a file. - * If $path is a file and not a directory, just gets the file info for it - * and return it in an array. - * @return an array of SplFileInfo object indexed by file path - */ - public function listEntriesRecursively($path) - { - if (!file_exists($path)) { - throw new Core_Foundation_FileSystem_Exception( - sprintf( - 'No such file or directory: %s', - $path - ) - ); - } + return $this->joinTwoPaths($arg_O, $arg_1); + } else if (func_num_args() > 2) { + $func_args = func_get_args(); + $arg_0 = func_get_arg(0); - if (!is_dir($path)) { - throw new Core_Foundation_FileSystem_Exception( - sprintf( - '%s is not a directory', - $path - ) - ); - } + return $this->joinPaths( + $arg_0, + call_user_func_array( + array($this, + 'joinPaths'), + array_slice($func_args, 1) + ) + ); + } + } - $entries = array(); + /** + * Performs a depth first listing of directory entries. + * Throws exception if $path is not a file. + * If $path is a file and not a directory, just gets the file info for it + * and return it in an array. + * @return an array of SplFileInfo object indexed by file path + */ + public function listEntriesRecursively($path) + { + if (!file_exists($path)) { + throw new Core_Foundation_FileSystem_Exception( + sprintf( + 'No such file or directory: %s', + $path + ) + ); + } - foreach (scandir($path) as $entry) { - if ($entry === '.' || $entry === '..') { - continue; - } + if (!is_dir($path)) { + throw new Core_Foundation_FileSystem_Exception( + sprintf( + '%s is not a directory', + $path + ) + ); + } - $newPath = $this->joinPaths($path, $entry); - $info = new SplFileInfo($newPath); + $entries = array(); - $entries[$newPath] = $info; + foreach (scandir($path) as $entry) { + if ($entry === '.' || $entry === '..') { + continue; + } - if ($info->isDir()) { - $entries = array_merge( - $entries, - $this->listEntriesRecursively($newPath) - ); - } - } + $newPath = $this->joinPaths($path, $entry); + $info = new SplFileInfo($newPath); - return $entries; - } + $entries[$newPath] = $info; - /** - * Filter used by listFilesRecursively. - */ - private function matchOnlyFiles(SplFileInfo $info) - { - return $info->isFile(); - } + if ($info->isDir()) { + $entries = array_merge( + $entries, + $this->listEntriesRecursively($newPath) + ); + } + } - /** - * Same as listEntriesRecursively but returns only files. - */ - public function listFilesRecursively($path) - { - return array_filter( - $this->listEntriesRecursively($path), - array($this, 'matchOnlyFiles') - ); - } + return $entries; + } + + /** + * Filter used by listFilesRecursively. + */ + private function matchOnlyFiles(SplFileInfo $info) + { + return $info->isFile(); + } + + /** + * Same as listEntriesRecursively but returns only files. + */ + public function listFilesRecursively($path) + { + return array_filter( + $this->listEntriesRecursively($path), + array($this, 'matchOnlyFiles') + ); + } } diff --git a/Core/Foundation/IoC/Core_Foundation_IoC_Container.php b/Core/Foundation/IoC/Core_Foundation_IoC_Container.php index 40dafdbf..762a101c 100644 --- a/Core/Foundation/IoC/Core_Foundation_IoC_Container.php +++ b/Core/Foundation/IoC/Core_Foundation_IoC_Container.php @@ -108,7 +108,7 @@ class Core_Foundation_IoC_Container $paramClass = $param->getClass(); if ($paramClass) { $args[] = $this->doMake($param->getClass()->getName(), $alreadySeen); - } else if ($param->isDefaultValueAvailable()) { + } elseif ($param->isDefaultValueAvailable()) { $args[] = $param->getDefaultValue(); } else { throw new Core_Foundation_IoC_Exception(sprintf('Cannot build a `%s`.', $className)); @@ -149,7 +149,7 @@ class Core_Foundation_IoC_Container if (is_callable($constructor)) { $service = call_user_func($constructor); - } else if (!is_string($constructor)) { + } elseif (!is_string($constructor)) { // user already provided the value, no need to construct it. $service = $constructor; } else { diff --git a/adm/ajax-tab.php b/adm/ajax-tab.php index 35a1d75d..6ef614a9 100644 --- a/adm/ajax-tab.php +++ b/adm/ajax-tab.php @@ -24,19 +24,23 @@ * International Registered Trademark & Property of PrestaShop SA */ -if (!defined('_PS_ADMIN_DIR_')) - define('_PS_ADMIN_DIR_', getcwd()); +if (!defined('_PS_ADMIN_DIR_')) { + define('_PS_ADMIN_DIR_', getcwd()); +} require(_PS_ADMIN_DIR_.'/../config/config.inc.php'); require(_PS_ADMIN_DIR_.'/functions.php'); // For retrocompatibility with "tab" parameter -if (!isset($_GET['controller']) && isset($_GET['tab'])) - $_GET['controller'] = strtolower($_GET['tab']); -if (!isset($_POST['controller']) && isset($_POST['tab'])) - $_POST['controller'] = strtolower($_POST['tab']); -if (!isset($_REQUEST['controller']) && isset($_REQUEST['tab'])) - $_REQUEST['controller'] = strtolower($_REQUEST['tab']); +if (!isset($_GET['controller']) && isset($_GET['tab'])) { + $_GET['controller'] = strtolower($_GET['tab']); +} +if (!isset($_POST['controller']) && isset($_POST['tab'])) { + $_POST['controller'] = strtolower($_POST['tab']); +} +if (!isset($_REQUEST['controller']) && isset($_REQUEST['tab'])) { + $_REQUEST['controller'] = strtolower($_REQUEST['tab']); +} // Retrocompatibility with 1.4 $_REQUEST['ajaxMode'] = $_POST['ajaxMode'] = $_GET['ajaxMode'] = $_REQUEST['ajax'] = $_POST['ajax'] = $_GET['ajax'] = 1; diff --git a/adm/ajax.php b/adm/ajax.php index 2e805159..ad2e2544 100644 --- a/adm/ajax.php +++ b/adm/ajax.php @@ -24,8 +24,9 @@ * International Registered Trademark & Property of PrestaShop SA */ -if (!defined('_PS_ADMIN_DIR_')) - define('_PS_ADMIN_DIR_', getcwd()); +if (!defined('_PS_ADMIN_DIR_')) { + define('_PS_ADMIN_DIR_', getcwd()); +} include(_PS_ADMIN_DIR_.'/../config/config.inc.php'); /* Getting cookie or logout */ @@ -33,27 +34,28 @@ require_once(_PS_ADMIN_DIR_.'/init.php'); $context = Context::getContext(); -if (Tools::isSubmit('ajaxReferrers')) - require(_PS_CONTROLLER_DIR_.'admin/AdminReferrersController.php'); - -if (Tools::getValue('page') == 'prestastore' AND @fsockopen('addons.prestashop.com', 80, $errno, $errst, 3)) - readfile('http://addons.prestashop.com/adminmodules.php?lang='.$context->language->iso_code); - -if (Tools::isSubmit('getAvailableFields') AND Tools::isSubmit('entity')) -{ - $jsonArray = array(); - $import = new AdminImportController(); - - $fields = $import->getAvailableFields(true); - foreach ($fields as $field) - $jsonArray[] = '{"field":"'.addslashes($field).'"}'; - die('['.implode(',', $jsonArray).']'); +if (Tools::isSubmit('ajaxReferrers')) { + require(_PS_CONTROLLER_DIR_.'admin/AdminReferrersController.php'); } -if (Tools::isSubmit('ajaxProductPackItems')) -{ - $jsonArray = array(); - $products = Db::getInstance()->executeS(' +if (Tools::getValue('page') == 'prestastore' and @fsockopen('addons.prestashop.com', 80, $errno, $errst, 3)) { + readfile('http://addons.prestashop.com/adminmodules.php?lang='.$context->language->iso_code); +} + +if (Tools::isSubmit('getAvailableFields') and Tools::isSubmit('entity')) { + $jsonArray = array(); + $import = new AdminImportController(); + + $fields = $import->getAvailableFields(true); + foreach ($fields as $field) { + $jsonArray[] = '{"field":"'.addslashes($field).'"}'; + } + die('['.implode(',', $jsonArray).']'); +} + +if (Tools::isSubmit('ajaxProductPackItems')) { + $jsonArray = array(); + $products = Db::getInstance()->executeS(' SELECT p.`id_product`, pl.`name` FROM `'._DB_PREFIX_.'product` p NATURAL LEFT JOIN `'._DB_PREFIX_.'product_lang` pl @@ -62,35 +64,32 @@ if (Tools::isSubmit('ajaxProductPackItems')) AND NOT EXISTS (SELECT 1 FROM `'._DB_PREFIX_.'pack` WHERE `id_product_pack` = p.`id_product`) AND p.`id_product` != '.(int)(Tools::getValue('id_product'))); - foreach ($products as $packItem) - $jsonArray[] = '{"value": "'.(int)($packItem['id_product']).'-'.addslashes($packItem['name']).'", "text":"'.(int)($packItem['id_product']).' - '.addslashes($packItem['name']).'"}'; - die('['.implode(',', $jsonArray).']'); + foreach ($products as $packItem) { + $jsonArray[] = '{"value": "'.(int)($packItem['id_product']).'-'.addslashes($packItem['name']).'", "text":"'.(int)($packItem['id_product']).' - '.addslashes($packItem['name']).'"}'; + } + die('['.implode(',', $jsonArray).']'); } -if (Tools::isSubmit('getChildrenCategories') && Tools::isSubmit('id_category_parent')) -{ - $children_categories = Category::getChildrenWithNbSelectedSubCat(Tools::getValue('id_category_parent'), Tools::getValue('selectedCat'), Context::getContext()->language->id, null, Tools::getValue('use_shop_context')); - die(Tools::jsonEncode($children_categories)); +if (Tools::isSubmit('getChildrenCategories') && Tools::isSubmit('id_category_parent')) { + $children_categories = Category::getChildrenWithNbSelectedSubCat(Tools::getValue('id_category_parent'), Tools::getValue('selectedCat'), Context::getContext()->language->id, null, Tools::getValue('use_shop_context')); + die(Tools::jsonEncode($children_categories)); } -if (Tools::isSubmit('getNotifications')) -{ - $notification = new Notification; - die(Tools::jsonEncode($notification->getLastElements())); +if (Tools::isSubmit('getNotifications')) { + $notification = new Notification; + die(Tools::jsonEncode($notification->getLastElements())); } -if (Tools::isSubmit('updateElementEmployee') && Tools::getValue('updateElementEmployeeType')) -{ - $notification = new Notification; - die($notification->updateEmployeeLastElement(Tools::getValue('updateElementEmployeeType'))); +if (Tools::isSubmit('updateElementEmployee') && Tools::getValue('updateElementEmployeeType')) { + $notification = new Notification; + die($notification->updateEmployeeLastElement(Tools::getValue('updateElementEmployeeType'))); } -if (Tools::isSubmit('searchCategory')) -{ - $q = Tools::getValue('q'); - $limit = Tools::getValue('limit'); - $results = Db::getInstance()->executeS( - 'SELECT c.`id_category`, cl.`name` +if (Tools::isSubmit('searchCategory')) { + $q = Tools::getValue('q'); + $limit = Tools::getValue('limit'); + $results = Db::getInstance()->executeS( + 'SELECT c.`id_category`, cl.`name` FROM `'._DB_PREFIX_.'category` c LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON (c.`id_category` = cl.`id_category`'.Shop::addSqlRestrictionOnLang('cl').') WHERE cl.`id_lang` = '.(int)$context->language->id.' AND c.`level_depth` <> 0 @@ -98,28 +97,30 @@ if (Tools::isSubmit('searchCategory')) GROUP BY c.id_category ORDER BY c.`position` LIMIT '.(int)$limit); - if ($results) - foreach ($results as $result) - echo trim($result['name']).'|'.(int)$result['id_category']."\n"; + if ($results) { + foreach ($results as $result) { + echo trim($result['name']).'|'.(int)$result['id_category']."\n"; + } + } } -if (Tools::isSubmit('getParentCategoriesId') && $id_category = Tools::getValue('id_category')) -{ - $category = new Category((int)$id_category); - $results = Db::getInstance()->executeS('SELECT `id_category` FROM `'._DB_PREFIX_.'category` c WHERE c.`nleft` < '.(int)$category->nleft.' AND c.`nright` > '.(int)$category->nright.''); - $output = array(); - foreach ($results as $result) - $output[] = $result; +if (Tools::isSubmit('getParentCategoriesId') && $id_category = Tools::getValue('id_category')) { + $category = new Category((int)$id_category); + $results = Db::getInstance()->executeS('SELECT `id_category` FROM `'._DB_PREFIX_.'category` c WHERE c.`nleft` < '.(int)$category->nleft.' AND c.`nright` > '.(int)$category->nright.''); + $output = array(); + foreach ($results as $result) { + $output[] = $result; + } - die(Tools::jsonEncode($output)); + die(Tools::jsonEncode($output)); } -if (Tools::isSubmit('getZones')) -{ - $html = ''; - $array = array('hasError' => false, 'errors' => '', 'data' => $html); - die(Tools::jsonEncode($array)); +if (Tools::isSubmit('getZones')) { + $html = ''; + $array = array('hasError' => false, 'errors' => '', 'data' => $html); + die(Tools::jsonEncode($array)); } diff --git a/adm/ajax_products_list.php b/adm/ajax_products_list.php index d0fd73ed..64415c49 100644 --- a/adm/ajax_products_list.php +++ b/adm/ajax_products_list.php @@ -23,15 +23,17 @@ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ -if (!defined('_PS_ADMIN_DIR_')) - define('_PS_ADMIN_DIR_', getcwd()); +if (!defined('_PS_ADMIN_DIR_')) { + define('_PS_ADMIN_DIR_', getcwd()); +} include(_PS_ADMIN_DIR_.'/../config/config.inc.php'); /* Getting cookie or logout */ require_once(_PS_ADMIN_DIR_.'/init.php'); $query = Tools::getValue('q', false); -if (!$query OR $query == '' OR strlen($query) < 1) - die(); +if (!$query or $query == '' or strlen($query) < 1) { + die(); +} /* * In the SQL request the "q" param is used entirely to match result in database. @@ -40,14 +42,16 @@ if (!$query OR $query == '' OR strlen($query) < 1) * is not write in the name field of the product. * So the ref pattern will be cut for the search request. */ -if($pos = strpos($query, ' (ref:')) - $query = substr($query, 0, $pos); +if ($pos = strpos($query, ' (ref:')) { + $query = substr($query, 0, $pos); +} $excludeIds = Tools::getValue('excludeIds', false); -if ($excludeIds && $excludeIds != 'NaN') - $excludeIds = implode(',', array_map('intval', explode(',', $excludeIds))); -else - $excludeIds = ''; +if ($excludeIds && $excludeIds != 'NaN') { + $excludeIds = implode(',', array_map('intval', explode(',', $excludeIds))); +} else { + $excludeIds = ''; +} // Excluding downloadable products from packs because download from pack is not supported $excludeVirtuals = (bool)Tools::getValue('excludeVirtuals', true); @@ -63,26 +67,24 @@ $sql = 'SELECT p.`id_product`, pl.`link_rewrite`, p.`reference`, pl.`name`, imag ON (image_shop.`id_product` = p.`id_product` AND image_shop.cover=1 AND image_shop.id_shop='.(int)$context->shop->id.') LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (image_shop.`id_image` = il.`id_image` AND il.`id_lang` = '.(int)$context->language->id.') WHERE (pl.name LIKE \'%'.pSQL($query).'%\' OR p.reference LIKE \'%'.pSQL($query).'%\')'. - (!empty($excludeIds) ? ' AND p.id_product NOT IN ('.$excludeIds.') ' : ' '). - ($excludeVirtuals ? 'AND NOT EXISTS (SELECT 1 FROM `'._DB_PREFIX_.'product_download` pd WHERE (pd.id_product = p.id_product))' : ''). - ($exclude_packs ? 'AND (p.cache_is_pack IS NULL OR p.cache_is_pack = 0)' : ''). - ' GROUP BY p.id_product'; + (!empty($excludeIds) ? ' AND p.id_product NOT IN ('.$excludeIds.') ' : ' '). + ($excludeVirtuals ? 'AND NOT EXISTS (SELECT 1 FROM `'._DB_PREFIX_.'product_download` pd WHERE (pd.id_product = p.id_product))' : ''). + ($exclude_packs ? 'AND (p.cache_is_pack IS NULL OR p.cache_is_pack = 0)' : ''). + ' GROUP BY p.id_product'; $items = Db::getInstance()->executeS($sql); -if ($items && ($excludeIds || strpos($_SERVER['HTTP_REFERER'], 'AdminScenes') !== false)) - foreach ($items as $item) - echo trim($item['name']).(!empty($item['reference']) ? ' (ref: '.$item['reference'].')' : '').'|'.(int)($item['id_product'])."\n"; -elseif ($items) -{ - // packs - $results = array(); - foreach ($items as $item) - { - // check if product have combination - if (Combination::isFeatureActive() && $item['cache_default_attribute']) - { - $sql = 'SELECT pa.`id_product_attribute`, pa.`reference`, ag.`id_attribute_group`, pai.`id_image`, agl.`name` AS group_name, al.`name` AS attribute_name, +if ($items && ($excludeIds || strpos($_SERVER['HTTP_REFERER'], 'AdminScenes') !== false)) { + foreach ($items as $item) { + echo trim($item['name']).(!empty($item['reference']) ? ' (ref: '.$item['reference'].')' : '').'|'.(int)($item['id_product'])."\n"; + } +} elseif ($items) { + // packs + $results = array(); + foreach ($items as $item) { + // check if product have combination + if (Combination::isFeatureActive() && $item['cache_default_attribute']) { + $sql = 'SELECT pa.`id_product_attribute`, pa.`reference`, ag.`id_attribute_group`, pai.`id_image`, agl.`name` AS group_name, al.`name` AS attribute_name, a.`id_attribute` FROM `'._DB_PREFIX_.'product_attribute` pa '.Shop::addSqlAssociation('product_attribute', 'pa').' @@ -96,47 +98,43 @@ elseif ($items) GROUP BY pa.`id_product_attribute`, ag.`id_attribute_group` ORDER BY pa.`id_product_attribute`'; - $combinations = Db::getInstance()->executeS($sql); - if (!empty($combinations)) - { - foreach ($combinations as $k => $combination) - { - $results[$combination['id_product_attribute']]['id'] = $item['id_product']; - $results[$combination['id_product_attribute']]['id_product_attribute'] = $combination['id_product_attribute']; - !empty($results[$combination['id_product_attribute']]['name']) ? $results[$combination['id_product_attribute']]['name'] .= ' '.$combination['group_name'].'-'.$combination['attribute_name'] - : $results[$combination['id_product_attribute']]['name'] = $item['name'].' '.$combination['group_name'].'-'.$combination['attribute_name']; - if (!empty($combination['reference'])) - $results[$combination['id_product_attribute']]['ref'] = $combination['reference']; - else - $results[$combination['id_product_attribute']]['ref'] = !empty($item['reference']) ? $item['reference'] : ''; - if (empty($results[$combination['id_product_attribute']]['image'])) - $results[$combination['id_product_attribute']]['image'] = str_replace('http://', Tools::getShopProtocol(), $context->link->getImageLink($item['link_rewrite'], $combination['id_image'], 'home_default')); - } - } - else - { - $product = array( - 'id' => (int)($item['id_product']), - 'name' => $item['name'], - 'ref' => (!empty($item['reference']) ? $item['reference'] : ''), - 'image' => str_replace('http://', Tools::getShopProtocol(), $context->link->getImageLink($item['link_rewrite'], $item['id_image'], 'home_default')), - ); - array_push($results, $product); - } - } - else - { - $product = array( - 'id' => (int)($item['id_product']), - 'name' => $item['name'], - 'ref' => (!empty($item['reference']) ? $item['reference'] : ''), - 'image' => str_replace('http://', Tools::getShopProtocol(), $context->link->getImageLink($item['link_rewrite'], $item['id_image'], 'home_default')), - ); - array_push($results, $product); - } - } - $results = array_values($results); - echo Tools::jsonEncode($results); + $combinations = Db::getInstance()->executeS($sql); + if (!empty($combinations)) { + foreach ($combinations as $k => $combination) { + $results[$combination['id_product_attribute']]['id'] = $item['id_product']; + $results[$combination['id_product_attribute']]['id_product_attribute'] = $combination['id_product_attribute']; + !empty($results[$combination['id_product_attribute']]['name']) ? $results[$combination['id_product_attribute']]['name'] .= ' '.$combination['group_name'].'-'.$combination['attribute_name'] + : $results[$combination['id_product_attribute']]['name'] = $item['name'].' '.$combination['group_name'].'-'.$combination['attribute_name']; + if (!empty($combination['reference'])) { + $results[$combination['id_product_attribute']]['ref'] = $combination['reference']; + } else { + $results[$combination['id_product_attribute']]['ref'] = !empty($item['reference']) ? $item['reference'] : ''; + } + if (empty($results[$combination['id_product_attribute']]['image'])) { + $results[$combination['id_product_attribute']]['image'] = str_replace('http://', Tools::getShopProtocol(), $context->link->getImageLink($item['link_rewrite'], $combination['id_image'], 'home_default')); + } + } + } else { + $product = array( + 'id' => (int)($item['id_product']), + 'name' => $item['name'], + 'ref' => (!empty($item['reference']) ? $item['reference'] : ''), + 'image' => str_replace('http://', Tools::getShopProtocol(), $context->link->getImageLink($item['link_rewrite'], $item['id_image'], 'home_default')), + ); + array_push($results, $product); + } + } else { + $product = array( + 'id' => (int)($item['id_product']), + 'name' => $item['name'], + 'ref' => (!empty($item['reference']) ? $item['reference'] : ''), + 'image' => str_replace('http://', Tools::getShopProtocol(), $context->link->getImageLink($item['link_rewrite'], $item['id_image'], 'home_default')), + ); + array_push($results, $product); + } + } + $results = array_values($results); + echo Tools::jsonEncode($results); +} else { + Tools::jsonEncode(new stdClass); } -else - Tools::jsonEncode(new stdClass); diff --git a/adm/backup.php b/adm/backup.php index aa5d3151..5b6ab464 100644 --- a/adm/backup.php +++ b/adm/backup.php @@ -24,53 +24,63 @@ * International Registered Trademark & Property of PrestaShop SA */ -if (!defined('_PS_ADMIN_DIR_')) - define('_PS_ADMIN_DIR_', getcwd()); +if (!defined('_PS_ADMIN_DIR_')) { + define('_PS_ADMIN_DIR_', getcwd()); +} include(_PS_ADMIN_DIR_.'/../config/config.inc.php'); -if (!Context::getContext()->employee->isLoggedBack()) - Tools::redirectAdmin(Context::getContext()->link->getAdminLink('AdminLogin')); +if (!Context::getContext()->employee->isLoggedBack()) { + Tools::redirectAdmin(Context::getContext()->link->getAdminLink('AdminLogin')); +} $tabAccess = Profile::getProfileAccess(Context::getContext()->employee->id_profile, - Tab::getIdFromClassName('AdminBackup')); + Tab::getIdFromClassName('AdminBackup')); -if ($tabAccess['view'] !== '1') - die (Tools::displayError('You do not have permission to view this.')); +if ($tabAccess['view'] !== '1') { + die(Tools::displayError('You do not have permission to view this.')); +} $backupdir = realpath(PrestaShopBackup::getBackupPath()); -if ($backupdir === false) - die (Tools::displayError('There is no "/backup" directory.')); +if ($backupdir === false) { + die(Tools::displayError('There is no "/backup" directory.')); +} -if (!$backupfile = Tools::getValue('filename')) - die (Tools::displayError('No file has been specified.')); +if (!$backupfile = Tools::getValue('filename')) { + die(Tools::displayError('No file has been specified.')); +} // Check the realpath so we can validate the backup file is under the backup directory $backupfile = realpath($backupdir.DIRECTORY_SEPARATOR.$backupfile); -if ($backupfile === false OR strncmp($backupdir, $backupfile, strlen($backupdir)) != 0 ) - die (Tools::dieOrLog('The backup file does not exist.')); +if ($backupfile === false or strncmp($backupdir, $backupfile, strlen($backupdir)) != 0) { + die(Tools::dieOrLog('The backup file does not exist.')); +} -if (substr($backupfile, -4) == '.bz2') +if (substr($backupfile, -4) == '.bz2') { $contentType = 'application/x-bzip2'; -else if (substr($backupfile, -3) == '.gz') +} elseif (substr($backupfile, -3) == '.gz') { $contentType = 'application/x-gzip'; -else +} else { $contentType = 'text/x-sql'; +} $fp = @fopen($backupfile, 'r'); -if ($fp === false) - die (Tools::displayError('Unable to open backup file(s).').' "'.addslashes($backupfile).'"'); +if ($fp === false) { + die(Tools::displayError('Unable to open backup file(s).').' "'.addslashes($backupfile).'"'); +} // Add the correct headers, this forces the file is saved header('Content-Type: '.$contentType); header('Content-Disposition: attachment; filename="'.Tools::getValue('filename'). '"'); -if (ob_get_level() && ob_get_length() > 0) - ob_clean(); +if (ob_get_level() && ob_get_length() > 0) { + ob_clean(); +} $ret = @fpassthru($fp); fclose($fp); -if ($ret === false) - die (Tools::displayError('Unable to display backup file(s).').' "'.addslashes($backupfile).'"'); +if ($ret === false) { + die(Tools::displayError('Unable to display backup file(s).').' "'.addslashes($backupfile).'"'); +} diff --git a/adm/cron_currency_rates.php b/adm/cron_currency_rates.php index 6f481094..b7389299 100644 --- a/adm/cron_currency_rates.php +++ b/adm/cron_currency_rates.php @@ -24,20 +24,18 @@ * International Registered Trademark & Property of PrestaShop SA */ -if (!defined('_PS_ADMIN_DIR_')) - define('_PS_ADMIN_DIR_', getcwd()); +if (!defined('_PS_ADMIN_DIR_')) { + define('_PS_ADMIN_DIR_', getcwd()); +} include(_PS_ADMIN_DIR_.'/../config/config.inc.php'); -if (isset($_GET['secure_key'])) -{ - $secureKey = md5(_COOKIE_KEY_.Configuration::get('PS_SHOP_NAME')); - if (!empty($secureKey) && $secureKey === $_GET['secure_key']) - { - $shop_ids = Shop::getCompleteListOfShopsID(); - foreach($shop_ids as $shop_id) - { - Shop::setContext(Shop::CONTEXT_SHOP, (int)$shop_id); - Currency::refreshCurrencies(); - } - } -} \ No newline at end of file +if (isset($_GET['secure_key'])) { + $secureKey = md5(_COOKIE_KEY_.Configuration::get('PS_SHOP_NAME')); + if (!empty($secureKey) && $secureKey === $_GET['secure_key']) { + $shop_ids = Shop::getCompleteListOfShopsID(); + foreach ($shop_ids as $shop_id) { + Shop::setContext(Shop::CONTEXT_SHOP, (int)$shop_id); + Currency::refreshCurrencies(); + } + } +} diff --git a/adm/displayImage.php b/adm/displayImage.php index 5bcfd9de..6b0ef9c9 100644 --- a/adm/displayImage.php +++ b/adm/displayImage.php @@ -24,14 +24,14 @@ * International Registered Trademark & Property of PrestaShop SA */ -if (!defined('_PS_ADMIN_DIR_')) - define('_PS_ADMIN_DIR_', getcwd()); +if (!defined('_PS_ADMIN_DIR_')) { + define('_PS_ADMIN_DIR_', getcwd()); +} require_once(_PS_ADMIN_DIR_.'/../config/config.inc.php'); require_once(_PS_ADMIN_DIR_.'/init.php'); -if (isset($_GET['img']) AND Validate::isMd5($_GET['img']) AND isset($_GET['name']) AND Validate::isGenericName($_GET['name']) AND file_exists(_PS_UPLOAD_DIR_.$_GET['img'])) -{ - header('Content-type: image/jpeg'); - header('Content-Disposition: attachment; filename="'.$_GET['name'].'.jpg"'); - echo file_get_contents(_PS_UPLOAD_DIR_.$_GET['img']); +if (isset($_GET['img']) and Validate::isMd5($_GET['img']) and isset($_GET['name']) and Validate::isGenericName($_GET['name']) and file_exists(_PS_UPLOAD_DIR_.$_GET['img'])) { + header('Content-type: image/jpeg'); + header('Content-Disposition: attachment; filename="'.$_GET['name'].'.jpg"'); + echo file_get_contents(_PS_UPLOAD_DIR_.$_GET['img']); } diff --git a/adm/drawer.php b/adm/drawer.php index c77f2601..dec7f464 100644 --- a/adm/drawer.php +++ b/adm/drawer.php @@ -24,8 +24,9 @@ * International Registered Trademark & Property of PrestaShop SA */ -if (!defined('_PS_ADMIN_DIR_')) - define('_PS_ADMIN_DIR_', getcwd()); +if (!defined('_PS_ADMIN_DIR_')) { + define('_PS_ADMIN_DIR_', getcwd()); +} include_once(_PS_ADMIN_DIR_.'/../config/config.inc.php'); $module = Tools::getValue('module'); @@ -38,67 +39,65 @@ $height = Tools::getValue('height'); $id_employee = Tools::getValue('id_employee'); $id_lang = Tools::getValue('id_lang'); -if (!isset($cookie->id_employee) || !$cookie->id_employee || $cookie->id_employee != $id_employee) +if (!isset($cookie->id_employee) || !$cookie->id_employee || $cookie->id_employee != $id_employee) { die(Tools::displayError()); +} -if (!Validate::isModuleName($module)) - die(Tools::displayError()); +if (!Validate::isModuleName($module)) { + die(Tools::displayError()); +} -if (!Tools::file_exists_cache($module_path = _PS_ROOT_DIR_.'/modules/'.$module.'/'.$module.'.php')) - die(Tools::displayError()); +if (!Tools::file_exists_cache($module_path = _PS_ROOT_DIR_.'/modules/'.$module.'/'.$module.'.php')) { + die(Tools::displayError()); +} $shop_id = ''; Shop::setContext(Shop::CONTEXT_ALL); -if (Context::getContext()->cookie->shopContext) -{ - $split = explode('-', Context::getContext()->cookie->shopContext); - if (count($split) == 2) - { - if ($split[0] == 'g') - { - if (Context::getContext()->employee->hasAuthOnShopGroup($split[1])) - Shop::setContext(Shop::CONTEXT_GROUP, $split[1]); - else - { - $shop_id = Context::getContext()->employee->getDefaultShopID(); - Shop::setContext(Shop::CONTEXT_SHOP, $shop_id); - } - } - else if (Shop::getShop($split[1]) && Context::getContext()->employee->hasAuthOnShop($split[1])) - { - $shop_id = $split[1]; - Shop::setContext(Shop::CONTEXT_SHOP, $shop_id); - } - else - { - $shop_id = Context::getContext()->employee->getDefaultShopID(); - Shop::setContext(Shop::CONTEXT_SHOP, $shop_id); - } - } +if (Context::getContext()->cookie->shopContext) { + $split = explode('-', Context::getContext()->cookie->shopContext); + if (count($split) == 2) { + if ($split[0] == 'g') { + if (Context::getContext()->employee->hasAuthOnShopGroup($split[1])) { + Shop::setContext(Shop::CONTEXT_GROUP, $split[1]); + } else { + $shop_id = Context::getContext()->employee->getDefaultShopID(); + Shop::setContext(Shop::CONTEXT_SHOP, $shop_id); + } + } elseif (Shop::getShop($split[1]) && Context::getContext()->employee->hasAuthOnShop($split[1])) { + $shop_id = $split[1]; + Shop::setContext(Shop::CONTEXT_SHOP, $shop_id); + } else { + $shop_id = Context::getContext()->employee->getDefaultShopID(); + Shop::setContext(Shop::CONTEXT_SHOP, $shop_id); + } + } } // Check multishop context and set right context if need -if (Shop::getContext()) -{ - if (Shop::getContext() == Shop::CONTEXT_SHOP && !Shop::CONTEXT_SHOP) - Shop::setContext(Shop::CONTEXT_GROUP, Shop::getContextShopGroupID()); - if (Shop::getContext() == Shop::CONTEXT_GROUP && !Shop::CONTEXT_GROUP) - Shop::setContext(Shop::CONTEXT_ALL); +if (Shop::getContext()) { + if (Shop::getContext() == Shop::CONTEXT_SHOP && !Shop::CONTEXT_SHOP) { + Shop::setContext(Shop::CONTEXT_GROUP, Shop::getContextShopGroupID()); + } + if (Shop::getContext() == Shop::CONTEXT_GROUP && !Shop::CONTEXT_GROUP) { + Shop::setContext(Shop::CONTEXT_ALL); + } } // Replace existing shop if necessary -if (!$shop_id) - Context::getContext()->shop = new Shop(Configuration::get('PS_SHOP_DEFAULT')); -elseif (Context::getContext()->shop->id != $shop_id) - Context::getContext()->shop = new Shop($shop_id); +if (!$shop_id) { + Context::getContext()->shop = new Shop(Configuration::get('PS_SHOP_DEFAULT')); +} elseif (Context::getContext()->shop->id != $shop_id) { + Context::getContext()->shop = new Shop($shop_id); +} require_once($module_path); $graph = new $module(); $graph->setEmployee($id_employee); $graph->setLang($id_lang); -if ($option) - $graph->setOption($option, $layers); +if ($option) { + $graph->setOption($option, $layers); +} $graph->create($render, $type, $width, $height, $layers); $graph->draw(); diff --git a/adm/filemanager/ajax_calls.php b/adm/filemanager/ajax_calls.php index 343f6008..e571d3fa 100644 --- a/adm/filemanager/ajax_calls.php +++ b/adm/filemanager/ajax_calls.php @@ -2,132 +2,131 @@ include('config/config.php'); -if ($_SESSION['verify'] != 'RESPONSIVEfilemanager') - die('forbiden'); +if ($_SESSION['verify'] != 'RESPONSIVEfilemanager') { + die('forbiden'); +} include('include/utils.php'); -if (isset($_GET['action'])) - switch ($_GET['action']) - { - case 'view': - if (isset($_GET['type'])) - $_SESSION['view_type'] = $_GET['type']; - else - die('view type number missing'); - break; - case 'sort': - if (isset($_GET['sort_by'])) - $_SESSION['sort_by'] = $_GET['sort_by']; - if (isset($_GET['descending'])) - $_SESSION['descending'] = $_GET['descending'] === 'true'; - break; - case 'image_size': - if (realpath(dirname(_PS_ROOT_DIR_.$_POST['path'])) != realpath(_PS_ROOT_DIR_.$upload_dir)) - die(); - $pos = strpos($_POST['path'], $upload_dir); - if ($pos !== false) - { - $info = getimagesize(substr_replace($_POST['path'], $current_path, $pos, strlen($upload_dir))); - echo json_encode($info); - } +if (isset($_GET['action'])) { + switch ($_GET['action']) { + case 'view': + if (isset($_GET['type'])) { + $_SESSION['view_type'] = $_GET['type']; + } else { + die('view type number missing'); + } + break; + case 'sort': + if (isset($_GET['sort_by'])) { + $_SESSION['sort_by'] = $_GET['sort_by']; + } + if (isset($_GET['descending'])) { + $_SESSION['descending'] = $_GET['descending'] === 'true'; + } + break; + case 'image_size': + if (realpath(dirname(_PS_ROOT_DIR_.$_POST['path'])) != realpath(_PS_ROOT_DIR_.$upload_dir)) { + die(); + } + $pos = strpos($_POST['path'], $upload_dir); + if ($pos !== false) { + $info = getimagesize(substr_replace($_POST['path'], $current_path, $pos, strlen($upload_dir))); + echo json_encode($info); + } - break; - case 'save_img': - $info = pathinfo($_POST['name']); - if (strpos($_POST['path'], '/') === 0 - || strpos($_POST['path'], '../') !== false - || strpos($_POST['path'], './') === 0 - || strpos($_POST['url'], 'http://featherfiles.aviary.com/') !== 0 - || $_POST['name'] != fix_filename($_POST['name'], $transliteration) - || !in_array(strtolower($info['extension']), array('jpg', 'jpeg', 'png')) - ) - die('wrong data'); - $image_data = get_file_by_url($_POST['url']); - if ($image_data === false) - { - die('file could not be loaded'); - } + break; + case 'save_img': + $info = pathinfo($_POST['name']); + if (strpos($_POST['path'], '/') === 0 + || strpos($_POST['path'], '../') !== false + || strpos($_POST['path'], './') === 0 + || strpos($_POST['url'], 'http://featherfiles.aviary.com/') !== 0 + || $_POST['name'] != fix_filename($_POST['name'], $transliteration) + || !in_array(strtolower($info['extension']), array('jpg', 'jpeg', 'png')) + ) { + die('wrong data'); + } + $image_data = get_file_by_url($_POST['url']); + if ($image_data === false) { + die('file could not be loaded'); + } - $put_contents_path = $current_path; + $put_contents_path = $current_path; - if (isset($_POST['path'])) - $put_contents_path .= str_replace("\0", "", $_POST['path']); + if (isset($_POST['path'])) { + $put_contents_path .= str_replace("\0", "", $_POST['path']); + } - if (isset($_POST['name'])) - $put_contents_path .= str_replace("\0", "", $_POST['name']); + if (isset($_POST['name'])) { + $put_contents_path .= str_replace("\0", "", $_POST['name']); + } - file_put_contents($put_contents_path, $image_data); - //new thumb creation - //try{ - create_img_gd($current_path.$_POST['path'].$_POST['name'], $thumbs_base_path.$_POST['path'].$_POST['name'], 122, 91); - new_thumbnails_creation($current_path.$_POST['path'], $current_path.$_POST['path'].$_POST['name'], $_POST['name'], $current_path, $relative_image_creation, $relative_path_from_current_pos, $relative_image_creation_name_to_prepend, $relative_image_creation_name_to_append, $relative_image_creation_width, $relative_image_creation_height, $fixed_image_creation, $fixed_path_from_filemanager, $fixed_image_creation_name_to_prepend, $fixed_image_creation_to_append, $fixed_image_creation_width, $fixed_image_creation_height); - /*} catch (Exception $e) { - $src_thumb=$mini_src=""; - }*/ - break; - case 'extract': - if (strpos($_POST['path'], '/') === 0 || strpos($_POST['path'], '../') !== false || strpos($_POST['path'], './') === 0) - die('wrong path'); - $path = $current_path.$_POST['path']; - $info = pathinfo($path); - $base_folder = $current_path.fix_dirname($_POST['path']).'/'; - switch ($info['extension']) - { - case 'zip': - $zip = new ZipArchive; - if ($zip->open($path) === true) - { - //make all the folders - for ($i = 0; $i < $zip->numFiles; $i++) - { - $OnlyFileName = $zip->getNameIndex($i); - $FullFileName = $zip->statIndex($i); - if ($FullFileName['name'][strlen($FullFileName['name']) - 1] == '/') - { - create_folder($base_folder.$FullFileName['name']); - } - } - //unzip into the folders - for ($i = 0; $i < $zip->numFiles; $i++) - { - $OnlyFileName = $zip->getNameIndex($i); - $FullFileName = $zip->statIndex($i); + file_put_contents($put_contents_path, $image_data); + //new thumb creation + //try{ + create_img_gd($current_path.$_POST['path'].$_POST['name'], $thumbs_base_path.$_POST['path'].$_POST['name'], 122, 91); + new_thumbnails_creation($current_path.$_POST['path'], $current_path.$_POST['path'].$_POST['name'], $_POST['name'], $current_path, $relative_image_creation, $relative_path_from_current_pos, $relative_image_creation_name_to_prepend, $relative_image_creation_name_to_append, $relative_image_creation_width, $relative_image_creation_height, $fixed_image_creation, $fixed_path_from_filemanager, $fixed_image_creation_name_to_prepend, $fixed_image_creation_to_append, $fixed_image_creation_width, $fixed_image_creation_height); + /*} catch (Exception $e) { + $src_thumb=$mini_src=""; + }*/ + break; + case 'extract': + if (strpos($_POST['path'], '/') === 0 || strpos($_POST['path'], '../') !== false || strpos($_POST['path'], './') === 0) { + die('wrong path'); + } + $path = $current_path.$_POST['path']; + $info = pathinfo($path); + $base_folder = $current_path.fix_dirname($_POST['path']).'/'; + switch ($info['extension']) { + case 'zip': + $zip = new ZipArchive; + if ($zip->open($path) === true) { + //make all the folders + for ($i = 0; $i < $zip->numFiles; $i++) { + $OnlyFileName = $zip->getNameIndex($i); + $FullFileName = $zip->statIndex($i); + if ($FullFileName['name'][strlen($FullFileName['name']) - 1] == '/') { + create_folder($base_folder.$FullFileName['name']); + } + } + //unzip into the folders + for ($i = 0; $i < $zip->numFiles; $i++) { + $OnlyFileName = $zip->getNameIndex($i); + $FullFileName = $zip->statIndex($i); - if (!($FullFileName['name'][strlen($FullFileName['name']) - 1] == '/')) - { - $fileinfo = pathinfo($OnlyFileName); - if (in_array(strtolower($fileinfo['extension']), $ext)) - { - copy('zip://'.$path.'#'.$OnlyFileName, $base_folder.$FullFileName['name']); - } - } - } - $zip->close(); - } - else - echo 'failed to open file'; - break; - case 'gz': - $p = new PharData($path); - $p->decompress(); // creates files.tar - break; - case 'tar': - // unarchive from the tar - $phar = new PharData($path); - $phar->decompressFiles(); - $files = array(); - check_files_extensions_on_phar($phar, $files, '', $ext); - $phar->extractTo($current_path.fix_dirname($_POST['path']).'/', $files, true); + if (!($FullFileName['name'][strlen($FullFileName['name']) - 1] == '/')) { + $fileinfo = pathinfo($OnlyFileName); + if (in_array(strtolower($fileinfo['extension']), $ext)) { + copy('zip://'.$path.'#'.$OnlyFileName, $base_folder.$FullFileName['name']); + } + } + } + $zip->close(); + } else { + echo 'failed to open file'; + } + break; + case 'gz': + $p = new PharData($path); + $p->decompress(); // creates files.tar + break; + case 'tar': + // unarchive from the tar + $phar = new PharData($path); + $phar->decompressFiles(); + $files = array(); + check_files_extensions_on_phar($phar, $files, '', $ext); + $phar->extractTo($current_path.fix_dirname($_POST['path']).'/', $files, true); - break; - } - break; - case 'media_preview': + break; + } + break; + case 'media_preview': - $preview_file = $_GET['file']; - $info = pathinfo($preview_file); - ?> + $preview_file = $_GET['file']; + $info = pathinfo($preview_file); + ?>