Initial commit

This commit is contained in:
2019-11-20 07:44:43 +01:00
commit 5bf49c4a81
41188 changed files with 5459177 additions and 0 deletions

10
web/src/.htaccess Normal file
View File

@@ -0,0 +1,10 @@
# Apache 2.2
<IfModule !mod_authz_core.c>
Order deny,allow
Deny from all
</IfModule>
# Apache 2.4
<IfModule mod_authz_core.c>
Require all denied
</IfModule>

View File

@@ -0,0 +1,294 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Addons;
use PrestaShop\PrestaShop\Adapter\Module\Module;
use PrestaShop\PrestaShop\Adapter\Module\ModuleZipManager;
use PrestaShopBundle\Service\DataProvider\Admin\AddonsInterface;
use PrestaShopBundle\Service\DataProvider\Marketplace\ApiClient;
use Symfony\Component\HttpFoundation\Request;
use Configuration;
use Context;
use Country;
use Exception;
use Tools;
use PhpEncryption;
/**
* Data provider for new Architecture, about Addons.
*
* This class will provide data from Addons API
*/
class AddonsDataProvider implements AddonsInterface
{
protected static $is_addons_up = true;
private $marketplaceClient;
private $zipManager;
private $encryption;
public $cacheDir;
public function __construct(ApiClient $apiClient, ModuleZipManager $zipManager)
{
$this->marketplaceClient = $apiClient;
$this->zipManager = $zipManager;
$this->encryption = new PhpEncryption(_NEW_COOKIE_KEY_);
}
public function downloadModule($module_id)
{
$params = array(
'id_module' => $module_id,
'format' => 'json',
);
// Module downloading
try {
$module_data = $this->request('module_download', $params);
} catch (Exception $e) {
if (!$this->isAddonsAuthenticated()) {
throw new Exception('Error sent by Addons. You may need to be logged.', 0, $e);
} else {
throw new Exception('Error sent by Addons. You may be not allowed to download this module.', 0, $e);
}
}
$temp_filename = tempnam($this->cacheDir, 'mod');
if (file_put_contents($temp_filename, $module_data) !== false) {
$this->zipManager->storeInModulesFolder($temp_filename);
return true;
} else {
throw new Exception('Cannot store module content in temporary folder !');
}
}
/** Does this function should be in a User related class ? **/
public function isAddonsAuthenticated()
{
$request = Request::createFromGlobals();
return $request->cookies->get('username_addons', false)
&& $request->cookies->get('password_addons', false);
}
/**
* {@inheritdoc}
*/
public function request($action, $params = array())
{
if (!$this->isAddonsUp()) {
throw new Exception('Previous call failed and disabled client.');
}
// We merge the addons credentials
if ($this->isAddonsAuthenticated()) {
$params = array_merge($this->getAddonsCredentials(), $params);
}
$post_query_data = array(
'version' => isset($params['version']) ? $params['version'] : _PS_VERSION_,
'iso_lang' => Tools::strtolower(isset($params['iso_lang']) ? $params['iso_lang']
: Context::getContext()->language->iso_code),
'iso_code' => Tools::strtolower(isset($params['iso_country']) ? $params['iso_country']
: Country::getIsoById(Configuration::get('PS_COUNTRY_DEFAULT'))),
'shop_url' => isset($params['shop_url']) ? $params['shop_url'] : Tools::getShopDomain(),
'mail' => isset($params['email']) ? $params['email'] : Configuration::get('PS_SHOP_EMAIL'),
'format' => isset($params['format']) ? $params['format'] : 'xml',
);
if (isset($params['source'])) {
$post_query_data['source'] = $params['source'];
}
$post_data = http_build_query($post_query_data);
$protocols = array('https');
$end_point = 'api.addons.prestashop.com';
switch ($action) {
case 'native':
try {
return $this->marketplaceClient->getNativesModules();
} catch (Exception $e) {
self::$is_addons_up = false;
throw $e;
}
case 'service':
try {
return $this->marketplaceClient->getServices();
} catch (Exception $e) {
self::$is_addons_up = false;
throw $e;
}
case 'native_all':
try {
return $this->marketplaceClient->setIsoCode('all')
->getNativesModules();
} catch (Exception $e) {
self::$is_addons_up = false;
throw $e;
}
case 'must-have':
try {
return $this->marketplaceClient->getMustHaveModules();
} catch (Exception $e) {
self::$is_addons_up = false;
throw $e;
}
case 'must-have-themes':
$protocols[] = 'http';
$post_data .= '&method=listing&action=must-have-themes';
break;
case 'customer':
try {
return $this->marketplaceClient->getCustomerModules($params['username_addons'], $params['password_addons']);
} catch (Exception $e) {
self::$is_addons_up = false;
throw $e;
}
case 'customer_themes':
$post_data .= '&method=listing&action=customer-themes&username='.urlencode($params['username_addons'])
.'&password='.urlencode($params['password_addons']);
break;
case 'check_customer':
$post_data .= '&method=check_customer&username='.urlencode($params['username_addons']).'&password='.urlencode($params['password_addons']);
break;
case 'check_module':
$post_data .= '&method=check&module_name='.urlencode($params['module_name']).'&module_key='.urlencode($params['module_key']);
break;
case 'module_download':
$post_data .= '&method=module&id_module='.urlencode($params['id_module']);
if (isset($params['username_addons']) && isset($params['password_addons'])) {
$post_data .= '&username='.urlencode($params['username_addons']).'&password='.urlencode($params['password_addons']);
} else {
$protocols[] = 'http';
}
break;
case 'module':
try {
return $this->marketplaceClient->getModule($params['id_module']);
} catch (Exception $e) {
self::$is_addons_up = false;
throw $e;
}
case 'hosted_module':
$post_data .= '&method=module&id_module='.urlencode((int) $params['id_module']).'&username='.urlencode($params['hosted_email'])
.'&password='.urlencode($params['password_addons'])
.'&shop_url='.urlencode(isset($params['shop_url']) ? $params['shop_url']
: Tools::getShopDomain())
.'&mail='.urlencode(isset($params['email']) ? $params['email']
: Configuration::get('PS_SHOP_EMAIL'));
$protocols[] = 'https';
break;
case 'install-modules':
$protocols[] = 'http';
$post_data .= '&method=listing&action=install-modules';
$post_data .= defined('_PS_HOST_MODE_') ? '-od' : '';
break;
case 'categories':
try {
return $this->marketplaceClient->getCategories();
} catch (Exception $e) {
self::$is_addons_up = false;
throw $e;
}
default:
return false;
}
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'content' => $post_data,
'header' => 'Content-type: application/x-www-form-urlencoded',
'timeout' => 5,
),
));
foreach ($protocols as $protocol) {
$content = Tools::file_get_contents($protocol.'://'.$end_point,
false, $context);
if (!$content) {
continue;
}
if ($post_query_data['format'] == 'json' && ctype_print($content)) {
$json_result = json_decode($content);
if ($json_result === false) {
self::$is_addons_up = false;
throw new Exception('Cannot decode JSON from Addons');
}
if (!empty($json_result->errors)) {
self::$is_addons_up = false;
throw new Exception('Error received from Addons: '.json_encode($json_result->errors));
}
return $json_result;
} else {
return $content; // Return raw result
}
}
self::$is_addons_up = false;
throw new Exception('Cannot execute request '.$action.' to Addons');
}
protected function getAddonsCredentials()
{
$request = Request::createFromGlobals();
$username = $this->encryption->decrypt($request->cookies->get('username_addons'));
$password = $this->encryption->decrypt($request->cookies->get('password_addons'));
return array(
'username_addons' => $username,
'password_addons' => $password,
);
}
/** Does this function should be in a User related class ? **/
public function getAddonsEmail()
{
$request = Request::createFromGlobals();
$username = $this->encryption->decrypt($request->cookies->get('username_addons'));
return array(
'username_addons' => $username,
);
}
/**
* Check if a request has already failed.
*
* @return bool
*/
public function isAddonsUp()
{
return self::$is_addons_up;
}
}

View File

@@ -0,0 +1,228 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Addons;
use PrestaShop\PrestaShop\Adapter\Module\ModuleZipManager;
use PrestaShopBundle\Service\DataProvider\Admin\AddonsInterface;
use PrestaShopBundle\Service\DataProvider\Marketplace\ApiClient;
use Symfony\Component\HttpFoundation\Request;
use Exception;
use PhpEncryption;
/**
* Data provider for new Architecture, about Addons.
*
* This class will provide data from Addons API
*/
class AddonsDataProvider implements AddonsInterface
{
/**
* @var bool
*/
protected static $is_addons_up = true;
/**
* @var ApiClient
*/
private $marketplaceClient;
/**
* @var ModuleZipManager
*/
private $zipManager;
/**
* @var PhpEncryption
*/
private $encryption;
/**
* @var string the cache directory location
*/
public $cacheDir;
public function __construct(ApiClient $apiClient, ModuleZipManager $zipManager)
{
$this->marketplaceClient = $apiClient;
$this->zipManager = $zipManager;
$this->encryption = new PhpEncryption(_NEW_COOKIE_KEY_);
}
/**
* @param $module_id
*
* @return bool
*
* @throws Exception
*/
public function downloadModule($module_id)
{
$params = array(
'id_module' => $module_id,
'format' => 'json',
);
// Module downloading
try {
$module_data = $this->request('module_download', $params);
} catch (Exception $e) {
if (!$this->isAddonsAuthenticated()) {
throw new Exception('Error sent by Addons. You may need to be logged.', 0, $e);
} else {
throw new Exception('Error sent by Addons. You may be not allowed to download this module.', 0, $e);
}
}
$temp_filename = tempnam($this->cacheDir, 'mod');
if (file_put_contents($temp_filename, $module_data) !== false) {
$this->zipManager->storeInModulesFolder($temp_filename);
return true;
} else {
throw new Exception('Cannot store module content in temporary folder !');
}
}
/**
* @return bool
*
* @todo Does this function should be in a User related class ?
*/
public function isAddonsAuthenticated()
{
$request = Request::createFromGlobals();
return $request->cookies->get('username_addons', false)
&& $request->cookies->get('password_addons', false);
}
/**
* {@inheritdoc}
*/
public function request($action, $params = array())
{
if (!$this->isAddonsUp()) {
throw new Exception('Previous call failed and disabled client.');
}
// We merge the addons credentials
if ($this->isAddonsAuthenticated()) {
$params = array_merge($this->getAddonsCredentials(), $params);
}
$this->marketplaceClient->reset();
try {
switch ($action) {
case 'native':
return $this->marketplaceClient->getNativesModules();
case 'service':
return $this->marketplaceClient->getServices();
case 'native_all':
return $this->marketplaceClient->setIsoCode('all')
->getNativesModules();
case 'must-have':
return $this->marketplaceClient->getMustHaveModules();
case 'customer':
return $this->marketplaceClient->getCustomerModules($params['username_addons'], $params['password_addons']);
case 'customer_themes':
return $this->marketplaceClient
->setUserMail($params['username_addons'])
->setPassword($params['password_addons'])
->getCustomerThemes();
case 'check_customer':
return $this->marketplaceClient
->setUserMail($params['username_addons'])
->setPassword($params['password_addons'])
->getCheckCustomer();
case 'check_module':
return $this->marketplaceClient
->setUserMail($params['username_addons'])
->setPassword($params['password_addons'])
->setModuleName($params['module_name'])
->setModuleKey($params['module_key'])
->getCheckModule();
case 'module_download':
if ($this->isAddonsAuthenticated()) {
return $this->marketplaceClient
->setUserMail($params['username_addons'])
->setPassword($params['password_addons'])
->getModuleZip($params['id_module']);
}
return $this->marketplaceClient->getModuleZip($params['id_module']);
case 'module':
return $this->marketplaceClient->getModule($params['id_module']);
case 'install-modules':
return $this->marketplaceClient->getPreInstalledModules();
case 'categories':
return $this->marketplaceClient->getCategories();
}
} catch (Exception $e) {
self::$is_addons_up = false;
throw $e;
}
}
/**
* @return array
*
* @throws Exception
*/
protected function getAddonsCredentials()
{
$request = Request::createFromGlobals();
$username = $this->encryption->decrypt($request->cookies->get('username_addons'));
$password = $this->encryption->decrypt($request->cookies->get('password_addons'));
return array(
'username_addons' => $username,
'password_addons' => $password,
);
}
/** Does this function should be in a User related class ? **/
public function getAddonsEmail()
{
$request = Request::createFromGlobals();
$username = $this->encryption->decrypt($request->cookies->get('username_addons'));
return array(
'username_addons' => $username,
);
}
/**
* Check if a request has already failed.
*
* @return bool
*/
public function isAddonsUp()
{
return self::$is_addons_up;
}
}

View File

@@ -0,0 +1,56 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter;
use Address;
class AddressFactory
{
/**
* Initialize 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)
{
return Address::addressExists($id_address);
}
}

View File

@@ -0,0 +1,63 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter;
use Address;
/**
* Class responsible of creation of Address ObjectModel.
*/
class AddressFactory
{
/**
* Initialize an address corresponding to the specified id address or if empty to the
* default shop configuration.
*
* @param int|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)
{
return Address::addressExists($id_address);
}
}

View File

@@ -0,0 +1,203 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Admin;
use PrestaShop\PrestaShop\Adapter\Validate;
use Symfony\Component\Process\Exception\LogicException;
/**
* Base class for data provider, to give common Adapter functions.
*
* Contains methods to compile SQL from parseable arrays of select, tables, joins, where, etc...
*/
abstract class AbstractAdminQueryBuilder
{
const FILTERING_LIKE_BOTH = 'LIKE \'%%%s%%\'';
const FILTERING_LIKE_LEFT = 'LIKE \'%%%s\'';
const FILTERING_LIKE_RIGHT = 'LIKE \'%s%%\'';
const FILTERING_EQUAL_NUMERIC = '= %s';
const FILTERING_EQUAL_STRING = '= \'%s\'';
private $lastCompiledSql = null;
final private function compileSqlWhere(array $whereArray)
{
$operator = 'AND';
$s = array();
while ($item = array_shift($whereArray)) {
if ($item == 'OR') {
$operator = 'OR';
} elseif ($item == 'AND') {
$operator = 'AND';
} else {
$s[] = (is_array($item)? $this->compileSqlWhere($item) : $item);
}
}
if (count($s) == 1) {
return $s[0];
}
return '('.implode(' '.$operator.' ', $s).')';
}
/**
* Compiles a SQL query (SELECT), from a group of associative arrays.
*
* @see PrestaShop\PrestaShop\Adapter\Product\AdminProductDataProvider::getCatalogProductList() for an example.
*
* Format example for $table:
* $table = array(
* 'p' => 'product', // First table: a simple name
* 'pl' => array( // Next: arrays to set join properly
* 'table' => 'product_lang',
* 'join' => 'LEFT JOIN',
* 'on' => 'pl.`id_product` = p.`id_product` AND pl.`id_lang` = '.$idLang.' AND pl.`id_shop` = '.$idShop
* ),
* 'sav' => array(
* 'table' => 'stock_available',
* 'join' => 'LEFT JOIN',
* 'on' => 'sav.`id_product` = p.`id_product` AND sav.`id_product_attribute` = 0 AND sav.id_shop_group = 1 AND sav.id_shop = 0'
* ),
* ...
* );
*
* Format example for $select:
* $select = array(
* 'id_product' => array('table' => 'p', 'field' => 'id_product', 'filtering' => self::FILTERING_EQUAL_NUMERIC),
* 'reference' => array('table' => 'p', 'field' => 'reference', 'filtering' => self::FILTERING_LIKE_BOTH),
* ...
* );
*
* Format example for $where:
* $where = array(
* 'AND', // optional if AND, mandatory if OR.
* 1, // First condition: let 1 here if there is no condition, then "WHERE 1;" will work better than "WHERE ;"
* array('OR', '2', '3'),
* array(
* 'AND',
* array('OR', '4', '5'),
* array('6', '7')
* )
* );
* In the WHERE, it's up to you to build each condition string. You can use the 'filtering' data in the $select array to help you:
* $where[] = $select[$field]['table'].'.`'.$select[$field]['field'].'` '.sprintf($select[$field]['filtering'], $filterValue);
*
* Format example for $order:
* $order = array('name ASC', 'id_product DESC');
*
* @param array[array[mixed]] $select
* @param array[mixed] $table
* @param array[mixed] $where
* @param array[string] $order
* @param string $limit
* @throws LogicException if SQL elements cannot be joined.
* @return string The SQL query ready to be executed.
*/
protected function compileSqlQuery(array $select, array $table, array $where = array(), array $order = array(), $limit = null)
{
$sql = array();
// SELECT
$s = array();
foreach ($select as $alias => $field) {
$a = is_string($alias)? ' AS `'.$alias.'`' : '';
if (is_array($field)) {
if (isset($field['table'])) {
$s[] = ' '.$field['table'].'.`'.$field['field'].'` '.$a;
} elseif (isset($field['select'])) {
$s[] = ' '.$field['select'].$a;
}
} else {
$s[] = ' '.$field.$a;
}
}
if (count($s) === 0) {
throw new LogicException('Compile SQL failed: No field to SELECT!');
}
$sql[] = 'SELECT SQL_CALC_FOUND_ROWS'.implode(','.PHP_EOL, $s);
// FROM / JOIN
$s = array();
foreach ($table as $alias => $join) {
if (!is_array($join)) {
if (count($s) > 0) {
throw new LogicException('Compile SQL failed: cannot join the table '.$join.' into SQL query without JOIN sepcs.');
}
$s[0] = ' `'._DB_PREFIX_.$join.'` '.$alias;
} else {
if (count($s) === 0) {
throw new LogicException('Compile SQL failed: cannot join the table alias '.$alias.' into SQL query before to insert initial table.');
}
$s[] = ' '.$join['join'].' `'._DB_PREFIX_.$join['table'].'` '.$alias.((isset($join['on']))?' ON ('.$join['on'].')':'');
}
}
if (count($s) === 0) {
throw new LogicException('Compile SQL failed: No table to insert into FROM!');
}
$sql[] = 'FROM '.implode(' '.PHP_EOL, $s);
// WHERE (recursive call)
if (count($where)) {
$s = $this->compileSqlWhere($where);
if (strlen($s) > 0) {
$sql[] = 'WHERE '.$s.PHP_EOL;
}
}
// ORDER
if (count($order) > 0) {
$goodOrder = array();
foreach ($order as $k => $o) {
$value = explode(' ', $o);
if (!empty($value) && 2 === count($value) && Validate::isOrderBy($value[0]) && Validate::isOrderWay($value[1])) {
$goodOrder[] = ' `'.bqSQL($value[0]).'` '. $value[1];
}
}
if (count($goodOrder) > 0) {
$sql[] = 'ORDER BY ' . implode(', ', $goodOrder) . PHP_EOL;
}
}
// LIMIT
if ($limit) {
$sql[] = 'LIMIT '.$limit.PHP_EOL;
}
$this->lastCompiledSql = implode(' '.PHP_EOL, $sql).';';
return $this->lastCompiledSql;
}
/**
* Returns the last SQL query that was compiled on this Provider.
*
* @return string The last SQL query that was compiled with $this->compileSqlQuery()
*/
public function getLastCompiledSql()
{
return $this->lastCompiledSql;
}
}

View File

@@ -0,0 +1,221 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Admin;
use PrestaShop\PrestaShop\Adapter\Validate;
use Symfony\Component\Process\Exception\LogicException;
/**
* Base class for data provider, to give common Adapter functions.
*
* Contains methods to compile SQL from parseable arrays of select, tables, joins, where, etc...
*/
abstract class AbstractAdminQueryBuilder
{
const FILTERING_LIKE_BOTH = 'LIKE \'%%%s%%\'';
const FILTERING_LIKE_LEFT = 'LIKE \'%%%s\'';
const FILTERING_LIKE_RIGHT = 'LIKE \'%s%%\'';
const FILTERING_EQUAL_NUMERIC = '= %s';
const FILTERING_EQUAL_STRING = '= \'%s\'';
/**
* @var string|null
*/
private $lastCompiledSql = null;
/**
* @param array $whereArray
*
* @return mixed|string
*/
private function compileSqlWhere(array $whereArray)
{
$operator = 'AND';
$s = array();
while ($item = array_shift($whereArray)) {
if ($item == 'OR') {
$operator = 'OR';
} elseif ($item == 'AND') {
$operator = 'AND';
} else {
$s[] = (is_array($item) ? $this->compileSqlWhere($item) : $item);
}
}
if (count($s) == 1) {
return $s[0];
}
return '(' . implode(' ' . $operator . ' ', $s) . ')';
}
/**
* Compiles a SQL query (SELECT), from a group of associative arrays.
*
* @see \PrestaShop\PrestaShop\Adapter\Product\AdminProductDataProvider::getCatalogProductList() for an example.
*
* Format example for $table:
* $table = array(
* 'p' => 'product', // First table: a simple name
* 'pl' => array( // Next: arrays to set join properly
* 'table' => 'product_lang',
* 'join' => 'LEFT JOIN',
* 'on' => 'pl.`id_product` = p.`id_product` AND pl.`id_lang` = '.$idLang.' AND pl.`id_shop` = '.$idShop
* ),
* 'sav' => array(
* 'table' => 'stock_available',
* 'join' => 'LEFT JOIN',
* 'on' => 'sav.`id_product` = p.`id_product` AND sav.`id_product_attribute` = 0 AND sav.id_shop_group = 1 AND sav.id_shop = 0'
* ),
* ...
* );
*
* Format example for $select:
* $select = array(
* 'id_product' => array('table' => 'p', 'field' => 'id_product', 'filtering' => self::FILTERING_EQUAL_NUMERIC),
* 'reference' => array('table' => 'p', 'field' => 'reference', 'filtering' => self::FILTERING_LIKE_BOTH),
* ...
* );
*
* Format example for $where:
* $where = array(
* 'AND', // optional if AND, mandatory if OR.
* 1, // First condition: let 1 here if there is no condition, then "WHERE 1;" will work better than "WHERE ;"
* array('OR', '2', '3'),
* array(
* 'AND',
* array('OR', '4', '5'),
* array('6', '7')
* )
* );
* In the WHERE, it's up to you to build each condition string. You can use the 'filtering' data in the $select array to help you:
* $where[] = $select[$field]['table'].'.`'.$select[$field]['field'].'` '.sprintf($select[$field]['filtering'], $filterValue);
*
* Format example for $order:
* $order = array('name ASC', 'id_product DESC');
*
* @param array[array[mixed]] $select
* @param array[mixed] $table
* @param array[mixed] $where
* @param array[string] $groupBy
* @param array[string] $order
* @param string $limit
*
* @throws LogicException if SQL elements cannot be joined
*
* @return string the SQL query ready to be executed
*/
protected function compileSqlQuery(array $select, array $table, array $where = array(), array $groupBy = array(), array $order = array(), $limit = null)
{
$sql = array();
// SELECT
$s = array();
foreach ($select as $alias => $field) {
$a = is_string($alias) ? ' AS `' . $alias . '`' : '';
if (is_array($field)) {
if (isset($field['table'])) {
$s[] = ' ' . $field['table'] . '.`' . $field['field'] . '` ' . $a;
} elseif (isset($field['select'])) {
$s[] = ' ' . $field['select'] . $a;
}
} else {
$s[] = ' ' . $field . $a;
}
}
if (count($s) === 0) {
throw new LogicException('Compile SQL failed: No field to SELECT!');
}
$sql[] = 'SELECT SQL_CALC_FOUND_ROWS' . implode(',' . PHP_EOL, $s);
// FROM / JOIN
$s = array();
foreach ($table as $alias => $join) {
if (!is_array($join)) {
if (count($s) > 0) {
throw new LogicException('Compile SQL failed: cannot join the table ' . $join . ' into SQL query without JOIN sepcs.');
}
$s[0] = ' `' . _DB_PREFIX_ . $join . '` ' . $alias;
} else {
if (count($s) === 0) {
throw new LogicException('Compile SQL failed: cannot join the table alias ' . $alias . ' into SQL query before to insert initial table.');
}
$s[] = ' ' . $join['join'] . ' `' . _DB_PREFIX_ . $join['table'] . '` ' . $alias . ((isset($join['on'])) ? ' ON (' . $join['on'] . ')' : '');
}
}
if (count($s) === 0) {
throw new LogicException('Compile SQL failed: No table to insert into FROM!');
}
$sql[] = 'FROM ' . implode(' ' . PHP_EOL, $s);
// WHERE (recursive call)
if (count($where)) {
$s = $this->compileSqlWhere($where);
if (strlen($s) > 0) {
$sql[] = 'WHERE ' . $s . PHP_EOL;
}
}
// GROUP BY
if (!empty($groupBy)) {
$sql[] = 'GROUP BY ' . implode(', ', array_map('pSQL', $groupBy)) . PHP_EOL;
}
// ORDER
if (count($order) > 0) {
$goodOrder = array();
foreach ($order as $o) {
$value = explode(' ', $o);
if (!empty($value) && 2 === count($value) && Validate::isOrderBy($value[0]) && Validate::isOrderWay($value[1])) {
$goodOrder[] = ' `' . bqSQL($value[0]) . '` ' . $value[1];
}
}
if (count($goodOrder) > 0) {
$sql[] = 'ORDER BY ' . implode(', ', $goodOrder) . PHP_EOL;
}
}
// LIMIT
if ($limit) {
$sql[] = 'LIMIT ' . $limit . PHP_EOL;
}
$this->lastCompiledSql = implode(' ' . PHP_EOL, $sql) . ';';
return $this->lastCompiledSql;
}
/**
* Returns the last SQL query that was compiled on this Provider.
*
* @return string The last SQL query that was compiled with $this->compileSqlQuery()
*/
public function getLastCompiledSql()
{
return $this->lastCompiledSql;
}
}

View File

@@ -0,0 +1,67 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Admin;
use PrestaShopBundle\Service\Hook\RenderingHookEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Adds listeners to renderhook Twig function, to let adding legacy helpers like Kpi, etc...
*
* @package PrestaShop\PrestaShop\Adapter\Admin
*/
class LegacyBlockHelperSubscriber implements EventSubscriberInterface
{
/**
* Returns an array of event names this subscriber wants to listen to.
*
* @return array The listeners array
*/
public static function getSubscribedEvents()
{
return array(
'legacy_block_kpi' => array('renderKpi', 0)
);
}
/**
* Renders a Kpi block for a given legacy controller name.
*
* @param RenderingHookEvent $event
* @throws \Exception
*/
public function renderKpi(RenderingHookEvent $event)
{
if (!array_key_exists('kpi_controller', $event->getHookParameters())) {
throw new \Exception('The legacy_kpi hook need a kpi_controller parameter (legacy controller full class name).');
}
$controller = $event->getHookParameters()['kpi_controller'];
$controller = new $controller('new-theme');
$event->setContent($controller->renderKpis());
}
}

View File

@@ -0,0 +1,68 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Admin;
use PrestaShopBundle\Service\Hook\RenderingHookEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Adds listeners to renderhook Twig function, to let adding legacy helpers like Kpi, etc...
*/
class LegacyBlockHelperSubscriber implements EventSubscriberInterface
{
/**
* Returns an array of event names this subscriber wants to listen to.
*
* @return array The listeners array
*/
public static function getSubscribedEvents()
{
return array(
'legacy_block_kpi' => array('renderKpi', 0),
);
}
/**
* Renders a Kpi block for a given legacy controller name.
*
* @param RenderingHookEvent $event
*
* @throws \Exception
*/
public function renderKpi(RenderingHookEvent $event)
{
if (!array_key_exists('kpi_controller', $event->getHookParameters())) {
throw new \Exception('The legacy_kpi hook need a kpi_controller parameter (legacy controller full class name).');
}
$controller = $event->getHookParameters()['kpi_controller'];
$controller = new $controller('new-theme');
$renderKpis = $controller->renderKpis() !== null ? $controller->renderKpis() : [];
$event->setContent($renderKpis);
}
}

View File

@@ -0,0 +1,86 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Admin;
use PrestaShop\PrestaShop\Adapter\Configuration;
use PrestaShop\PrestaShop\Core\Configuration\DataConfigurationInterface;
/**
* Manages the configuration data about notifications options.
*/
class NotificationsConfiguration implements DataConfigurationInterface
{
/**
* @var Configuration
*/
private $configuration;
public function __construct(Configuration $configuration)
{
$this->configuration = $configuration;
}
/**
* {@inheritdoc}
*/
public function getConfiguration()
{
return array(
'show_notifs_new_orders' => $this->configuration->getBoolean('PS_SHOW_NEW_ORDERS'),
'show_notifs_new_customers' => $this->configuration->getBoolean('PS_SHOW_NEW_CUSTOMERS'),
'show_notifs_new_messages' => $this->configuration->getBoolean('PS_SHOW_NEW_MESSAGES'),
);
}
/**
* {@inheritdoc}
*/
public function updateConfiguration(array $configuration)
{
$errors = array();
if ($this->validateConfiguration($configuration)) {
$this->configuration->set('PS_SHOW_NEW_ORDERS', (bool) $configuration['show_notifs_new_orders']);
$this->configuration->set('PS_SHOW_NEW_CUSTOMERS', (bool) $configuration['show_notifs_new_customers']);
$this->configuration->set('PS_SHOW_NEW_MESSAGES', (bool) $configuration['show_notifs_new_messages']);
}
return $errors;
}
/**
* {@inheritdoc}
*/
public function validateConfiguration(array $configuration)
{
return isset(
$configuration['show_notifs_new_orders'],
$configuration['show_notifs_new_customers'],
$configuration['show_notifs_new_messages']
);
}
}

View File

@@ -0,0 +1,119 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Admin;
use PrestaShopBundle\Service\TransitionalBehavior\AdminPagePreferenceInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpFoundation\Session\Storage\PhpBridgeSessionStorage;
use Db;
/**
* Adapter to know which page's version to display.
*
* This implementation gives methods to use to take decision:
* - if we should display the new refactored page, or the old legacy one.
* - if we should display the switch on the admin layout to change this setting.
*
* Data is stored in the cookie, as legacy does.
*/
class PagePreference implements AdminPagePreferenceInterface
{
private $session;
public function __construct(SessionInterface $session)
{
if ($session->isStarted()) {
$this->session = $session;
} else {
$sessionClass = get_class($session);
$this->session = new $sessionClass(new PhpBridgeSessionStorage());
}
}
/* (non-PHPdoc)
* @see \PrestaShopCoreAdminBundle\TransitionalBehavior\AdminPagePreferenceInterface::getTemporaryShouldUseLegacyPage()
*/
public function getTemporaryShouldUseLegacyPage($page)
{
if (!$page) {
throw new \InvalidParameterException('$page parameter missing');
}
return ($this->session->has('should_use_legacy_page_for_'.$page) && $this->session->get('should_use_legacy_page_for_'.$page, 0) == 1);
}
/* (non-PHPdoc)
* @see \PrestaShopCoreAdminBundle\TransitionalBehavior\AdminPagePreferenceInterface::setTemporaryShouldUseLegacyPage()
*/
public function setTemporaryShouldUseLegacyPage($page, $useLegacy)
{
if (!$page) {
throw new \InvalidParameterException('$page parameter missing');
}
if ((bool)$useLegacy) {
$this->session->set('should_use_legacy_page_for_'.$page, 1);
} else {
$this->session->remove('should_use_legacy_page_for_'.$page);
}
}
/* (non-PHPdoc)
* @see \PrestaShopCoreAdminBundle\TransitionalBehavior\AdminPagePreferenceInterface::getTemporaryShouldAllowUseLegacyPage()
*/
public function getTemporaryShouldAllowUseLegacyPage($page = null)
{
// Dev mode: always shown
if (_PS_MODE_DEV_) {
return true;
}
$version = Db::getInstance()->getValue('SELECT `value` FROM `'._DB_PREFIX_.'configuration` WHERE `name` = "PS_INSTALL_VERSION"');
if (!$version) {
return false;
}
$installVersion = explode('.', $version);
$currentVersion = explode('.', _PS_VERSION_);
// Prod mode, depends on the page
switch ($page) {
case 'product':
// never show it for Product page in production mode.
return false;
default:
// show only for 1.7.x
if ($currentVersion[0] != '1' || $currentVersion[1] != '7') {
return false;
}
// show only if upgrade from older version than current one
if ($installVersion[0] >= $currentVersion[0] || $installVersion[1] >= $currentVersion[1]) {
return false;
}
}
return true;
}
}

View File

@@ -0,0 +1,124 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Admin;
use PrestaShopBundle\Service\TransitionalBehavior\AdminPagePreferenceInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpFoundation\Session\Storage\PhpBridgeSessionStorage;
use AppKernel;
use Db;
/**
* Adapter to know which page's version to display.
*
* This implementation gives methods to use to take decision:
* - if we should display the new refactored page, or the old legacy one.
* - if we should display the switch on the admin layout to change this setting.
*
* Data is stored in the cookie, as legacy does.
*/
class PagePreference implements AdminPagePreferenceInterface
{
/**
* @var SessionInterface
*/
private $session;
public function __construct(SessionInterface $session)
{
if ($session->isStarted()) {
$this->session = $session;
} else {
$sessionClass = get_class($session);
$this->session = new $sessionClass(new PhpBridgeSessionStorage());
}
}
/**
* {@inheritdoc}
*/
public function getTemporaryShouldUseLegacyPage($page)
{
if (!$page) {
throw new \InvalidParameterException('$page parameter missing');
}
return $this->session->has('should_use_legacy_page_for_' . $page) && $this->session->get('should_use_legacy_page_for_' . $page, 0) == 1;
}
/**
* {@inheritdoc}
*/
public function setTemporaryShouldUseLegacyPage($page, $useLegacy)
{
if (!$page) {
throw new \InvalidParameterException('$page parameter missing');
}
if ((bool) $useLegacy) {
$this->session->set('should_use_legacy_page_for_' . $page, 1);
} else {
$this->session->remove('should_use_legacy_page_for_' . $page);
}
}
/**
* {@inheritdoc}
*/
public function getTemporaryShouldAllowUseLegacyPage($page = null)
{
// Dev mode: always shown
if (_PS_MODE_DEV_) {
return true;
}
$version = Db::getInstance()->getValue('SELECT `value` FROM `' . _DB_PREFIX_ . 'configuration` WHERE `name` = "PS_INSTALL_VERSION"');
if (!$version) {
return false;
}
$installVersion = explode('.', $version);
$currentVersion = explode('.', AppKernel::VERSION);
// Prod mode, depends on the page
switch ($page) {
case 'product':
// never show it for Product page in production mode.
return false;
default:
// show only for 1.7.x
if ($currentVersion[0] != '1' || $currentVersion[1] != '7') {
return false;
}
// show only if upgrade from older version than current one
if ($installVersion[0] >= $currentVersion[0] || $installVersion[1] >= $currentVersion[1]) {
return false;
}
}
return true;
}
}

View File

@@ -0,0 +1,127 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Admin;
use Symfony\Component\Routing\Router;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RequestContext;
use PrestaShop\PrestaShop\Adapter\LegacyContext;
use Symfony\Component\Process\Exception\LogicException;
use ReflectionClass;
/**
* This UrlGeneratorInterface implementation (in a Sf service) will provides Legacy URLs.
*
* To be used by Symfony controllers, to generate a link to a Legacy page.
* Call an instance of it through the Symfony container:
* $container->get('prestashop.core.admin.url_generator_legacy');
* Or via the UrlGeneratorFactory (as Sf service):
* $container->get('prestashop.core.admin.url_generator_factory')->forLegacy();
*/
class UrlGenerator implements UrlGeneratorInterface
{
/**
* @var LegacyContext
*/
private $legacyContext;
/**
* @var Router
*/
private $router;
/**
* Constructor.
*
* @param LegacyContext $legacyContext
* @param Router
*/
public function __construct(LegacyContext $legacyContext, Router $router)
{
$this->legacyContext = $legacyContext;
$this->router = $router;
}
/* (non-PHPdoc)
* @see \Symfony\Component\Routing\Generator\UrlGeneratorInterface::generate()
*/
public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH)
{
// By default, consider given parameters in legacy format (no mapping if route not found).
$legacyController = $name;
$legacyParameters = $parameters;
// resolve route & legacy mapping
list($legacyController, $legacyParameters) = $this->getLegacyOptions($name, $parameters);
return $this->legacyContext->getAdminLink($legacyController, true, $legacyParameters);
}
/**
* Try to get controller & parameters with mapping options.
*
* If failed to find options, then return the input values.
*
* @param string $routeName
* @param string[] $parameters The route parameters to convert
* @return array[] An array with: the legacy controller name, then the parameters array
*/
final public function getLegacyOptions($routeName, $parameters = array())
{
$legacyController = $routeName;
$legacyParameters = $parameters;
$route = $this->router->getRouteCollection()->get($routeName);
if ($route) {
if ($route->hasDefault('_legacy_controller')) {
$legacyController = $route->getDefault('_legacy_controller');
if ($route->hasDefault('_legacy_param_mapper_class') && $route->hasDefault('_legacy_param_mapper_method')) {
$class = $route->getDefault('_legacy_param_mapper_class');
$method = $route->getDefault('_legacy_param_mapper_method');
$method = (new ReflectionClass('\\'.$class))->getMethod($method);
$legacyParameters = $method->invoke(($method->isStatic())?null:$method->getDeclaringClass()->newInstance(), $parameters);
}
}
}
return array($legacyController, $legacyParameters);
}
/* (non-PHPdoc)
* @see \Symfony\Component\Routing\RequestContextAwareInterface::setContext()
*/
public function setContext(RequestContext $context)
{
throw new LogicException('Cannot use this UrlGeneratorInterface implementation with a Symfony context. Please call AdminUrlGeneratorFactory::forLegacy() to reach the right instance.');
}
/* (non-PHPdoc)
* @see \Symfony\Component\Routing\RequestContextAwareInterface::getContext()
*/
public function getContext()
{
throw new LogicException('Cannot use this UrlGeneratorInterface implementation with a Symfony context. Please call AdminUrlGeneratorFactory::forLegacy() to reach the right instance.');
}
}

View File

@@ -0,0 +1,130 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Admin;
use Symfony\Component\Routing\Router;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RequestContext;
use PrestaShop\PrestaShop\Adapter\LegacyContext;
use Symfony\Component\Process\Exception\LogicException;
use ReflectionClass;
/**
* This UrlGeneratorInterface implementation (in a Sf service) will provides Legacy URLs.
*
* To be used by Symfony controllers, to generate a link to a Legacy page.
* Call an instance of it through the Symfony container:
* $container->get('prestashop.core.admin.url_generator_legacy');
* Or via the UrlGeneratorFactory (as Sf service):
* $container->get('prestashop.core.admin.url_generator_factory')->forLegacy();
*/
class UrlGenerator implements UrlGeneratorInterface
{
/**
* @var LegacyContext
*/
private $legacyContext;
/**
* @var Router
*/
private $router;
/**
* Constructor.
*
* @param LegacyContext $legacyContext
* @param Router
*/
public function __construct(LegacyContext $legacyContext, Router $router)
{
$this->legacyContext = $legacyContext;
$this->router = $router;
}
/**
* {@inheritdoc}
*/
public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH)
{
// By default, consider given parameters in legacy format (no mapping if route not found).
$legacyController = $name;
$legacyParameters = $parameters;
// resolve route & legacy mapping
list($legacyController, $legacyParameters) = $this->getLegacyOptions($name, $parameters);
return $this->legacyContext->getAdminLink($legacyController, true, $legacyParameters);
}
/**
* Try to get controller & parameters with mapping options.
*
* If failed to find options, then return the input values.
*
* @param string $routeName
* @param string[] $parameters The route parameters to convert
*
* @return array[] An array with: the legacy controller name, then the parameters array
*/
final public function getLegacyOptions($routeName, $parameters = array())
{
$legacyController = $routeName;
$legacyParameters = $parameters;
$route = $this->router->getRouteCollection()->get($routeName);
if ($route) {
if ($route->hasDefault('_legacy_controller')) {
$legacyController = $route->getDefault('_legacy_controller');
if ($route->hasDefault('_legacy_param_mapper_class') && $route->hasDefault('_legacy_param_mapper_method')) {
$class = $route->getDefault('_legacy_param_mapper_class');
$method = $route->getDefault('_legacy_param_mapper_method');
$method = (new ReflectionClass('\\' . $class))->getMethod($method);
$legacyParameters = $method->invoke(($method->isStatic()) ? null : $method->getDeclaringClass()->newInstance(), $parameters);
}
}
}
return array($legacyController, $legacyParameters);
}
/**
* {@inheritdoc}
*/
public function setContext(RequestContext $context)
{
throw new LogicException('Cannot use this UrlGeneratorInterface implementation with a Symfony context. Please call AdminUrlGeneratorFactory::forLegacy() to reach the right instance.');
}
/**
* {@inheritdoc}
*/
public function getContext()
{
throw new LogicException('Cannot use this UrlGeneratorInterface implementation with a Symfony context. Please call AdminUrlGeneratorFactory::forLegacy() to reach the right instance.');
}
}

View File

@@ -0,0 +1,62 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Assets;
use Tools as ToolsLegacy;
trait AssetUrlGeneratorTrait
{
protected $fqdn;
protected function getUriFromPath($fullPath)
{
return str_replace($this->configuration->get('_PS_ROOT_DIR_'), rtrim($this->configuration->get('__PS_BASE_URI__'), '/'), $fullPath);
}
protected function getPathFromUri($fullUri)
{
if ('' !== ($trimmedUri = rtrim($this->configuration->get('__PS_BASE_URI__'), '/'))) {
return $this->configuration->get('_PS_ROOT_DIR_').preg_replace('#\\'.$trimmedUri.'#', '', $fullUri, 1);
}
return $this->configuration->get('_PS_ROOT_DIR_').$fullUri;
}
protected function getFQDN()
{
if (is_null($this->fqdn)) {
if ($this->configuration->get('PS_SSL_ENABLED') && ToolsLegacy::usingSecureMode()) {
$this->fqdn = $this->configuration->get('_PS_BASE_URL_SSL_');
} else {
$this->fqdn = $this->configuration->get('_PS_BASE_URL_');
}
}
return $this->fqdn;
}
}

View File

@@ -0,0 +1,78 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Assets;
use Tools as ToolsLegacy;
trait AssetUrlGeneratorTrait
{
/**
* @var string
*/
protected $fqdn;
/**
* @param string $fullPath
*
* @return string
*/
protected function getUriFromPath($fullPath)
{
return str_replace($this->configuration->get('_PS_ROOT_DIR_'), rtrim($this->configuration->get('__PS_BASE_URI__'), '/'), $fullPath);
}
/**
* @param string $fullUri
*
* @return string
*/
protected function getPathFromUri($fullUri)
{
if ('' !== ($trimmedUri = rtrim($this->configuration->get('__PS_BASE_URI__'), '/'))) {
return $this->configuration->get('_PS_ROOT_DIR_') . preg_replace('#\\' . $trimmedUri . '#', '', $fullUri, 1);
}
return $this->configuration->get('_PS_ROOT_DIR_') . $fullUri;
}
/**
* @return string
*/
protected function getFQDN()
{
if (is_null($this->fqdn)) {
if ($this->configuration->get('PS_SSL_ENABLED') && ToolsLegacy::usingSecureMode()) {
$this->fqdn = $this->configuration->get('_PS_BASE_URL_SSL_');
} else {
$this->fqdn = $this->configuration->get('_PS_BASE_URL_');
}
}
return $this->fqdn;
}
}

View File

@@ -0,0 +1,127 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Attribute;
use Context;
use Validate;
use Product;
use SpecificPriceRule;
use AdminAttributeGeneratorController;
use Combination;
use StockAvailable;
use Tools;
use Stock;
/**
* Admin controller wrapper for new Architecture, about Category admin controller.
*/
class AdminAttributeGeneratorControllerWrapper
{
private $translator;
public function __construct()
{
$context = Context::getContext();
$this->translator = $context->getTranslator();
}
/**
* Generate product attributes
*
* @param object $product The product
* @param array $options The array with all attributes combinations
*/
public function processGenerate($product, $options)
{
SpecificPriceRule::disableAnyApplication();
//add combination if not already exists
$combinations = array_values(AdminAttributeGeneratorController::createCombinations(array_values($options)));
$combinationsValues = array_values(array_map(function () use ($product) {
return array(
'id_product' => $product->id
);
}, $combinations));
$product->generateMultipleCombinations($combinationsValues, $combinations, false);
Product::updateDefaultAttribute($product->id);
SpecificPriceRule::enableAnyApplication();
SpecificPriceRule::applyAllRules(array((int)$product->id));
}
/**
* Delete a product attribute
*
* @param int $idAttribute The attribute ID
* @param int $idProduct The product ID
*
* @return array
*/
public function ajaxProcessDeleteProductAttribute($idAttribute, $idProduct)
{
if (!Combination::isFeatureActive()) {
return false;
}
if ($idProduct && Validate::isUnsignedId($idProduct) && Validate::isLoadedObject($product = new Product($idProduct))) {
if (($depends_on_stock = StockAvailable::dependsOnStock($idProduct)) && StockAvailable::getQuantityAvailableByProduct($idProduct, $idAttribute)) {
return array(
'status' => 'error',
'message'=> $this->translator->trans('It is not possible to delete a combination while it still has some quantities in the Advanced Stock Management. You must delete its stock first.', array(), 'Admin.Catalog.Notification'),
);
} else {
$product->deleteAttributeCombination((int)$idAttribute);
$product->checkDefaultAttributes();
Tools::clearColorListCache((int)$product->id);
if (!$product->hasAttributes()) {
$product->cache_default_attribute = 0;
$product->update();
} else {
Product::updateDefaultAttribute($idProduct);
}
if ($depends_on_stock && !Stock::deleteStockByIds($idProduct, $idAttribute)) {
return array(
'status' => 'error',
'message'=> $this->translator->trans('Error while deleting the stock', array(), 'Admin.Catalog.Notification'),
);
} else {
return array(
'status' => 'ok',
'message'=> $this->translator->trans('Successful deletion', array(), 'Admin.Catalog.Notification'),
);
}
}
} else {
return array(
'status' => 'error',
'message'=> $this->translator->trans('You cannot delete this attribute.', array(), 'Admin.Catalog.Notification'),
);
}
}
}

View File

@@ -0,0 +1,131 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Attribute;
use Context;
use Symfony\Component\Translation\TranslatorInterface;
use Validate;
use Product;
use SpecificPriceRule;
use AdminAttributeGeneratorController;
use Combination;
use StockAvailable;
use Tools;
use Stock;
/**
* Admin controller wrapper for new Architecture, about Category admin controller.
*/
class AdminAttributeGeneratorControllerWrapper
{
/**
* @var TranslatorInterface
*/
private $translator;
public function __construct()
{
$context = Context::getContext();
$this->translator = $context->getTranslator();
}
/**
* Generate product attributes.
*
* @param object $product The product
* @param array $options The array with all attributes combinations
*/
public function processGenerate($product, $options)
{
SpecificPriceRule::disableAnyApplication();
//add combination if not already exists
$combinations = array_values(AdminAttributeGeneratorController::createCombinations(array_values($options)));
$combinationsValues = array_values(array_map(function () use ($product) {
return array(
'id_product' => $product->id,
);
}, $combinations));
$product->generateMultipleCombinations($combinationsValues, $combinations, false);
Product::updateDefaultAttribute($product->id);
SpecificPriceRule::enableAnyApplication();
SpecificPriceRule::applyAllRules(array((int) $product->id));
}
/**
* Delete a product attribute.
*
* @param int $idAttribute The attribute ID
* @param int $idProduct The product ID
*
* @return array
*/
public function ajaxProcessDeleteProductAttribute($idAttribute, $idProduct)
{
if (!Combination::isFeatureActive()) {
return false;
}
if ($idProduct && Validate::isUnsignedId($idProduct) && Validate::isLoadedObject($product = new Product($idProduct))) {
if (($depends_on_stock = StockAvailable::dependsOnStock($idProduct)) && StockAvailable::getQuantityAvailableByProduct($idProduct, $idAttribute)) {
return array(
'status' => 'error',
'message' => $this->translator->trans('It is not possible to delete a combination while it still has some quantities in the Advanced Stock Management. You must delete its stock first.', array(), 'Admin.Catalog.Notification'),
);
} else {
$product->deleteAttributeCombination((int) $idAttribute);
$product->checkDefaultAttributes();
Tools::clearColorListCache((int) $product->id);
if (!$product->hasAttributes()) {
$product->cache_default_attribute = 0;
$product->update();
} else {
Product::updateDefaultAttribute($idProduct);
}
if ($depends_on_stock && !Stock::deleteStockByIds($idProduct, $idAttribute)) {
return array(
'status' => 'error',
'message' => $this->translator->trans('Error while deleting the stock', array(), 'Admin.Catalog.Notification'),
);
} else {
return array(
'status' => 'ok',
'message' => $this->translator->trans('Successful deletion', array(), 'Admin.Catalog.Notification'),
);
}
}
} else {
return array(
'status' => 'error',
'message' => $this->translator->trans('You cannot delete this attribute.', array(), 'Admin.Catalog.Notification'),
);
}
}
}

View File

@@ -0,0 +1,131 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Attribute;
use Product;
use Attribute;
use Combination;
use Db;
use Shop;
use Context;
/**
* This class will provide data from DB / ORM about Attributes
*/
class AttributeDataProvider
{
/**
* Get all attributes for a given language
*
* @param int $id_lang Language id
* @param bool $not_null Get only not null fields if true
*
* @return array Attributes
*/
public static function getAttributes($id_lang, $not_null = false)
{
return Attribute::getAttributes($id_lang, $not_null);
}
/**
* Get all attributes ids for a given group
*
* @param int $id_group Attribute group id
* @param bool $not_null Get only not null fields if true
* @return array Attributes
*/
public static function getAttributeIdsByGroup($id_group, $not_null = false)
{
if (!Combination::isFeatureActive()) {
return array();
}
$result = Db::getInstance()->executeS('
SELECT DISTINCT a.`id_attribute`
FROM `'._DB_PREFIX_.'attribute_group` ag
LEFT JOIN `'._DB_PREFIX_.'attribute` a
ON a.`id_attribute_group` = ag.`id_attribute_group`
'.Shop::addSqlAssociation('attribute_group', 'ag').'
'.Shop::addSqlAssociation('attribute', 'a').'
WHERE ag.`id_attribute_group` = '.(int)$id_group.'
'.($not_null ? 'AND a.`id_attribute` IS NOT NULL' : '').'
ORDER BY a.`position` ASC
');
return array_map(function ($a) {
return $a['id_attribute'];
}, $result);
}
/**
* Get combination for a product
*
* @param int $idProduct
*
* @return array Combinations
*/
public function getProductCombinations($idProduct)
{
$context = Context::getContext();
//get product
$product = new Product((int)$idProduct, false);
if (!is_object($product) || empty($product->id)) {
return false;
}
$allCombinations = $product->getAttributeCombinations(1, false);
$allCombinationsIds = array_map(function ($o) {
return $o['id_product_attribute'];
}, $allCombinations);
$combinations = [];
foreach ($allCombinationsIds as $combinationId) {
$combinations[] = $product->getAttributeCombinationsById($combinationId, $context->employee->id_lang)[0];
}
return $combinations;
}
/**
* Get combination images ids
*
* @param int $idAttribute
*
* @return array
*/
public function getImages($idAttribute)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
SELECT a.`id_image` as id
FROM `'._DB_PREFIX_.'product_attribute_image` a
'.Shop::addSqlAssociation('product_attribute', 'a').'
WHERE a.`id_product_attribute` = '.(int)$idAttribute.'
');
}
}

View File

@@ -0,0 +1,131 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Attribute;
use Product;
use Attribute;
use Combination;
use Db;
use Shop;
use Context;
/**
* This class will provide data from DB / ORM about Attributes.
*/
class AttributeDataProvider
{
/**
* Get all attributes for a given language.
*
* @param int $id_lang Language id
* @param bool $not_null Get only not null fields if true
*
* @return array Attributes
*/
public static function getAttributes($id_lang, $not_null = false)
{
return Attribute::getAttributes($id_lang, $not_null);
}
/**
* Get all attributes ids for a given group.
*
* @param int $id_group Attribute group id
* @param bool $not_null Get only not null fields if true
*
* @return array Attributes
*/
public static function getAttributeIdsByGroup($id_group, $not_null = false)
{
if (!Combination::isFeatureActive()) {
return array();
}
$result = Db::getInstance()->executeS('
SELECT DISTINCT a.`id_attribute`
FROM `' . _DB_PREFIX_ . 'attribute_group` ag
LEFT JOIN `' . _DB_PREFIX_ . 'attribute` a
ON a.`id_attribute_group` = ag.`id_attribute_group`
' . Shop::addSqlAssociation('attribute_group', 'ag') . '
' . Shop::addSqlAssociation('attribute', 'a') . '
WHERE ag.`id_attribute_group` = ' . (int) $id_group . '
' . ($not_null ? 'AND a.`id_attribute` IS NOT NULL' : '') . '
ORDER BY a.`position` ASC
');
return array_map(function ($a) {
return $a['id_attribute'];
}, $result);
}
/**
* Get combination for a product.
*
* @param int $idProduct
*
* @return array Combinations
*/
public function getProductCombinations($idProduct)
{
$context = Context::getContext();
//get product
$product = new Product((int) $idProduct, false);
if (!is_object($product) || empty($product->id)) {
return false;
}
$allCombinations = $product->getAttributeCombinations(1, false);
$allCombinationsIds = array_map(function ($o) {
return $o['id_product_attribute'];
}, $allCombinations);
$combinations = [];
foreach ($allCombinationsIds as $combinationId) {
$combinations[] = $product->getAttributeCombinationsById($combinationId, $context->employee->id_lang)[0];
}
return $combinations;
}
/**
* Get combination images ids.
*
* @param int $idAttribute
*
* @return array
*/
public function getImages($idAttribute)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
SELECT a.`id_image` as id
FROM `' . _DB_PREFIX_ . 'product_attribute_image` a
' . Shop::addSqlAssociation('product_attribute', 'a') . '
WHERE a.`id_product_attribute` = ' . (int) $idAttribute . '
');
}
}

View File

@@ -0,0 +1,100 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Backup;
use DateTimeImmutable;
use PrestaShop\PrestaShop\Adapter\Entity\PrestaShopBackup;
use PrestaShop\PrestaShop\Core\Backup\BackupInterface;
/**
* Class Backup represents single database backup.
*
* @internal
*/
final class Backup implements BackupInterface
{
/**
* @var PrestaShopBackup
*/
private $legacyBackup;
/**
* @var string
*/
private $fileName;
/**
* @param string $fileName Backup file name
*/
public function __construct($fileName)
{
$this->fileName = $fileName;
$this->legacyBackup = new PrestaShopBackup($fileName);
}
/**
* {@inheritdoc}
*/
public function getFileName()
{
return $this->fileName;
}
/**
* {@inheritdoc}
*/
public function getUrl()
{
return $this->legacyBackup->getBackupURL();
}
/**
* {@inheritdoc}
*/
public function getSize()
{
return filesize($this->legacyBackup->id);
}
/**
* {@inheritdoc}
*/
public function getAge()
{
return time() - $this->getDate()->getTimestamp();
}
/**
* {@inheritdoc}
*/
public function getDate()
{
list($timestamp) = explode('-', $this->fileName);
return new DateTimeImmutable('@' . $timestamp);
}
}

View File

@@ -0,0 +1,49 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Backup;
use PrestaShop\PrestaShop\Adapter\Entity\PrestaShopBackup;
use PrestaShop\PrestaShop\Core\Backup\BackupInterface;
use PrestaShop\PrestaShop\Core\Backup\Manager\BackupRemoverInterface;
/**
* Class BackupRemover deletes given backup.
*
* @internal
*/
final class BackupRemover implements BackupRemoverInterface
{
/**
* {@inheritdoc}
*/
public function remove(BackupInterface $backup)
{
$legacyBackup = new PrestaShopBackup($backup->getFileName());
return $legacyBackup->delete();
}
}

View File

@@ -0,0 +1,63 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Backup;
use PrestaShop\PrestaShop\Adapter\Entity\PrestaShopBackup;
use PrestaShop\PrestaShop\Core\Backup\BackupCollection;
use PrestaShop\PrestaShop\Core\Backup\Repository\BackupRepositoryInterface;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
/**
* Class BackupRepository is responsible for providing available backups.
*
* @internal
*/
final class BackupRepository implements BackupRepositoryInterface
{
/**
* {@inheritdoc}
*/
public function retrieveBackups()
{
$backupFinder = (new Finder())
->files()
->in(PrestaShopBackup::getBackupPath())
->name('/^([_a-zA-Z0-9\-]*[\d]+-[a-z\d]+)\.sql(\.gz|\.bz2)?$/')
->depth(0)
;
$backups = new BackupCollection();
/** @var SplFileInfo $file */
foreach ($backupFinder as $file) {
$backups->add(new Backup($file->getFilename()));
}
return $backups;
}
}

View File

@@ -0,0 +1,61 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Backup;
use PrestaShop\PrestaShop\Adapter\Entity\PrestaShopBackup;
use PrestaShop\PrestaShop\Core\Backup\Exception\BackupException;
use PrestaShop\PrestaShop\Core\Backup\Exception\DirectoryIsNotWritableException;
use PrestaShop\PrestaShop\Core\Backup\Manager\BackupCreatorInterface;
/**
* Class DatabaseBackupCreator is responsible for creating database backups.
*
* @internal
*/
final class DatabaseBackupCreator implements BackupCreatorInterface
{
/**
* {@inheritdoc}
*/
public function createBackup()
{
ini_set('max_execution_time', 0);
if (!is_writable(PrestaShopBackup::getBackupPath())) {
throw new DirectoryIsNotWritableException('To create backup, its directory must be writable');
}
$legacyBackup = new PrestaShopBackup();
if (!$legacyBackup->add()) {
throw new BackupException('Failed to create backup');
}
$backupFilePathParts = explode(DIRECTORY_SEPARATOR, $legacyBackup->id);
return new Backup(end($backupFilePathParts));
}
}

View File

@@ -0,0 +1,94 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\BestSales;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchProviderInterface;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchContext;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchQuery;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchResult;
use PrestaShop\PrestaShop\Core\Product\Search\SortOrderFactory;
use PrestaShop\PrestaShop\Core\Product\Search\SortOrder;
use Symfony\Component\Translation\TranslatorInterface;
use ProductSale;
class BestSalesProductSearchProvider implements ProductSearchProviderInterface
{
private $translator;
private $sortOrderFactory;
public function __construct(
TranslatorInterface $translator
) {
$this->translator = $translator;
$this->sortOrderFactory = new SortOrderFactory($this->translator);
}
public function runQuery(
ProductSearchContext $context,
ProductSearchQuery $query
) {
if (!$products = ProductSale::getBestSales(
$context->getIdLang(),
$query->getPage(),
$query->getResultsPerPage(),
$query->getSortOrder()->toLegacyOrderBy(),
$query->getSortOrder()->toLegacyOrderWay()
)) {
$products = array();
}
$count = (int) ProductSale::getNbSales();
$result = new ProductSearchResult();
if (!empty($products)) {
$result
->setProducts($products)
->setTotalProductsCount($count);
$result->setAvailableSortOrders(
array(
(new SortOrder('product', 'name', 'asc'))->setLabel(
$this->translator->trans('Name, A to Z', array(), 'Shop.Theme.Catalog')
),
(new SortOrder('product', 'name', 'desc'))->setLabel(
$this->translator->trans('Name, Z to A', array(), 'Shop.Theme.Catalog')
),
(new SortOrder('product', 'price', 'asc'))->setLabel(
$this->translator->trans('Price, low to high', array(), 'Shop.Theme.Catalog')
),
(new SortOrder('product', 'price', 'desc'))->setLabel(
$this->translator->trans('Price, high to low', array(), 'Shop.Theme.Catalog')
),
)
);
}
return $result;
}
}

View File

@@ -0,0 +1,116 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\BestSales;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchProviderInterface;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchContext;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchQuery;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchResult;
use PrestaShop\PrestaShop\Core\Product\Search\SortOrderFactory;
use PrestaShop\PrestaShop\Core\Product\Search\SortOrder;
use Symfony\Component\Translation\TranslatorInterface;
use ProductSale;
use Tools;
class BestSalesProductSearchProvider implements ProductSearchProviderInterface
{
/**
* @var TranslatorInterface
*/
private $translator;
/**
* @var SortOrderFactory
*/
private $sortOrderFactory;
public function __construct(
TranslatorInterface $translator
) {
$this->translator = $translator;
$this->sortOrderFactory = new SortOrderFactory($this->translator);
}
/**
* @param ProductSearchContext $context
* @param ProductSearchQuery $query
*
* @return ProductSearchResult
*/
public function runQuery(
ProductSearchContext $context,
ProductSearchQuery $query
) {
$sortBySales = (new SortOrder('product', 'sales', 'desc'))->setLabel(
$this->translator->trans('Sales, highest to lowest', array(), 'Shop.Theme.Catalog')
);
if (!Tools::getValue('order', 0)) {
$query->setSortOrder($sortBySales);
}
if (!$products = ProductSale::getBestSales(
$context->getIdLang(),
$query->getPage(),
$query->getResultsPerPage(),
$query->getSortOrder()->toLegacyOrderBy(),
$query->getSortOrder()->toLegacyOrderWay()
)) {
$products = array();
}
$count = (int) ProductSale::getNbSales();
$result = new ProductSearchResult();
if (!empty($products)) {
$result
->setProducts($products)
->setTotalProductsCount($count);
$result->setAvailableSortOrders(
array(
$sortBySales,
(new SortOrder('product', 'name', 'asc'))->setLabel(
$this->translator->trans('Name, A to Z', array(), 'Shop.Theme.Catalog')
),
(new SortOrder('product', 'name', 'desc'))->setLabel(
$this->translator->trans('Name, Z to A', array(), 'Shop.Theme.Catalog')
),
(new SortOrder('product', 'price', 'asc'))->setLabel(
$this->translator->trans('Price, low to high', array(), 'Shop.Theme.Catalog')
),
(new SortOrder('product', 'price', 'desc'))->setLabel(
$this->translator->trans('Price, high to low', array(), 'Shop.Theme.Catalog')
),
)
);
}
return $result;
}
}

View File

@@ -0,0 +1,77 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\CMS;
use CMS;
/**
* Class CMSDataProvider provides CMS data using legacy code.
*/
class CMSDataProvider
{
/**
* Gets all CMS pages.
*
* @param int $languageId
*
* @return array
*/
public function getCMSPages($languageId = null)
{
return CMS::listCms($languageId);
}
/**
* Gets one CMS object by ID.
*
* @param int $cmsId
*
* @return CMS
*/
public function getCMSById($cmsId)
{
return new CMS($cmsId);
}
/**
* Gets CMS choices for choice type.
*
* @param int $languageId
*
* @return array
*/
public function getCMSChoices($languageId = null)
{
$choices = [];
foreach ($this->getCMSPages($languageId) as $cms) {
$choices[$cms['meta_title']] = $cms['id_cms'];
}
return $choices;
}
}

View File

@@ -0,0 +1,64 @@
<?php
/**
* 2007-2017 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Cache;
use Cache;
/**
* Adapter for generic cache methods.
*/
class CacheAdapter
{
/**
* @param string $key
* @param string $value
*/
public function store($key, $value)
{
return Cache::store($key, $value);
}
/**
* @param string $key
*
* @return mixed
*/
public function retrieve($key)
{
return Cache::retrieve($key);
}
/**
* @param string $key
*
* @return bool
*/
public function isStored($key)
{
return Cache::isStored($key);
}
}

View File

@@ -0,0 +1,72 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Cache;
use Tools;
use Media;
/**
* Class able to clear application caches.
*/
class CacheClearer
{
/**
* Clear all application caches.
*/
public function clearAllCaches()
{
$this->clearSymfonyCache();
$this->clearSmartyCache();
Tools::clearXMLCache();
$this->clearMediaCache();
Tools::generateIndex();
}
/**
* Clear Symfony cache.
*/
public function clearSymfonyCache()
{
Tools::clearSf2Cache();
}
/**
* Clear media cache only.
*/
public function clearMediaCache()
{
Media::clearCache();
}
/**
* Clear smarty cache only.
*/
public function clearSmartyCache()
{
Tools::clearSmartyCache();
}
}

View File

@@ -0,0 +1,149 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Cache;
use PrestaShop\PrestaShop\Adapter\Configuration\PhpParameters;
use PrestaShop\PrestaShop\Core\Configuration\DataConfigurationInterface;
/**
* This class manages Caching configuration for a Shop.
*/
class CachingConfiguration implements DataConfigurationInterface
{
/**
* @var MemcacheServerManager
*/
private $memcacheServerManager;
/**
* @var PhpParameters
*/
private $phpParameters;
/**
* @var CacheClearer
*/
private $cacheClearer;
/**
* @var bool check if the caching is enabled
*/
private $isCachingEnabled;
/**
* @var string the selected Caching system: 'CacheApc' for instance
*/
private $cachingSystem;
public function __construct(
MemcacheServerManager $memcacheServerManager,
PhpParameters $phpParameters,
CacheClearer $cacheClearer,
$isCachingEnabled,
$cachingSystem
) {
$this->memcacheServerManager = $memcacheServerManager;
$this->phpParameters = $phpParameters;
$this->cacheClearer = $cacheClearer;
$this->isCachingEnabled = $isCachingEnabled;
$this->cachingSystem = $cachingSystem;
}
/**
* {@inheritdoc}
*/
public function getConfiguration()
{
return array(
'use_cache' => $this->isCachingEnabled,
'caching_system' => $this->cachingSystem,
'servers' => $this->memcacheServerManager->getServers(),
);
}
/**
* {@inheritdoc}
*/
public function updateConfiguration(array $configuration)
{
$errors = array();
if ($this->validateConfiguration($configuration)) {
$errors = $this->updatePhpCacheConfiguration($configuration);
}
return $errors;
}
/**
* {@inheritdoc}
*/
public function validateConfiguration(array $configuration)
{
return isset(
$configuration['use_cache'],
$configuration['caching_system'],
$configuration['servers']
);
}
/**
* Update the Php configuration for Cache feature and system.
*
* @return array the errors list during the update operation
*/
private function updatePhpCacheConfiguration(array $configuration)
{
$errors = array();
if (
$configuration['use_cache'] !== $this->isCachingEnabled
&& !is_null($configuration['caching_system'])
) {
$this->phpParameters->setProperty('parameters.ps_cache_enable', $configuration['use_cache']);
}
if (
!is_null($configuration['caching_system'])
&& $configuration['caching_system'] !== $this->cachingSystem
) {
$this->phpParameters->setProperty('parameters.ps_caching', $configuration['caching_system']);
}
if (false === $this->phpParameters->saveConfiguration()) {
$errors[] = array(
'key' => 'The settings file cannot be overwritten.',
'domain' => 'Admin.Advparameters.Notification',
'parameters' => array(),
);
}
$this->cacheClearer->clearSymfonyCache();
return $errors;
}
}

View File

@@ -0,0 +1,224 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Cache;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
use PrestaShop\PrestaShop\Adapter\Configuration;
use PrestaShop\PrestaShop\Core\Configuration\DataConfigurationInterface;
use PrestaShop\PrestaShop\Adapter\Tools;
/**
* This class manages CCC features configuration for a Shop.
*/
class CombineCompressCacheConfiguration implements DataConfigurationInterface
{
/**
* @var Configuration
*/
private $configuration;
/**
* @var Filesystem
*/
private $filesystem;
/**
* @var Tools
*/
private $tools;
/**
* @var string Absolute path to the theme directory
*/
private $themePath;
/**
* @var string Current active theme name
*/
private $themeName;
public function __construct(
Configuration $configuration,
Filesystem $filesystem,
Tools $tools,
$themePath,
$themeName
) {
$this->configuration = $configuration;
$this->filesystem = $filesystem;
$this->tools = $tools;
$this->themePath = $themePath;
$this->themeName = $themeName;
}
/**
* {@inheritdoc}
*/
public function getConfiguration()
{
return array(
'smart_cache_css' => $this->configuration->getBoolean('PS_CSS_THEME_CACHE'),
'smart_cache_js' => $this->configuration->getBoolean('PS_JS_THEME_CACHE'),
'apache_optimization' => $this->configuration->getBoolean('PS_HTACCESS_CACHE_CONTROL'),
);
}
/**
* {@inheritdoc}
*/
public function updateConfiguration(array $configuration)
{
$errors = array();
if ($this->validateConfiguration($configuration)) {
$this->updateCachesVersionsIfNeeded($configuration);
if ($configuration['smart_cache_css'] || $configuration['smart_cache_js']) {
// Manage JS & CSS Smart cache
if (!$this->createThemeCacheFolder()) {
$errors[] = array(
'key' => 'To use Smarty Cache, the directory %directorypath% must be writable.',
'domain' => 'Admin.Advparameters.Notification',
'parameters' => array(
'%directorypath%' => $this->getThemeCacheFolder(),
),
);
}
}
// Manage Apache optimization
$apacheError = $this->manageApacheOptimization((bool) $configuration['apache_optimization']);
if (count($apacheError) > 0) {
$errors[] = $apacheError;
}
}
return $errors;
}
/**
* {@inheritdoc}
*/
public function validateConfiguration(array $configuration)
{
return isset(
$configuration['smart_cache_css'],
$configuration['smart_cache_js'],
$configuration['apache_optimization']
);
}
/**
* @return string Absolute path the the current active theme
*/
private function getThemeCacheFolder()
{
return $this->themePath . '/' . $this->themeName . '/cache/';
}
/**
* Creates Cache folder for the active theme.
*
* @return bool
*/
private function createThemeCacheFolder()
{
try {
$folder = $this->getThemeCacheFolder();
$this->filesystem->mkdir($folder, '0777');
return true;
} catch (IOExceptionInterface $e) {
return false;
}
}
/**
* Update Cache version of assets if needed.
*
* @param array the configuration
*/
private function updateCachesVersionsIfNeeded(array $configuration)
{
$cacheCSS = $configuration['smart_cache_css'];
$currentCacheCSS = $this->configuration->get('PS_CSS_THEME_CACHE');
$cacheJS = $configuration['smart_cache_js'];
$currentCacheJS = $this->configuration->get('PS_JS_THEME_CACHE');
if ($cacheCSS !== $currentCacheCSS) {
$cssCacheVersion = $this->configuration->get('PS_CCCCSS_VERSION') + 1;
$this->configuration->set('PS_CCCCSS_VERSION', $cssCacheVersion);
$this->configuration->set('PS_CSS_THEME_CACHE', $cacheCSS);
}
if ($cacheJS !== $currentCacheJS) {
$jsCacheVersion = $this->configuration->get('PS_CCCJS_VERSION') + 1;
$this->configuration->set('PS_CCCCSS_VERSION', $jsCacheVersion);
$this->configuration->set('PS_JS_THEME_CACHE', $cacheJS);
}
}
/**
* Creates .htaccess if Apache optimization feature is enabled.
*
* @param bool $enabled
*
* @return array not empty in case of error
*/
private function manageApacheOptimization($enabled)
{
$errors = array();
$isCurrentlyEnabled = (bool) $this->configuration->get('PS_HTACCESS_CACHE_CONTROL');
// feature activation
if (false === $isCurrentlyEnabled && true === $enabled) {
$this->configuration->set('PS_HTACCESS_CACHE_CONTROL', true);
if (!$this->tools->generateHtaccess()) {
$errors = array(
'key' => 'Before being able to use this tool, you need to:[1][2]Create a blank .htaccess in your root directory.[/2][2]Give it write permissions (CHMOD 666 on Unix system).[/2][/1]',
'domain' => 'Admin.Advparameters.Notification',
'parameters' => array(
'[1]' => '<ul>',
'[/1]' => '</ul>',
'[2]' => '<li>',
'[/2]' => '</li>',
),
);
$this->configuration->set('PS_HTACCESS_CACHE_CONTROL', false);
}
}
if (true === $isCurrentlyEnabled && false === $enabled) {
$this->configuration->set('PS_HTACCESS_CACHE_CONTROL', false);
$this->tools->generateHtaccess();
}
return $errors;
}
}

View File

@@ -0,0 +1,121 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Cache;
use Memcache;
use Memcached;
use Doctrine\DBAL\Connection;
/**
* This class manages Memcache(d) servers in "Configure > Advanced Parameters > Performance" page.
*/
class MemcacheServerManager
{
/**
* @var Connection
*/
private $connection;
/**
* @var string
*/
private $tableName;
public function __construct(Connection $connection, $dbPrefix)
{
$this->connection = $connection;
$this->tableName = $dbPrefix . 'memcached_servers';
}
/**
* Add a memcache server.
*
* @param string $serverIp
* @param int $serverPort
* @param int $serverWeight
*/
public function addServer($serverIp, $serverPort, $serverWeight)
{
$this->connection->executeUpdate('INSERT INTO ' . $this->tableName . ' (ip, port, weight) VALUES(:serverIp, :serverPort, :serverWeight)', array(
'serverIp' => $serverIp,
'serverPort' => (int) $serverPort,
'serverWeight' => (int) $serverWeight,
));
return array(
'id' => $this->connection->lastInsertId(),
'server_ip' => $serverIp,
'server_port' => $serverPort,
'server_weight' => $serverWeight,
);
}
/**
* Test if a Memcache configuration is valid.
*
* @param string $serverIp
* @param string @serverPort
*
* @return bool
*/
public function testConfiguration($serverIp, $serverPort)
{
if (extension_loaded('memcached')) {
$memcached = new Memcached();
$memcached->addServer($serverIp, $serverPort);
$version = $memcached->getVersion();
return is_array($version) && false === in_array('255.255.255', $version, true);
}
return true === @memcache_connect($serverIp, $serverPort);
}
/**
* Delete a memcache server (a deletion returns the number of rows deleted).
*
* @param int $serverId_server id (in database)
*
* @return bool
*/
public function deleteServer($serverId)
{
$deletionSuccess = $this->connection->delete($this->tableName, array('id_memcached_server' => $serverId));
return 1 === $deletionSuccess;
}
/**
* Get list of memcached servers.
*
* @return array
*/
public function getServers()
{
return $this->connection->fetchAll('SELECT * FROM ' . $this->tableName, array());
}
}

View File

@@ -0,0 +1,48 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter;
use Cache;
/**
* Class CacheManager drives the cache behavior.
*
* Features to drive the legacy cache from new code architecture.
*
* @package PrestaShop\PrestaShop\Adapter
*/
class CacheManager
{
/**
* Cleans the cache for specific cache key.
*
* @param $key
*/
public function clean($key)
{
Cache::clean($key);
}
}

View File

@@ -0,0 +1,47 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter;
use Cache;
/**
* Class CacheManager drives the cache behavior.
*
* Features to drive the legacy cache from new code architecture.
*/
class CacheManager
{
/**
* Cleans the cache for specific cache key.
*
* @param $key
*/
public function clean($key)
{
Cache::clean($key);
}
}

View File

@@ -0,0 +1,67 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Carrier;
use Carrier;
/**
* This class will provide data from DB / ORM about Category
*/
class CarrierDataProvider
{
/**
* Get all carriers in a given language
*
* @param int $id_lang Language id
* @param bool $active Returns only active carriers when true
* @param bool $delete
* @param bool|int $id_zone
* @param null|string $ids_group
* @param $modules_filters, possible values:
* PS_CARRIERS_ONLY
* CARRIERS_MODULE
* CARRIERS_MODULE_NEED_RANGE
* PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE
* ALL_CARRIERS
*
* @return array Carriers
*/
public function getCarriers($id_lang, $active = false, $delete = false, $id_zone = false, $ids_group = null, $modules_filters = self::PS_CARRIERS_ONLY)
{
return Carrier::getCarriers($id_lang, $active, $delete, $id_zone, $ids_group, $modules_filters);
}
/**
* Get the CarrierCore class ALL_CARRIERS constant value
*
* @return int
*/
public function getAllCarriersConstant()
{
return Carrier::ALL_CARRIERS;
}
}

View File

@@ -0,0 +1,127 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Carrier;
use Carrier;
use PrestaShop\PrestaShop\Adapter\Configuration;
/**
* This class will provide data from DB / ORM about Category.
*/
class CarrierDataProvider
{
/**
* @var Configuration
*/
private $configuration;
public function __construct(Configuration $configuration)
{
$this->configuration = $configuration;
}
/**
* Get all carriers in a given language.
*
* @param int $id_lang Language id
* @param bool $active Returns only active carriers when true
* @param bool $delete
* @param bool|int $id_zone
* @param null|string $ids_group
* @param $modules_filters , possible values:
* PS_CARRIERS_ONLY
* CARRIERS_MODULE
* CARRIERS_MODULE_NEED_RANGE
* PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE
* ALL_CARRIERS
*
* @return array Carriers
*/
public function getCarriers($id_lang, $active = false, $delete = false, $id_zone = false, $ids_group = null, $modules_filters = Carrier::PS_CARRIERS_ONLY)
{
return Carrier::getCarriers($id_lang, $active, $delete, $id_zone, $ids_group, $modules_filters);
}
/**
* Get all active carriers in given language, usable for choice form type.
*
* @param int|null $languageId if not provided - will use the default language
*
* @return array carrier choices
*/
public function getActiveCarriersChoices($languageId = null)
{
if (null === $languageId) {
$languageId = $this->configuration->getInt('PS_LANG_DEFAULT');
}
$carriers = $this->getCarriers($languageId, true, false, false, null, $this->getAllCarriersConstant());
$carriersChoices = [];
foreach ($carriers as $carrier) {
$carriersChoices[$carrier['name']] = $carrier['id_carrier'];
}
return $carriersChoices;
}
/**
* Get carriers order by choices.
*
* @return array order by choices
*/
public function getOrderByChoices()
{
return [
'Price' => Carrier::SORT_BY_PRICE,
'Position' => Carrier::SORT_BY_POSITION,
];
}
/**
* Get carriers order way choices.
*
* @return array order way choices
*/
public function getOrderWayChoices()
{
return [
'Ascending' => Carrier::SORT_BY_ASC,
'Descending' => Carrier::SORT_BY_DESC,
];
}
/**
* Get the CarrierCore class ALL_CARRIERS constant value.
*
* @return int
*/
public function getAllCarriersConstant()
{
return Carrier::ALL_CARRIERS;
}
}

View File

@@ -0,0 +1,89 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Carrier;
use PrestaShop\PrestaShop\Adapter\Configuration;
use PrestaShop\PrestaShop\Core\Configuration\DataConfigurationInterface;
/**
* Class CarrierOptionsConfiguration is responsible for saving and loading Carrier Options configuration.
*/
class CarrierOptionsConfiguration implements DataConfigurationInterface
{
/**
* @var Configuration
*/
private $configuration;
/**
* CarrierOptionsConfiguration constructor.
*
* @param Configuration $configuration
*/
public function __construct(Configuration $configuration)
{
$this->configuration = $configuration;
}
/**
* {@inheritdoc}
*/
public function getConfiguration()
{
return [
'default_carrier' => $this->configuration->getInt('PS_CARRIER_DEFAULT'),
'carrier_default_order_by' => $this->configuration->getInt('PS_CARRIER_DEFAULT_SORT'),
'carrier_default_order_way' => $this->configuration->getInt('PS_CARRIER_DEFAULT_ORDER'),
];
}
/**
* {@inheritdoc}
*/
public function updateConfiguration(array $configuration)
{
if ($this->validateConfiguration($configuration)) {
$this->configuration->set('PS_CARRIER_DEFAULT', $configuration['default_carrier']);
$this->configuration->set('PS_CARRIER_DEFAULT_SORT', $configuration['carrier_default_order_by']);
$this->configuration->set('PS_CARRIER_DEFAULT_ORDER', $configuration['carrier_default_order_way']);
}
return [];
}
/**
* {@inheritdoc}
*/
public function validateConfiguration(array $configuration)
{
return isset(
$configuration['default_carrier'],
$configuration['carrier_default_order_by'],
$configuration['carrier_default_order_way']
);
}
}

View File

@@ -0,0 +1,89 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Carrier;
use PrestaShop\PrestaShop\Adapter\Configuration;
use PrestaShop\PrestaShop\Core\Configuration\DataConfigurationInterface;
/**
* Class HandlingConfiguration is responsible for saving and loading Handling options configuration.
*/
class HandlingConfiguration implements DataConfigurationInterface
{
/**
* @var Configuration
*/
private $configuration;
/**
* HandlingConfiguration constructor.
*
* @param Configuration $configuration
*/
public function __construct(Configuration $configuration)
{
$this->configuration = $configuration;
}
/**
* {@inheritdoc}
*/
public function getConfiguration()
{
return [
'shipping_handling_charges' => $this->configuration->get('PS_SHIPPING_HANDLING'),
'free_shipping_price' => $this->configuration->get('PS_SHIPPING_FREE_PRICE'),
'free_shipping_weight' => $this->configuration->get('PS_SHIPPING_FREE_WEIGHT'),
];
}
/**
* {@inheritdoc}
*/
public function updateConfiguration(array $configuration)
{
if ($this->validateConfiguration($configuration)) {
$this->configuration->set('PS_SHIPPING_HANDLING', $configuration['shipping_handling_charges']);
$this->configuration->set('PS_SHIPPING_FREE_PRICE', $configuration['free_shipping_price']);
$this->configuration->set('PS_SHIPPING_FREE_WEIGHT', $configuration['free_shipping_weight']);
}
return [];
}
/**
* {@inheritdoc}
*/
public function validateConfiguration(array $configuration)
{
return isset(
$configuration['shipping_handling_charges'],
$configuration['free_shipping_price'],
$configuration['free_shipping_weight']
);
}
}

View File

@@ -0,0 +1,498 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Cart;
use PrestaShop\PrestaShop\Core\Foundation\Templating\PresenterInterface;
use PrestaShop\PrestaShop\Core\Product\ProductListingPresenter;
use PrestaShop\PrestaShop\Core\Product\ProductPresentationSettings;
use PrestaShop\PrestaShop\Adapter\Product\PriceFormatter;
use PrestaShop\PrestaShop\Adapter\Product\ProductColorsRetriever;
use PrestaShop\PrestaShop\Adapter\Image\ImageRetriever;
use Context;
use Cart;
use Product;
use Configuration;
use TaxConfiguration;
use CartRule;
use Tools;
use Hook;
class CartPresenter implements PresenterInterface
{
private $priceFormatter;
private $link;
private $translator;
private $imageRetriever;
private $taxConfiguration;
public function __construct()
{
$context = Context::getContext();
$this->priceFormatter = new PriceFormatter();
$this->link = $context->link;
$this->translator = $context->getTranslator();
$this->imageRetriever = new ImageRetriever($this->link);
$this->taxConfiguration = new TaxConfiguration();
}
private function includeTaxes()
{
return $this->taxConfiguration->includeTaxes();
}
private function presentProduct(array $rawProduct)
{
$settings = new ProductPresentationSettings();
$settings->catalog_mode = Configuration::isCatalogMode();
$settings->include_taxes = $this->includeTaxes();
$settings->allow_add_variant_to_cart_from_listing = (int) Configuration::get('PS_ATTRIBUTE_CATEGORY_DISPLAY');
$settings->stock_management_enabled = Configuration::get('PS_STOCK_MANAGEMENT');
$settings->showPrices = Configuration::showPrices();
if (isset($rawProduct['attributes']) && is_string($rawProduct['attributes'])) {
// return an array of attributes
$rawProduct['attributes'] = explode(Configuration::get('PS_ATTRIBUTE_ANCHOR_SEPARATOR'), $rawProduct['attributes']);
$attributesArray = array();
foreach ($rawProduct['attributes'] as $attribute) {
list($key, $value) = explode(':', $attribute);
$attributesArray[trim($key)] = ltrim($value);
}
$rawProduct['attributes'] = $attributesArray;
}
$rawProduct['remove_from_cart_url'] = $this->link->getRemoveFromCartURL(
$rawProduct['id_product'],
$rawProduct['id_product_attribute']
);
$rawProduct['up_quantity_url'] = $this->link->getUpQuantityCartURL(
$rawProduct['id_product'],
$rawProduct['id_product_attribute']
);
$rawProduct['down_quantity_url'] = $this->link->getDownQuantityCartURL(
$rawProduct['id_product'],
$rawProduct['id_product_attribute']
);
$rawProduct['update_quantity_url'] = $this->link->getUpdateQuantityCartURL(
$rawProduct['id_product'],
$rawProduct['id_product_attribute']
);
$resetFields = array(
'ecotax_rate',
'specific_prices',
'customizable',
'online_only',
'reduction',
'new',
'condition',
'pack',
);
foreach ($resetFields as $field) {
if (!array_key_exists($field, $rawProduct)) {
$rawProduct[$field] = '';
}
}
if ($this->includeTaxes()) {
$rawProduct['price_amount'] = $rawProduct['price_wt'];
$rawProduct['price'] = $this->priceFormatter->format($rawProduct['price_wt']);
} else {
$rawProduct['price_amount'] = $rawProduct['price'];
$rawProduct['price'] = $rawProduct['price_tax_exc'] = $this->priceFormatter->format($rawProduct['price']);
}
if ($rawProduct['price_amount'] && $rawProduct['unit_price_ratio'] > 0) {
$rawProduct['unit_price'] = $rawProduct['price_amount'] / $rawProduct['unit_price_ratio'];
}
$rawProduct['total'] = $this->priceFormatter->format(
$this->includeTaxes() ?
$rawProduct['total_wt'] :
$rawProduct['total']
);
$rawProduct['quantity_wanted'] = $rawProduct['cart_quantity'];
$presenter = new ProductListingPresenter(
$this->imageRetriever,
$this->link,
$this->priceFormatter,
new ProductColorsRetriever(),
$this->translator
);
return $presenter->present(
$settings,
$rawProduct,
Context::getContext()->language
);
}
public function addCustomizedData(array $products, Cart $cart)
{
return array_map(function (array $product) use ($cart) {
$product['customizations'] = array();
$data = Product::getAllCustomizedDatas($cart->id, null, true, null, (int) $product['id_customization']);
if (!$data) {
$data = array();
}
$id_product = (int) $product['id_product'];
$id_product_attribute = (int) $product['id_product_attribute'];
if (array_key_exists($id_product, $data)) {
if (array_key_exists($id_product_attribute, $data[$id_product])) {
foreach ($data[$id_product] as $byAddress) {
foreach ($byAddress as $customizations) {
foreach ($customizations as $customization) {
$presentedCustomization = array(
'quantity' => $customization['quantity'],
'fields' => array(),
'id_customization' => null,
);
foreach ($customization['datas'] as $byType) {
foreach ($byType as $data) {
$field = array();
switch ($data['type']) {
case Product::CUSTOMIZE_FILE:
$field['type'] = 'image';
$field['image'] = $this->imageRetriever->getCustomizationImage(
$data['value']
);
break;
case Product::CUSTOMIZE_TEXTFIELD:
$field['type'] = 'text';
$field['text'] = $data['value'];
break;
default:
$field['type'] = null;
}
$field['label'] = $data['name'];
$field['id_module'] = $data['id_module'];
$presentedCustomization['id_customization'] = $data['id_customization'];
$presentedCustomization['fields'][] = $field;
}
}
$product['up_quantity_url'] = $this->link->getUpQuantityCartURL(
$product['id_product'],
$product['id_product_attribute'],
$presentedCustomization['id_customization']
);
$product['down_quantity_url'] = $this->link->getDownQuantityCartURL(
$product['id_product'],
$product['id_product_attribute'],
$presentedCustomization['id_customization']
);
$product['remove_from_cart_url'] = $this->link->getRemoveFromCartURL(
$product['id_product'],
$product['id_product_attribute'],
$presentedCustomization['id_customization']
);
$product['update_quantity_url'] = $this->link->getUpdateQuantityCartURL(
$product['id_product'],
$product['id_product_attribute'],
$presentedCustomization['id_customization']
);
$presentedCustomization['up_quantity_url'] = $this->link->getUpQuantityCartURL(
$product['id_product'],
$product['id_product_attribute'],
$presentedCustomization['id_customization']
);
$presentedCustomization['down_quantity_url'] = $this->link->getDownQuantityCartURL(
$product['id_product'],
$product['id_product_attribute'],
$presentedCustomization['id_customization']
);
$presentedCustomization['remove_from_cart_url'] = $this->link->getRemoveFromCartURL(
$product['id_product'],
$product['id_product_attribute'],
$presentedCustomization['id_customization']
);
$presentedCustomization['update_quantity_url'] = $product['update_quantity_url'];
$product['customizations'][] = $presentedCustomization;
}
}
}
}
}
usort($product['customizations'], function (array $a, array $b) {
if (
$a['quantity'] > $b['quantity']
|| count($a['fields']) > count($b['fields'])
|| $a['id_customization'] > $b['id_customization']
) {
return -1;
} else {
return 1;
}
});
return $product;
}, $products);
}
/**
* @param $cart
* @param bool $shouldSeparateGifts
* @return array
* @throws \Exception
*/
public function present($cart, $shouldSeparateGifts = false)
{
if (!is_a($cart, 'Cart')) {
throw new \Exception('CartPresenter can only present instance of Cart');
}
if ($shouldSeparateGifts) {
$rawProducts = $cart->getProductsWithSeparatedGifts();
} else {
$rawProducts = $cart->getProducts(true);
}
$products = array_map(array($this, 'presentProduct'), $rawProducts);
$products = $this->addCustomizedData($products, $cart);
$subtotals = array();
$productsTotalExcludingTax = $cart->getOrderTotal(false, Cart::ONLY_PRODUCTS);
$total_excluding_tax = $cart->getOrderTotal(false);
$total_including_tax = $cart->getOrderTotal(true);
$total_discount = $cart->getDiscountSubtotalWithoutGifts();
$totalCartAmount = $cart->getOrderTotal($this->includeTaxes(), Cart::ONLY_PRODUCTS);
$subtotals['products'] = array(
'type' => 'products',
'label' => $this->translator->trans('Subtotal', array(), 'Shop.Theme.Checkout'),
'amount' => $totalCartAmount,
'value' => $this->priceFormatter->format($totalCartAmount),
);
if ($total_discount) {
$subtotals['discounts'] = array(
'type' => 'discount',
'label' => $this->translator->trans('Discount', array(), 'Shop.Theme.Checkout'),
'amount' => $total_discount,
'value' => $this->priceFormatter->format($total_discount),
);
} else {
$subtotals['discounts'] = null;
}
if ($cart->gift) {
$giftWrappingPrice = ($cart->getGiftWrappingPrice($this->includeTaxes()) != 0)
? $cart->getGiftWrappingPrice($this->includeTaxes())
: 0;
$subtotals['gift_wrapping'] = array(
'type' => 'gift_wrapping',
'label' => $this->translator->trans('Gift wrapping', array(), 'Shop.Theme.Checkout'),
'amount' => $giftWrappingPrice,
'value' => ($giftWrappingPrice > 0)
? $this->priceFormatter->convertAndFormat($giftWrappingPrice)
: $this->translator->trans('Free', array(), 'Shop.Theme.Checkout'),
);
}
if (!$cart->isVirtualCart()) {
$shippingCost = $cart->getTotalShippingCost(null, $this->includeTaxes());
} else {
$shippingCost = 0;
}
$subtotals['shipping'] = array(
'type' => 'shipping',
'label' => $this->translator->trans('Shipping', array(), 'Shop.Theme.Checkout'),
'amount' => $shippingCost,
'value' => $shippingCost != 0
? $this->priceFormatter->format($shippingCost)
: $this->translator->trans('Free', array(), 'Shop.Theme.Checkout'),
);
$subtotals['tax'] = null;
if (Configuration::get('PS_TAX_DISPLAY')) {
$taxAmount = $total_including_tax - $total_excluding_tax;
$subtotals['tax'] = array(
'type' => 'tax',
'label' => ($this->includeTaxes())
? $this->translator->trans('Included taxes', array(), 'Shop.Theme.Checkout')
: $this->translator->trans('Taxes', array(), 'Shop.Theme.Checkout'),
'amount' => $taxAmount,
'value' => $this->priceFormatter->format($taxAmount),
);
}
$totals = array(
'total' => array(
'type' => 'total',
'label' => $this->translator->trans('Total', array(), 'Shop.Theme.Checkout'),
'amount' => $this->includeTaxes() ? $total_including_tax : $total_excluding_tax,
'value' => $this->priceFormatter->format(
$this->includeTaxes() ? $total_including_tax : $total_excluding_tax
),
),
'total_including_tax' => array(
'type' => 'total',
'label' => $this->translator->trans('Total (tax incl.)', array(), 'Shop.Theme.Checkout'),
'amount' => $total_including_tax,
'value' => $this->priceFormatter->format($total_including_tax),
),
'total_excluding_tax' => array(
'type' => 'total',
'label' => $this->translator->trans('Total (tax excl.)', array(), 'Shop.Theme.Checkout'),
'amount' => $total_excluding_tax,
'value' => $this->priceFormatter->format($total_excluding_tax),
),
);
$products_count = array_reduce($products, function ($count, $product) {
return $count + $product['quantity'];
}, 0);
$summary_string = $products_count === 1 ?
$this->translator->trans('1 item', array(), 'Shop.Theme.Checkout') :
sprintf($this->translator->trans('%d items', array(), 'Shop.Theme.Checkout'), $products_count)
;
$minimalPurchase = $this->priceFormatter->convertAmount((float) Configuration::get('PS_PURCHASE_MINIMUM'));
Hook::exec('overrideMinimalPurchasePrice', array(
'minimalPurchase' => &$minimalPurchase
));
// TODO: move it to a common parent, since it's copied in OrderPresenter and ProductPresenter
$labels = array(
'tax_short' => ($this->includeTaxes())
? $this->translator->trans('(tax incl.)', array(), 'Shop.Theme.Global')
: $this->translator->trans('(tax excl.)', array(), 'Shop.Theme.Global'),
'tax_long' => ($this->includeTaxes())
? $this->translator->trans('(tax included)', array(), 'Shop.Theme.Global')
: $this->translator->trans('(tax excluded)', array(), 'Shop.Theme.Global'),
);
$discounts = $cart->getDiscounts();
$vouchers = $this->getTemplateVarVouchers($cart);
$cartRulesIds = array_flip(array_map(
function ($voucher) {
return $voucher['id_cart_rule'];
},
$vouchers['added']
));
$discounts = array_filter($discounts, function ($discount) use ($cartRulesIds) {
return !array_key_exists($discount['id_cart_rule'], $cartRulesIds);
});
return array(
'products' => $products,
'totals' => $totals,
'subtotals' => $subtotals,
'products_count' => $products_count,
'summary_string' => $summary_string,
'labels' => $labels,
'id_address_delivery' => $cart->id_address_delivery,
'id_address_invoice' => $cart->id_address_invoice,
'is_virtual' => $cart->isVirtualCart(),
'vouchers' => $vouchers,
'discounts' => $discounts,
'minimalPurchase' => $minimalPurchase,
'minimalPurchaseRequired' => ($this->priceFormatter->convertAmount($productsTotalExcludingTax) < $minimalPurchase) ?
sprintf(
$this->translator->trans(
'A minimum shopping cart total of %amount% (tax excl.) is required to validate your order. Current cart total is %total% (tax excl.).',
array(
'%amount%' => $this->priceFormatter->convertAndFormat($minimalPurchase),
'%total%' => $this->priceFormatter->convertAndFormat($productsTotalExcludingTax),
),
'Shop.Theme.Checkout'
)
) :
'',
);
}
private function getTemplateVarVouchers(Cart $cart)
{
$cartVouchers = $cart->getCartRules();
$vouchers = array();
$cartHasTax = is_null($cart->id) ? false : $cart::getTaxesAverageUsed($cart);
foreach ($cartVouchers as $cartVoucher) {
$vouchers[$cartVoucher['id_cart_rule']]['id_cart_rule'] = $cartVoucher['id_cart_rule'];
$vouchers[$cartVoucher['id_cart_rule']]['name'] = $cartVoucher['name'];
$vouchers[$cartVoucher['id_cart_rule']]['reduction_percent'] = $cartVoucher['reduction_percent'];
$vouchers[$cartVoucher['id_cart_rule']]['reduction_currency'] = $cartVoucher['reduction_currency'];
// Voucher reduction depending of the cart tax rule
// if $cartHasTax & voucher is tax excluded, set amount voucher to tax included
if ($cartHasTax && $cartVoucher['reduction_tax'] == '0') {
$cartVoucher['reduction_amount'] = $cartVoucher['reduction_amount'] * (1 + $cartHasTax / 100);
}
$vouchers[$cartVoucher['id_cart_rule']]['reduction_amount'] = $cartVoucher['reduction_amount'];
if (array_key_exists('gift_product', $cartVoucher) && $cartVoucher['gift_product']) {
$cartVoucher['reduction_amount'] = $cartVoucher['value_real'];
}
if (isset($cartVoucher['reduction_percent']) && $cartVoucher['reduction_amount'] == '0.00') {
$cartVoucher['reduction_formatted'] = $cartVoucher['reduction_percent'].'%';
} elseif (isset($cartVoucher['reduction_amount']) && $cartVoucher['reduction_amount'] > 0) {
$cartVoucher['reduction_formatted'] = $this->priceFormatter->convertAndFormat($cartVoucher['reduction_amount']);
}
$vouchers[$cartVoucher['id_cart_rule']]['reduction_formatted'] = '-'.$cartVoucher['reduction_formatted'];
$vouchers[$cartVoucher['id_cart_rule']]['delete_url'] = $this->link->getPageLink(
'cart',
true,
null,
array(
'deleteDiscount' => $cartVoucher['id_cart_rule'],
'token' => Tools::getToken(false),
)
);
}
return array(
'allowed' => (int) CartRule::isFeatureActive(),
'added' => $vouchers,
);
}
}

View File

@@ -0,0 +1,35 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Cart;
/**
* @deprecated since 1.7.4.0
* @see \PrestaShop\PrestaShop\Adapter\Presenter\Cart\CartPresenter
*/
class CartPresenter extends \PrestaShop\PrestaShop\Adapter\Presenter\Cart\CartPresenter
{
}

View File

@@ -0,0 +1,45 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Category;
use AdminCategoriesController;
/**
* Admin controller wrapper for new Architecture, about Category admin controller.
*/
class AdminCategoryControllerWrapper
{
/**
* Get instance of legacy class AdminCategoriesController
*
* @return AdminCategoriesController
*/
public function getInstance()
{
return new AdminCategoriesController();
}
}

View File

@@ -0,0 +1,45 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Category;
use AdminCategoriesController;
/**
* Admin controller wrapper for new Architecture, about Category admin controller.
*/
class AdminCategoryControllerWrapper
{
/**
* Get instance of legacy class AdminCategoriesController.
*
* @return AdminCategoriesController
*/
public function getInstance()
{
return new AdminCategoriesController();
}
}

View File

@@ -0,0 +1,240 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Category;
use ObjectModel;
use PrestaShop\PrestaShop\Adapter\LegacyContext;
use Category;
use Context;
/**
* This class will provide data from DB / ORM about Category
*/
class CategoryDataProvider
{
private $languageId;
public function __construct(LegacyContext $context)
{
$this->languageId = $context->getLanguage()->id;
}
/**
* Get a category
*
* @param null $idCategory
* @param null $idLang
* @param null $idShop
*
* @throws \LogicException If the category id is not set
*
* @return Category
*/
public function getCategory($idCategory = null, $idLang = null, $idShop = null)
{
if (!$idCategory) {
throw new \LogicException('You need to provide a category id', 5002);
}
$category = new Category($idCategory, $idLang, $idShop);
if ($category) {
$category->image = Context::getContext()->link->getCatImageLink($category->name, $category->id);
}
return $category;
}
/**
* Get all nested categories
*
* @param int|null $root_category
* @param bool|int $id_lang
* @param bool $active
* @param int|null $groups
* @param bool $use_shop_restriction
* @param string $sql_filter
* @param string $sql_sort
* @param string $sql_limit
*
* @return array categories
*/
public function getNestedCategories($root_category = null, $id_lang = false, $active = true, $groups = null, $use_shop_restriction = true, $sql_filter = '', $sql_sort = '', $sql_limit = '')
{
if (!$id_lang) {
$id_lang = $this->languageId;
}
return Category::getNestedCategories($root_category, $id_lang, $active, $groups, $use_shop_restriction, $sql_filter, $sql_sort, $sql_limit);
}
/**
* Return available categories Names - excluding Root category
*
* @param int|null $root_category
* @param bool|int $id_lang
* @param bool $active return only active categories
* @param $groups
* @param bool $use_shop_restriction
* @param string $sql_filter
* @param string $sql_sort
* @param string $sql_limit
* @return array Categories
*/
public function getAllCategoriesName($root_category = null, $id_lang = false, $active = true, $groups = null, $use_shop_restriction = true, $sql_filter = '', $sql_sort = '', $sql_limit = '')
{
if (!$id_lang) {
$id_lang = $this->languageId;
}
$categories = Category::getAllCategoriesName($root_category, $id_lang, $active, $groups, $use_shop_restriction, $sql_filter, $sql_sort, $sql_limit);
array_shift($categories);
return $categories;
}
/**
* Return a simple array id/name of categories for a specified product
* @param Product $product
*
* @return array Categories
*/
public function getCategoriesByProduct(ObjectModel $product)
{
$allCategories = $this->getAllCategoriesName();
$productCategories = $product->getCategories();
$results = [];
foreach ($allCategories as $category) {
foreach($productCategories as $productCategory) {
if ($productCategory == $category['id_category']) {
$results[] = [
'id' => $category['id_category'],
'name' => $category['name'],
'breadcrumb' => $this->getBreadCrumb($category['id_category'])
];
}
$productCategories[$category['name']] = $category['id_category'];
}
}
return $results;
}
/**
* Return a simple array id/name of categories
*
* @return array Categories
*/
public function getCategoriesWithBreadCrumb()
{
$allCategories = $this->getAllCategoriesName();
$results = [];
foreach ($allCategories as $category) {
$results[] = [
'id' => $category['id_category'],
'name' => $category['name'],
'breadcrumb' => $this->getBreadCrumb($category['id_category'])
];
}
return $results;
}
/**
* Returns a simple breacrumb from a categoryId, the delimiter can be choosen
* @param $categoryId
* @param string $delimiter
* @return string
*/
public function getBreadCrumb($categoryId, $delimiter = " > ")
{
$currentCategory = new Category($categoryId);
$categories = $currentCategory->getParentsCategories();
$categories = array_reverse($categories, true);
$breadCrumb = '';
foreach($categories as $category) {
$breadCrumb .= ' > '.$category['name'];
}
return substr($breadCrumb, strlen($delimiter));
}
/**
* Get Categories formatted like ajax_product_file.php using Category::getNestedCategories
*
* @param $query
* @param $limit
* @param bool $nameAsBreadCrumb
* @return array
*/
public function getAjaxCategories($query, $limit, $nameAsBreadCrumb = false)
{
if (empty($query)) {
$query = '';
} else {
$query = "AND cl.name LIKE '%".pSQL($query)."%'";
}
if (is_integer($limit)) {
$limit = 'LIMIT ' . $limit;
} else {
$limit = '';
}
$searchCategories = Category::getAllCategoriesName(
$root_category = null,
$id_lang = Context::getContext()->language->id,
$active = true,
$groups = null,
$use_shop_restriction = true,
$sql_filter = $query,
$sql_sort = '',
$limit
);
$results = [];
foreach ($searchCategories as $category) {
$breadCrumb = $this->getBreadCrumb($category['id_category']);
$results[] = [
'id' => $category['id_category'],
'name' => ($nameAsBreadCrumb ? $breadCrumb : $category['name']),
'breadcrumb' => $breadCrumb,
'image' => Context::getContext()->link->getCatImageLink($category['name'], $category['id_category']),
];
}
return $results;
}
public function getRootCategory($idLang = null, Shop $shop = null)
{
return Category::getRootCategory($idLang, $shop);
}
}

View File

@@ -0,0 +1,271 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Category;
use ObjectModel;
use PrestaShop\PrestaShop\Adapter\LegacyContext;
use Category;
use Context;
use Shop;
/**
* This class will provide data from DB / ORM about Category.
*/
class CategoryDataProvider
{
/**
* @var int
*/
private $languageId;
/** @var array the list of existing active categories until root */
private $categoryList;
public function __construct(LegacyContext $context)
{
$this->languageId = $context->getLanguage()->id;
$categories = Category::getSimpleCategoriesWithParentInfos($this->languageId);
// index by categories and construct the categoryList
foreach ($categories as $category) {
$this->categoryList[$category['id_category']] = $category;
}
}
/**
* Get a category.
*
* @param null $idCategory
* @param null $idLang
* @param null $idShop
*
* @throws \LogicException If the category id is not set
*
* @return Category
*/
public function getCategory($idCategory = null, $idLang = null, $idShop = null)
{
if (!$idCategory) {
throw new \LogicException('You need to provide a category id', 5002);
}
$category = new Category($idCategory, $idLang, $idShop);
if ($category) {
$category->image = Context::getContext()->link->getCatImageLink($category->name, $category->id);
}
return $category;
}
/**
* Get all nested categories.
*
* @param int|null $root_category
* @param bool|int $id_lang
* @param bool $active
* @param int|null $groups
* @param bool $use_shop_restriction
* @param string $sql_filter
* @param string $sql_sort
* @param string $sql_limit
*
* @return array categories
*/
public function getNestedCategories($root_category = null, $id_lang = false, $active = true, $groups = null, $use_shop_restriction = true, $sql_filter = '', $sql_sort = '', $sql_limit = '')
{
if (!$id_lang) {
$id_lang = $this->languageId;
}
return Category::getNestedCategories($root_category, $id_lang, $active, $groups, $use_shop_restriction, $sql_filter, $sql_sort, $sql_limit);
}
/**
* Return available categories Names - excluding Root category.
*
* @param int|null $root_category
* @param bool|int $id_lang
* @param bool $active return only active categories
* @param $groups
* @param bool $use_shop_restriction
* @param string $sql_filter
* @param string $sql_sort
* @param string $sql_limit
*
* @return array Categories
*/
public function getAllCategoriesName($root_category = null, $id_lang = false, $active = true, $groups = null, $use_shop_restriction = true, $sql_filter = '', $sql_sort = '', $sql_limit = '')
{
if (!$id_lang) {
$id_lang = $this->languageId;
}
$categories = Category::getAllCategoriesName($root_category, $id_lang, $active, $groups, $use_shop_restriction, $sql_filter, $sql_sort, $sql_limit);
array_shift($categories);
return $categories;
}
/**
* Return a simple array id/name of categories for a specified product.
*
* @param \Product $product
*
* @return array Categories
*/
public function getCategoriesByProduct(ObjectModel $product)
{
$productCategories = $product->getCategories();
$results = [];
foreach ($productCategories as $productCategory) {
if (isset($this->categoryList[$productCategory])) {
$category = $this->categoryList[$productCategory];
$results[] = [
'id' => $category['id_category'],
'name' => $category['name'],
'breadcrumb' => $this->getBreadCrumb($category['id_category']),
];
$productCategories[$category['name']] = $category['id_category'];
}
}
return $results;
}
/**
* Return a simple array id/name of categories.
*
* @return array Categories
*/
public function getCategoriesWithBreadCrumb()
{
$results = [];
foreach ($this->categoryList as $category) {
$results[] = [
'id' => $category['id_category'],
'name' => $category['name'],
'breadcrumb' => $this->getBreadCrumb($category['id_category']),
];
}
return $results;
}
/**
* Construct the breadcrumb using the already constructed list of all categories.
*
* @param int $categoryId
* @param string $delimiter
*
* @return string
*/
public function getBreadCrumb($categoryId, $delimiter = ' > ')
{
$categories = $this->getParentNamesFromList($categoryId);
$categories = array_reverse($categories, true);
return implode($delimiter, $categories);
}
/**
* @param int $categoryId
*
* @return array
*/
public function getParentNamesFromList($categoryId)
{
$categories = [];
while (isset($this->categoryList[$categoryId])) {
$category = $this->categoryList[$categoryId];
$categories[] = $category['name'];
$categoryId = $category['id_parent'];
}
return $categories;
}
/**
* Get Categories formatted like ajax_product_file.php using Category::getNestedCategories.
*
* @param $query
* @param $limit
* @param bool $nameAsBreadCrumb
*
* @return array
*/
public function getAjaxCategories($query, $limit, $nameAsBreadCrumb = false)
{
if (empty($query)) {
$query = '';
} else {
$query = "AND cl.name LIKE '%" . pSQL($query) . "%'";
}
if (is_integer($limit)) {
$limit = 'LIMIT ' . $limit;
} else {
$limit = '';
}
$searchCategories = Category::getAllCategoriesName(
null,
Context::getContext()->language->id,
true,
null,
true,
$query,
'',
$limit
);
$results = [];
foreach ($searchCategories as $category) {
$breadCrumb = $this->getBreadCrumb($category['id_category']);
$results[] = [
'id' => $category['id_category'],
'name' => ($nameAsBreadCrumb ? $breadCrumb : $category['name']),
'breadcrumb' => $breadCrumb,
'image' => Context::getContext()->link->getCatImageLink($category['name'], $category['id_category']),
];
}
return $results;
}
/**
* @param int|null $idLang
* @param Shop|null $shop
*
* @return Category
*/
public function getRootCategory($idLang = null, Shop $shop = null)
{
return Category::getRootCategory($idLang, $shop);
}
}

View File

@@ -0,0 +1,103 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Category;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchProviderInterface;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchContext;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchQuery;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchResult;
use PrestaShop\PrestaShop\Core\Product\Search\SortOrderFactory;
use Symfony\Component\Translation\TranslatorInterface;
use Category;
class CategoryProductSearchProvider implements ProductSearchProviderInterface
{
private $translator;
private $category;
private $sortOrderFactory;
public function __construct(
TranslatorInterface $translator,
Category $category
) {
$this->translator = $translator;
$this->category = $category;
$this->sortOrderFactory = new SortOrderFactory($this->translator);
}
private function getProductsOrCount(
ProductSearchContext $context,
ProductSearchQuery $query,
$type = 'products'
) {
if ($query->getSortOrder()->isRandom()) {
return $this->category->getProducts(
$context->getIdLang(),
1,
$query->getResultsPerPage(),
null,
null,
$type !== 'products',
true,
true,
$query->getResultsPerPage()
);
} else {
return $this->category->getProducts(
$context->getIdLang(),
$query->getPage(),
$query->getResultsPerPage(),
$query->getSortOrder()->toLegacyOrderBy(),
$query->getSortOrder()->toLegacyOrderWay(),
$type !== 'products'
);
}
}
public function runQuery(
ProductSearchContext $context,
ProductSearchQuery $query
) {
$products = $this->getProductsOrCount($context, $query, 'products');
$count = $this->getProductsOrCount($context, $query, 'count');
$result = new ProductSearchResult();
if (!empty($products)) {
$result
->setProducts($products)
->setTotalProductsCount($count);
$result->setAvailableSortOrders(
$this->sortOrderFactory->getDefaultSortOrders()
);
}
return $result;
}
}

View File

@@ -0,0 +1,122 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Category;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchProviderInterface;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchContext;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchQuery;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchResult;
use PrestaShop\PrestaShop\Core\Product\Search\SortOrderFactory;
use Symfony\Component\Translation\TranslatorInterface;
use Category;
/**
* Responsible of getting products for specific category.
*/
class CategoryProductSearchProvider implements ProductSearchProviderInterface
{
private $translator;
private $category;
private $sortOrderFactory;
public function __construct(
TranslatorInterface $translator,
Category $category
) {
$this->translator = $translator;
$this->category = $category;
$this->sortOrderFactory = new SortOrderFactory($this->translator);
}
/**
* @param ProductSearchContext $context
* @param ProductSearchQuery $query
* @param string $type
*
* @return array|false|int
*
* @throws \PrestaShopDatabaseException
*/
private function getProductsOrCount(
ProductSearchContext $context,
ProductSearchQuery $query,
$type = 'products'
) {
if ($query->getSortOrder()->isRandom()) {
return $this->category->getProducts(
$context->getIdLang(),
1,
$query->getResultsPerPage(),
null,
null,
$type !== 'products',
true,
true,
$query->getResultsPerPage()
);
} else {
return $this->category->getProducts(
$context->getIdLang(),
$query->getPage(),
$query->getResultsPerPage(),
$query->getSortOrder()->toLegacyOrderBy(),
$query->getSortOrder()->toLegacyOrderWay(),
$type !== 'products'
);
}
}
/**
* @param ProductSearchContext $context
* @param ProductSearchQuery $query
*
* @return ProductSearchResult
*
* @throws \PrestaShopDatabaseException
*/
public function runQuery(
ProductSearchContext $context,
ProductSearchQuery $query
) {
$products = $this->getProductsOrCount($context, $query, 'products');
$count = $this->getProductsOrCount($context, $query, 'count');
$result = new ProductSearchResult();
if (!empty($products)) {
$result
->setProducts($products)
->setTotalProductsCount($count);
$result->setAvailableSortOrders(
$this->sortOrderFactory->getDefaultSortOrders()
);
}
return $result;
}
}

View File

@@ -0,0 +1,54 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter;
class ClassLang
{
/**
* @var string
*/
private $locale;
/**
* ClassLang constructor.
* @param $locale
*/
public function __construct($locale) {
$this->locale = $locale;
}
/**
* @param $className
* @return bool
*/
public function getClassLang($className) {
if (!class_exists($className)) {
return false;
}
return new $className($this->locale);
}
}

View File

@@ -0,0 +1,64 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter;
/**
* Not used in PrestaShop.
*
* @deprecated since 1.7.5, to be removed in 1.8
*/
class ClassLang
{
/**
* @var string
*/
private $locale;
/**
* ClassLang constructor.
*
* @param $locale
*/
public function __construct($locale)
{
$this->locale = $locale;
}
/**
* @param $className
*
* @return bool
*/
public function getClassLang($className)
{
if (!class_exists($className)) {
return false;
}
return new $className($this->locale);
}
}

View File

@@ -0,0 +1,137 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter;
use PrestaShop\Decimal\Number;
use PrestaShop\PrestaShop\Adapter\Product\ProductDataProvider;
use PrestaShopBundle\Form\Admin\Type\CommonAbstractType;
use PrestaShop\PrestaShop\Adapter\Tools;
use Tools as ToolsLegacy;
use Product;
use Combination;
/**
* This class will provide data from DB / ORM about product combination
*/
class CombinationDataProvider
{
private $context;
private $productAdapter;
private $cldrRepository;
public function __construct()
{
$this->context = new LegacyContext();
$this->productAdapter = new ProductDataProvider();
$this->cldrRepository = ToolsLegacy::getCldr($this->context->getContext());
}
/**
* Get a combination values
*
* @param int $combinationId The id_product_attribute
*
* @return array combinations
*/
public function getFormCombination($combinationId)
{
$product = new Product((new Combination($combinationId))->id_product);
return $this->completeCombination(
$product->getAttributeCombinationsById(
$combinationId,
$this->context->getContext()->language->id
),
$product
);
}
public function completeCombination($attributesCombinations, $product)
{
$combination = $attributesCombinations[0];
$attribute_price_impact = 0;
if ($combination['price'] > 0) {
$attribute_price_impact = 1;
} elseif ($combination['price'] < 0) {
$attribute_price_impact = -1;
}
$attribute_weight_impact = 0;
if ($combination['weight'] > 0) {
$attribute_weight_impact = 1;
} elseif ($combination['weight'] < 0) {
$attribute_weight_impact = -1;
}
$attribute_unity_price_impact = 0;
if ($combination['unit_price_impact'] > 0) {
$attribute_unity_price_impact = 1;
} elseif ($combination['unit_price_impact'] < 0) {
$attribute_unity_price_impact = -1;
}
$finalPrice = (new Number((string) $product->price))
->plus(new Number((string) $combination['price']))
->toPrecision(CommonAbstractType::PRESTASHOP_DECIMALS);
return array(
'id_product_attribute' => $combination['id_product_attribute'],
'attribute_reference' => $combination['reference'],
'attribute_ean13' => $combination['ean13'],
'attribute_isbn' => $combination['isbn'],
'attribute_upc' => $combination['upc'],
'attribute_wholesale_price' => $combination['wholesale_price'],
'attribute_price_impact' => $attribute_price_impact,
'attribute_price' => $combination['price'],
'attribute_price_display' => $this->cldrRepository->getPrice($combination['price'], $this->context->getContext()->currency->iso_code),
'final_price' => (string) $finalPrice,
'attribute_priceTI' => '',
'attribute_ecotax' => $combination['ecotax'],
'attribute_weight_impact' => $attribute_weight_impact,
'attribute_weight' => $combination['weight'],
'attribute_unit_impact' => $attribute_unity_price_impact,
'attribute_unity' => $combination['unit_price_impact'],
'attribute_minimal_quantity' => $combination['minimal_quantity'],
'available_date_attribute' => $combination['available_date'],
'attribute_default' => (bool)$combination['default_on'],
'attribute_quantity' => $this->productAdapter->getQuantity($product->id, $combination['id_product_attribute']),
'name' => $this->getCombinationName($attributesCombinations),
'id_product' => $product->id,
);
}
private function getCombinationName($attributesCombinations)
{
$name = array();
foreach ($attributesCombinations as $attribute) {
$name[] = $attribute['group_name'].' - '.$attribute['attribute_name'];
}
return implode(', ', $name);
}
}

View File

@@ -0,0 +1,194 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter;
use PrestaShop\Decimal\Number;
use PrestaShop\PrestaShop\Adapter\Product\ProductDataProvider;
use PrestaShopBundle\Form\Admin\Type\CommonAbstractType;
use Tools as ToolsLegacy;
use Product;
use Combination;
/**
* This class will provide data from DB / ORM about product combination.
*/
class CombinationDataProvider
{
/**
* @var LegacyContext
*/
private $context;
/**
* @var ProductDataProvider
*/
private $productAdapter;
/**
* @var \PrestaShop\PrestaShop\Core\Cldr\Repository
*/
private $cldrRepository;
public function __construct()
{
$this->context = new LegacyContext();
$this->productAdapter = new ProductDataProvider();
$this->cldrRepository = ToolsLegacy::getCldr($this->context->getContext());
}
/**
* Get a combination values.
*
* @deprecated since 1.7.3.1 really slow, use getFormCombinations instead.
*
* @param int $combinationId The id_product_attribute
*
* @return array combinations
*/
public function getFormCombination($combinationId)
{
$product = new Product((new Combination($combinationId))->id_product);
return $this->completeCombination(
$product->getAttributeCombinationsById(
$combinationId,
$this->context->getContext()->language->id
),
$product
);
}
/**
* Retrieve combinations data for a specific language id.
*
* @param array $combinationIds
* @param int $languageId
*
* @return array a list of formatted combinations
*
* @throws \PrestaShopDatabaseException
* @throws \PrestaShopException
*/
public function getFormCombinations(array $combinationIds, $languageId)
{
$productId = (new Combination($combinationIds[0]))->id_product;
$product = new Product($productId);
$combinations = array();
foreach ($combinationIds as $combinationId) {
$combinations[$combinationId] = $this->completeCombination(
$product->getAttributeCombinationsById(
$combinationId,
$languageId
),
$product
);
}
return $combinations;
}
/**
* @param array $attributesCombinations
* @param Product $product
*
* @return array
*/
public function completeCombination($attributesCombinations, $product)
{
$combination = $attributesCombinations[0];
$attribute_price_impact = 0;
if ($combination['price'] > 0) {
$attribute_price_impact = 1;
} elseif ($combination['price'] < 0) {
$attribute_price_impact = -1;
}
$attribute_weight_impact = 0;
if ($combination['weight'] > 0) {
$attribute_weight_impact = 1;
} elseif ($combination['weight'] < 0) {
$attribute_weight_impact = -1;
}
$attribute_unity_price_impact = 0;
if ($combination['unit_price_impact'] > 0) {
$attribute_unity_price_impact = 1;
} elseif ($combination['unit_price_impact'] < 0) {
$attribute_unity_price_impact = -1;
}
$finalPrice = (new Number((string) $product->price))
->plus(new Number((string) $combination['price']))
->toPrecision(CommonAbstractType::PRESTASHOP_DECIMALS);
return array(
'id_product_attribute' => $combination['id_product_attribute'],
'attribute_reference' => $combination['reference'],
'attribute_ean13' => $combination['ean13'],
'attribute_isbn' => $combination['isbn'],
'attribute_upc' => $combination['upc'],
'attribute_wholesale_price' => $combination['wholesale_price'],
'attribute_price_impact' => $attribute_price_impact,
'attribute_price' => $combination['price'],
'attribute_price_display' => $this->cldrRepository->getPrice($combination['price'], $this->context->getContext()->currency->iso_code),
'final_price' => (string) $finalPrice,
'attribute_priceTI' => '',
'attribute_ecotax' => $combination['ecotax'],
'attribute_weight_impact' => $attribute_weight_impact,
'attribute_weight' => $combination['weight'],
'attribute_unit_impact' => $attribute_unity_price_impact,
'attribute_unity' => $combination['unit_price_impact'],
'attribute_minimal_quantity' => $combination['minimal_quantity'],
'attribute_low_stock_threshold' => $combination['low_stock_threshold'],
'attribute_low_stock_alert' => (bool) $combination['low_stock_alert'],
'available_date_attribute' => $combination['available_date'],
'attribute_default' => (bool) $combination['default_on'],
'attribute_location' => $this->productAdapter->getLocation($product->id, $combination['id_product_attribute']),
'attribute_quantity' => $this->productAdapter->getQuantity($product->id, $combination['id_product_attribute']),
'name' => $this->getCombinationName($attributesCombinations),
'id_product' => $product->id,
);
}
/**
* @param array $attributesCombinations
*
* @return string
*/
private function getCombinationName($attributesCombinations)
{
$name = array();
foreach ($attributesCombinations as $attribute) {
$name[] = $attribute['group_name'] . ' - ' . $attribute['attribute_name'];
}
return implode(', ', $name);
}
}

View File

@@ -0,0 +1,131 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter;
use PrestaShop\PrestaShop\Core\ConfigurationInterface;
use Shop;
use Combination;
use Feature;
use Configuration as ConfigurationLegacy;
class Configuration implements ConfigurationInterface
{
private $shop;
/**
* 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);
} else {
return ConfigurationLegacy::get($key);
}
}
/**
* Set configuration value
* @param $key
* @param $value
* @return $this
* @throws \Exception
*/
public function set($key, $value)
{
// By default, set a piece of configuration for all available shops and shop groups
$shopGroupId = 0;
$shopId = 0;
if ($this->shop instanceof Shop) {
$shopGroupId = $this->shop->id_shop_group;
$shopId = $this->shop->id;
}
$success = ConfigurationLegacy::updateValue(
$key,
$value,
false,
$shopGroupId,
$shopId
);
if (!$success) {
throw new \Exception("Could not update configuration");
}
return $this;
}
/**
* Unset configuration value
* @param $key
* @return $this
* @throws \Exception
*/
public function delete($key)
{
$success = \Configuration::deleteByName(
$key
);
if (!$success) {
throw new \Exception("Could not update configuration");
}
return $this;
}
/**
* Return if Feature feature is active or not
* @return bool
*/
public function featureIsActive()
{
return Feature::isFeatureActive();
}
/**
* Return if Combination feature is active or not
* @return bool
*/
public function combinationIsActive()
{
return Combination::isFeatureActive();
}
/**
* Restrict updates of a piece of configuration to a single shop.
* @param Shop $shop
*/
public function restrictUpdatesTo(Shop $shop)
{
$this->shop = $shop;
}
}

View File

@@ -0,0 +1,245 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter;
use PrestaShop\PrestaShop\Core\ConfigurationInterface;
use PrestaShopBundle\Exception\NotImplementedException;
use Symfony\Component\HttpFoundation\ParameterBag;
use Shop;
use Combination;
use Feature;
use Configuration as ConfigurationLegacy;
/**
* Adapter of Configuration ObjectModel.
*/
class Configuration extends ParameterBag implements ConfigurationInterface
{
/**
* @var Shop
*/
private $shop;
public function __construct(array $parameters = array())
{
// Do nothing
if (!empty($parameters)) {
throw new \LogicException('No parameter can be handled in constructor. Use method set() instead.');
}
}
/**
* @throws NotImplementedException
*/
public function all()
{
throw new NotImplementedException();
}
/**
* {@inheritdoc}
*/
public function keys()
{
return array_keys($this->all());
}
/**
* {@inheritdoc}
*/
public function replace(array $parameters = array())
{
$this->add($parameters);
}
/**
* {@inheritdoc}
*/
public function add(array $parameters = array())
{
foreach ($parameters as $key => $value) {
$this->set($key, $value);
}
}
/**
* Returns constant defined by given $key if exists or check directly into PrestaShop
* \Configuration.
*
* @param string $key
* @param mixed $default The default value if the parameter key does not exist
*
* @return mixed
*/
public function get($key, $default = null)
{
if (defined($key)) {
return constant($key);
}
// if the key is multi lang related, we return an array with the value per language.
// getInt() meaning probably getInternational()
if (ConfigurationLegacy::isLangKey($key)) {
return ConfigurationLegacy::getInt($key);
}
if (ConfigurationLegacy::hasKey($key)) {
return ConfigurationLegacy::get($key);
}
return $default;
}
/**
* Set configuration value.
*
* @param string $key
* @param mixed $value
* @param array $options Options
*
* @return $this
*
* @throws \Exception
*/
public function set($key, $value, array $options = [])
{
// By default, set a piece of configuration for all available shops and shop groups
$shopGroupId = null;
$shopId = null;
if ($this->shop instanceof Shop) {
$shopGroupId = $this->shop->id_shop_group;
$shopId = $this->shop->id;
}
$html = isset($options['html']) ? (bool) $options['html'] : false;
$success = ConfigurationLegacy::updateValue(
$key,
$value,
$html,
$shopGroupId,
$shopId
);
if (!$success) {
throw new \Exception('Could not update configuration');
}
return $this;
}
/**
* {@inheritdoc}
*/
public function has($key)
{
return ConfigurationLegacy::hasKey($key);
}
/**
* Removes a configuration key.
*
* @param type $key
*
* @return type
*/
public function remove($key)
{
$success = \Configuration::deleteByName(
$key
);
if (!$success) {
throw new \Exception('Could not update configuration');
}
return $this;
}
/**
* Unset configuration value.
*
* @param $key
*
* @return $this
*
* @throws \Exception
*
* @deprecated since version 1.7.4.0
*/
public function delete($key)
{
$this->remove($key);
}
/**
* {@inheritdoc}
*/
public function getIterator()
{
return new \ArrayIterator($this->all());
}
/**
* {@inheritdoc}
*/
public function count()
{
return count($this->all());
}
/**
* Return if Feature feature is active or not.
*
* @return bool
*/
public function featureIsActive()
{
return Feature::isFeatureActive();
}
/**
* Return if Combination feature is active or not.
*
* @return bool
*/
public function combinationIsActive()
{
return Combination::isFeatureActive();
}
/**
* Restrict updates of a piece of configuration to a single shop.
*
* @param Shop $shop
*/
public function restrictUpdatesTo(Shop $shop)
{
$this->shop = $shop;
}
}

View File

@@ -0,0 +1,55 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Configuration;
use ConfigurationKPI;
use PrestaShop\PrestaShop\Adapter\Configuration;
/**
* Class KpiConfiguration provides access to legacy ConfigurationKpi methods.
*/
class KpiConfiguration extends Configuration
{
/**
* Changes configuration definition before calling it's methods.
*
* @param $name
* @param $arguments
*
* @return mixed
*/
public function __call($name, $arguments)
{
if (is_callable([$this, $name])) {
ConfigurationKPI::setKpiDefinition();
$result = call_user_func([$this, $name], $arguments);
ConfigurationKPI::unsetKpiDefinition();
return $result;
}
}
}

View File

@@ -0,0 +1,81 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Configuration;
use PrestaShop\PrestaShop\Core\Configuration\DataConfigurationInterface;
use PrestaShop\PrestaShop\Core\ConfigurationInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* This class will manage Logs configuration for a Shop.
*/
class LogsConfiguration implements DataConfigurationInterface
{
/**
* @var ConfigurationInterface
*/
private $configuration;
public function __construct(ConfigurationInterface $configuration)
{
$this->configuration = $configuration;
}
/**
* {@inheritdoc}
*/
public function getConfiguration()
{
return array('logs_by_email' => $this->configuration->get('PS_LOGS_BY_EMAIL'));
}
/**
* {@inheritdoc}
*/
public function updateConfiguration(array $configuration)
{
if ($this->validateConfiguration($configuration)) {
$this->configuration->set('PS_LOGS_BY_EMAIL', $configuration['logs_by_email']);
}
return array();
}
/**
* {@inheritdoc}
*/
public function validateConfiguration(array $configuration)
{
$resolver = new OptionsResolver();
$resolver
->setRequired(array('logs_by_email'))
->resolve($configuration)
;
return true;
}
}

View File

@@ -0,0 +1,99 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Configuration;
use Symfony\Component\Filesystem\Filesystem;
use Shudrum\Component\ArrayFinder\ArrayFinder;
use Symfony\Component\Filesystem\Exception\IOException;
use InvalidArgumentException;
/**
* Class able to manage configuration stored in Php files.
*/
class PhpParameters
{
/**
* @var array the current configuration
*/
private $configuration = array();
/**
* @var string the PHP filename
*/
private $filename;
public function __construct($filename)
{
if (!is_readable($filename)) {
throw new InvalidArgumentException("File $filename is not readable for configuration");
}
$this->filename = $filename;
$phpArray = require $this->filename;
$this->configuration = new ArrayFinder($phpArray);
}
/**
* @return array return the complete configuration
*/
public function getConfiguration()
{
return $this->configuration->get();
}
/**
* Insert a value into configuration at the specified path.
*
* @param $propertyPath
* @param $value
*/
public function setProperty($propertyPath, $value)
{
$this->configuration->set($propertyPath, $value);
}
/**
* Persist the modifications done on the original configuration file.
*
* @return bool
*/
public function saveConfiguration()
{
try {
$filesystem = new Filesystem();
$filesystem->dumpFile($this->filename, '<?php return ' . var_export($this->configuration->get(), true) . ';' . "\n");
if (function_exists('opcache_invalidate')) {
opcache_invalidate($this->filename);
}
} catch (IOException $e) {
return false;
}
return true;
}
}

View File

@@ -0,0 +1,72 @@
<?php
/**
* 2007-2017 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter;
use Symfony\Component\DependencyInjection\ContainerBuilder as SfContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
use Symfony\Component\Config\FileLocator;
use LegacyCompilerPass;
/**
* Build the Container for PrestaShop Legacy.
*/
class ContainerBuilder
{
/**
* @param string $name
* @param bool $isDebug
*
* @return SfContainerBuilder
*
* @throws \Exception
*/
public static function getContainer($name, $isDebug)
{
$containerName = ucfirst($name) . 'Container';
$file = _PS_CACHE_DIR_ . "${containerName}.php";
if (!$isDebug && file_exists($file)) {
require_once $file;
return new $containerName();
}
$container = new SfContainerBuilder();
$container->addCompilerPass(new LegacyCompilerPass());
$loader = new YamlFileLoader($container, new FileLocator(__DIR__));
$env = $isDebug ? 'dev' : 'prod';
$servicesPath = _PS_CONFIG_DIR_ . "services/${name}/services_${env}.yml";
$loader->load($servicesPath);
$container->compile();
$dumper = new PhpDumper($container);
file_put_contents($file, $dumper->dump(array('class' => $containerName)));
return $container;
}
}

View File

@@ -0,0 +1,30 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter;
class CoreException extends \Exception
{
}

View File

@@ -0,0 +1,34 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter;
/**
* @todo: find why this class have been created and used.
*/
class CoreException extends \Exception
{
}

View File

@@ -0,0 +1,65 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Country;
use Country;
use Configuration;
/**
* This class will provide data from DB / ORM about Country
*/
class CountryDataProvider
{
/**
* Return available countries
*
* @param int $id_lang Language ID
* @param bool $active return only active coutries
* @param bool $contain_states return only country with states
* @param bool $list_states Include the states list with the returned list
*
* @return array Countries and corresponding zones
*/
public function getCountries($id_lang, $active = false, $contain_states = false, $list_states = true)
{
return Country::getCountries($id_lang, $active = false, $contain_states = false, $list_states = true);
}
/**
* Get Country IsoCode by Id
*
* @param int $id Country Id
*
* @return string the related iso code
*/
public function getIsoCodebyId($id = null)
{
$countryId = (null === $id) ? Configuration::get('PS_COUNTRY_DEFAULT') : $id;
return Country::getIsoById($countryId);
}
}

View File

@@ -0,0 +1,77 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Country;
use Country;
use Configuration;
/**
* This class will provide data from DB / ORM about Country.
*/
class CountryDataProvider
{
/**
* Return available countries.
*
* @param int $id_lang Language ID
* @param bool $active return only active coutries
* @param bool $contain_states return only country with states
* @param bool $list_states Include the states list with the returned list
*
* @return array Countries and corresponding zones
*/
public function getCountries($id_lang, $active = false, $contain_states = false, $list_states = true)
{
return Country::getCountries($id_lang, $active = false, $contain_states = false, $list_states = true);
}
/**
* Get Country IsoCode by Id.
*
* @param int $id Country Id
*
* @return string the related iso code
*/
public function getIsoCodebyId($id = null)
{
$countryId = (null === $id) ? Configuration::get('PS_COUNTRY_DEFAULT') : $id;
return Country::getIsoById($countryId);
}
/**
* Get country Id by ISO code.
*
* @param string $isoCode Country ISO code
*
* @return int
*/
public function getIdByIsoCode($isoCode)
{
return Country::getByIso($isoCode);
}
}

View File

@@ -0,0 +1,45 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Currency;
use Currency;
/**
* This class will provide data from DB / ORM about Currency
*/
class CurrencyDataProvider
{
/**
* Return available currencies
*
* @return array Currencies
*/
public function getCurrencies($object = false, $active = true, $group_by = false)
{
return Currency::getCurrencies($object = false, $active = true, $group_by = false);
}
}

View File

@@ -0,0 +1,156 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Currency;
use PrestaShop\PrestaShop\Adapter\Configuration;
use Currency;
/**
* This class will provide data from DB / ORM about Currency.
*/
class CurrencyDataProvider
{
/**
* @var \PrestaShop\PrestaShop\Adapter\Configuration
*/
private $configuration;
/**
* @var int
*/
private $shopId;
public function __construct(Configuration $configuration, $shopId)
{
$this->configuration = $configuration;
$this->shopId = $shopId;
}
/**
* Return available currencies.
*
* @return array Currencies
*/
public function getCurrencies($object = false, $active = true, $group_by = false)
{
return Currency::getCurrencies($object = false, $active = true, $group_by = false);
}
/**
* Get a Currency entity instance by ISO code.
*
* @param string $isoCode
* An ISO 4217 currency code
* @param int|null $idLang
* Set this parameter if you want the currency in a specific language.
* If null, default language will be used
*
* @return currency|null
* The asked Currency object, or null if not found
*/
public function getCurrencyByIsoCode($isoCode, $idLang = null)
{
$currencyId = Currency::getIdByIsoCode($isoCode);
if (!$currencyId) {
return null;
}
if (null === $idLang) {
$idLang = $this->configuration->get('PS_LANG_DEFAULT');
}
return new Currency($currencyId, $idLang);
}
/**
* Get a Currency entity instance.
* If the passed ISO code is known, this Currency entity will be loaded with known data.
*
* @param string $isoCode
* An ISO 4217 currency code
* @param int|null $idLang
* Set this parameter if you want the currency in a specific language.
* If null, default language will be used
*
* @return currency
* The asked Currency object, loaded with relevant data if passed ISO code is known
*/
public function getCurrencyByIsoCodeOrCreate($isoCode, $idLang = null)
{
if (null === $idLang) {
$idLang = $this->configuration->get('PS_LANG_DEFAULT');
}
$currency = $this->getCurrencyByIsoCode($isoCode, $idLang);
if (null === $currency) {
$currency = new Currency(null, $idLang);
}
return $currency;
}
/**
* Persists a Currency entity into DB.
* If this entity already exists in DB (has a known currency_id), it will be updated.
*
* @param Currency $currencyEntity
* Currency object model to save
*
* @throws PrestaShopException
* If something wrong happened with DB when saving $currencyEntity
* @throws Exception
* If an unexpected result is retrieved when saving $currencyEntity
*/
public function saveCurrency(Currency $currencyEntity)
{
if (false === $currencyEntity->save()) {
throw new Exception('Failed saving Currency entity');
}
}
/**
* Gets a legacy Currency instance by ID.
*
* @param int $currencyId
*
* @return Currency
*/
public function getCurrencyById($currencyId)
{
return new Currency($currencyId);
}
/**
* Get Default currency Iso code.
*/
public function getDefaultCurrencyIsoCode()
{
$defaultCurrencyId = $this->configuration->get('PS_CURRENCY_DEFAULT');
return (new Currency($defaultCurrencyId, null, $this->shopId))->iso_code;
}
}

View File

@@ -0,0 +1,60 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Currency;
use Currency;
use ObjectModel;
use Shop;
/**
* Class CurrencyManager is responsible for dealing with currency data using legacy classes.
*/
class CurrencyManager
{
/**
* Updates currency data after default currency has changed.
*/
public function updateDefaultCurrency()
{
/* Set conversion rate of default currency to 1 */
ObjectModel::updateMultishopTable('Currency', ['conversion_rate' => 1], 'a.id_currency');
$tmpContext = Shop::getContext();
if ($tmpContext == Shop::CONTEXT_GROUP) {
$tmpShop = Shop::getContextShopGroupID();
} else {
$tmpShop = (int) Shop::getContextShopID();
}
foreach (Shop::getContextListShopID() as $shopId) {
Shop::setContext(Shop::CONTEXT_SHOP, (int) $shopId);
Currency::refreshCurrencies();
}
Shop::setContext($tmpContext, $tmpShop);
}
}

View File

@@ -0,0 +1,93 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Customer;
use PrestaShop\PrestaShop\Adapter\Configuration;
use PrestaShop\PrestaShop\Core\Configuration\DataConfigurationInterface;
/**
* Class CustomerConfiguration is responsible for saving & loading customer configuration.
*/
class CustomerConfiguration implements DataConfigurationInterface
{
/**
* @var Configuration
*/
private $configuration;
public function __construct(Configuration $configuration)
{
$this->configuration = $configuration;
}
/**
* {@inheritdoc}
*/
public function getConfiguration()
{
return [
'redisplay_cart_at_login' => $this->configuration->getBoolean('PS_CART_FOLLOWING'),
'send_email_after_registration' => $this->configuration->getBoolean('PS_CUSTOMER_CREATION_EMAIL'),
'password_reset_delay' => $this->configuration->getInt('PS_PASSWD_TIME_FRONT'),
'enable_b2b_mode' => $this->configuration->getBoolean('PS_B2B_ENABLE'),
'ask_for_birthday' => $this->configuration->getBoolean('PS_CUSTOMER_BIRTHDATE'),
'enable_offers' => $this->configuration->getBoolean('PS_CUSTOMER_OPTIN'),
];
}
/**
* {@inheritdoc}
*/
public function updateConfiguration(array $config)
{
if ($this->validateConfiguration($config)) {
$this->configuration->set('PS_CART_FOLLOWING', (int) $config['redisplay_cart_at_login']);
$this->configuration->set('PS_CUSTOMER_CREATION_EMAIL', (int) $config['send_email_after_registration']);
$this->configuration->set('PS_PASSWD_TIME_FRONT', (int) $config['password_reset_delay']);
$this->configuration->set('PS_B2B_ENABLE', (int) $config['enable_b2b_mode']);
$this->configuration->set('PS_CUSTOMER_BIRTHDATE', (int) $config['ask_for_birthday']);
$this->configuration->set('PS_CUSTOMER_OPTIN', (int) $config['enable_offers']);
}
return [];
}
/**
* {@inheritdoc}
*/
public function validateConfiguration(array $config)
{
return isset(
$config['redisplay_cart_at_login'],
$config['send_email_after_registration'],
$config['password_reset_delay'],
$config['enable_b2b_mode'],
$config['ask_for_birthday'],
$config['enable_offers']
);
}
}

View File

@@ -0,0 +1,54 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Customer;
use Symfony\Component\Process\Exception\LogicException;
use Customer;
/**
* This class will provide data from DB / ORM about Customer
*/
class CustomerDataProvider
{
/**
* Get a customer
*
* @param int $id
*
* @throws LogicException If the customer id is not set
*
* @return object customer
*/
public function getCustomer($id)
{
if (!$id) {
throw new LogicException('You need to provide a customer id', null, 5002);
}
$customer = new Customer($id);
return $customer;
}
}

View File

@@ -0,0 +1,68 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Customer;
use Symfony\Component\Process\Exception\LogicException;
use Customer;
/**
* This class will provide data from DB / ORM about Customer.
*/
class CustomerDataProvider
{
/**
* Get a customer.
*
* @param int $id
*
* @throws LogicException If the customer id is not set
*
* @return object customer
*/
public function getCustomer($id)
{
if (!$id) {
throw new LogicException('You need to provide a customer id', null, 5002);
}
$customer = new Customer($id);
return $customer;
}
/**
* Get Default Customer Group ID.
*
* @param int $idCustomer Customer ID
*
* @return mixed|null|string
*/
public function getDefaultGroupId($idCustomer)
{
return Customer::getDefaultGroupId($idCustomer);
}
}

View File

@@ -0,0 +1,54 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter;
use Db;
class Database implements \PrestaShop\PrestaShop\Core\Foundation\Database\DatabaseInterface
{
/**
* 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)
{
return Db::getInstance()->escape($unsafeData, true, true);
}
}

View File

@@ -0,0 +1,76 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter;
use Db;
use DbQuery;
/**
* Adapter for Db legacy class.
*/
class Database implements \PrestaShop\PrestaShop\Core\Foundation\Database\DatabaseInterface
{
/**
* Perform a SELECT sql statement.
*
* @param string $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 string $unsafeData
*
* @return string
*/
public function escape($unsafeData)
{
return Db::getInstance()->escape($unsafeData, true, true);
}
/**
* Returns a value from the first row, first column of a SELECT query.
*
* @param string|DbQuery $sql
* @param bool $useMaster
* @param bool $useCache
*
* @return string|false|null
*/
public function getValue($sql, $useMaster = true, $useCache = true)
{
return Db::getInstance($useMaster)->getValue($sql, $useCache);
}
}

View File

@@ -0,0 +1,185 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Debug;
use Tools;
/**
* Utilitary class to manages the Debug mode legacy application.
*/
class DebugMode
{
const DEBUG_MODE_SUCCEEDED = 0;
const DEBUG_MODE_ERROR_NO_READ_ACCESS = 1;
const DEBUG_MODE_ERROR_NO_READ_ACCESS_CUSTOM = 2;
const DEBUG_MODE_ERROR_NO_WRITE_ACCESS = 3;
const DEBUG_MODE_ERROR_NO_WRITE_ACCESS_CUSTOM = 4;
const DEBUG_MODE_ERROR_NO_DEFINITION_FOUND = 5;
/**
* Is Debug Mode enabled? Checks on custom defines file first.
*
* @return bool Whether debug mode is enabled
*/
public function isDebugModeEnabled()
{
$definesClean = '';
$customDefinesPath = _PS_ROOT_DIR_ . '/config/defines_custom.inc.php';
$definesPath = _PS_ROOT_DIR_ . '/config/defines.inc.php';
if (is_readable($customDefinesPath)) {
$definesClean = php_strip_whitespace($customDefinesPath);
}
if (!preg_match('/define\(\'_PS_MODE_DEV_\', ([a-zA-Z]+)\);/Ui', $definesClean, $debugModeValue)) {
$definesClean = php_strip_whitespace($definesPath);
if (!preg_match('/define\(\'_PS_MODE_DEV_\', ([a-zA-Z]+)\);/Ui', $definesClean, $debugModeValue)) {
return false;
}
}
return 'true' === Tools::strtolower($debugModeValue[1]);
}
/**
* Enable Debug mode.
*
* @return int Whether changing debug mode succeeded or error code
*/
public function enable()
{
return $this->changePsModeDevValue('true');
}
/**
* Disable debug mode.
*
* @return int Whether changing debug mode succeeded or error code
*/
public function disable()
{
return $this->changePsModeDevValue('false');
}
/**
* Check read permission on custom defines.inc.php.
*
* @return bool Whether the file can be read
*/
private function isCustomDefinesReadable()
{
return is_readable(_PS_ROOT_DIR_ . '/config/defines_custom.inc.php');
}
/**
* Check read permission on main defines.inc.php.
*
* @return bool Whether the file can be read
*/
private function isMainDefinesReadable()
{
return is_readable(_PS_ROOT_DIR_ . '/config/defines.inc.php');
}
/**
* Update Debug Mode value in main defines file.
*
* @param string $value should be "true" or "false"
*
* @return int the debug mode
*/
private function updateDebugModeValueInMainFile($value)
{
$filename = _PS_ROOT_DIR_ . '/config/defines.inc.php';
$cleanedFileContent = php_strip_whitespace($filename);
$fileContent = Tools::file_get_contents($filename);
if (!preg_match('/define\(\'_PS_MODE_DEV_\', ([a-zA-Z]+)\);/Ui', $cleanedFileContent)) {
return self::DEBUG_MODE_ERROR_NO_DEFINITION_FOUND;
}
$fileContent = preg_replace('/define\(\'_PS_MODE_DEV_\', ([a-zA-Z]+)\);/Ui', 'define(\'_PS_MODE_DEV_\', ' . $value . ');', $fileContent);
if (!@file_put_contents($filename, $fileContent)) {
return self::DEBUG_MODE_ERROR_NO_WRITE_ACCESS;
}
if (function_exists('opcache_invalidate')) {
opcache_invalidate($filename);
}
return self::DEBUG_MODE_SUCCEEDED;
}
/**
* Update Debug Mode value in custom defines file.
*
* @param string $value should be "true" or "false"
*
* @return int the debug mode
*/
private function updateDebugModeValueInCustomFile($value)
{
$customFileName = _PS_ROOT_DIR_ . '/config/defines_custom.inc.php';
$cleanedFileContent = php_strip_whitespace($customFileName);
$fileContent = Tools::file_get_contents($customFileName);
if (!empty($cleanedFileContent) && preg_match('/define\(\'_PS_MODE_DEV_\', ([a-zA-Z]+)\);/Ui', $cleanedFileContent)) {
$fileContent = preg_replace('/define\(\'_PS_MODE_DEV_\', ([a-zA-Z]+)\);/Ui', 'define(\'_PS_MODE_DEV_\', ' . $value . ');', $fileContent);
if (!@file_put_contents($customFileName, $fileContent)) {
return self::DEBUG_MODE_ERROR_NO_WRITE_ACCESS_CUSTOM;
}
if (function_exists('opcache_invalidate')) {
opcache_invalidate($customFileName);
}
return self::DEBUG_MODE_SUCCEEDED;
}
}
/**
* Change value of _PS_MODE_DEV_ constant.
*
* @param string $value should be "true" or "false"
*
* @return int the debug mode
*/
private function changePsModeDevValue($value)
{
// Check custom defines file first
if ($this->isCustomDefinesReadable()) {
return $this->updateDebugModeValueInCustomFile($value);
}
if ($this->isMainDefinesReadable()) {
return $this->updateDebugModeValueInMainFile($value);
} else {
return self::DEBUG_MODE_ERROR_NO_READ_ACCESS;
}
}
}

View File

@@ -0,0 +1,152 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Debug;
use PrestaShop\PrestaShop\Adapter\Configuration;
use PrestaShop\PrestaShop\Core\Configuration\DataConfigurationInterface;
/**
* This class manages Debug mode configuration for a Shop.
*/
class DebugModeConfiguration implements DataConfigurationInterface
{
/**
* @var Configuration
*/
private $configuration;
/**
* @var DebugMode Debug mode manager
*/
private $debugMode;
/**
* @var string Path to the application defines path
*/
private $configDefinesPath;
public function __construct(DebugMode $debugMode, Configuration $configuration, $configDefinesPath)
{
$this->debugMode = $debugMode;
$this->configuration = $configuration;
$this->configDefinesPath = $configDefinesPath;
}
/**
* Returns configuration used to manage Debug mode in back office.
*
* @return array
*/
public function getConfiguration()
{
return array(
'disable_non_native_modules' => $this->configuration->getBoolean('PS_DISABLE_NON_NATIVE_MODULE'),
'disable_overrides' => $this->configuration->getBoolean('PS_DISABLE_OVERRIDES'),
'debug_mode' => $this->debugMode->isDebugModeEnabled(),
);
}
/**
* {@inheritdoc}
*/
public function updateConfiguration(array $configuration)
{
$errors = array();
if ($this->validateConfiguration($configuration)) {
$this->configuration->set('PS_DISABLE_NON_NATIVE_MODULE', $configuration['disable_non_native_modules']);
$this->configuration->set('PS_DISABLE_OVERRIDES', $configuration['disable_overrides']);
$status = $this->updateDebugMode((bool) $configuration['debug_mode']);
switch ($status) {
case DebugMode::DEBUG_MODE_SUCCEEDED:
break;
case DebugMode::DEBUG_MODE_ERROR_NO_WRITE_ACCESS:
$errors[] = array(
'key' => 'Error: Could not write to file. Make sure that the correct permissions are set on the file %s',
'domain' => 'Admin.Advparameters.Notification',
'parameters' => array($this->configDefinesPath),
);
break;
case DebugMode::DEBUG_MODE_ERROR_NO_DEFINITION_FOUND:
$errors[] = array(
'key' => 'Error: Could not find whether debug mode is enabled. Make sure that the correct permissions are set on the file %s',
'domain' => 'Admin.Advparameters.Notification',
'parameters' => array($this->configDefinesPath),
);
break;
case DebugMode::DEBUG_MODE_ERROR_NO_WRITE_ACCESS_CUSTOM:
$errors[] = array(
'key' => 'Error: Could not write to file. Make sure that the correct permissions are set on the file %s',
'domain' => 'Admin.Advparameters.Notification',
'parameters' => array($this->configDefinesPath),
);
break;
case DebugMode::DEBUG_MODE_ERROR_NO_READ_ACCESS:
$errors[] = array(
'key' => 'Error: Could not write to file. Make sure that the correct permissions are set on the file %s',
'domain' => 'Admin.Advparameters.Notification',
'parameters' => array($this->configDefinesPath),
);
break;
default:
break;
}
}
return $errors;
}
/**
* {@inheritdoc}
*/
public function validateConfiguration(array $configuration)
{
return isset(
$configuration['disable_non_native_modules'],
$configuration['disable_overrides'],
$configuration['debug_mode']
);
}
/**
* Change Debug mode value if needed.
*
* @param $enableStatus
*
* @return int the status of update
*/
private function updateDebugMode($enableStatus)
{
$currentDebugMode = $this->debugMode->isDebugModeEnabled();
if ($enableStatus !== $currentDebugMode) {
return (true === $enableStatus) ? $this->debugMode->enable() : $this->debugMode->disable();
}
}
}

View File

@@ -0,0 +1,116 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Email;
use PrestaShop\PrestaShop\Adapter\Entity\Mail;
use PrestaShop\PrestaShop\Adapter\Entity\Tools;
use PrestaShop\PrestaShop\Core\ConfigurationInterface;
use PrestaShop\PrestaShop\Core\Email\EmailConfigurationTesterInterface;
use PrestaShop\PrestaShop\Core\Email\MailOption;
use Symfony\Component\Translation\TranslatorInterface;
/**
* Class EmailConfigurationTester is responsible for sending test email.
*
* @internal
*/
final class EmailConfigurationTester implements EmailConfigurationTesterInterface
{
/**
* @var ConfigurationInterface
*/
private $configuration;
/**
* @var TranslatorInterface
*/
private $translator;
/**
* @param ConfigurationInterface $configuration
* @param TranslatorInterface $translator
*/
public function __construct(
ConfigurationInterface $configuration,
TranslatorInterface $translator
) {
$this->configuration = $configuration;
$this->translator = $translator;
}
/**
* {@inheritdoc}
*/
public function testConfiguration(array $config)
{
$content = $this->translator->trans(
'This is a test message. Your server is now configured to send email.',
[],
'Admin.Advparameters.Feature'
);
$subject = $this->translator->trans('Test message -- Prestashop', [], 'Admin.Advparameters.Feature');
$smtpChecked = MailOption::METHOD_SMTP === (int) $config['mail_method'];
$password = !empty($config['smtp_password']) ?
urldecode($config['smtp_password']) :
$this->configuration->get('PS_MAIL_PASSWD')
;
$password = str_replace(
['&lt;', '&gt;', '&quot;', '&amp;'],
['<', '>', '"', '&'],
Tools::htmlentitiesUTF8($password)
);
$result = Mail::sendMailTest(
Tools::htmlentitiesUTF8($smtpChecked),
Tools::htmlentitiesUTF8($config['smtp_server']),
Tools::htmlentitiesUTF8($content),
Tools::htmlentitiesUTF8($subject),
Tools::htmlentitiesUTF8('text/html'),
Tools::htmlentitiesUTF8($config['send_email_to']),
Tools::htmlentitiesUTF8($this->configuration->get('PS_SHOP_EMAIL')),
Tools::htmlentitiesUTF8($config['smtp_username']),
$password,
Tools::htmlentitiesUTF8($config['smtp_port']),
Tools::htmlentitiesUTF8($config['smtp_encryption'])
);
$errors = [];
if (false === $result || is_string($result)) {
$errors[] =
$this->translator->trans('Error: Please check your configuration', [], 'Admin.Advparameters.Feature');
}
if (is_string($result)) {
$errors[] = $result;
}
return $errors;
}
}

View File

@@ -0,0 +1,85 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Email;
use PrestaShop\PrestaShop\Adapter\Entity\Mail;
use PrestaShop\PrestaShop\Adapter\Entity\PrestaShopCollection;
use PrestaShop\PrestaShop\Core\Email\EmailLogEraserInterface;
/**
* Class EmailLogEraser provides API for erasing email logs.
*
* @internal
*/
final class EmailLogEraser implements EmailLogEraserInterface
{
/**
* {@inheritdoc}
*/
public function erase(array $mailLogIds)
{
$errors = [];
if (empty($mailLogIds)) {
$errors[] = [
'key' => 'You must select at least one element to delete.',
'parameters' => [],
'domain' => 'Admin.Notifications.Error',
];
return $errors;
}
$emailLogs = new PrestaShopCollection('Mail');
$emailLogs->where('id_mail', 'in', $mailLogIds);
/** @var Mail $emailLog */
foreach ($emailLogs->getResults() as $emailLog) {
if (!$emailLog->delete()) {
$errors[] = [
'key' => 'Can\'t delete #%id%',
'parameters' => [
'%id%' => $emailLog->id,
],
'domain' => 'Admin.Notifications.Error',
];
continue;
}
}
return $errors;
}
/**
* {@inheritdoc}
*/
public function eraseAll()
{
return Mail::eraseAllLogs();
}
}

View File

@@ -0,0 +1,110 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter;
use DbQuery;
use Db;
use Shop;
use Cache;
class 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);
// 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 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 *
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 : '');
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;
}
}
}
}
}

View File

@@ -0,0 +1,119 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter;
use DbQuery;
use Db;
use Shop;
use Cache;
/**
* Not used in PrestaShop core, only in tests.
*
* @deprecated since 1.7.5, to be removed in 1.8
*/
class 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);
// 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 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 *
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 : '');
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_defs['fields'])
|| 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;
}
}
}
}
}

View File

@@ -0,0 +1,55 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter;
use PrestaShop\PrestaShop\Core\Foundation\Database\EntityMetaData;
use PrestaShop\PrestaShop\Adapter\CoreException;
class EntityMetaDataRetriever
{
public function getEntityMetaData($className)
{
$metaData = new EntityMetaData();
$metaData->setEntityClassName($className);
if (property_exists($className, 'definition')) {
// Legacy entity
$classVars = get_class_vars($className);
$metaData->setTableName($classVars['definition']['table']);
$metaData->setPrimaryKeyFieldNames(array($classVars['definition']['primary']));
} else {
throw new CoreException(
sprintf(
'Cannot get metadata for entity `%s`.',
$className
)
);
}
return $metaData;
}
}

View File

@@ -0,0 +1,65 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter;
use PrestaShop\PrestaShop\Core\Foundation\Database\EntityMetaData;
/**
* Retrieve all meta data of an ObjectModel.
*/
class EntityMetaDataRetriever
{
/**
* @param string $className
*
* @return EntityMetaData
*
* @throws \PrestaShop\PrestaShop\Adapter\CoreException
*/
public function getEntityMetaData($className)
{
$metaData = new EntityMetaData();
$metaData->setEntityClassName($className);
if (property_exists($className, 'definition')) {
// Legacy entity
$classVars = get_class_vars($className);
$metaData->setTableName($classVars['definition']['table']);
$metaData->setPrimaryKeyFieldNames(array($classVars['definition']['primary']));
} else {
throw new CoreException(
sprintf(
'Cannot get metadata for entity `%s`.',
$className
)
);
}
return $metaData;
}
}

View File

@@ -0,0 +1,87 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Feature;
use Combination;
use PrestaShop\PrestaShop\Core\Feature\FeatureInterface;
use PrestaShop\PrestaShop\Adapter\Configuration;
/**
* This class manages Combination feature.
*/
class CombinationFeature implements FeatureInterface
{
/**
* @var Configuration
*/
private $configuration;
public function __construct(Configuration $configuration)
{
$this->configuration = $configuration;
}
/**
* {@inheritdoc}
*/
public function isUsed()
{
return Combination::isCurrentlyUsed();
}
/**
* {@inheritdoc}
*/
public function isActive()
{
return Combination::isFeatureActive();
}
/**
* {@inheritdoc}
*/
public function enable()
{
$this->configuration->set('PS_COMBINATION_FEATURE_ACTIVE', true);
}
/**
* {@inheritdoc}
*/
public function disable()
{
$this->configuration->set('PS_COMBINATION_FEATURE_ACTIVE', false);
}
/**
* {@inheritdoc}
*/
public function update($status)
{
true === $status ? $this->enable() : $this->disable();
}
}

View File

@@ -0,0 +1,72 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Feature;
use Feature;
use FeatureValue;
/**
* This class will provide data from DB / ORM about Feature
*/
class FeatureDataProvider
{
/**
* Get all features for a given language
*
* @param int $id_lang Language id
* @param bool $with_shop
* @return array Multiple arrays with feature's data
*/
public static function getFeatures($id_lang, $with_shop = true)
{
return Feature::getFeatures($id_lang, $with_shop);
}
/**
* Get all values for a given feature and language
*
* @param int $id_lang Language id
* @param int $id_feature Feature id
* @param bool $custom
* @return array Array with feature's values
*/
public static function getFeatureValuesWithLang($id_lang, $id_feature, $custom = false)
{
return FeatureValue::getFeatureValuesWithLang($id_lang, $id_feature, $custom);
}
/**
* Get all language for a given value
*
* @param bool $id_feature_value Feature value id
* @return array Array with value's languages
*/
public static function getFeatureValueLang($id_feature_value)
{
return FeatureValue::getFeatureValueLang($id_feature_value);
}
}

View File

@@ -0,0 +1,75 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Feature;
use Feature;
use FeatureValue;
/**
* This class will provide data from DB / ORM about Feature.
*/
class FeatureDataProvider
{
/**
* Get all features for a given language.
*
* @param int $id_lang Language id
* @param bool $with_shop
*
* @return array Multiple arrays with feature's data
*/
public static function getFeatures($id_lang, $with_shop = true)
{
return Feature::getFeatures($id_lang, $with_shop);
}
/**
* Get all values for a given feature and language.
*
* @param int $id_lang Language id
* @param int $id_feature Feature id
* @param bool $custom
*
* @return array Array with feature's values
*/
public static function getFeatureValuesWithLang($id_lang, $id_feature, $custom = false)
{
return FeatureValue::getFeatureValuesWithLang($id_lang, $id_feature, $custom);
}
/**
* Get all language for a given value.
*
* @param bool $id_feature_value Feature value id
*
* @return array Array with value's languages
*/
public static function getFeatureValueLang($id_feature_value)
{
return FeatureValue::getFeatureValueLang($id_feature_value);
}
}

View File

@@ -0,0 +1,87 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Feature;
use Feature;
use PrestaShop\PrestaShop\Adapter\Configuration;
use PrestaShop\PrestaShop\Core\Feature\FeatureInterface;
/**
* This class manages Feature feature.
*/
class FeatureFeature implements FeatureInterface
{
/**
* @var Configuration
*/
private $configuration;
public function __construct(Configuration $configuration)
{
$this->configuration = $configuration;
}
/**
* {@inheritdoc}
*/
public function isUsed()
{
return Feature::isCurrentlyUsed();
}
/**
* {@inheritdoc}
*/
public function isActive()
{
return Feature::isFeatureActive();
}
/**
* {@inheritdoc}
*/
public function enable()
{
$this->configuration->set('PS_FEATURE_FEATURE_ACTIVE', true);
}
/**
* {@inheritdoc}
*/
public function disable()
{
$this->configuration->set('PS_FEATURE_FEATURE_ACTIVE', false);
}
/**
* {@inheritdoc}
*/
public function update($status)
{
true === $status ? $this->enable() : $this->disable();
}
}

View File

@@ -0,0 +1,87 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Feature;
use Group;
use PrestaShop\PrestaShop\Adapter\Configuration;
use PrestaShop\PrestaShop\Core\Feature\FeatureInterface;
/**
* This class manages Group feature.
*/
class GroupFeature implements FeatureInterface
{
/**
* @var Configuration
*/
private $configuration;
public function __construct(Configuration $configuration)
{
$this->configuration = $configuration;
}
/**
* {@inheritdoc}
*/
public function isUsed()
{
return Group::isCurrentlyUsed();
}
/**
* {@inheritdoc}
*/
public function isActive()
{
return Group::isFeatureActive();
}
/**
* {@inheritdoc}
*/
public function enable()
{
$this->configuration->set('PS_GROUP_FEATURE_ACTIVE', true);
}
/**
* {@inheritdoc}
*/
public function disable()
{
$this->configuration->set('PS_GROUP_FEATURE_ACTIVE', false);
}
/**
* {@inheritdoc}
*/
public function update($status)
{
true === $status ? $this->enable() : $this->disable();
}
}

View File

@@ -0,0 +1,94 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Feature;
use PrestaShop\PrestaShop\Adapter\Entity\Shop;
use PrestaShop\PrestaShop\Adapter\Configuration;
use PrestaShop\PrestaShop\Core\Feature\FeatureInterface;
/**
* Class MultistoreFeature provides data about multishop feature usage.
*
* @internal
*/
final class MultistoreFeature implements FeatureInterface
{
/**
* @var Configuration
*/
private $configuration;
/**
* @param Configuration $configuration
*/
public function __construct(Configuration $configuration)
{
$this->configuration = $configuration;
}
/**
* {@inheritdoc}
*/
public function isUsed()
{
// internally it checks if feature is active
// and at least 2 shops exist
return Shop::isFeatureActive();
}
/**
* {@inheritdoc}
*/
public function isActive()
{
return $this->configuration->getBoolean('PS_MULTISHOP_FEATURE_ACTIVE');
}
/**
* {@inheritdoc}
*/
public function enable()
{
$this->configuration->set('PS_MULTISHOP_FEATURE_ACTIVE', 1);
}
/**
* {@inheritdoc}
*/
public function disable()
{
$this->configuration->set('PS_MULTISHOP_FEATURE_ACTIVE', 0);
}
/**
* {@inheritdoc}
*/
public function update($status)
{
$status ? $this->enable() : $this->disable();
}
}

View File

@@ -0,0 +1,87 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\File;
use PrestaShop\PrestaShop\Adapter\Cache\CacheClearer;
use PrestaShop\PrestaShop\Adapter\Tools;
/**
* Class HtaccessFileGenerator is responsible for generating htaccess file with its default content.
*/
class HtaccessFileGenerator
{
/**
* @var CacheClearer
*/
private $cacheClearer;
/**
* @var Tools
*/
private $tools;
/**
* @var bool
*/
private $multipleViewsConfiguration;
/**
* HtaccessFileGenerator constructor.
*
* @param CacheClearer $cacheClearer
* @param Tools $tools
* @param bool $multipleViewsConfiguration
*/
public function __construct(CacheClearer $cacheClearer, Tools $tools, $multipleViewsConfiguration)
{
$this->cacheClearer = $cacheClearer;
$this->tools = $tools;
$this->multipleViewsConfiguration = $multipleViewsConfiguration;
}
/**
* Generates htaccess file and its content.
*
* @param null|bool $disableMultiView if null, rely on the Shop configuration
*
* @return bool
*/
public function generateFile($disableMultiView = null)
{
if (null === $disableMultiView) {
$disableMultiView = $this->multipleViewsConfiguration;
}
$isGenerated = $disableMultiView ? $this->tools->generateHtaccessWithMultiViews() : $this->tools->generateHtaccessWithoutMultiViews();
if ($isGenerated) {
$this->cacheClearer->clearAllCaches();
}
return $isGenerated;
}
}

View File

@@ -0,0 +1,45 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\File;
use Tools;
/**
* Class RobotsTextFileGenerator is responsible for generating robots txt file.
*/
class RobotsTextFileGenerator
{
/**
* Generates the robots.txt file.
*
* @return bool
*/
public function generateFile()
{
return Tools::generateRobotsFile(true);
}
}

View File

@@ -0,0 +1,88 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter;
use PrestaShop\PrestaShop\Core\Configuration\DataConfigurationInterface;
/**
* Manages the configuration data about general options.
*/
class GeneralConfiguration implements DataConfigurationInterface
{
/**
* @var Configuration
*/
private $configuration;
public function __construct(Configuration $configuration)
{
$this->configuration = $configuration;
}
/**
* {@inheritdoc}
*/
public function getConfiguration()
{
return array(
'check_modules_update' => $this->configuration->getBoolean('PRESTASTORE_LIVE'),
'check_ip_address' => $this->configuration->getBoolean('PS_COOKIE_CHECKIP'),
'front_cookie_lifetime' => $this->configuration->get('PS_COOKIE_LIFETIME_FO'),
'back_cookie_lifetime' => $this->configuration->get('PS_COOKIE_LIFETIME_BO'),
);
}
/**
* {@inheritdoc}
*/
public function updateConfiguration(array $configuration)
{
$errors = array();
if ($this->validateConfiguration($configuration)) {
$this->configuration->set('PRESTASTORE_LIVE', (bool) $configuration['check_modules_update']);
$this->configuration->set('PS_COOKIE_CHECKIP', (bool) $configuration['check_ip_address']);
$this->configuration->set('PS_COOKIE_LIFETIME_FO', (int) $configuration['front_cookie_lifetime']);
$this->configuration->set('PS_COOKIE_LIFETIME_BO', (int) $configuration['back_cookie_lifetime']);
}
return $errors;
}
/**
* {@inheritdoc}
*/
public function validateConfiguration(array $configuration)
{
return isset(
$configuration['check_modules_update'],
$configuration['check_ip_address'],
$configuration['front_cookie_lifetime'],
$configuration['back_cookie_lifetime']
);
}
}

View File

@@ -0,0 +1,80 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Geolocation;
use PrestaShop\PrestaShop\Adapter\Configuration;
use PrestaShop\PrestaShop\Core\Configuration\DataConfigurationInterface;
/**
* Class GeolocationByIpAddressConfiguration is responsible for configuring geolocation configuration.
*/
final class GeolocationByIpAddressConfiguration implements DataConfigurationInterface
{
/**
* @var Configuration
*/
private $configuration;
/**
* @param Configuration $configuration
*/
public function __construct(
Configuration $configuration
) {
$this->configuration = $configuration;
}
/**
* {@inheritdoc}
*/
public function getConfiguration()
{
return [
'geolocation_enabled' => $this->configuration->getBoolean('PS_GEOLOCATION_ENABLED'),
];
}
/**
* {@inheritdoc}
*/
public function updateConfiguration(array $config)
{
if ($this->validateConfiguration($config)) {
$this->configuration->set('PS_GEOLOCATION_ENABLED', $config['geolocation_enabled']);
}
return [];
}
/**
* {@inheritdoc}
*/
public function validateConfiguration(array $config)
{
return isset($config['geolocation_enabled']);
}
}

View File

@@ -0,0 +1,81 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Geolocation;
use PrestaShop\PrestaShop\Core\Configuration\DataConfigurationInterface;
use PrestaShop\PrestaShop\Core\ConfigurationInterface;
/**
* Class GeolocationIpAddressWhitelistConfiguration is responsible for configuring geolocation IP address whitelist data.
*/
final class GeolocationIpAddressWhitelistConfiguration implements DataConfigurationInterface
{
/**
* @var ConfigurationInterface
*/
private $configuration;
/**
* @param ConfigurationInterface $configuration
*/
public function __construct(ConfigurationInterface $configuration)
{
$this->configuration = $configuration;
}
/**
* {@inheritdoc}
*/
public function getConfiguration()
{
return [
'geolocation_whitelist' => $this->configuration->get('PS_GEOLOCATION_WHITELIST'),
];
}
/**
* {@inheritdoc}
*/
public function updateConfiguration(array $config)
{
if ($this->validateConfiguration($config)) {
$this->configuration->set('PS_GEOLOCATION_WHITELIST', $config['geolocation_whitelist']);
}
return [];
}
/**
* {@inheritdoc}
*/
public function validateConfiguration(array $config)
{
return isset(
$config['geolocation_whitelist']
);
}
}

View File

@@ -0,0 +1,86 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Geolocation;
use PrestaShop\PrestaShop\Adapter\Configuration;
use PrestaShop\PrestaShop\Core\Configuration\DataConfigurationInterface;
/**
* Class GeolocationOptionsConfiguration is responsible for configuring geolocation options data.
*/
final class GeolocationOptionsConfiguration implements DataConfigurationInterface
{
/**
* @var Configuration
*/
private $configuration;
/**
* @param Configuration $configuration
*/
public function __construct(Configuration $configuration)
{
$this->configuration = $configuration;
}
/**
* {@inheritdoc}
*/
public function getConfiguration()
{
return [
'geolocation_behaviour' => $this->configuration->get('PS_GEOLOCATION_BEHAVIOR'),
'geolocation_na_behaviour' => $this->configuration->getInt('PS_GEOLOCATION_NA_BEHAVIOR'),
'geolocation_countries' => $this->configuration->get('PS_ALLOWED_COUNTRIES'),
];
}
/**
* {@inheritdoc}
*/
public function updateConfiguration(array $config)
{
if ($this->validateConfiguration($config)) {
$this->configuration->set('PS_GEOLOCATION_BEHAVIOR', $config['geolocation_behaviour']);
$this->configuration->set('PS_GEOLOCATION_NA_BEHAVIOR', $config['geolocation_na_behaviour']);
$this->configuration->set('PS_ALLOWED_COUNTRIES', $config['geolocation_countries']);
}
return [];
}
/**
* {@inheritdoc}
*/
public function validateConfiguration(array $config)
{
return isset(
$config['geolocation_behaviour'],
$config['geolocation_na_behaviour']
);
}
}

View File

@@ -0,0 +1,48 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Group;
use Group;
/**
* This class will provide data from DB / ORM about Group
*/
class GroupDataProvider
{
/**
* Return available groups
*
* @param int $id_lang
* @param bool $id_shop
*
* @return array Groups
*/
public function getGroups($id_lang, $id_shop = false)
{
return Group::getGroups($id_lang, $id_shop);
}
}

View File

@@ -0,0 +1,59 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Group;
use Group;
/**
* This class will provide data from DB / ORM about Group.
*/
class GroupDataProvider
{
/**
* Return available groups.
*
* @param int $id_lang
* @param bool $id_shop
*
* @return array Groups
*/
public function getGroups($id_lang, $id_shop = false)
{
return Group::getGroups($id_lang, $id_shop);
}
/**
* Return current group object
* Use context.
*
* @return Group Group object
*/
public static function getCurrent()
{
return Group::getCurrent();
}
}

View File

@@ -0,0 +1,200 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Hook;
use PrestaShop\PrestaShop\Core\Hook\HookDispatcherInterface;
use PrestaShopBundle\Service\Hook\HookEvent;
use Symfony\Component\EventDispatcher\EventDispatcher;
use PrestaShopBundle\Service\Hook\RenderingHookEvent;
use PrestaShop\PrestaShop\Core\Hook\HookInterface;
use Symfony\Component\EventDispatcher\Event;
use PrestaShop\PrestaShop\Core\Hook\RenderedHook;
use PrestaShop\PrestaShop\Core\Hook\Hook;
/**
* This dispatcher is used to trigger hook listeners.
*
* The dispatch process cannot be stopped like a common EventDispatcher.
*
* If the event is a RenderingHookEvent, then the final result is
* an array of contents accessed from $event->getContent().
*/
class HookDispatcher extends EventDispatcher implements HookDispatcherInterface
{
/**
* @var array
*/
private $renderingContent = [];
/**
* @var bool
*/
private $propagationStoppedCalledBy = false;
/**
* {@inheritdoc}
* This override will check if $event is an instance of HookEvent.
*
* @throws \Exception if the Event is not HookEvent or a subclass
*/
public function dispatch($eventName, Event $event = null)
{
if ($event === null) {
$event = new HookEvent();
}
if (!$event instanceof HookEvent) {
throw new \Exception('HookDispatcher must dispatch a HookEvent subclass only. ' . get_class($event) . ' given.');
}
return parent::dispatch($eventName, $event);
}
/**
* {@inheritdoc}
*/
public function dispatchHook(HookInterface $hook)
{
return $this->dispatchForParameters(
$hook->getName(),
$hook->getParameters()
);
}
/**
* Calls multiple hooks with the same parameter set.
*
* Each event is independent for each hook call. Parameter set is duplicated.
*
* @param array $eventNames the hooks to dispatch to
* @param array $eventParameters the parameters set to insert in each HookEvent instance
*
* @throws \Exception if the Event is not HookEvent or a subclass
*/
public function dispatchMultiple(array $eventNames, array $eventParameters)
{
foreach ($eventNames as $name) {
$this->dispatch($name, (new HookEvent())->setHookParameters($eventParameters));
}
}
/**
* {@inheritdoc}
* This override will avoid PropagationStopped to break the dispatching process.
* After dispatch, in case of RenderingHookEvent, the final content array will be set in event.
*/
protected function doDispatch($listeners, $eventName, Event $event)
{
$this->propagationStoppedCalledBy = false;
foreach ($listeners as $listener) {
// removes $this to parameters. Hooks should not have access to dispatcher
ob_start();
$listener($event, $eventName, null);
$obContent = ob_get_clean();
if ($event instanceof RenderingHookEvent) {
$listenerName = $event->popListener() ?: $listener[1];
$eventContent = $event->popContent();
$this->renderingContent[$listenerName] = (!is_string($eventContent) || strlen($eventContent) > strlen($obContent))
? $eventContent
: $obContent;
}
if ($event->isPropagationStopped()) {
$this->propagationStoppedCalledBy = $listener;
}
}
if ($event instanceof RenderingHookEvent) {
$event->setContent($this->renderingContent);
$this->renderingContent = [];
}
}
/**
* Creates a HookEvent, sets its parameters, and dispatches it.
*
* @param $eventName string The hook name
* @param array $parameters Hook parameters
*
* @return Event the event that has been passed to each listener
*
* @throws \Exception
*/
public function dispatchForParameters($eventName, array $parameters = [])
{
$event = new HookEvent();
$event->setHookParameters($parameters);
return $this->dispatch($eventName, $event);
}
/**
* Creates a RenderingHookEvent, sets its parameters, and dispatches it. Returns the event with the response(s).
*
* @param string $eventName the hook name
* @param array $parameters Hook parameters
*
* @return Event The event that has been passed to each listener. Contains the responses.
*
* @throws \Exception
*/
public function renderForParameters($eventName, array $parameters = [])
{
$event = new RenderingHookEvent();
$event->setHookParameters($parameters);
return $this->dispatch($eventName, $event);
}
/**
* {@inheritdoc}
*/
public function dispatchWithParameters($hookName, array $hookParameters = [])
{
$this->dispatch(new Hook($hookName, $hookParameters));
}
/**
* {@inheritdoc}
*/
public function dispatchRendering(HookInterface $hook)
{
$event = $this->renderForParameters(
$hook->getName(),
$hook->getParameters()
);
return new RenderedHook($hook, $event->getContent());
}
/**
* {@inheritdoc}
*/
public function dispatchRenderingWithParameters($hookName, array $hookParameters = [])
{
return $this->dispatchRendering(new Hook($hookName, $hookParameters));
}
}

View File

@@ -0,0 +1,38 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Hook;
use Hook;
class HookInformationProvider
{
public function isDisplayHookName($hook_name)
{
return Hook::isDisplayHookName($hook_name);
}
}

View File

@@ -0,0 +1,71 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Hook;
use Hook;
/**
* Give information about the hooks.
*/
class HookInformationProvider
{
/**
* @param string $hookName
*
* @return bool
*/
public function isDisplayHookName($hookName)
{
return Hook::isDisplayHookName($hookName);
}
/**
* Return Hooks List.
*
* @param bool $position Where position is active
* @param bool $onlyDisplayHooks Only hook with display hook name
*
* @return array Hooks List
*/
public function getHooks($position = false, $onlyDisplayHooks = false)
{
return Hook::getHooks($position, $onlyDisplayHooks);
}
/**
* Return Hooks list.
*
* @param int $hookId Hook id
* @param int $moduleId Module id
*
* @return array Modules list
*/
public function getModulesFromHook($hookId, $moduleId = null)
{
return Hook::getModulesFromHook($hookId, $moduleId);
}
}

View File

@@ -0,0 +1,76 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter;
use Hook;
use PrestaShop\PrestaShop\Adapter\ServiceLocator;
class 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
) {
global $kernel;
if (!is_null($kernel)) {
// Ensure Request
if (!is_null($kernel->getContainer()->get('request_stack')->getCurrentRequest())) {
$hook_args = array_merge(array('request' => $kernel->getContainer()->get('request')), $hook_args);
}
// If the Symfony kernel is instanciated, we use it for the event fonctionnality
$hookDispatcher = $kernel->getContainer()->get('prestashop.hook.dispatcher');
return $hookDispatcher->renderForParameters($hook_name, $hook_args)->getContent();
} else {
try {
return Hook::exec($hook_name, $hook_args, $id_module, $array_return, $check_exceptions, $use_push, $id_shop);
} catch (\Exception $e) {
$logger = ServiceLocator::get('\\PrestaShop\\PrestaShop\\Adapter\\LegacyLogger');
$logger->error(sprintf('Exception on hook %s for module %s. %s', $hook_name, $id_module, $e->getMessage()));
}
}
}
}

View File

@@ -0,0 +1,87 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter;
use Hook;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Bridge to execute hooks in modern pages.
*/
class 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
) {
$sfContainer = SymfonyContainer::getInstance();
$request = null;
if ($sfContainer instanceof ContainerInterface) {
$request = $sfContainer->get('request_stack')->getCurrentRequest();
}
if (!is_null($request)) {
$hook_args = array_merge(array('request' => $request), $hook_args);
// If Symfony application is booted, we use it to dispatch Hooks
$hookDispatcher = $sfContainer->get('prestashop.core.hook.dispatcher');
return $hookDispatcher
->dispatchRenderingWithParameters($hook_name, $hook_args)
->getContent()
;
} else {
try {
return Hook::exec($hook_name, $hook_args, $id_module, $array_return, $check_exceptions, $use_push, $id_shop);
} catch (\Exception $e) {
$logger = ServiceLocator::get('\\PrestaShop\\PrestaShop\\Adapter\\LegacyLogger');
$logger->error(sprintf('Exception on hook %s for module %s. %s', $hook_name, $id_module, $e->getMessage()));
}
}
}
}

View File

@@ -0,0 +1,102 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Hosting;
use Tools;
use Db;
/**
* Provides hosting system information.
*/
class HostingInformation
{
/**
* @return array
*/
public function getDatabaseInformation()
{
return array(
'version' => Db::getInstance()->getVersion(),
'server' => _DB_SERVER_,
'name' => _DB_NAME_,
'user' => _DB_USER_,
'prefix' => _DB_PREFIX_,
'engine' => _MYSQL_ENGINE_,
'driver' => Db::getClass(),
);
}
/**
* @return array
*/
public function getServerInformation()
{
return [
'version' => isset($_SERVER['SERVER_SOFTWARE']) ? $_SERVER['SERVER_SOFTWARE'] : 'n/a',
'php' => $this->getPhpInformation(),
];
}
/**
* @return array
*/
private function getPhpInformation()
{
return array(
'version' => phpversion(),
'memoryLimit' => ini_get('memory_limit'),
'maxExecutionTime' => ini_get('max_execution_time'),
'maxFileSizeUpload' => ini_get('upload_max_filesize'),
);
}
/**
* @return string
*/
public function getUname()
{
return function_exists('php_uname') ? php_uname('s') . ' ' . php_uname('v') . ' ' . php_uname('m') : '';
}
/**
* @return bool
*/
public function isApacheInstawebModule()
{
return Tools::apacheModExists('mod_instaweb');
}
/**
* Check if the shop is hosted on PrestaCloud.
*
* @return bool
*/
public function isHostMode()
{
return defined('_PS_HOST_MODE_');
}
}

View File

@@ -0,0 +1,214 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Image;
use Link;
use Language;
use Product;
use ImageType;
use Image;
use ImageManager;
class ImageRetriever
{
private $link;
public function __construct(Link $link)
{
$this->link = $link;
}
public function getProductImages(array $product, Language $language)
{
$productAttributeId = $product['id_product_attribute'];
$productInstance = new Product(
$product['id_product'],
false,
$language->id
);
$images = $productInstance->getImages($language->id);
if (empty($images)) {
return [];
}
$combinationImages = $productInstance->getCombinationImages($language->id);
if (!$combinationImages) {
$combinationImages = [];
}
$imageToCombinations = [];
foreach ($combinationImages as $imgs) {
foreach ($imgs as $img) {
$imageToCombinations[$img['id_image']][] = $img['id_product_attribute'];
}
}
$images = array_map(function (array $image) use (
$productInstance,
$imageToCombinations,
$productAttributeId
) {
$image = array_merge($this->getImage(
$productInstance,
$image['id_image']
), $image);
if (isset($imageToCombinations[$image['id_image']])) {
$image['associatedVariants'] = $imageToCombinations[$image['id_image']];
} else {
$image['associatedVariants'] = [];
}
return $image;
}, $images);
$filteredImages = array();
foreach ($images as $image) {
if (in_array($productAttributeId, $image['associatedVariants'])) {
$filteredImages[] = $image;
}
}
return (0 === count($filteredImages)) ? $images : $filteredImages;
}
public function getImage($object, $id_image)
{
if (!$id_image) {
return null;
}
if (get_class($object) === 'Product') {
$type = 'products';
$getImageURL = 'getImageLink';
$root = _PS_PROD_IMG_DIR_;
$imageFolderPath = implode(DIRECTORY_SEPARATOR, array(
rtrim($root, DIRECTORY_SEPARATOR),
rtrim(Image::getImgFolderStatic($id_image), DIRECTORY_SEPARATOR),
));
} else if (get_class($object) === 'Store') {
$type = 'stores';
$getImageURL = 'getStoreImageLink';
$root = _PS_STORE_IMG_DIR_;
$imageFolderPath = rtrim($root, DIRECTORY_SEPARATOR);
} else {
$type = 'categories';
$getImageURL = 'getCatImageLink';
$root = _PS_CAT_IMG_DIR_;
$imageFolderPath = rtrim($root, DIRECTORY_SEPARATOR);
}
$urls = [];
$image_types = ImageType::getImagesTypes($type, true);
$extPath = $imageFolderPath . DIRECTORY_SEPARATOR . 'fileType';
$ext = @file_get_contents($extPath) ?: 'jpg';
$mainImagePath = implode(DIRECTORY_SEPARATOR, [
$imageFolderPath,
$id_image.'.'.$ext
]);
foreach ($image_types as $image_type) {
$resizedImagePath = implode(DIRECTORY_SEPARATOR, [
$imageFolderPath,
$id_image.'-'.$image_type['name'].'.'.$ext
]);
if (!file_exists($resizedImagePath)) {
ImageManager::resize(
$mainImagePath,
$resizedImagePath,
(int)$image_type['width'],
(int)$image_type['height']
);
}
$url = $this->link->$getImageURL(
isset($object->link_rewrite) ? $object->link_rewrite : $object->name,
$id_image,
$image_type['name']
);
$urls[$image_type['name']] = [
'url' => $url,
'width' => (int)$image_type['width'],
'height' => (int)$image_type['height'],
];
}
uasort($urls, function (array $a, array $b) {
return $a['width'] * $a['height'] > $b['width'] * $b['height'] ? 1 : -1;
});
$keys = array_keys($urls);
$small = $urls[$keys[0]];
$large = end($urls);
$medium = $urls[$keys[ceil((count($keys) - 1) / 2)]];
return array(
'bySize' => $urls,
'small' => $small,
'medium' => $medium,
'large' => $large,
'legend' => isset($object->meta_title) ? $object->meta_title : $object->name,
);
}
public function getCustomizationImage($imageHash)
{
$large_image_url = rtrim($this->link->getBaseLink(), '/') . '/upload/' . $imageHash;
$small_image_url = $large_image_url . '_small';
$small = [
'url' => $small_image_url
];
$large = [
'url' => $large_image_url
];
$medium = $large;
return [
'bySize' => [
'small' => $small,
'medium' => $medium,
'large' => $large
],
'small' => $small,
'medium' => $medium,
'large' => $large,
'legend' => ''
];
}
}

View File

@@ -0,0 +1,284 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter\Image;
use Link;
use Language;
use Product;
use ImageType;
use Image;
use ImageManager;
/**
* This class is mainly responsible of Product images.
*/
class ImageRetriever
{
/**
* @var Link
*/
private $link;
public function __construct(Link $link)
{
$this->link = $link;
}
/**
* @param array $product
* @param Language $language
*
* @return array
*/
public function getProductImages(array $product, Language $language)
{
$productAttributeId = $product['id_product_attribute'];
$productInstance = new Product(
$product['id_product'],
false,
$language->id
);
$images = $productInstance->getImages($language->id);
if (empty($images)) {
return [];
}
$combinationImages = $productInstance->getCombinationImages($language->id);
if (!$combinationImages) {
$combinationImages = [];
}
$imageToCombinations = [];
foreach ($combinationImages as $imgs) {
foreach ($imgs as $img) {
$imageToCombinations[$img['id_image']][] = $img['id_product_attribute'];
}
}
$images = array_map(function (array $image) use (
$productInstance,
$imageToCombinations,
$productAttributeId
) {
$image = array_merge($this->getImage(
$productInstance,
$image['id_image']
), $image);
if (isset($imageToCombinations[$image['id_image']])) {
$image['associatedVariants'] = $imageToCombinations[$image['id_image']];
} else {
$image['associatedVariants'] = [];
}
return $image;
}, $images);
$filteredImages = array();
foreach ($images as $image) {
if (in_array($productAttributeId, $image['associatedVariants'])) {
$filteredImages[] = $image;
}
}
return (0 === count($filteredImages)) ? $images : $filteredImages;
}
/**
* @param $object
* @param int $id_image
*
* @return array|null
*
* @throws \PrestaShopDatabaseException
*/
public function getImage($object, $id_image)
{
if (!$id_image) {
return null;
}
if (get_class($object) === 'Product') {
$type = 'products';
$getImageURL = 'getImageLink';
$root = _PS_PROD_IMG_DIR_;
$imageFolderPath = implode(DIRECTORY_SEPARATOR, array(
rtrim($root, DIRECTORY_SEPARATOR),
rtrim(Image::getImgFolderStatic($id_image), DIRECTORY_SEPARATOR),
));
} elseif (get_class($object) === 'Store') {
$type = 'stores';
$getImageURL = 'getStoreImageLink';
$root = _PS_STORE_IMG_DIR_;
$imageFolderPath = rtrim($root, DIRECTORY_SEPARATOR);
} else {
$type = 'categories';
$getImageURL = 'getCatImageLink';
$root = _PS_CAT_IMG_DIR_;
$imageFolderPath = rtrim($root, DIRECTORY_SEPARATOR);
}
$urls = [];
$image_types = ImageType::getImagesTypes($type, true);
$extPath = $imageFolderPath . DIRECTORY_SEPARATOR . 'fileType';
$ext = @file_get_contents($extPath) ?: 'jpg';
$mainImagePath = implode(DIRECTORY_SEPARATOR, [
$imageFolderPath,
$id_image . '.' . $ext,
]);
foreach ($image_types as $image_type) {
$resizedImagePath = implode(DIRECTORY_SEPARATOR, [
$imageFolderPath,
$id_image . '-' . $image_type['name'] . '.' . $ext,
]);
if (!file_exists($resizedImagePath)) {
ImageManager::resize(
$mainImagePath,
$resizedImagePath,
(int) $image_type['width'],
(int) $image_type['height']
);
}
$url = $this->link->$getImageURL(
isset($object->link_rewrite) ? $object->link_rewrite : $object->name,
$id_image,
$image_type['name']
);
$urls[$image_type['name']] = [
'url' => $url,
'width' => (int) $image_type['width'],
'height' => (int) $image_type['height'],
];
}
uasort($urls, function (array $a, array $b) {
return $a['width'] * $a['height'] > $b['width'] * $b['height'] ? 1 : -1;
});
$keys = array_keys($urls);
$small = $urls[$keys[0]];
$large = end($urls);
$medium = $urls[$keys[ceil((count($keys) - 1) / 2)]];
return array(
'bySize' => $urls,
'small' => $small,
'medium' => $medium,
'large' => $large,
'legend' => isset($object->meta_title) ? $object->meta_title : $object->name,
);
}
/**
* @param string $imageHash
*
* @return array
*/
public function getCustomizationImage($imageHash)
{
$large_image_url = rtrim($this->link->getBaseLink(), '/') . '/upload/' . $imageHash;
$small_image_url = $large_image_url . '_small';
$small = [
'url' => $small_image_url,
];
$large = [
'url' => $large_image_url,
];
$medium = $large;
return [
'bySize' => [
'small' => $small,
'medium' => $medium,
'large' => $large,
],
'small' => $small,
'medium' => $medium,
'large' => $large,
'legend' => '',
];
}
/**
* @param Language $language
*
* @return array
*
* @throws \PrestaShopDatabaseException
*/
public function getNoPictureImage(Language $language)
{
$urls = [];
$type = 'products';
$image_types = ImageType::getImagesTypes($type, true);
foreach ($image_types as $image_type) {
$url = $this->link->getImageLink(
'',
$language->iso_code . '-default',
$image_type['name']
);
$urls[$image_type['name']] = [
'url' => $url,
'width' => (int) $image_type['width'],
'height' => (int) $image_type['height'],
];
}
uasort($urls, function (array $a, array $b) {
return $a['width'] * $a['height'] > $b['width'] * $b['height'] ? 1 : -1;
});
$keys = array_keys($urls);
$small = $urls[$keys[0]];
$large = end($urls);
$medium = $urls[$keys[ceil((count($keys) - 1) / 2)]];
return array(
'bySize' => $urls,
'small' => $small,
'medium' => $medium,
'large' => $large,
'legend' => '',
);
}
}

View File

@@ -0,0 +1,135 @@
<?php
/**
* 2007-2017 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2017 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter;
use Image;
use ImageManager as LegacyImageManager;
class ImageManager
{
/**
* @var LegacyContext
*/
private $legacyContext;
/**
* @param LegacyContext $legacyContext
*/
public function __construct(LegacyContext $legacyContext)
{
$this->legacyContext = $legacyContext;
}
/**
* Old legacy way to generate a thumbnail.
*
* Use it upon a new Image management system is available.
*
* @param $imageId
* @param string $imageType
* @param string $tableName
* @param string $imageDir
* @return string The HTML < img > tag
*/
public function getThumbnailForListing($imageId, $imageType = 'jpg', $tableName = 'product', $imageDir = 'p')
{
$thumbPath = $this->getThumbnailTag($imageId, $imageType, $tableName, $imageDir);
// because legacy uses relative path to reach a directory under root directory...
$replacement = 'src="'.$this->legacyContext->getRootUrl();
$thumbPath = preg_replace('/src="(\\.\\.\\/)+/', $replacement, $thumbPath);
return $thumbPath;
}
public function getThumbnailPath($imageId)
{
$imageType = 'jpg';
$tableName = 'product';
$imageDir = 'p';
$imagePath = $this->getImagePath($imageId, $imageType, $tableName, $imageDir);
$thumbnailCachedImageName = $this->makeCachedImageName($imageId, $imageType, $tableName);
LegacyImageManager::thumbnail(
$imagePath,
$thumbnailCachedImageName,
45,
$imageType
);
return LegacyImageManager::getThumbnailPath($thumbnailCachedImageName, false);
}
/**
* @param $imageId
* @param string $imageType
* @param string $tableName
* @param string $imageDir
* @return string
*/
private function getThumbnailTag($imageId, $imageType, $tableName, $imageDir)
{
$imagePath = $this->getImagePath($imageId, $imageType, $tableName, $imageDir);
return LegacyImageManager::thumbnail(
$imagePath,
$this->makeCachedImageName($imageId, $imageType, $tableName),
45,
$imageType
);
}
/**
* @param $imageId
* @param $imageType
* @param $tableName
* @param $imageDir
* @return string
*/
private function getImagePath($imageId, $imageType, $tableName, $imageDir)
{
$parentDirectory = _PS_IMG_DIR_ . $imageDir;
if ($tableName == 'product') {
$image = new Image($imageId);
return $parentDirectory . '/' . $image->getExistingImgPath() . '.' . $imageType;
}
return $parentDirectory . '/' . $imageId . '.' . $imageType;
}
/**
* @param $imageId
* @param $imageType
* @param $tableName
* @return string
*/
private function makeCachedImageName($imageId, $imageType, $tableName)
{
return $tableName . '_mini_' . $imageId . '.' . $imageType;
}
}

View File

@@ -0,0 +1,143 @@
<?php
/**
* 2007-2018 PrestaShop.
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2018 PrestaShop SA
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
namespace PrestaShop\PrestaShop\Adapter;
use Image;
use ImageManager as LegacyImageManager;
/**
* Class responsible of finding images and creating thumbnails.
*/
class ImageManager
{
/**
* @var LegacyContext
*/
private $legacyContext;
/**
* @param LegacyContext $legacyContext
*/
public function __construct(LegacyContext $legacyContext)
{
$this->legacyContext = $legacyContext;
}
/**
* Old legacy way to generate a thumbnail.
*
* Use it upon a new Image management system is available.
*
* @param $imageId
* @param string $imageType
* @param string $tableName
* @param string $imageDir
*
* @return string The HTML < img > tag
*/
public function getThumbnailForListing($imageId, $imageType = 'jpg', $tableName = 'product', $imageDir = 'p')
{
$thumbPath = $this->getThumbnailTag($imageId, $imageType, $tableName, $imageDir);
// because legacy uses relative path to reach a directory under root directory...
$replacement = 'src="' . $this->legacyContext->getRootUrl();
$thumbPath = preg_replace('/src="(\\.\\.\\/)+/', $replacement, $thumbPath);
return $thumbPath;
}
public function getThumbnailPath($imageId)
{
$imageType = 'jpg';
$tableName = 'product';
$imageDir = 'p';
$imagePath = $this->getImagePath($imageId, $imageType, $tableName, $imageDir);
$thumbnailCachedImageName = $this->makeCachedImageName($imageId, $imageType, $tableName);
LegacyImageManager::thumbnail(
$imagePath,
$thumbnailCachedImageName,
45,
$imageType
);
return LegacyImageManager::getThumbnailPath($thumbnailCachedImageName, false);
}
/**
* @param $imageId
* @param string $imageType
* @param string $tableName
* @param string $imageDir
*
* @return string
*/
private function getThumbnailTag($imageId, $imageType, $tableName, $imageDir)
{
$imagePath = $this->getImagePath($imageId, $imageType, $tableName, $imageDir);
return LegacyImageManager::thumbnail(
$imagePath,
$this->makeCachedImageName($imageId, $imageType, $tableName),
45,
$imageType
);
}
/**
* @param $imageId
* @param $imageType
* @param $tableName
* @param $imageDir
*
* @return string
*/
private function getImagePath($imageId, $imageType, $tableName, $imageDir)
{
$parentDirectory = _PS_IMG_DIR_ . $imageDir;
if ($tableName == 'product') {
$image = new Image($imageId);
return $parentDirectory . '/' . $image->getExistingImgPath() . '.' . $imageType;
}
return $parentDirectory . '/' . $imageId . '.' . $imageType;
}
/**
* @param $imageId
* @param $imageType
* @param $tableName
*
* @return string
*/
private function makeCachedImageName($imageId, $imageType, $tableName)
{
return $tableName . '_mini_' . $imageId . '.' . $imageType;
}
}

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