PageRenderTime 64ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/classes/module/Module.php

https://bitbucket.org/yhjohn/ayanapure.com
PHP | 1973 lines | 1248 code | 241 blank | 484 comment | 213 complexity | e8462408e7c5bf5aa7af585bb8c11846 MD5 | raw file
Possible License(s): LGPL-2.1, LGPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /*
  3. * 2007-2012 PrestaShop
  4. *
  5. * NOTICE OF LICENSE
  6. *
  7. * This source file is subject to the Open Software License (OSL 3.0)
  8. * that is bundled with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://opensource.org/licenses/osl-3.0.php
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@prestashop.com so we can send you a copy immediately.
  14. *
  15. * DISCLAIMER
  16. *
  17. * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
  18. * versions in the future. If you wish to customize PrestaShop for your
  19. * needs please refer to http://www.prestashop.com for more information.
  20. *
  21. * @author PrestaShop SA <contact@prestashop.com>
  22. * @copyright 2007-2012 PrestaShop SA
  23. * @version Release: $Revision: 7436 $
  24. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  25. * International Registered Trademark & Property of PrestaShop SA
  26. */
  27. abstract class ModuleCore
  28. {
  29. /** @var integer Module ID */
  30. public $id = null;
  31. /** @var float Version */
  32. public $version;
  33. /**
  34. * @since 1.5.0.1
  35. * @var string Registered Version in database
  36. */
  37. public $registered_version;
  38. /** @var array filled with known compliant PS versions */
  39. public $ps_versions_compliancy = array('min' => '1.4', 'max' => '1.6');
  40. /** @var array filled with modules needed for install */
  41. public $dependencies = array();
  42. /** @var string Unique name */
  43. public $name;
  44. /** @var string Human name */
  45. public $displayName;
  46. /** @var string A little description of the module */
  47. public $description;
  48. /** @var string author of the module */
  49. public $author;
  50. /** @var int need_instance */
  51. public $need_instance = 1;
  52. /** @var string Admin tab correponding to the module */
  53. public $tab = null;
  54. /** @var boolean Status */
  55. public $active = false;
  56. /** @var string Fill it if the module is installed but not yet set up */
  57. public $warning;
  58. /** @var array to store the limited country */
  59. public $limited_countries = array();
  60. /** @var array used by AdminTab to determine which lang file to use (admin.php or module lang file) */
  61. public static $classInModule = array();
  62. /** @var array current language translations */
  63. protected $_lang = array();
  64. /** @var string Module web path (eg. '/shop/modules/modulename/') */
  65. protected $_path = null;
  66. /**
  67. * @since 1.5.0.1
  68. * @var string Module local path (eg. '/home/prestashop/modules/modulename/')
  69. */
  70. protected $local_path = null;
  71. /** @var protected array filled with module errors */
  72. protected $_errors = array();
  73. /** @var protected array filled with module success */
  74. protected $_confirmations = array();
  75. /** @var protected string main table used for modules installed */
  76. protected $table = 'module';
  77. /** @var protected string identifier of the main table */
  78. protected $identifier = 'id_module';
  79. /** @var protected array cache filled with modules informations */
  80. protected static $modules_cache;
  81. /** @var protected array cache filled with modules instances */
  82. protected static $_INSTANCE = array();
  83. /** @var protected boolean filled with config xml generation mode */
  84. protected static $_generate_config_xml_mode = false;
  85. /** @var protected array filled with cache translations */
  86. protected static $l_cache = array();
  87. /** @var protected array filled with cache permissions (modules / employee profiles) */
  88. protected static $cache_permissions = array();
  89. /** @var Context */
  90. protected $context;
  91. /** @var Smarty_Data */
  92. protected $smarty;
  93. const CACHE_FILE_MODULES_LIST = '/config/xml/modules_list.xml';
  94. const CACHE_FILE_DEFAULT_COUNTRY_MODULES_LIST = '/config/xml/default_country_modules_list.xml';
  95. const CACHE_FILE_CUSTOMER_MODULES_LIST = '/config/xml/customer_modules_list.xml';
  96. const CACHE_FILE_MUST_HAVE_MODULES_LIST = '/config/xml/must_have_modules_list.xml';
  97. /**
  98. * Constructor
  99. *
  100. * @param string $name Module unique name
  101. * @param Context $context
  102. */
  103. public function __construct($name = null, Context $context = null)
  104. {
  105. // Load context and smarty
  106. $this->context = $context ? $context : Context::getContext();
  107. $this->smarty = $this->context->smarty->createData($this->context->smarty);
  108. // If the module has no name we gave him its id as name
  109. if ($this->name == null)
  110. $this->name = $this->id;
  111. // If the module has the name we load the corresponding data from the cache
  112. if ($this->name != null)
  113. {
  114. // If cache is not generated, we generate it
  115. if (self::$modules_cache == null && !is_array(self::$modules_cache))
  116. {
  117. // Join clause is done to check if the module is activated in current shop context
  118. $sql_limit_shop = 'SELECT COUNT(*) FROM `'._DB_PREFIX_.'module_shop` ms WHERE m.`id_module` = ms.`id_module` AND ms.`id_shop` = '.(int)Context::getContext()->shop->id;
  119. $sql = 'SELECT m.`id_module`, m.`name`, ('.$sql_limit_shop.') as total FROM `'._DB_PREFIX_.'module` m';
  120. // Result is cached
  121. self::$modules_cache = array();
  122. $result = Db::getInstance()->executeS($sql);
  123. foreach ($result as $row)
  124. {
  125. self::$modules_cache[$row['name']] = $row;
  126. self::$modules_cache[$row['name']]['active'] = ($row['total'] > 0) ? 1 : 0;
  127. }
  128. }
  129. // We load configuration from the cache
  130. if (isset(self::$modules_cache[$this->name]))
  131. {
  132. if (isset(self::$modules_cache[$this->name]['id_module']))
  133. $this->id = self::$modules_cache[$this->name]['id_module'];
  134. foreach (self::$modules_cache[$this->name] as $key => $value)
  135. if (key_exists($key, $this))
  136. $this->{$key} = $value;
  137. $this->_path = __PS_BASE_URI__.'modules/'.$this->name.'/';
  138. }
  139. $this->local_path = _PS_MODULE_DIR_.$this->name.'/';
  140. }
  141. }
  142. /**
  143. * Insert module into datable
  144. */
  145. public function install()
  146. {
  147. // Check module name validation
  148. if (!Validate::isModuleName($this->name))
  149. die(Tools::displayError());
  150. // Check PS version compliancy
  151. if (version_compare(_PS_VERSION_, $this->ps_versions_compliancy['min']) < 0 || version_compare(_PS_VERSION_, $this->ps_versions_compliancy['max']) >= 0)
  152. {
  153. $this->_errors[] = $this->l('The version of your module is not compliant with your PrestaShop version.');
  154. return false;
  155. }
  156. // Check module dependencies
  157. if (count($this->dependencies) > 0)
  158. foreach ($this->dependencies as $dependency)
  159. if (!Db::getInstance()->getRow('SELECT `id_module` FROM `'._DB_PREFIX_.'module` WHERE `name` = \''.pSQL($dependency).'\''))
  160. {
  161. $error = $this->l('Before installing this module, you have to installed these/this module(s) first :').'<br />';
  162. foreach ($this->dependencies as $d)
  163. $error .= '- '.$d.'<br />';
  164. $this->_errors[] = $error;
  165. return false;
  166. }
  167. // Check if module is installed
  168. $result = Db::getInstance()->getRow('SELECT `id_module` FROM `'._DB_PREFIX_.'module` WHERE `name` = \''.pSQL($this->name).'\'');
  169. if ($result)
  170. {
  171. $this->_errors[] = $this->l('This module has already been installed.');
  172. return false;
  173. }
  174. // Install overrides
  175. try {
  176. $this->installOverrides();
  177. } catch (Exception $e) {
  178. $this->_errors[] = sprintf(Tools::displayError('Unable to install override: %s'), $e->getMessage());
  179. $this->uninstallOverrides();
  180. return false;
  181. }
  182. // Install module and retrieve the installation id
  183. $result = Db::getInstance()->insert($this->table, array('name' => $this->name, 'active' => 1, 'version' => $this->version));
  184. if (!$result)
  185. {
  186. $this->_errors[] = $this->l('Technical error : PrestaShop could not installed this module.');
  187. return false;
  188. }
  189. $this->id = Db::getInstance()->Insert_ID();
  190. Cache::clean('Module::isInstalled'.$this->name);
  191. // Enable the module for current shops in context
  192. $this->enable();
  193. // Permissions management
  194. Db::getInstance()->execute('
  195. INSERT INTO `'._DB_PREFIX_.'module_access` (`id_profile`, `id_module`, `view`, `configure`) (
  196. SELECT id_profile, '.(int)$this->id.', 1, 1
  197. FROM '._DB_PREFIX_.'access a
  198. WHERE id_tab = (
  199. SELECT `id_tab` FROM '._DB_PREFIX_.'tab
  200. WHERE class_name = \'AdminModules\' LIMIT 1)
  201. AND a.`view` = 1)');
  202. Db::getInstance()->execute('
  203. INSERT INTO `'._DB_PREFIX_.'module_access` (`id_profile`, `id_module`, `view`, `configure`) (
  204. SELECT id_profile, '.(int)$this->id.', 1, 0
  205. FROM '._DB_PREFIX_.'access a
  206. WHERE id_tab = (
  207. SELECT `id_tab` FROM '._DB_PREFIX_.'tab
  208. WHERE class_name = \'AdminModules\' LIMIT 1)
  209. AND a.`view` = 0)');
  210. // Adding Restrictions for client groups
  211. Group::addRestrictionsForModule($this->id, Shop::getShops(true, null, true));
  212. return true;
  213. }
  214. /**
  215. * Set errors, warning or success message of a module upgrade
  216. *
  217. * @param $upgrade_detail
  218. */
  219. protected function setUpgradeMessage($upgrade_detail)
  220. {
  221. // Store information if a module has been upgraded (memory optimization)
  222. if ($upgrade_detail['available_upgrade'])
  223. {
  224. if ($upgrade_detail['success'])
  225. {
  226. $this->_confirmations[] = $this->l('Current version: ').$this->version;
  227. $this->_confirmations[] = $upgrade_detail['number_upgraded'].' '.$this->l('file upgrade applied');
  228. }
  229. else
  230. {
  231. if (!$upgrade_detail['number_upgraded'])
  232. $this->_errors[] = $this->l('None upgrades have been applied');
  233. else
  234. {
  235. $this->_errors[] = $this->l('Upgraded from: ').$upgrade_detail['upgraded_from'].$this->l(' to ').
  236. $upgrade_detail['upgraded_to'];
  237. $this->_errors[] = $upgrade_detail['number_upgrade_left'].' '.$this->l('upgrade left');
  238. }
  239. $this->_errors[] = $this->l('To prevent any problem, this module has been turned off');
  240. }
  241. }
  242. }
  243. /**
  244. * Init the upgrade module
  245. *
  246. * @static
  247. * @param $module_name
  248. * @param $module_version
  249. * @return bool
  250. */
  251. public static function initUpgradeModule($module)
  252. {
  253. // Init cache upgrade details
  254. self::$modules_cache[$module->name]['upgrade'] = array(
  255. 'success' => false, // bool to know if upgrade succeed or not
  256. 'available_upgrade' => 0, // Number of available module before any upgrade
  257. 'number_upgraded' => 0, // Number of upgrade done
  258. 'number_upgrade_left' => 0,
  259. 'upgrade_file_left' => array(), // List of the upgrade file left
  260. 'version_fail' => 0, // Version of the upgrade failure
  261. 'upgraded_from' => 0, // Version number before upgrading anything
  262. 'upgraded_to' => 0, // Last upgrade applied
  263. );
  264. // Need Upgrade will check and load upgrade file to the moduleCache upgrade case detail
  265. $ret = $module->installed && Module::needUpgrade($module);
  266. return $ret;
  267. }
  268. /**
  269. * Run the upgrade for a given module name and version
  270. *
  271. * @return array
  272. */
  273. public function runUpgradeModule()
  274. {
  275. $upgrade = &self::$modules_cache[$this->name]['upgrade'];
  276. foreach ($upgrade['upgrade_file_left'] as $num => $file_detail)
  277. {
  278. // Default variable required in the included upgrade file need to be set by default there:
  279. // upgrade_version, success_upgrade
  280. $upgrade_result = false;
  281. include($file_detail['file']);
  282. // Call the upgrade function if defined
  283. if (function_exists($file_detail['upgrade_function']))
  284. $upgrade_result = $file_detail['upgrade_function']($this);
  285. $upgrade['success'] = $upgrade_result;
  286. // Set detail when an upgrade succeed or failed
  287. if ($upgrade_result)
  288. {
  289. $upgrade['number_upgraded'] += 1;
  290. $upgrade['upgraded_to'] = $file_detail['version'];
  291. unset($upgrade['upgrade_file_left'][$num]);
  292. }
  293. else
  294. {
  295. $upgrade['version_fail'] = $file_detail['version'];
  296. // If any errors, the module is disabled
  297. $this->disable();
  298. break;
  299. }
  300. }
  301. $upgrade['number_upgrade_left'] = count($upgrade['upgrade_file_left']);
  302. // Update module version in DB with the last succeed upgrade
  303. if ($upgrade['upgraded_to'])
  304. Module::upgradeModuleVersion($this->name, $upgrade['upgraded_to']);
  305. $this->setUpgradeMessage($upgrade);
  306. return $upgrade;
  307. }
  308. /**
  309. * Upgrade the registered version to a new one
  310. *
  311. * @static
  312. * @param $name
  313. * @param $version
  314. * @return bool
  315. */
  316. public static function upgradeModuleVersion($name, $version)
  317. {
  318. return Db::getInstance()->execute('
  319. UPDATE `'._DB_PREFIX_.'module` m
  320. SET m.version = \''.bqSQL($version).'\'
  321. WHERE m.name = \''.bqSQL($name).'\'');
  322. }
  323. /**
  324. * Check if a module need to be upgraded.
  325. * This method modify the module_cache adding an upgrade list file
  326. *
  327. * @static
  328. * @param $module_name
  329. * @param $module_version
  330. * @return bool
  331. */
  332. public static function needUpgrade($module)
  333. {
  334. self::$modules_cache[$module->name]['upgrade']['upgraded_from'] = $module->database_version;
  335. // Check the version of the module with the registered one and look if any upgrade file exist
  336. return Tools::version_compare($module->version, $module->database_version, '>')
  337. && Module::loadUpgradeVersionList($module->name, $module->version, $module->database_version);
  338. }
  339. /**
  340. * Load the available list of upgrade of a specified module
  341. * with an associated version
  342. *
  343. * @static
  344. * @param $module_name
  345. * @param $module_version
  346. * @param $registered_version
  347. * @return bool to know directly if any files have been found
  348. */
  349. protected static function loadUpgradeVersionList($module_name, $module_version, $registered_version)
  350. {
  351. $list = array();
  352. $upgrade_path = _PS_MODULE_DIR_.$module_name.'/upgrade/';
  353. // Check if folder exist and it could be read
  354. if (file_exists($upgrade_path) && ($files = scandir($upgrade_path)))
  355. {
  356. // Read each file name
  357. foreach ($files as $file)
  358. if (!in_array($file, array('.', '..', '.svn', 'index.php')))
  359. {
  360. $tab = explode('-', $file);
  361. $file_version = basename($tab[1], '.php');
  362. // Compare version, if minor than actual, we need to upgrade the module
  363. if (count($tab) == 2 &&
  364. (Tools::version_compare($file_version, $module_version, '<=') &&
  365. Tools::version_compare($file_version, $registered_version, '>')))
  366. {
  367. $list[] = array(
  368. 'file' => $upgrade_path.$file,
  369. 'version' => $file_version,
  370. 'upgrade_function' => 'upgrade_module_'.str_replace('.', '_', $file_version));
  371. }
  372. }
  373. }
  374. // No files upgrade, then upgrade succeed
  375. if (count($list) == 0)
  376. {
  377. self::$modules_cache[$module_name]['upgrade']['success'] = true;
  378. Module::upgradeModuleVersion($module_name, $module_version);
  379. }
  380. // Set the list to module cache
  381. self::$modules_cache[$module_name]['upgrade']['upgrade_file_left'] = $list;
  382. self::$modules_cache[$module_name]['upgrade']['available_upgrade'] = count($list);
  383. return (bool)count($list);
  384. }
  385. /**
  386. * Return the status of the upgraded module
  387. *
  388. * @static
  389. * @param $module_name
  390. * @return bool
  391. */
  392. public static function getUpgradeStatus($module_name)
  393. {
  394. return (isset(self::$modules_cache[$module_name]) &&
  395. self::$modules_cache[$module_name]['upgrade']['success']);
  396. }
  397. /**
  398. * Delete module from datable
  399. *
  400. * @return boolean result
  401. */
  402. public function uninstall()
  403. {
  404. // Check module installation id validation
  405. if (!Validate::isUnsignedId($this->id))
  406. {
  407. $this->_errors[] = $this->l('The module is not installed.');
  408. return false;
  409. }
  410. // Uninstall overrides
  411. if (!$this->uninstallOverrides())
  412. return false;
  413. // Retrieve hooks used by the module
  414. $sql = 'SELECT `id_hook` FROM `'._DB_PREFIX_.'hook_module` WHERE `id_module` = '.(int)$this->id;
  415. $result = Db::getInstance()->executeS($sql);
  416. foreach ($result as $row)
  417. {
  418. $sql = 'DELETE FROM `'._DB_PREFIX_.'hook_module` WHERE `id_module` = '.(int)$this->id.' AND `id_hook` = '.(int)$row['id_hook'];
  419. Db::getInstance()->execute($sql);
  420. $this->cleanPositions($row['id_hook']);
  421. }
  422. // Disable the module for all shops
  423. $this->disable(true);
  424. // Delete permissions module access
  425. Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'module_access` WHERE `id_module` = '.(int)$this->id);
  426. // Remove restrictions for client groups
  427. Group::truncateRestrictionsByModule($this->id);
  428. // Uninstall the module
  429. if (Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'module` WHERE `id_module` = '.(int)$this->id))
  430. {
  431. Cache::clean('Module::isInstalled'.$this->name);
  432. return true;
  433. }
  434. return false;
  435. }
  436. /**
  437. * This function enable module $name. If an $name is an array,
  438. * this will enable all of them
  439. *
  440. * @param array|string $name
  441. * @return true if succeed
  442. * @since 1.4.1
  443. */
  444. public static function enableByName($name)
  445. {
  446. // If $name is not an array, we set it as an array
  447. if (!is_array($name))
  448. $name = array($name);
  449. // Enable each module
  450. foreach ($name as $k => $v)
  451. Module::getInstanceByName($name)->enable();
  452. }
  453. /**
  454. * Activate current module.
  455. *
  456. * @param bool $forceAll If true, enable module for all shop
  457. */
  458. public function enable($forceAll = false)
  459. {
  460. // Retrieve all shops where the module is enabled
  461. $list = Shop::getContextListShopID();
  462. $sql = 'SELECT `id_shop` FROM `'._DB_PREFIX_.'module_shop`
  463. WHERE `id_module` = '.$this->id.
  464. ((!$forceAll) ? ' AND `id_shop` IN('.implode(', ', $list).')' : '');
  465. // Store the results in an array
  466. $items = array();
  467. if ($results = Db::getInstance($sql)->executeS($sql))
  468. foreach ($results as $row)
  469. $items[] = $row['id_shop'];
  470. // Enable module in the shop where it is not enabled yet
  471. foreach ($list as $id)
  472. if (!in_array($id, $items))
  473. Db::getInstance()->insert('module_shop', array(
  474. 'id_module' => $this->id,
  475. 'id_shop' => $id,
  476. ));
  477. return true;
  478. }
  479. /**
  480. * This function disable module $name. If an $name is an array,
  481. * this will disable all of them
  482. *
  483. * @param array|string $name
  484. * @return true if succeed
  485. * @since 1.4.1
  486. */
  487. public static function disableByName($name)
  488. {
  489. // If $name is not an array, we set it as an array
  490. if (!is_array($name))
  491. $name = array($name);
  492. // Disable each module
  493. foreach ($name as $k => $v)
  494. Module::getInstanceByName($name)->disable();
  495. return true;
  496. }
  497. /**
  498. * Desactivate current module.
  499. *
  500. * @param bool $forceAll If true, disable module for all shop
  501. */
  502. public function disable($forceAll = false)
  503. {
  504. // Disable module for all shops
  505. $sql = 'DELETE FROM `'._DB_PREFIX_.'module_shop` WHERE `id_module` = '.(int)$this->id.' '.((!$forceAll) ? ' AND `id_shop` IN('.implode(', ', Shop::getContextListShopID()).')' : '');
  506. Db::getInstance()->execute($sql);
  507. }
  508. /**
  509. * Display flags in forms for translations
  510. *
  511. * @param array $languages All languages available
  512. * @param integer $default_language Default language id
  513. * @param string $ids Multilingual div ids in form
  514. * @param string $id Current div id]
  515. * @param boolean $return define the return way : false for a display, true for a return
  516. * @param boolean $use_vars_instead_of_ids use an js vars instead of ids seperate by "¤"
  517. */
  518. public function displayFlags($languages, $default_language, $ids, $id, $return = false, $use_vars_instead_of_ids = false)
  519. {
  520. if (count($languages) == 1)
  521. return false;
  522. $output = '
  523. <div class="displayed_flag">
  524. <img src="../img/l/'.$default_language.'.jpg" class="pointer" id="language_current_'.$id.'" onclick="toggleLanguageFlags(this);" alt="" />
  525. </div>
  526. <div id="languages_'.$id.'" class="language_flags">
  527. '.$this->l('Choose language:').'<br /><br />';
  528. foreach ($languages as $language)
  529. if ($use_vars_instead_of_ids)
  530. $output .= '<img src="../img/l/'.(int)$language['id_lang'].'.jpg" class="pointer" alt="'.$language['name'].'" title="'.$language['name'].'" onclick="changeLanguage(\''.$id.'\', '.$ids.', '.$language['id_lang'].', \''.$language['iso_code'].'\');" /> ';
  531. else
  532. $output .= '<img src="../img/l/'.(int)$language['id_lang'].'.jpg" class="pointer" alt="'.$language['name'].'" title="'.$language['name'].'" onclick="changeLanguage(\''.$id.'\', \''.$ids.'\', '.$language['id_lang'].', \''.$language['iso_code'].'\');" /> ';
  533. $output .= '</div>';
  534. if ($return)
  535. return $output;
  536. echo $output;
  537. }
  538. /**
  539. * Connect module to a hook
  540. *
  541. * @param string $hook_name Hook name
  542. * @param array $shop_list List of shop linked to the hook (if null, link hook to all shops)
  543. * @return boolean result
  544. */
  545. public function registerHook($hook_name, $shop_list = null)
  546. {
  547. // Check hook name validation and if module is installed
  548. if (!Validate::isHookName($hook_name))
  549. throw new PrestaShopException('Invalid hook name');
  550. if (!isset($this->id) || !is_numeric($this->id))
  551. return false;
  552. // Retrocompatibility
  553. if ($alias = Hook::getRetroHookName($hook_name))
  554. $hook_name = $alias;
  555. // Get hook id
  556. $id_hook = Hook::getIdByName($hook_name);
  557. // If hook does not exist, we create it
  558. if (!$id_hook)
  559. {
  560. $new_hook = new Hook();
  561. $new_hook->name = pSQL($hook_name);
  562. $new_hook->title = pSQL($hook_name);
  563. $new_hook->add();
  564. $id_hook = $new_hook->id;
  565. if (!$id_hook)
  566. return false;
  567. }
  568. // If shop lists is null, we fill it with all shops
  569. if (is_null($shop_list))
  570. $shop_list = Shop::getShops(true, null, true);
  571. $return = true;
  572. foreach ($shop_list as $shop_id)
  573. {
  574. // Check if already register
  575. $sql = 'SELECT hm.`id_module`
  576. FROM `'._DB_PREFIX_.'hook_module` hm, `'._DB_PREFIX_.'hook` h
  577. WHERE hm.`id_module` = '.(int)($this->id).' AND h.`id_hook` = '.$id_hook.'
  578. AND h.`id_hook` = hm.`id_hook` AND `id_shop` = '.(int)$shop_id;
  579. if (Db::getInstance()->getRow($sql))
  580. continue;
  581. // Get module position in hook
  582. $sql = 'SELECT MAX(`position`) AS position
  583. FROM `'._DB_PREFIX_.'hook_module`
  584. WHERE `id_hook` = '.(int)$id_hook.' AND `id_shop` = '.(int)$shop_id;
  585. if (!$position = Db::getInstance()->getValue($sql))
  586. $position = 0;
  587. // Register module in hook
  588. $return &= Db::getInstance()->insert('hook_module', array(
  589. 'id_module' => (int)$this->id,
  590. 'id_hook' => (int)$id_hook,
  591. 'id_shop' => (int)$shop_id,
  592. 'position' => (int)($position + 1),
  593. ));
  594. }
  595. return $return;
  596. }
  597. /**
  598. * Unregister module from hook
  599. *
  600. * @param mixed $id_hook Hook id (can be a hook name since 1.5.0)
  601. * @param array $shop_list List of shop
  602. * @return boolean result
  603. */
  604. public function unregisterHook($hook_id, $shop_list = null)
  605. {
  606. // Get hook id if a name is given as argument
  607. if (!is_numeric($hook_id))
  608. {
  609. // Retrocompatibility
  610. $hook_id = Hook::getIdByName($hook_id);
  611. if (!$hook_id)
  612. return false;
  613. }
  614. // Unregister module on hook by id
  615. $sql = 'DELETE FROM `'._DB_PREFIX_.'hook_module`
  616. WHERE `id_module` = '.(int)$this->id.' AND `id_hook` = '.(int)$hook_id
  617. .(($shop_list) ? ' AND `id_shop` IN('.implode(', ', $shop_list).')' : '');
  618. $result = Db::getInstance()->execute($sql);
  619. // Clean modules position
  620. $this->cleanPositions($hook_id, $shop_list);
  621. return $result;
  622. }
  623. /**
  624. * Unregister exceptions linked to module
  625. *
  626. * @param int $id_hook Hook id
  627. * @param array $shop_list List of shop
  628. * @return boolean result
  629. */
  630. public function unregisterExceptions($hook_id, $shop_list = null)
  631. {
  632. $sql = 'DELETE FROM `'._DB_PREFIX_.'hook_module_exceptions`
  633. WHERE `id_module` = '.(int)$this->id.' AND `id_hook` = '.(int)$hook_id
  634. .(($shop_list) ? ' AND `id_shop` IN('.implode(', ', $shop_list).')' : '');
  635. return Db::getInstance()->execute($sql);
  636. }
  637. /**
  638. * Add exceptions for module->Hook
  639. *
  640. * @param int $id_hook Hook id
  641. * @param array $excepts List of file name
  642. * @param array $shop_list List of shop
  643. * @return boolean result
  644. */
  645. public function registerExceptions($id_hook, $excepts, $shop_list = null)
  646. {
  647. // If shop lists is null, we fill it with all shops
  648. if (is_null($shop_list))
  649. $shop_list = Shop::getContextListShopID();
  650. // Save modules exception for each shop
  651. foreach ($shop_list as $shop_id)
  652. {
  653. foreach ($excepts as $except)
  654. {
  655. if (!$except)
  656. continue;
  657. $insertException = array(
  658. 'id_module' => (int)$this->id,
  659. 'id_hook' => (int)$id_hook,
  660. 'id_shop' => (int)$shop_id,
  661. 'file_name' => pSQL($except),
  662. );
  663. $result = Db::getInstance()->insert('hook_module_exceptions', $insertException);
  664. if (!$result)
  665. return false;
  666. }
  667. }
  668. return true;
  669. }
  670. /**
  671. * Edit exceptions for module->Hook
  672. *
  673. * @param int $hookID Hook id
  674. * @param array $excepts List of shopID and file name
  675. * @return boolean result
  676. */
  677. public function editExceptions($id_hook, $excepts)
  678. {
  679. $result = true;
  680. foreach ($excepts as $shop_id => $except)
  681. {
  682. $shop_list = ($shop_id == 0) ? Shop::getContextListShopID() : array($shop_id);
  683. $this->unregisterExceptions($id_hook, $shop_list);
  684. $result &= $this->registerExceptions($id_hook, $except, $shop_list);
  685. }
  686. return $result;
  687. }
  688. /**
  689. * This function is used to determine the module name
  690. * of an AdminTab which belongs to a module, in order to keep translation
  691. * related to a module in its directory (instead of $_LANGADM)
  692. *
  693. * @param mixed $currentClass the
  694. * @return boolean|string if the class belongs to a module, will return the module name. Otherwise, return false.
  695. */
  696. public static function getModuleNameFromClass($currentClass)
  697. {
  698. // Module can now define AdminTab keeping the module translations method,
  699. // i.e. in modules/[module name]/[iso_code].php
  700. if (!isset(self::$classInModule[$currentClass]) && class_exists($currentClass))
  701. {
  702. global $_MODULES;
  703. $_MODULE = array();
  704. $reflectionClass = new ReflectionClass($currentClass);
  705. $filePath = realpath($reflectionClass->getFileName());
  706. $realpathModuleDir = realpath(_PS_MODULE_DIR_);
  707. if (substr(realpath($filePath), 0, strlen($realpathModuleDir)) == $realpathModuleDir)
  708. {
  709. // For controllers in module/controllers path
  710. if (basename(dirname(dirname($filePath))) == 'controllers')
  711. self::$classInModule[$currentClass] = basename(dirname(dirname(dirname($filePath))));
  712. // For old AdminTab controllers
  713. else
  714. self::$classInModule[$currentClass] = substr(dirname($filePath), strlen($realpathModuleDir) + 1);
  715. $file = _PS_MODULE_DIR_.self::$classInModule[$currentClass].'/'.Context::getContext()->language->iso_code.'.php';
  716. if (Tools::file_exists_cache($file) && include_once($file))
  717. $_MODULES = !empty($_MODULES) ? array_merge($_MODULES, $_MODULE) : $_MODULE;
  718. }
  719. else
  720. self::$classInModule[$currentClass] = false;
  721. }
  722. // return name of the module, or false
  723. return self::$classInModule[$currentClass];
  724. }
  725. /**
  726. * Return an instance of the specified module
  727. *
  728. * @param string $module_name Module name
  729. * @return Module
  730. */
  731. public static function getInstanceByName($module_name)
  732. {
  733. if (!Validate::isModuleName($module_name))
  734. die(Tools::displayError());
  735. if (!isset(self::$_INSTANCE[$module_name]))
  736. {
  737. if (Tools::file_exists_cache(_PS_MODULE_DIR_.$module_name.'/'.$module_name.'.php'))
  738. {
  739. include_once(_PS_MODULE_DIR_.$module_name.'/'.$module_name.'.php');
  740. if (class_exists($module_name, false))
  741. return self::$_INSTANCE[$module_name] = new $module_name;
  742. }
  743. return false;
  744. }
  745. return self::$_INSTANCE[$module_name];
  746. }
  747. /**
  748. * Return an instance of the specified module
  749. *
  750. * @param integer $id_module Module ID
  751. * @return Module instance
  752. */
  753. public static function getInstanceById($id_module)
  754. {
  755. static $id2name = null;
  756. if (is_null($id2name))
  757. {
  758. $id2name = array();
  759. $sql = 'SELECT `id_module`, `name` FROM `'._DB_PREFIX_.'module`';
  760. if ($results = Db::getInstance()->executeS($sql))
  761. foreach ($results as $row)
  762. $id2name[$row['id_module']] = $row['name'];
  763. }
  764. if (isset($id2name[$id_module]))
  765. return Module::getInstanceByName($id2name[$id_module]);
  766. return false;
  767. }
  768. public static function configXmlStringFormat($string)
  769. {
  770. return str_replace('\'', '\\\'', Tools::htmlentitiesDecodeUTF8($string));
  771. }
  772. public static function getModuleName($module)
  773. {
  774. // Config file
  775. $configFile = _PS_MODULE_DIR_.$module.'/config.xml';
  776. if (!file_exists($configFile))
  777. return 'Module '.ucfirst($module);
  778. // Load config.xml
  779. libxml_use_internal_errors(true);
  780. $xml_module = simplexml_load_file($configFile);
  781. foreach (libxml_get_errors() as $error)
  782. {
  783. libxml_clear_errors();
  784. return 'Module '.ucfirst($module);
  785. }
  786. libxml_clear_errors();
  787. // Find translations
  788. global $_MODULES;
  789. $file = _PS_MODULE_DIR_.$module.'/'.Context::getContext()->language->iso_code.'.php';
  790. if (Tools::file_exists_cache($file) && include_once($file))
  791. if (isset($_MODULE) && is_array($_MODULE))
  792. $_MODULES = !empty($_MODULES) ? array_merge($_MODULES, $_MODULE) : $_MODULE;
  793. // Return Name
  794. return Translate::getModuleTranslation((string)$xml_module->name, Module::configXmlStringFormat($xml_module->displayName), (string)$xml_module->name);
  795. }
  796. /**
  797. * Return available modules
  798. *
  799. * @param boolean $useConfig in order to use config.xml file in module dir
  800. * @return array Modules
  801. */
  802. public static function getModulesOnDisk($useConfig = false, $loggedOnAddons = false, $id_employee = false)
  803. {
  804. global $_MODULES;
  805. // Init var
  806. $module_list = array();
  807. $module_name_list = array();
  808. $modulesNameToCursor = array();
  809. $errors = array();
  810. // Get modules directory list and memory limit
  811. $modules_dir = Module::getModulesDirOnDisk();
  812. $memory_limit = Tools::getMemoryLimit();
  813. $modules_installed = array();
  814. $result = Db::getInstance()->executeS('
  815. SELECT name, version, interest
  816. FROM `'._DB_PREFIX_.'module`
  817. LEFT JOIN `'._DB_PREFIX_.'module_preference` ON (`module` = `name` AND `id_employee` = '.(int)$id_employee.')');
  818. foreach ($result as $row)
  819. $modules_installed[$row['name']] = $row;
  820. foreach ($modules_dir as $module)
  821. {
  822. // Memory usage checking
  823. if (function_exists('memory_get_usage') && $memory_limit != '-1')
  824. {
  825. $current_memory = memory_get_usage(true);
  826. // memory_threshold in MB
  827. $memory_threshold = (Tools::isX86_64arch() ? 3 : 1.5);
  828. if (($memory_limit - $current_memory) <= ($memory_threshold * 1024 * 1024))
  829. {
  830. $errors[] = Tools::displayError('All modules cannot be loaded due to memory limit restrictions, please increase your memory_limit value on your server configuration');
  831. break;
  832. }
  833. }
  834. // Check if config.xml module file exists and if it's not outdated
  835. $configFile = _PS_MODULE_DIR_.$module.'/config.xml';
  836. $xml_exist = file_exists($configFile);
  837. if ($xml_exist)
  838. $needNewConfigFile = (filemtime($configFile) < filemtime(_PS_MODULE_DIR_.$module.'/'.$module.'.php'));
  839. else
  840. $needNewConfigFile = true;
  841. // If config.xml exists and that the use config flag is at true
  842. if ($useConfig && $xml_exist)
  843. {
  844. // Load config.xml
  845. libxml_use_internal_errors(true);
  846. $xml_module = simplexml_load_file($configFile);
  847. foreach (libxml_get_errors() as $error)
  848. $errors[] = '['.$module.'] '.Tools::displayError('Error found in config file:').' '.htmlentities($error->message);
  849. libxml_clear_errors();
  850. // If no errors in Xml, no need instand and no need new config.xml file, we load only translations
  851. if (!count($errors) && (int)$xml_module->need_instance == 0 && !$needNewConfigFile)
  852. {
  853. $file = _PS_MODULE_DIR_.$module.'/'.Context::getContext()->language->iso_code.'.php';
  854. if (Tools::file_exists_cache($file) && include_once($file))
  855. if (isset($_MODULE) && is_array($_MODULE))
  856. $_MODULES = !empty($_MODULES) ? array_merge($_MODULES, $_MODULE) : $_MODULE;
  857. $item = new stdClass();
  858. $item->id = 0;
  859. $item->warning = '';
  860. foreach ($xml_module as $k => $v)
  861. $item->$k = (string)$v;
  862. $item->displayName = stripslashes(Translate::getModuleTranslation((string)$xml_module->name, Module::configXmlStringFormat($xml_module->displayName), (string)$xml_module->name));
  863. $item->description = stripslashes(Translate::getModuleTranslation((string)$xml_module->name, Module::configXmlStringFormat($xml_module->description), (string)$xml_module->name));
  864. $item->author = stripslashes(Translate::getModuleTranslation((string)$xml_module->name, Module::configXmlStringFormat($xml_module->author), (string)$xml_module->name));
  865. if (isset($xml_module->confirmUninstall))
  866. $item->confirmUninstall = Translate::getModuleTranslation((string)$xml_module->name, Module::configXmlStringFormat($xml_module->confirmUninstall), (string)$xml_module->name);
  867. $item->active = 0;
  868. $item->onclick_option = false;
  869. $module_list[] = $item;
  870. $module_name_list[] = '\''.pSQL($item->name).'\'';
  871. $modulesNameToCursor[strval($item->name)] = $item;
  872. }
  873. }
  874. // If use config flag is at false or config.xml does not exist OR need instance OR need a new config.xml file
  875. if (!$useConfig || !$xml_exist || (isset($xml_module->need_instance) && (int)$xml_module->need_instance == 1) || $needNewConfigFile)
  876. {
  877. // If class does not exists, we include the file
  878. if (!class_exists($module, false))
  879. {
  880. // Get content from php file
  881. $filepath = _PS_MODULE_DIR_.$module.'/'.$module.'.php';
  882. $file = trim(file_get_contents(_PS_MODULE_DIR_.$module.'/'.$module.'.php'));
  883. if (substr($file, 0, 5) == '<?php')
  884. $file = substr($file, 5);
  885. if (substr($file, -2) == '?>')
  886. $file = substr($file, 0, -2);
  887. // If (false) is a trick to not load the class with "eval".
  888. // This way require_once will works correctly
  889. if (eval('if (false){ '.$file.' }') !== false)
  890. require_once( _PS_MODULE_DIR_.$module.'/'.$module.'.php' );
  891. else
  892. $errors[] = sprintf(Tools::displayError('%1$s (parse error in %2$s)'), $module, substr($filepath, strlen(_PS_ROOT_DIR_)));
  893. }
  894. // If class exists, we just instanciate it
  895. if (class_exists($module, false))
  896. {
  897. $tmp_module = new $module;
  898. $item = new stdClass();
  899. $item->id = $tmp_module->id;
  900. $item->warning = $tmp_module->warning;
  901. $item->name = $tmp_module->name;
  902. $item->version = $tmp_module->version;
  903. $item->tab = $tmp_module->tab;
  904. $item->displayName = $tmp_module->displayName;
  905. $item->description = stripslashes($tmp_module->description);
  906. $item->author = $tmp_module->author;
  907. $item->limited_countries = $tmp_module->limited_countries;
  908. $item->parent_class = get_parent_class($module);
  909. $item->is_configurable = $tmp_module->is_configurable = method_exists($tmp_module, 'getContent') ? 1 : 0;
  910. $item->need_instance = isset($tmp_module->need_instance) ? $tmp_module->need_instance : 0;
  911. $item->active = $tmp_module->active;
  912. $item->currencies = isset($tmp_module->currencies) ? $tmp_module->currencies : null;
  913. $item->currencies_mode = isset($tmp_module->currencies_mode) ? $tmp_module->currencies_mode : null;
  914. // Method pointer to get dynamically the onclick content
  915. $item->onclick_option = method_exists($module, 'onclickOption') ? true : false;
  916. $module_list[] = $item;
  917. if (!$xml_exist || $needNewConfigFile)
  918. {
  919. self::$_generate_config_xml_mode = true;
  920. $tmp_module->_generateConfigXml();
  921. self::$_generate_config_xml_mode = false;
  922. }
  923. unset($tmp_module);
  924. }
  925. else
  926. $errors[] = sprintf(Tools::displayError('%1$s (class missing in %2$s)'), $module, substr($filepath, strlen(_PS_ROOT_DIR_)));
  927. }
  928. }
  929. // Get modules information from database
  930. if (!empty($module_name_list))
  931. {
  932. $list = Shop::getContextListShopID();
  933. $sql = 'SELECT m.id_module, m.name, (
  934. SELECT COUNT(*) FROM '._DB_PREFIX_.'module_shop ms WHERE m.id_module = ms.id_module AND ms.id_shop IN ('.implode(',', $list).')
  935. ) as total
  936. FROM '._DB_PREFIX_.'module m
  937. WHERE m.name IN ('.implode(',', $module_name_list).')';
  938. $results = Db::getInstance()->executeS($sql);
  939. foreach ($results as $result)
  940. {
  941. $moduleCursor = $modulesNameToCursor[$result['name']];
  942. $moduleCursor->id = $result['id_module'];
  943. $moduleCursor->active = ($result['total'] == count($list)) ? 1 : 0;
  944. }
  945. }
  946. // Get Default Country Modules and customer module
  947. $files_list = array(
  948. array('type' => 'addonsNative', 'file' => _PS_ROOT_DIR_.self::CACHE_FILE_DEFAULT_COUNTRY_MODULES_LIST, 'loggedOnAddons' => 0),
  949. array('type' => 'addonsBought', 'file' => _PS_ROOT_DIR_.self::CACHE_FILE_CUSTOMER_MODULES_LIST, 'loggedOnAddons' => 1),
  950. array('type' => 'addonsMustHave', 'file' => _PS_ROOT_DIR_.self::CACHE_FILE_MUST_HAVE_MODULES_LIST, 'loggedOnAddons' => 0),
  951. );
  952. foreach ($files_list as $f)
  953. if (file_exists($f['file']) && ($f['loggedOnAddons'] == 0 || $loggedOnAddons))
  954. {
  955. $file = $f['file'];
  956. $content = Tools::file_get_contents($file);
  957. $xml = @simplexml_load_string($content, null, LIBXML_NOCDATA);
  958. if ($xml && isset($xml->module))
  959. foreach ($xml->module as $modaddons)
  960. {
  961. $flag_found = 0;
  962. foreach ($module_list as $k => $m)
  963. if ($m->name == $modaddons->name && !isset($m->available_on_addons))
  964. {
  965. $flag_found = 1;
  966. if ($m->version != $modaddons->version && version_compare($m->version, $modaddons->version) === -1)
  967. $module_list[$k]->version_addons = $modaddons->version;
  968. }
  969. if ($flag_found == 0)
  970. {
  971. $item = new stdClass();
  972. $item->id = 0;
  973. $item->warning = '';
  974. $item->type = strip_tags((string)$f['type']);
  975. $item->name = strip_tags((string)$modaddons->name);
  976. $item->version = strip_tags((string)$modaddons->version);
  977. $item->tab = strip_tags((string)$modaddons->tab);
  978. $item->displayName = strip_tags((string)$modaddons->displayName).' (Addons)';
  979. $item->description = stripslashes(strip_tags((string)$modaddons->description));
  980. $item->author = strip_tags((string)$modaddons->author);
  981. $item->limited_countries = array();
  982. $item->parent_class = '';
  983. $item->onclick_option = false;
  984. $item->is_configurable = 0;
  985. $item->need_instance = 0;
  986. $item->not_on_disk = 1;
  987. $item->available_on_addons = 1;
  988. $item->active = 0;
  989. if (isset($modaddons->img))
  990. {
  991. if (!file_exists('../img/tmp/'.md5($modaddons->name).'.jpg'))
  992. if (!@copy($modaddons->img, '../img/tmp/'.md5($modaddons->name).'.jpg'))
  993. @copy('../img/404.gif', '../img/tmp/'.md5($modaddons->name).'.jpg');
  994. if (file_exists('../img/tmp/'.md5($modaddons->name).'.jpg'))
  995. $item->image = '../img/tmp/'.md5($modaddons->name).'.jpg';
  996. }
  997. if ($item->type == 'addonsMustHave')
  998. {
  999. $item->addons_buy_url = strip_tags((string)$modaddons->url);
  1000. $prices = (array)$modaddons->price;
  1001. $id_default_currency = Configuration::get('PS_CURRENCY_DEFAULT');
  1002. foreach ($prices as $currency => $price)
  1003. if ($id_currency = Currency::getIdByIsoCode($currency))
  1004. if ($id_default_currency == $id_currency)
  1005. {
  1006. $item->price = (float)$price;
  1007. $item->id_currency = (int)$id_currency;
  1008. }
  1009. }
  1010. $module_list[] = $item;
  1011. }
  1012. }
  1013. }
  1014. foreach ($module_list as &$module)
  1015. if (isset($modules_installed[$module->name]))
  1016. {
  1017. $module->installed = true;
  1018. $module->database_version = $modules_installed[$module->name]['version'];
  1019. $module->interest = $modules_installed[$module->name]['interest'];
  1020. }
  1021. else
  1022. {
  1023. $module->installed = false;
  1024. $module->database_version = 0;
  1025. $module->interest = 0;
  1026. }
  1027. usort($module_list, create_function('$a,$b', '
  1028. if ($a->displayName == $b->displayName)
  1029. return 0;
  1030. return ($a->displayName < $b->displayName) ? -1 : 1;
  1031. '));
  1032. if ($errors)
  1033. {
  1034. echo '<div class="alert error"><h3>'.Tools::displayError('The following module(s) could not be loaded').':</h3><ol>';
  1035. foreach ($errors as $error)
  1036. echo '<li>'.$error.'</li>';
  1037. echo '</ol></div>';
  1038. }
  1039. return $module_list;
  1040. }
  1041. /**
  1042. * Return modules directory list
  1043. *
  1044. * @return array Modules Directory List
  1045. */
  1046. public static function getModulesDirOnDisk()
  1047. {
  1048. $module_list = array();
  1049. $modules = scandir(_PS_MODULE_DIR_);
  1050. foreach ($modules as $name)
  1051. {
  1052. if (is_dir(_PS_MODULE_DIR_.$name) && Tools::file_exists_cache(_PS_MODULE_DIR_.$name.'/'.$name.'.php'))
  1053. {
  1054. if (!Validate::isModuleName($name))
  1055. throw new PrestaShopException(sprintf('Module %s is not a valid module name', $name));
  1056. $module_list[] = $name;
  1057. }
  1058. }
  1059. return $module_list;
  1060. }
  1061. /**
  1062. * Return non native module
  1063. *
  1064. * @param int $position Take only positionnables modules
  1065. * @return array Modules
  1066. */
  1067. public static function getNonNativeModuleList()
  1068. {
  1069. $db = Db::getInstance();
  1070. $module_list_xml = _PS_ROOT_DIR_.self::CACHE_FILE_MODULES_LIST;
  1071. $native_modules = simplexml_load_file($module_list_xml);
  1072. $native_modules = $native_modules->modules;
  1073. foreach ($native_modules as $native_modules_type)
  1074. if (in_array($native_modules_type['type'], array('native', 'partner')))
  1075. {
  1076. $arr_native_modules[] = '""';
  1077. foreach ($native_modules_type->module as $module)
  1078. $arr_native_modules[] = '"'.pSQL($module['name']).'"';
  1079. }
  1080. return $db->executeS('SELECT * FROM `'._DB_PREFIX_.'module` m WHERE `name` NOT IN ('.implode(',', $arr_native_modules).') ');
  1081. }
  1082. /**
  1083. * Return installed modules
  1084. *
  1085. * @param int $position Take only positionnables modules
  1086. * @return array Modules
  1087. */
  1088. public static function getModulesInstalled($position = 0)
  1089. {
  1090. $sql = 'SELECT m.* FROM `'._DB_PREFIX_.'module` m ';
  1091. if ($position)
  1092. $sql .= 'LEFT JOIN `'._DB_PREFIX_.'hook_module` hm ON m.`id_module` = hm.`id_module`
  1093. LEFT JOIN `'._DB_PREFIX_.'hook` k ON hm.`id_hook` = k.`id_hook`
  1094. WHERE k.`position` = 1
  1095. GROUP BY m.id_module';
  1096. return Db::getInstance()->executeS($sql);
  1097. }
  1098. /**
  1099. * Execute modules for specified hook
  1100. *
  1101. * @param string $hook_name Hook Name
  1102. * @param array $hookArgs Parameters for the functions
  1103. * @return string modules output
  1104. */
  1105. public static function hookExec($hook_name, $hookArgs = array(), $id_module = null)
  1106. {
  1107. Tools::displayAsDeprecated();
  1108. return Hook::exec($hook_name, $hookArgs, $id_module);
  1109. }
  1110. public static function hookExecPayment()
  1111. {
  1112. Tools::displayAsDeprecated();
  1113. return Hook::exec('displayPayment');
  1114. }
  1115. public static function preCall($module_name)
  1116. {
  1117. return true;
  1118. }
  1119. /**
  1120. * Returns the list of the payment module associated to the current customer
  1121. * @see PaymentModule::getInstalledPaymentModules() if you don't care about the context
  1122. *
  1123. * @return array module informations
  1124. */
  1125. public static function getPaymentModules()
  1126. {
  1127. $context = Context::getContext();
  1128. if (isset($context->cart))
  1129. $billing = new Address((int)$context->cart->id_address_invoice);
  1130. $frontend = true;
  1131. $groups = array();
  1132. if (isset($context->employee))
  1133. $frontend = false;
  1134. elseif (isset($context->customer))
  1135. {
  1136. $groups = $context->customer->getGroups();
  1137. if (empty($groups))
  1138. $groups = array(Configuration::get('PS_UNIDENTIFIED_GROUP'));
  1139. }
  1140. $hookPayment = 'Payment';
  1141. if (Db::getInstance()->getValue('SELECT `id_hook` FROM `'._DB_PREFIX_.'hook` WHERE `name` = \'displayPayment\''))
  1142. $hookPayment = 'displayPayment';
  1143. $paypal_condition = '';
  1144. $iso_code = Country::getIsoById((int)Configuration::get('PS_COUNTRY_DEFAULT'));
  1145. $paypal_countries = array('ES', 'FR', 'PL', 'IT');
  1146. if (Context::getContext()->getMobileDevice() && Context::getContext()->shop->getTheme() == 'default' && in_array($iso_code, $paypal_countries))
  1147. $paypal_condition = ' AND m.`name` = \'paypal\'';
  1148. $list = Shop::getContextListShopID();
  1149. return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('SELECT DISTINCT m.`id_module`, h.`id_hook`, m.`name`, hm.`position`
  1150. FROM `'._DB_PREFIX_.'module` m
  1151. '.($frontend ? 'LEFT JOIN `'._DB_PREFIX_.'module_country` mc ON (m.`id_module` = mc.`id_module` AND mc.id_shop = '.(int)$context->shop->id.')' : '').'
  1152. '.($frontend ? 'INNER JOIN `'._DB_PREFIX_.'module_group` mg ON (m.`id_module` = mg.`id_module` AND mg.id_shop = '.(int)$context->shop->id.')' : '').'
  1153. '.($frontend && isset($context->customer) ? 'INNER JOIN `'._DB_PREFIX_.'customer_group` cg on (cg.`id_group` = mg.`id_group`AND cg.`id_customer` = '.(int)$context->customer->id.')' : '').'
  1154. LEFT JOIN `'._DB_PREFIX_.'hook_module` hm ON hm.`id_module` = m.`id_module`
  1155. LEFT JOIN `'._DB_PREFIX_.'hook` h ON hm.`id_hook` = h.`id_hook`
  1156. WHERE h.`name` = \''.pSQL($hookPayment).'\'
  1157. '.(isset($billing) && $frontend ? 'AND mc.id_country = '.(int)$billing->id_country : '').'
  1158. AND (SELECT COUNT(*) FROM '._DB_PREFIX_.'module_shop ms WHERE ms.id_module = m.id_module AND ms.id_shop IN('.implode(', ', $list).')) = '.count($list).'
  1159. AND hm.id_shop IN('.implode(', ', $list).')
  1160. '.(count($groups) && $frontend ? 'AND (mg.`id_group` IN('.implode(', ', $groups).'))' : '').$paypal_condition.'
  1161. GROUP BY hm.id_hook, hm.id_module
  1162. ORDER BY hm.`position`, m.`name` DESC');
  1163. }
  1164. /**
  1165. * @deprecated 1.5.0 Use Translate::getModuleTranslation()
  1166. */
  1167. public static function findTranslation($name, $string, $source)
  1168. {
  1169. return Translate::getModuleTranslation($name, $string, $source);
  1170. }
  1171. /**
  1172. * Get translation for a given module text
  1173. *
  1174. * Note: $specific parameter is mandatory for library files.
  1175. * Otherwise, translation key will not match for Module library
  1176. * when module is loaded with eval() Module::getModulesOnDisk()
  1177. *
  1178. * @param string $string String to translate
  1179. * @param boolean|string $specific filename to use in translation key
  1180. * @return string Translation
  1181. */
  1182. public function l($string, $specific = false, $id_lang = null)
  1183. {
  1184. if (self::$_generate_config_xml_mode)
  1185. return $string;
  1186. return Translate::getModuleTranslation($this, $string, ($specific) ? $specific : $this->name);
  1187. }
  1188. /*
  1189. * Reposition module
  1190. *
  1191. * @param boolean $id_hook Hook ID
  1192. * @param boolean $way Up (1) or Down (0)
  1193. * @param int $position
  1194. */
  1195. public function updatePosition($id_hook, $way, $position = null)
  1196. {
  1197. foreach (Shop::getContextListShopID() as $shop_id)
  1198. {
  1199. $sql = 'SELECT hm.`id_module`, hm.`position`, hm.`id_hook`
  1200. FROM `'._DB_PREFIX_.'hook_module` hm
  1201. WHERE hm.`id_hook` = '.(int)$id_hook.' AND hm.`id_shop` = '.$shop_id.'
  1202. ORDER BY hm.`position` '.($way ? 'ASC' : 'DESC');
  1203. if (!$res = Db::getInstance()->executeS($sql))
  1204. continue;
  1205. foreach ($res as $key => $values)
  1206. if ((int)$values[$this->identifier] == (int)$this->id)
  1207. {
  1208. $k = $key;
  1209. break;
  1210. }
  1211. if (!isset($k) || !isset($res[$k]) || !isset($res[$k + 1]))
  1212. return false;
  1213. $from = $res[$k];
  1214. $to = $res[$k + 1];
  1215. if (isset($position) && !empty($position))
  1216. $to['position'] = (int)$position;
  1217. $sql = 'UPDATE `'._DB_PREFIX_.'hook_module`
  1218. SET `position`= position '.($way ? '-1' : '+1').'
  1219. WHERE position between '.(int)(min(array($from['position'], $to['position']))).' AND '.max(array($from['position'], $to['position'])).'
  1220. AND `id_hook` = '.(int)$from['id_hook'].' AND `id_shop` = '.$shop_id;
  1221. if (!Db::getInstance()->execute($sql))
  1222. return false;
  1223. $sql = 'UPDATE `'._DB_PREFIX_.'hook_module`
  1224. SET `position`='.(int)$to['position'].'
  1225. WHERE `'.pSQL($this->identifier).'` = '.(int)$from[$this->identifier].'
  1226. AND `id_hook` = '.(int)$to['id_hook'].' AND `id_shop` = '.$shop_id;
  1227. if (!Db::getInstance()->execute($sql))
  1228. return false;
  1229. }
  1230. return true;
  1231. }
  1232. /*
  1233. * Reorder modules position
  1234. *
  1235. * @param boolean $id_hook Hook ID
  1236. * @param array $shop_list List of shop
  1237. */
  1238. public function cleanPositions($id_hook, $shop_list = null)
  1239. {
  1240. $sql = 'SELECT `id_module`, `id_shop`
  1241. FROM `'._DB_PREFIX_.'hook_module`
  1242. WHERE `id_hook` = '.(int)$id_hook.'
  1243. '.((!is_null($shop_list) && $shop_list) ? ' AND `id_shop` IN('.implode(', ', $shop_list).')' : '').'
  1244. ORDER BY `position`';
  1245. $results = Db::getInstance()->executeS($sql);
  1246. $position = array();
  1247. foreach ($results as $row)
  1248. {
  1249. if (!isset($position[$row['id_shop']]))
  1250. $position[$row['id_shop']] = 1;
  1251. $sql = 'UPDATE `'._DB_PREFIX_.'hook_module`
  1252. SET `position` = '.$position[$row['id_shop']].'
  1253. WHERE `id_hook` = '.(int)$id_hook.'
  1254. AND `id_module` = '.$row['id_module'].' AND `id_shop` = '.$row['id_shop'];
  1255. Db::getInstance()->execute($sql);
  1256. $position[$row['id_shop']]++;
  1257. }
  1258. return true;
  1259. }
  1260. public function displayError($error)
  1261. {
  1262. $output = '
  1263. <div class="module_error alert error">
  1264. '.$error.'
  1265. </div>';
  1266. $this->error = true;
  1267. return $output;
  1268. }
  1269. public function displayConfirmation($string)
  1270. {
  1271. $output = '
  1272. <div class="module_confirmation conf confirm">
  1273. '.$string.'
  1274. </div>';
  1275. return $output;
  1276. }
  1277. /*
  1278. * Return exceptions for module in hook
  1279. *
  1280. * @param int $id_hook Hook ID
  1281. * @return array Exceptions
  1282. */
  1283. protected static $exceptionsCache = null;
  1284. public function getExceptions($hookID, $dispatch = false)
  1285. {
  1286. if (self::$exceptionsCache === null)
  1287. {
  1288. self::$exceptionsCache = array();
  1289. $sql = 'SELECT * FROM `'._DB_PREFIX_.'hook_module_exceptions`
  1290. WHERE `id_shop` IN ('.implode(', ', Shop::getContextListShopID()).')';
  1291. $result = Db::getInstance()->executeS($sql);
  1292. foreach ($result as $row)
  1293. {
  1294. if (!$row['file_name'])
  1295. continue;
  1296. $key = $row['id_hook'].'-'.$row['id_module'];
  1297. if (!isset(self::$exceptionsCache[$key]))
  1298. self::$exceptionsCache[$key] = array();
  1299. if (!isset(self::$exceptionsCache[$key][$row['id_shop']]))
  1300. self::$exceptionsCache[$key][$row['id_shop']] = array();
  1301. self::$exceptionsCache[$key][$row['id_shop']][] = $row['file_name'];
  1302. }
  1303. }
  1304. $key = $hookID.'-'.$this->id;
  1305. if (!$dispatch)
  1306. {
  1307. $files = array();
  1308. foreach (Shop::getContextListShopID() as $shop_id)
  1309. if (isset(self::$exceptionsCache[$key], self::$exceptionsCache[$key][$shop_id]))
  1310. foreach (self::$exceptionsCache[$key][$shop_id] as $file)
  1311. if (!in_array($file, $files))
  1312. $files[] = $file;
  1313. return $files;
  1314. }
  1315. else
  1316. {
  1317. $list = array();
  1318. foreach (Shop::getContextListShopID() as $shop_id)
  1319. if (isset(self::$exceptionsCache[$key], self::$exceptionsCache[$key][$shop_id]))
  1320. $list[$shop_id] = self::$exceptionsCache[$key][$shop_id];
  1321. return $list;
  1322. }
  1323. }
  1324. public static function isInstalled($module_name)
  1325. {
  1326. if (

Large files files are truncated, but you can click here to view the full file