PageRenderTime 41ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 1ms

/classes/controller/AdminController.php

https://github.com/OnjanirinaPro/PrestaShop
PHP | 3861 lines | 2880 code | 475 blank | 506 comment | 763 complexity | 6366fbe0beb391373768ff6c94a464ae MD5 | raw file
  1. <?php
  2. /*
  3. * 2007-2014 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-2014 PrestaShop SA
  23. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  24. * International Registered Trademark & Property of PrestaShop SA
  25. */
  26. class AdminControllerCore extends Controller
  27. {
  28. public $path;
  29. public static $currentIndex;
  30. public $content;
  31. public $warnings = array();
  32. public $informations = array();
  33. public $confirmations = array();
  34. public $shopShareDatas = false;
  35. public $_languages = array();
  36. public $default_form_language;
  37. public $allow_employee_form_lang;
  38. public $layout = 'layout.tpl';
  39. public $bootstrap = false ;
  40. protected $meta_title;
  41. public $template = 'content.tpl';
  42. /** @var string Associated table name */
  43. public $table = 'configuration';
  44. public $list_id;
  45. /** @var string Object identifier inside the associated table */
  46. protected $identifier = false;
  47. protected $identifier_name = 'name';
  48. /** @var string Tab name */
  49. public $className;
  50. /** @var array tabAccess */
  51. public $tabAccess;
  52. /** @var integer Tab id */
  53. public $id = -1;
  54. public $required_database = false;
  55. /** @var string Security token */
  56. public $token;
  57. /** @var string shop | group_shop */
  58. public $shopLinkType;
  59. /** @var string Default ORDER BY clause when $_orderBy is not defined */
  60. protected $_defaultOrderBy = false;
  61. protected $_defaultOrderWay = 'ASC';
  62. public $tpl_form_vars = array();
  63. public $tpl_list_vars = array();
  64. public $tpl_delete_link_vars = array();
  65. public $tpl_option_vars = array();
  66. public $tpl_view_vars = array();
  67. public $tpl_required_fields_vars = array();
  68. public $base_tpl_view = null;
  69. public $base_tpl_form = null;
  70. /** @var bool if you want more fieldsets in the form */
  71. public $multiple_fieldsets = false;
  72. public $fields_value = false;
  73. /** @var array Errors displayed after post processing */
  74. public $errors = array();
  75. /** @var define if the header of the list contains filter and sorting links or not */
  76. protected $list_simple_header;
  77. /** @var array list to be generated */
  78. protected $fields_list;
  79. /** @var array modules list filters */
  80. protected $filter_modules_list = null;
  81. /** @var array modules list filters */
  82. protected $modules_list = array();
  83. /** @var array edit form to be generated */
  84. protected $fields_form;
  85. /** @var override of $fields_form */
  86. protected $fields_form_override;
  87. /** @var override form action */
  88. protected $submit_action;
  89. /** @var array list of option forms to be generated */
  90. protected $fields_options = array();
  91. protected $shopLink;
  92. /** @var string SQL query */
  93. protected $_listsql = '';
  94. /** @var array Cache for query results */
  95. protected $_list = array();
  96. /** @var define if the header of the list contains filter and sorting links or not */
  97. protected $toolbar_title;
  98. /** @var array list of toolbar buttons */
  99. protected $toolbar_btn = null;
  100. /** @var boolean scrolling toolbar */
  101. protected $toolbar_scroll = true;
  102. /** @var boolean set to false to hide toolbar and page title */
  103. protected $show_toolbar = true;
  104. /** @var boolean set to true to show toolbar and page title for options */
  105. protected $show_toolbar_options = false;
  106. /** @var integer Number of results in list */
  107. protected $_listTotal = 0;
  108. /** @var boolean Automatically join language table if true */
  109. public $lang = false;
  110. /** @var array WHERE clause determined by filter fields */
  111. protected $_filter;
  112. /** @var array Temporary SQL table WHERE clause determinated by filter fields */
  113. protected $_tmpTableFilter = '';
  114. /** @var array Number of results in list per page (used in select field) */
  115. protected $_pagination = array(20, 50, 100, 300, 1000);
  116. /** @var integer Default number of results in list per page */
  117. protected $_default_pagination = 50;
  118. /** @var string ORDER BY clause determined by field/arrows in list header */
  119. protected $_orderBy;
  120. /** @var string Order way (ASC, DESC) determined by arrows in list header */
  121. protected $_orderWay;
  122. /** @var array list of available actions for each list row - default actions are view, edit, delete, duplicate */
  123. protected $actions_available = array('view', 'edit', 'duplicate', 'delete');
  124. /** @var array list of required actions for each list row */
  125. protected $actions = array();
  126. /** @var array list of row ids associated with a given action for witch this action have to not be available */
  127. protected $list_skip_actions = array();
  128. /* @var boolean don't show header & footer */
  129. protected $lite_display = false;
  130. /** @var bool boolean List content lines are clickable if true */
  131. protected $list_no_link = false;
  132. protected $allow_export = false;
  133. /** @var array $cache_lang cache for traduction */
  134. public static $cache_lang = array();
  135. /** @var array required_fields to display in the Required Fields form */
  136. public $required_fields = array();
  137. /** @var Helper */
  138. protected $helper;
  139. /**
  140. * @var array actions to execute on multiple selections
  141. * Usage:
  142. * array(
  143. * 'actionName' => array(
  144. * 'text' => $this->l('Message displayed on the submit button (mandatory)'),
  145. * 'confirm' => $this->l('If set, this confirmation message will pop-up (optional)')),
  146. * 'anotherAction' => array(...)
  147. * );
  148. *
  149. * If your action is named 'actionName', you need to have a method named bulkactionName() that will be executed when the button is clicked.
  150. */
  151. protected $bulk_actions;
  152. /**
  153. * @var array ids of the rows selected
  154. */
  155. protected $boxes;
  156. /** @var string Do not automatically select * anymore but select only what is necessary */
  157. protected $explicitSelect = false;
  158. /** @var string Add fields into data query to display list */
  159. protected $_select;
  160. /** @var string Join tables into data query to display list */
  161. protected $_join;
  162. /** @var string Add conditions into data query to display list */
  163. protected $_where;
  164. /** @var string Group rows into data query to display list */
  165. protected $_group;
  166. /** @var string Having rows into data query to display list */
  167. protected $_having;
  168. protected $is_cms = false;
  169. /** @var string identifier to use for changing positions in lists (can be omitted if positions cannot be changed) */
  170. protected $position_identifier;
  171. protected $position_group_identifier;
  172. /** @var boolean Table records are not deleted but marked as deleted if set to true */
  173. protected $deleted = false;
  174. /**
  175. * @var bool is a list filter set
  176. */
  177. protected $filter;
  178. protected $noLink;
  179. protected $specificConfirmDelete = null;
  180. protected $colorOnBackground;
  181. /** @var bool If true, activates color on hover */
  182. protected $row_hover = true;
  183. /** @string Action to perform : 'edit', 'view', 'add', ... */
  184. protected $action;
  185. protected $display;
  186. protected $_includeContainer = true;
  187. protected $tab_modules_list = array('default_list' => array(), 'slider_list' => array());
  188. public $tpl_folder;
  189. protected $bo_theme;
  190. /** @var bool Redirect or not ater a creation */
  191. protected $_redirect = true;
  192. /** @var array Name and directory where class image are located */
  193. public $fieldImageSettings = array();
  194. /** @var string Image type */
  195. public $imageType = 'jpg';
  196. /** @var instanciation of the class associated with the AdminController */
  197. protected $object;
  198. /** @var int current object ID */
  199. protected $id_object;
  200. /**
  201. * @var current controller name without suffix
  202. */
  203. public $controller_name;
  204. public $multishop_context = -1;
  205. public $multishop_context_group = true;
  206. /**
  207. * Current breadcrumb position as an array of tab names
  208. */
  209. protected $breadcrumbs;
  210. //Bootstrap variable
  211. public $show_page_header_toolbar = false;
  212. public $page_header_toolbar_title;
  213. public $page_header_toolbar_btn = array();
  214. public $show_form_cancel_button;
  215. public $admin_webpath;
  216. protected $list_natives_modules = array();
  217. protected $list_partners_modules = array();
  218. public $modals = array();
  219. protected $logged_on_addons = false;
  220. public function __construct()
  221. {
  222. global $timer_start;
  223. $this->timer_start = $timer_start;
  224. // Has to be remove for the next Prestashop version
  225. global $token;
  226. $this->controller_type = 'admin';
  227. $this->controller_name = get_class($this);
  228. if (strpos($this->controller_name, 'Controller'))
  229. $this->controller_name = substr($this->controller_name, 0, -10);
  230. parent::__construct();
  231. if ($this->multishop_context == -1)
  232. $this->multishop_context = Shop::CONTEXT_ALL | Shop::CONTEXT_GROUP | Shop::CONTEXT_SHOP;
  233. $this->bo_theme = ((Validate::isLoadedObject($this->context->employee) && $this->context->employee->bo_theme) ? $this->context->employee->bo_theme : 'default');
  234. if (!file_exists(_PS_BO_ALL_THEMES_DIR_.$this->bo_theme.DIRECTORY_SEPARATOR.'template'))
  235. $this->bo_theme = 'default';
  236. $this->bo_css = ((Validate::isLoadedObject($this->context->employee) && $this->context->employee->bo_css) ? $this->context->employee->bo_css : 'admin-theme.css');
  237. if (!file_exists(_PS_BO_ALL_THEMES_DIR_.$this->bo_theme.DIRECTORY_SEPARATOR.'css'.DIRECTORY_SEPARATOR.$this->bo_css))
  238. $this->bo_css = 'admin-theme.css';
  239. $this->context->smarty->setTemplateDir(array(
  240. _PS_BO_ALL_THEMES_DIR_.$this->bo_theme.DIRECTORY_SEPARATOR.'template',
  241. _PS_OVERRIDE_DIR_.'controllers'.DIRECTORY_SEPARATOR.'admin'.DIRECTORY_SEPARATOR.'templates'
  242. ));
  243. $this->id = Tab::getIdFromClassName($this->controller_name);
  244. $this->token = Tools::getAdminToken($this->controller_name.(int)$this->id.(int)$this->context->employee->id);
  245. $token = $this->token;
  246. $this->_conf = array(
  247. 1 => $this->l('Successful deletion'),
  248. 2 => $this->l('The selection has been successfully deleted.'),
  249. 3 => $this->l('Successful creation'),
  250. 4 => $this->l('Successful update'),
  251. 5 => $this->l('The status has been successfully updated.'),
  252. 6 => $this->l('The settings have been successfully updated.'),
  253. 7 => $this->l('The image was successfully deleted.'),
  254. 8 => $this->l('The module was successfully downloaded.'),
  255. 9 => $this->l('The thumbnails were successfully regenerated.'),
  256. 10 => $this->l('The message was successfully sent to the customer.'),
  257. 11 => $this->l('Comment successfully added'),
  258. 12 => $this->l('Module(s) installed successfully.'),
  259. 13 => $this->l('Module(s) uninstalled successfully.'),
  260. 14 => $this->l('The translation was successfully copied.'),
  261. 15 => $this->l('The translations have been successfully added.'),
  262. 16 => $this->l('The module transplanted successfully to the hook.'),
  263. 17 => $this->l('The module was successfully removed from the hook.'),
  264. 18 => $this->l('Successful upload'),
  265. 19 => $this->l('Duplication was completed successfully.'),
  266. 20 => $this->l('The translation was added successfully, but the language has not been created.'),
  267. 21 => $this->l('Module reset successfully.'),
  268. 22 => $this->l('Module deleted successfully.'),
  269. 23 => $this->l('Localization pack imported successfully.'),
  270. 24 => $this->l('Localization pack imported successfully.'),
  271. 25 => $this->l('The selected images have successfully been moved.'),
  272. 26 => $this->l('Your cover image selection has been saved.'),
  273. 27 => $this->l('The image\'s shop association has been modified.'),
  274. 28 => $this->l('A zone has been assigned to the selection successfully.'),
  275. 29 => $this->l('Successful upgrade'),
  276. 30 => $this->l('A partial refund was successfully created.'),
  277. 31 => $this->l('The discount was successfully generated.'),
  278. 32 => $this->l('Successfully signed in to PrestaShop Addons')
  279. );
  280. if (!$this->identifier) $this->identifier = 'id_'.$this->table;
  281. if (!$this->_defaultOrderBy) $this->_defaultOrderBy = $this->identifier;
  282. $this->tabAccess = Profile::getProfileAccess($this->context->employee->id_profile, $this->id);
  283. // Fix for homepage
  284. if ($this->controller_name == 'AdminDashboard')
  285. $_POST['token'] = $this->token;
  286. if (!Shop::isFeatureActive())
  287. $this->shopLinkType = '';
  288. //$this->base_template_folder = _PS_BO_ALL_THEMES_DIR_.$this->bo_theme.'/template';
  289. $this->override_folder = Tools::toUnderscoreCase(substr($this->controller_name, 5)).'/';
  290. // Get the name of the folder containing the custom tpl files
  291. $this->tpl_folder = Tools::toUnderscoreCase(substr($this->controller_name, 5)).'/';
  292. $this->initShopContext();
  293. $this->context->currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));
  294. $this->admin_webpath = str_ireplace(_PS_CORE_DIR_, '', _PS_ADMIN_DIR_);
  295. $this->admin_webpath = preg_replace('/^'.preg_quote(DIRECTORY_SEPARATOR, '/').'/', '', $this->admin_webpath);
  296. // Check if logged on Addons
  297. if (isset($this->context->cookie->username_addons) && isset($this->context->cookie->password_addons) && !empty($this->context->cookie->username_addons) && !empty($this->context->cookie->password_addons))
  298. $this->logged_on_addons = true;
  299. }
  300. /**
  301. * Set breadcrumbs array for the controller page
  302. */
  303. public function initBreadcrumbs($tab_id = null, $tabs = null)
  304. {
  305. if (is_array($tabs) || count($tabs))
  306. $tabs = array();
  307. if (is_null($tab_id))
  308. $tab_id = $this->id;
  309. $tabs = Tab::recursiveTab($tab_id, $tabs);
  310. $dummy = array('name' => '', 'href' => '', 'icon' => '');
  311. $breadcrumbs2 = array(
  312. 'container' => $dummy,
  313. 'tab' => $dummy,
  314. 'action' => $dummy
  315. );
  316. if (isset($tabs[0]))
  317. {
  318. $breadcrumbs2['tab']['name'] = $tabs[0]['name'];
  319. $breadcrumbs2['tab']['href'] = __PS_BASE_URI__.basename(_PS_ADMIN_DIR_ ).'/'.$this->context->link->getAdminLink($tabs[0]['class_name']);
  320. if (!isset($tabs[1]))
  321. $breadcrumbs2['tab']['icon'] = 'icon-'.$tabs[0]['class_name'];
  322. }
  323. if (isset($tabs[1]))
  324. {
  325. $breadcrumbs2['container']['name'] = $tabs[1]['name'];
  326. $breadcrumbs2['container']['href'] = __PS_BASE_URI__.basename(_PS_ADMIN_DIR_ ).'/'.$this->context->link->getAdminLink($tabs[1]['class_name']);
  327. $breadcrumbs2['container']['icon'] = 'icon-'.$tabs[1]['class_name'];
  328. }
  329. /* content, edit, list, add, details, options, view */
  330. switch ($this->display)
  331. {
  332. case 'add':
  333. $breadcrumbs2['action']['name'] = $this->l('Add', null, null, false);
  334. $breadcrumbs2['action']['icon'] = 'icon-plus';
  335. break;
  336. case 'edit':
  337. $breadcrumbs2['action']['name'] = $this->l('Edit', null, null, false);
  338. $breadcrumbs2['action']['icon'] = 'icon-pencil';
  339. break;
  340. case '':
  341. case 'list':
  342. $breadcrumbs2['action']['name'] = $this->l('List', null, null, false);
  343. $breadcrumbs2['action']['icon'] = 'icon-th-list';
  344. break;
  345. case 'details':
  346. case 'view':
  347. $breadcrumbs2['action']['name'] = $this->l('View details', null, null, false);
  348. $breadcrumbs2['action']['icon'] = 'icon-zoom-in';
  349. break;
  350. case 'options':
  351. $breadcrumbs2['action']['name'] = $this->l('Options', null, null, false);
  352. $breadcrumbs2['action']['icon'] = 'icon-cogs';
  353. break;
  354. case 'generator':
  355. $breadcrumbs2['action']['name'] = $this->l('Generator', null, null, false);
  356. $breadcrumbs2['action']['icon'] = 'icon-flask';
  357. break;
  358. }
  359. $this->context->smarty->assign('breadcrumbs2', $breadcrumbs2);
  360. /* BEGIN - Backward compatibility < 1.6.0.3 */
  361. $this->breadcrumbs[] = $tabs[0]['name'];
  362. $navigationPipe = (Configuration::get('PS_NAVIGATION_PIPE') ? Configuration::get('PS_NAVIGATION_PIPE') : '>');
  363. $this->context->smarty->assign('navigationPipe', $navigationPipe);
  364. /* END - Backward compatibility < 1.6.0.3 */
  365. }
  366. /**
  367. * set default toolbar_title to admin breadcrumb
  368. *
  369. * @return void
  370. */
  371. public function initToolbarTitle()
  372. {
  373. $this->toolbar_title = is_array($this->breadcrumbs) ? array_unique($this->breadcrumbs) : array($this->breadcrumbs);
  374. switch ($this->display)
  375. {
  376. case 'edit':
  377. $this->toolbar_title[] = $this->l('Edit', null, null, false);
  378. break;
  379. case 'add':
  380. $this->toolbar_title[] = $this->l('Add new', null, null, false);
  381. break;
  382. case 'view':
  383. $this->toolbar_title[] = $this->l('View', null, null, false);
  384. break;
  385. }
  386. if ($filter = $this->addFiltersToBreadcrumbs())
  387. $this->toolbar_title[] = $filter;
  388. }
  389. public function addFiltersToBreadcrumbs()
  390. {
  391. if ($this->filter && is_array($this->fields_list))
  392. {
  393. $filters = array();
  394. foreach ($this->fields_list as $field => $t)
  395. {
  396. if (isset($t['filter_key']))
  397. $field = $t['filter_key'];
  398. if ($val = Tools::getValue($this->table.'Filter_'.$field))
  399. {
  400. if (!is_array($val))
  401. {
  402. $filter_value = '';
  403. if (isset($t['type']) && $t['type'] == 'bool')
  404. $filter_value = ((bool)$val) ? $this->l('yes') : $this->l('no');
  405. elseif (is_string($val))
  406. $filter_value = htmlspecialchars($val, ENT_QUOTES, 'UTF-8');
  407. if (!empty($filter_value))
  408. $filters[] = sprintf($this->l('%s: %s'), $t['title'], $filter_value);
  409. }
  410. else
  411. {
  412. $filter_value = '';
  413. foreach ($val as $v)
  414. if (is_string($v) && !empty($v))
  415. $filter_value .= ' - '.htmlspecialchars($v, ENT_QUOTES, 'UTF-8');
  416. $filter_value = ltrim($filter_value, ' -');
  417. if (!empty($filter_value))
  418. $filters[] = sprintf($this->l('%s: %s'), $t['title'], $filter_value);
  419. }
  420. }
  421. }
  422. if (count($filters))
  423. return sprintf($this->l('filter by %s'), implode(', ', $filters));
  424. }
  425. }
  426. /**
  427. * Check rights to view the current tab
  428. *
  429. * @param bool $disable
  430. * @return boolean
  431. */
  432. public function viewAccess($disable = false)
  433. {
  434. if ($disable)
  435. return true;
  436. if ($this->tabAccess['view'] === '1')
  437. return true;
  438. return false;
  439. }
  440. /**
  441. * Check for security token
  442. */
  443. public function checkToken()
  444. {
  445. $token = Tools::getValue('token');
  446. return (!empty($token) && $token === $this->token);
  447. }
  448. /**
  449. * Set the filters used for the list display
  450. */
  451. public function processFilter()
  452. {
  453. if (!isset($this->list_id))
  454. $this->list_id = $this->table;
  455. $prefix = str_replace(array('admin', 'controller'), '', Tools::strtolower(get_class($this)));
  456. if (isset($this->list_id))
  457. {
  458. foreach ($_POST as $key => $value)
  459. {
  460. if ($value === '')
  461. unset($this->context->cookie->{$prefix.$key});
  462. elseif (stripos($key, $this->list_id.'Filter_') === 0)
  463. $this->context->cookie->{$prefix.$key} = !is_array($value) ? $value : serialize($value);
  464. elseif (stripos($key, 'submitFilter') === 0)
  465. $this->context->cookie->$key = !is_array($value) ? $value : serialize($value);
  466. }
  467. foreach ($_GET as $key => $value)
  468. if (stripos($key, $this->list_id.'Orderby') === 0 && Validate::isOrderBy($value))
  469. {
  470. if ($value === '' || $value == $this->_defaultOrderBy)
  471. unset($this->context->cookie->{$prefix.$key});
  472. else
  473. $this->context->cookie->{$prefix.$key} = $value;
  474. }
  475. elseif (stripos($key, $this->list_id.'Orderway') === 0 && Validate::isOrderWay($value))
  476. {
  477. if ($value === '' || $value == $this->_defaultOrderWay)
  478. unset($this->context->cookie->{$prefix.$key});
  479. else
  480. $this->context->cookie->{$prefix.$key} = $value;
  481. }
  482. }
  483. $filters = $this->context->cookie->getFamily($prefix.$this->list_id.'Filter_');
  484. foreach ($filters as $key => $value)
  485. {
  486. /* Extracting filters from $_POST on key filter_ */
  487. if ($value != null && !strncmp($key, $prefix.$this->list_id.'Filter_', 7 + Tools::strlen($prefix.$this->list_id)))
  488. {
  489. $key = Tools::substr($key, 7 + Tools::strlen($prefix.$this->list_id));
  490. /* Table alias could be specified using a ! eg. alias!field */
  491. $tmp_tab = explode('!', $key);
  492. $filter = count($tmp_tab) > 1 ? $tmp_tab[1] : $tmp_tab[0];
  493. if ($field = $this->filterToField($key, $filter))
  494. {
  495. $type = (array_key_exists('filter_type', $field) ? $field['filter_type'] : (array_key_exists('type', $field) ? $field['type'] : false)); if (($type == 'date' || $type == 'datetime') && is_string($value))
  496. $value = Tools::unSerialize($value);
  497. $key = isset($tmp_tab[1]) ? $tmp_tab[0].'.`'.$tmp_tab[1].'`' : '`'.$tmp_tab[0].'`';
  498. // Assignement by reference
  499. if (array_key_exists('tmpTableFilter', $field))
  500. $sql_filter = & $this->_tmpTableFilter;
  501. elseif (array_key_exists('havingFilter', $field))
  502. $sql_filter = & $this->_filterHaving;
  503. else
  504. $sql_filter = & $this->_filter;
  505. /* Only for date filtering (from, to) */
  506. if (is_array($value))
  507. {
  508. if (isset($value[0]) && !empty($value[0]))
  509. {
  510. if (!Validate::isDate($value[0]))
  511. $this->errors[] = Tools::displayError('The \'From\' date format is invalid (YYYY-MM-DD)');
  512. else
  513. $sql_filter .= ' AND '.pSQL($key).' >= \''.pSQL(Tools::dateFrom($value[0])).'\'';
  514. }
  515. if (isset($value[1]) && !empty($value[1]))
  516. {
  517. if (!Validate::isDate($value[1]))
  518. $this->errors[] = Tools::displayError('The \'To\' date format is invalid (YYYY-MM-DD)');
  519. else
  520. $sql_filter .= ' AND '.pSQL($key).' <= \''.pSQL(Tools::dateTo($value[1])).'\'';
  521. }
  522. }
  523. else
  524. {
  525. $sql_filter .= ' AND ';
  526. $check_key = ($key == $this->identifier || $key == '`'.$this->identifier.'`');
  527. if ($type == 'int' || $type == 'bool')
  528. $sql_filter .= (($check_key || $key == '`active`') ? 'a.' : '').pSQL($key).' = '.(int)$value.' ';
  529. elseif ($type == 'decimal')
  530. $sql_filter .= ($check_key ? 'a.' : '').pSQL($key).' = '.(float)$value.' ';
  531. elseif ($type == 'select')
  532. $sql_filter .= ($check_key ? 'a.' : '').pSQL($key).' = \''.pSQL($value).'\' ';
  533. else
  534. {
  535. if ($type == 'price')
  536. $value = (float)str_replace(',', '.', $value);
  537. $sql_filter .= ($check_key ? 'a.' : '').pSQL($key).' LIKE \'%'.pSQL($value).'%\' ';
  538. }
  539. }
  540. }
  541. }
  542. }
  543. }
  544. /**
  545. * @todo uses redirectAdmin only if !$this->ajax
  546. */
  547. public function postProcess()
  548. {
  549. try {
  550. if ($this->ajax)
  551. {
  552. // from ajax-tab.php
  553. $action = Tools::getValue('action');
  554. // no need to use displayConf() here
  555. if (!empty($action) && method_exists($this, 'ajaxProcess'.Tools::toCamelCase($action)))
  556. {
  557. Hook::exec('actionAdmin'.ucfirst($this->action).'Before', array('controller' => $this));
  558. Hook::exec('action'.get_class($this).ucfirst($this->action).'Before', array('controller' => $this));
  559. $return = $this->{'ajaxProcess'.Tools::toCamelCase($action)}();
  560. Hook::exec('actionAdmin'.ucfirst($this->action).'After', array('controller' => $this, 'return' => $return));
  561. Hook::exec('action'.get_class($this).ucfirst($this->action).'After', array('controller' => $this, 'return' => $return));
  562. return $return;
  563. }
  564. elseif (!empty($action) && $this->controller_name == 'AdminModules' && Tools::getIsset('configure'))
  565. {
  566. $module_obj = Module::getInstanceByName(Tools::getValue('configure'));
  567. if (Validate::isLoadedObject($module_obj) && method_exists($module_obj, 'ajaxProcess'.$action))
  568. return $module_obj->{'ajaxProcess'.$action}();
  569. }
  570. elseif (method_exists($this, 'ajaxProcess'))
  571. return $this->ajaxProcess();
  572. }
  573. else
  574. {
  575. // Process list filtering
  576. if ($this->filter)
  577. $this->processFilter();
  578. // If the method named after the action exists, call "before" hooks, then call action method, then call "after" hooks
  579. if (!empty($this->action) && method_exists($this, 'process'.ucfirst(Tools::toCamelCase($this->action))))
  580. {
  581. // Hook before action
  582. Hook::exec('actionAdmin'.ucfirst($this->action).'Before', array('controller' => $this));
  583. Hook::exec('action'.get_class($this).ucfirst($this->action).'Before', array('controller' => $this));
  584. // Call process
  585. $return = $this->{'process'.Tools::toCamelCase($this->action)}();
  586. // Hook After Action
  587. Hook::exec('actionAdmin'.ucfirst($this->action).'After', array('controller' => $this, 'return' => $return));
  588. Hook::exec('action'.get_class($this).ucfirst($this->action).'After', array('controller' => $this, 'return' => $return));
  589. return $return;
  590. }
  591. }
  592. } catch (PrestaShopException $e) {
  593. $this->errors[] = $e->getMessage();
  594. };
  595. return false;
  596. }
  597. /**
  598. * Object Delete images
  599. */
  600. public function processDeleteImage()
  601. {
  602. if (Validate::isLoadedObject($object = $this->loadObject()))
  603. {
  604. if (($object->deleteImage()))
  605. {
  606. $redirect = self::$currentIndex.'&add'.$this->table.'&'.$this->identifier.'='.Tools::getValue($this->identifier).'&conf=7&token='.$this->token;
  607. if (!$this->ajax)
  608. $this->redirect_after = $redirect;
  609. else
  610. $this->content = 'ok';
  611. }
  612. }
  613. $this->errors[] = Tools::displayError('An error occurred while attempting to delete the image. (cannot load object).');
  614. return $object;
  615. }
  616. public function processExport($text_delimiter = '"')
  617. {
  618. // clean buffer
  619. if (ob_get_level() && ob_get_length() > 0)
  620. ob_clean();
  621. $this->getList($this->context->language->id, null, null, 0, false);
  622. if (!count($this->_list))
  623. return;
  624. header('Content-type: text/csv');
  625. header('Content-Type: application/force-download; charset=UTF-8');
  626. header('Cache-Control: no-store, no-cache');
  627. header('Content-disposition: attachment; filename="'.$this->table.'_'.date('Y-m-d_His').'.csv"');
  628. $headers = array();
  629. foreach ($this->fields_list as $datas)
  630. $headers[] = Tools::htmlentitiesDecodeUTF8($datas['title']);
  631. $content = array();
  632. foreach ($this->_list as $i => $row)
  633. {
  634. $content[$i] = array();
  635. $path_to_image = false;
  636. foreach ($this->fields_list as $key => $params)
  637. {
  638. $field_value = isset($row[$key]) ? Tools::htmlentitiesDecodeUTF8(
  639. Tools::nl2br($row[$key])) : '';
  640. if ($key == 'image')
  641. {
  642. if ($params['image'] != 'p' || Configuration::get('PS_LEGACY_IMAGES'))
  643. $path_to_image = Tools::getShopDomain(true)._PS_IMG_.$params['image'].'/'.$row['id_'.$this->table].(isset($row['id_image']) ? '-'.(int)$row['id_image'] : '').'.'.$this->imageType;
  644. else
  645. $path_to_image = Tools::getShopDomain(true)._PS_IMG_.$params['image'].'/'.Image::getImgFolderStatic($row['id_image']).(int)$row['id_image'].'.'.$this->imageType;
  646. if ($path_to_image)
  647. $field_value = $path_to_image;
  648. }
  649. if (isset($params['callback']))
  650. {
  651. $callback_obj = (isset($params['callback_object'])) ? $params['callback_object'] : $this->context->controller;
  652. $field_value = call_user_func_array(array($callback_obj, $params['callback']), array($field_value, $row));
  653. }
  654. $content[$i][] = $field_value;
  655. }
  656. }
  657. $this->context->smarty->assign(array(
  658. 'export_precontent' => "\xEF\xBB\xBF",
  659. 'export_headers' => $headers,
  660. 'export_content' => $content,
  661. 'text_delimiter' => $text_delimiter
  662. )
  663. );
  664. $this->layout = 'layout-export.tpl';
  665. }
  666. /**
  667. * Object Delete
  668. */
  669. public function processDelete()
  670. {
  671. if (Validate::isLoadedObject($object = $this->loadObject()))
  672. {
  673. $res = true;
  674. // check if request at least one object with noZeroObject
  675. if (isset($object->noZeroObject) && count(call_user_func(array($this->className, $object->noZeroObject))) <= 1)
  676. {
  677. $this->errors[] = Tools::displayError('You need at least one object.').
  678. ' <b>'.$this->table.'</b><br />'.
  679. Tools::displayError('You cannot delete all of the items.');
  680. }
  681. elseif (array_key_exists('delete', $this->list_skip_actions) && in_array($object->id, $this->list_skip_actions['delete'])) //check if some ids are in list_skip_actions and forbid deletion
  682. $this->errors[] = Tools::displayError('You cannot delete this item.');
  683. else
  684. {
  685. if ($this->deleted)
  686. {
  687. if (!empty($this->fieldImageSettings))
  688. $res = $object->deleteImage();
  689. if (!$res)
  690. $this->errors[] = Tools::displayError('Unable to delete associated images.');
  691. $object->deleted = 1;
  692. if ($res = $object->update())
  693. $this->redirect_after = self::$currentIndex.'&conf=1&token='.$this->token;
  694. }
  695. elseif ($res = $object->delete())
  696. $this->redirect_after = self::$currentIndex.'&conf=1&token='.$this->token;
  697. $this->errors[] = Tools::displayError('An error occurred during deletion.');
  698. if ($res)
  699. PrestaShopLogger::addLog(sprintf($this->l('%s deletion', 'AdminTab', false, false), $this->className), 1, null, $this->className, (int)$this->object->id, true, (int)$this->context->employee->id);
  700. }
  701. }
  702. else
  703. {
  704. $this->errors[] = Tools::displayError('An error occurred while deleting the object.').
  705. ' <b>'.$this->table.'</b> '.
  706. Tools::displayError('(cannot load object)');
  707. }
  708. return $object;
  709. }
  710. /**
  711. * Call the right method for creating or updating object
  712. *
  713. * @return mixed
  714. */
  715. public function processSave()
  716. {
  717. if ($this->id_object)
  718. {
  719. $this->object = $this->loadObject();
  720. return $this->processUpdate();
  721. }
  722. else
  723. return $this->processAdd();
  724. }
  725. /**
  726. * Object creation
  727. */
  728. public function processAdd()
  729. {
  730. if (!isset($this->className) || empty($this->className))
  731. return false;
  732. $this->validateRules();
  733. if (count($this->errors) <= 0)
  734. {
  735. $this->object = new $this->className();
  736. $this->copyFromPost($this->object, $this->table);
  737. $this->beforeAdd($this->object);
  738. if (method_exists($this->object, 'add') && !$this->object->add())
  739. {
  740. $this->errors[] = Tools::displayError('An error occurred while creating an object.').
  741. ' <b>'.$this->table.' ('.Db::getInstance()->getMsgError().')</b>';
  742. }
  743. /* voluntary do affectation here */
  744. elseif (($_POST[$this->identifier] = $this->object->id) && $this->postImage($this->object->id) && !count($this->errors) && $this->_redirect)
  745. {
  746. PrestaShopLogger::addLog(sprintf($this->l('%s addition', 'AdminTab', false, false), $this->className), 1, null, $this->className, (int)$this->object->id, true, (int)$this->context->employee->id);
  747. $parent_id = (int)Tools::getValue('id_parent', 1);
  748. $this->afterAdd($this->object);
  749. $this->updateAssoShop($this->object->id);
  750. // Save and stay on same form
  751. if (empty($this->redirect_after) && $this->redirect_after !== false && Tools::isSubmit('submitAdd'.$this->table.'AndStay'))
  752. $this->redirect_after = self::$currentIndex.'&'.$this->identifier.'='.$this->object->id.'&conf=3&update'.$this->table.'&token='.$this->token;
  753. // Save and back to parent
  754. if (empty($this->redirect_after) && $this->redirect_after !== false && Tools::isSubmit('submitAdd'.$this->table.'AndBackToParent'))
  755. $this->redirect_after = self::$currentIndex.'&'.$this->identifier.'='.$parent_id.'&conf=3&token='.$this->token;
  756. // Default behavior (save and back)
  757. if (empty($this->redirect_after) && $this->redirect_after !== false)
  758. $this->redirect_after = self::$currentIndex.($parent_id ? '&'.$this->identifier.'='.$this->object->id : '').'&conf=3&token='.$this->token;
  759. }
  760. }
  761. $this->errors = array_unique($this->errors);
  762. if (!empty($this->errors))
  763. {
  764. // if we have errors, we stay on the form instead of going back to the list
  765. $this->display = 'edit';
  766. return false;
  767. }
  768. return $this->object;
  769. }
  770. /**
  771. * Object update
  772. */
  773. public function processUpdate()
  774. {
  775. /* Checking fields validity */
  776. $this->validateRules();
  777. if (empty($this->errors))
  778. {
  779. $id = (int)Tools::getValue($this->identifier);
  780. /* Object update */
  781. if (isset($id) && !empty($id))
  782. {
  783. $object = new $this->className($id);
  784. if (Validate::isLoadedObject($object))
  785. {
  786. /* Specific to objects which must not be deleted */
  787. if ($this->deleted && $this->beforeDelete($object))
  788. {
  789. // Create new one with old objet values
  790. $object_new = $object->duplicateObject();
  791. if (Validate::isLoadedObject($object_new))
  792. {
  793. // Update old object to deleted
  794. $object->deleted = 1;
  795. $object->update();
  796. // Update new object with post values
  797. $this->copyFromPost($object_new, $this->table);
  798. $result = $object_new->update();
  799. if (Validate::isLoadedObject($object_new))
  800. $this->afterDelete($object_new, $object->id);
  801. }
  802. }
  803. else
  804. {
  805. $this->copyFromPost($object, $this->table);
  806. $result = $object->update();
  807. $this->afterUpdate($object);
  808. }
  809. if ($object->id)
  810. $this->updateAssoShop($object->id);
  811. if (!$result)
  812. {
  813. $this->errors[] = Tools::displayError('An error occurred while updating an object.').
  814. ' <b>'.$this->table.'</b> ('.Db::getInstance()->getMsgError().')';
  815. }
  816. elseif ($this->postImage($object->id) && !count($this->errors) && $this->_redirect)
  817. {
  818. $parent_id = (int)Tools::getValue('id_parent', 1);
  819. // Specific back redirect
  820. if ($back = Tools::getValue('back'))
  821. $this->redirect_after = urldecode($back).'&conf=4';
  822. // Specific scene feature
  823. // @todo change stay_here submit name (not clear for redirect to scene ... )
  824. if (Tools::getValue('stay_here') == 'on' || Tools::getValue('stay_here') == 'true' || Tools::getValue('stay_here') == '1')
  825. $this->redirect_after = self::$currentIndex.'&'.$this->identifier.'='.$object->id.'&conf=4&updatescene&token='.$this->token;
  826. // Save and stay on same form
  827. // @todo on the to following if, we may prefer to avoid override redirect_after previous value
  828. if (Tools::isSubmit('submitAdd'.$this->table.'AndStay'))
  829. $this->redirect_after = self::$currentIndex.'&'.$this->identifier.'='.$object->id.'&conf=4&update'.$this->table.'&token='.$this->token;
  830. // Save and back to parent
  831. if (Tools::isSubmit('submitAdd'.$this->table.'AndBackToParent'))
  832. $this->redirect_after = self::$currentIndex.'&'.$this->identifier.'='.$parent_id.'&conf=4&token='.$this->token;
  833. // Default behavior (save and back)
  834. if (empty($this->redirect_after) && $this->redirect_after !== false)
  835. $this->redirect_after = self::$currentIndex.($parent_id ? '&'.$this->identifier.'='.$object->id : '').'&conf=4&token='.$this->token;
  836. }
  837. PrestaShopLogger::addLog(sprintf($this->l('%s edition', 'AdminTab', false, false), $this->className), 1, null, $this->className, (int)$object->id, true, (int)$this->context->employee->id);
  838. }
  839. else
  840. $this->errors[] = Tools::displayError('An error occurred while updating an object.').
  841. ' <b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)');
  842. }
  843. }
  844. $this->errors = array_unique($this->errors);
  845. if (!empty($this->errors))
  846. {
  847. // if we have errors, we stay on the form instead of going back to the list
  848. $this->display = 'edit';
  849. return false;
  850. }
  851. if (isset($object))
  852. return $object;
  853. return;
  854. }
  855. /**
  856. * Change object required fields
  857. */
  858. public function processUpdateFields()
  859. {
  860. if (!is_array($fields = Tools::getValue('fieldsBox')))
  861. $fields = array();
  862. $object = new $this->className();
  863. if (!$object->addFieldsRequiredDatabase($fields))
  864. $this->errors[] = Tools::displayError('An error occurred when attempting to update the required fields.');
  865. else
  866. $this->redirect_after = self::$currentIndex.'&conf=4&token='.$this->token;
  867. return $object;
  868. }
  869. /**
  870. * Change object status (active, inactive)
  871. */
  872. public function processStatus()
  873. {
  874. if (Validate::isLoadedObject($object = $this->loadObject()))
  875. {
  876. if ($object->toggleStatus())
  877. {
  878. $matches = array();
  879. if (preg_match('/[\?|&]controller=([^&]*)/', (string)$_SERVER['HTTP_REFERER'], $matches) !== FALSE
  880. && strtolower($matches[1]) != strtolower(preg_replace('/controller/i', '', get_class($this))))
  881. $this->redirect_after = preg_replace('/[\?|&]conf=([^&]*)/i', '', (string)$_SERVER['HTTP_REFERER']);
  882. else
  883. $this->redirect_after = self::$currentIndex.'&token='.$this->token;
  884. $id_category = (($id_category = (int)Tools::getValue('id_category')) && Tools::getValue('id_product')) ? '&id_category='.$id_category : '';
  885. $this->redirect_after .= '&conf=5'.$id_category;
  886. }
  887. else
  888. $this->errors[] = Tools::displayError('An error occurred while updating the status.');
  889. }
  890. else
  891. $this->errors[] = Tools::displayError('An error occurred while updating the status for an object.').
  892. ' <b>'.$this->table.'</b> '.
  893. Tools::displayError('(cannot load object)');
  894. return $object;
  895. }
  896. /**
  897. * Change object position
  898. */
  899. public function processPosition()
  900. {
  901. if (!Validate::isLoadedObject($object = $this->loadObject()))
  902. {
  903. $this->errors[] = Tools::displayError('An error occurred while updating the status for an object.').
  904. ' <b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)');
  905. }
  906. elseif (!$object->updatePosition((int)Tools::getValue('way'), (int)Tools::getValue('position')))
  907. $this->errors[] = Tools::displayError('Failed to update the position.');
  908. else
  909. {
  910. $id_identifier_str = ($id_identifier = (int)Tools::getValue($this->identifier)) ? '&'.$this->identifier.'='.$id_identifier : '';
  911. $redirect = self::$currentIndex.'&'.$this->table.'Orderby=position&'.$this->table.'Orderway=asc&conf=5'.$id_identifier_str.'&token='.$this->token;
  912. $this->redirect_after = $redirect;
  913. }
  914. return $object;
  915. }
  916. /**
  917. * Cancel all filters for this tab
  918. */
  919. public function processResetFilters($list_id = null)
  920. {
  921. if ($list_id === null)
  922. $list_id = isset($this->list_id) ? $this->list_id : $this->table;
  923. $prefix = str_replace(array('admin', 'controller'), '', Tools::strtolower(get_class($this)));
  924. $filters = $this->context->cookie->getFamily($prefix.$list_id.'Filter_');
  925. foreach ($filters as $cookie_key => $filter)
  926. if (strncmp($cookie_key, $prefix.$list_id.'Filter_', 7 + Tools::strlen($prefix.$list_id)) == 0)
  927. {
  928. $key = substr($cookie_key, 7 + Tools::strlen($prefix.$list_id));
  929. if (is_array($this->fields_list) && array_key_exists($key, $this->fields_list))
  930. $this->context->cookie->$cookie_key = null;
  931. unset($this->context->cookie->$cookie_key);
  932. }
  933. if (isset($this->context->cookie->{'submitFilter'.$list_id}))
  934. unset($this->context->cookie->{'submitFilter'.$list_id});
  935. if (isset($this->context->cookie->{$prefix.$list_id.'Orderby'}))
  936. unset($this->context->cookie->{$prefix.$list_id.'Orderby'});
  937. if (isset($this->context->cookie->{$prefix.$list_id.'Orderway'}))
  938. unset($this->context->cookie->{$prefix.$list_id.'Orderway'});
  939. $_POST = array();
  940. $this->_filter = false;
  941. unset($this->_filterHaving);
  942. unset($this->_having);
  943. }
  944. /**
  945. * Update options and preferences
  946. */
  947. protected function processUpdateOptions()
  948. {
  949. $this->beforeUpdateOptions();
  950. $languages = Language::getLanguages(false);
  951. $hide_multishop_checkbox = (Shop::getTotalShops(false, null) < 2) ? true : false;
  952. foreach ($this->fields_options as $category_data)
  953. {
  954. if (!isset($category_data['fields']))
  955. continue;
  956. $fields = $category_data['fields'];
  957. foreach ($fields as $field => $values)
  958. {
  959. if (isset($values['type']) && $values['type'] == 'selectLang')
  960. {
  961. foreach ($languages as $lang)
  962. if (Tools::getValue($field.'_'.strtoupper($lang['iso_code'])))
  963. $fields[$field.'_'.strtoupper($lang['iso_code'])] = array(
  964. 'type' => 'select',
  965. 'cast' => 'strval',
  966. 'identifier' => 'mode',
  967. 'list' => $values['list']
  968. );
  969. }
  970. }
  971. // Validate fields
  972. foreach ($fields as $field => $values)
  973. {
  974. // We don't validate fields with no visibility
  975. if (!$hide_multishop_checkbox && Shop::isFeatureActive() && isset($values['visibility']) && $values['visibility'] > Shop::getContext())
  976. continue;
  977. // Check if field is required
  978. if ((!Shop::isFeatureActive() && isset($values['required']) && $values['required'])
  979. || (Shop::isFeatureActive() && isset($_POST['multishopOverrideOption'][$field]) && isset($values['required']) && $values['required']))
  980. if (isset($values['type']) && $values['type'] == 'textLang')
  981. {
  982. foreach ($languages as $language)
  983. if (($value = Tools::getValue($field.'_'.$language['id_lang'])) == false && (string)$value != '0')
  984. $this->errors[] = sprintf(Tools::displayError('field %s is required.'), $values['title']);
  985. }
  986. elseif (($value = Tools::getValue($field)) == false && (string)$value != '0')
  987. $this->errors[] = sprintf(Tools::displayError('field %s is required.'), $values['title']);
  988. // Check field validator
  989. if (isset($values['type']) && $values['type'] == 'textLang')
  990. {
  991. foreach ($languages as $language)
  992. if (Tools::getValue($field.'_'.$language['id_lang']) && isset($values['validation']))
  993. if (!Validate::$values['validation'](Tools::getValue($field.'_'.$language['id_lang'])))
  994. $this->errors[] = sprintf(Tools::displayError('field %s is invalid.'), $values['title']);
  995. }
  996. elseif (Tools::getValue($field) && isset($values['validation']))
  997. if (!Validate::$values['validation'](Tools::getValue($field)))
  998. $this->errors[] = sprintf(Tools::displayError('field %s is invalid.'), $values['title']);
  999. // Set default value
  1000. if (Tools::getValue($field) === false && isset($values['default']))
  1001. $_POST[$field] = $values['default'];
  1002. }
  1003. if (!count($this->errors))
  1004. {
  1005. foreach ($fields as $key => $options)
  1006. {
  1007. if (!$hide_multishop_checkbox && Shop::isFeatureActive() && isset($options['visibility']) && $options['visibility'] > Shop::getContext())
  1008. continue;
  1009. if (!$hide_multishop_checkbox && Shop::isFeatureActive() && Shop::getContext() != Shop::CONTEXT_ALL && empty($options['no_multishop_checkbox']) && empty($_POST['multishopOverrideOption'][$key]))
  1010. {
  1011. Configuration::deleteFromContext($key);
  1012. continue;
  1013. }
  1014. // check if a method updateOptionFieldName is available
  1015. $method_name = 'updateOption'.Tools::toCamelCase($key, true);
  1016. if (method_exists($this, $method_name))
  1017. $this->$method_name(Tools::getValue($key));
  1018. elseif (isset($options['type']) && in_array($options['type'], array('textLang', 'textareaLang')))
  1019. {
  1020. $list = array();
  1021. foreach ($languages as $language)
  1022. {
  1023. $key_lang = Tools::getValue($key.'_'.$language['id_lang']);
  1024. $val = (isset($options['cast']) ? $options['cast']($key_lang) : $key_lang);
  1025. if ($this->validateField($val, $options))
  1026. {
  1027. if (Validate::isCleanHtml($val))
  1028. $list[$language['id_lang']] = $val;
  1029. else
  1030. $this->errors[] = Tools::displayError('Can not add configuration '.$key.' for lang '.Language::getIsoById((int)$language['id_lang']));
  1031. }
  1032. }
  1033. Configuration::updateValue($key, $list);
  1034. }
  1035. else
  1036. {
  1037. $val = (isset($options['cast']) ? $options['cast'](Tools::getValue($key)) : Tools::getValue($key));
  1038. if ($this->validateField($val, $options))
  1039. {
  1040. if (Validate::isCleanHtml($val))
  1041. Configuration::updateValue($key, $val);
  1042. else
  1043. $this->errors[] = Tools::displayError('Can not add configuration '.$key);
  1044. }
  1045. }
  1046. }
  1047. }
  1048. }
  1049. $this->display = 'list';
  1050. if (empty($this->errors))
  1051. $this->confirmations[] = $this->_conf[6];
  1052. }
  1053. public function initPageHeaderToolbar()
  1054. {
  1055. if (empty($this->toolbar_title))
  1056. $this->initToolbarTitle();
  1057. if (!is_array($this->toolbar_title))
  1058. $this->toolbar_title = array($this->toolbar_title);
  1059. switch ($this->display)
  1060. {
  1061. case 'view':
  1062. // Default cancel button - like old back link
  1063. $back = Tools::safeOutput(Tools::getValue('back', ''));
  1064. if (empty($back))
  1065. $back = self::$currentIndex.'&token='.$this->token;
  1066. if (!Validate::isCleanHtml($back))
  1067. die(Tools::displayError());
  1068. if (!$this->lite_display)
  1069. $this->page_header_toolbar_btn['back'] = array(
  1070. 'href' => $back,
  1071. 'desc' => $this->l('Back to list')
  1072. );
  1073. $obj = $this->loadObject(true);
  1074. if (Validate::isLoadedObject($obj) && isset($obj->{$this->identifier_name}) && !empty($obj->{$this->identifier_name}))
  1075. {
  1076. array_pop($this->toolbar_title);
  1077. $this->toolbar_title[] = is_array($obj->{$this->identifier_name}) ? $obj->{$this->identifier_name}[$this->context->employee->id_lang] : $obj->{$this->identifier_name};
  1078. }
  1079. break;
  1080. case 'edit':
  1081. $obj = $this->loadObject(true);
  1082. if (Validate::isLoadedObject($obj) && isset($obj->{$this->identifier_name}) && !empty($obj->{$this->identifier_name}))
  1083. {
  1084. array_pop($this->toolbar_title);
  1085. $this->toolbar_title[] = sprintf($this->l('Edit: %s'),
  1086. is_array($obj->{$this->identifier_name}) ? $obj->{$this->identifier_name}[$this->context->employee->id_lang] : $obj->{$this->identifier_name});
  1087. }
  1088. break;
  1089. }
  1090. if (is_array($this->page_header_toolbar_btn)
  1091. && $this->page_header_toolbar_btn instanceof Traversable
  1092. || count($this->toolbar_title))
  1093. $this->show_page_header_toolbar = true;
  1094. if (empty($this->page_header_toolbar_title))
  1095. $this->page_header_toolbar_title = array_pop($this->toolbar_title);
  1096. $this->addPageHeaderToolBarModulesListButton();
  1097. $this->context->smarty->assign('help_link', 'http://help.prestashop.com/'.$this->context->language->iso_code.'/doc/'.Tools::getValue('controller').'?version='._PS_VERSION_.'&country='.$this->context->country->iso_code);
  1098. }
  1099. /**
  1100. * assign default action in toolbar_btn smarty var, if they are not set.
  1101. * uses override to specifically add, modify or remove items
  1102. *
  1103. */
  1104. public function initToolbar()
  1105. {
  1106. switch ($this->display)
  1107. {
  1108. case 'add':
  1109. case 'edit':
  1110. // Default save button - action dynamically handled in javascript
  1111. $this->toolbar_btn['save'] = array(
  1112. 'href' => '#',
  1113. 'desc' => $this->l('Save')
  1114. );
  1115. $back = Tools::safeOutput(Tools::getValue('back', ''));
  1116. if (empty($back))
  1117. $back = self::$currentIndex.'&token='.$this->token;
  1118. if (!Validate::isCleanHtml($back))
  1119. die(Tools::displayError());
  1120. if (!$this->lite_display)
  1121. $this->toolbar_btn['cancel'] = array(
  1122. 'href' => $back,
  1123. 'desc' => $this->l('Cancel')
  1124. );
  1125. break;
  1126. case 'view':
  1127. // Default cancel button - like old back link
  1128. $back = Tools::safeOutput(Tools::getValue('back', ''));
  1129. if (empty($back))
  1130. $back = self::$currentIndex.'&token='.$this->token;
  1131. if (!Validate::isCleanHtml($back))
  1132. die(Tools::displayError());
  1133. if (!$this->lite_display)
  1134. $this->toolbar_btn['back'] = array(
  1135. 'href' => $back,
  1136. 'desc' => $this->l('Back to list')
  1137. );
  1138. break;
  1139. case 'options':
  1140. $this->toolbar_btn['save'] = array(
  1141. 'href' => '#',
  1142. 'desc' => $this->l('Save')
  1143. );
  1144. break;
  1145. default: // list
  1146. $this->toolbar_btn['new'] = array(
  1147. 'href' => self::$currentIndex.'&add'.$this->table.'&token='.$this->token,
  1148. 'desc' => $this->l('Add new')
  1149. );
  1150. if ($this->allow_export)
  1151. $this->toolbar_btn['export'] = array(
  1152. 'href' => self::$currentIndex.'&export'.$this->table.'&token='.$this->token,
  1153. 'desc' => $this->l('Export')
  1154. );
  1155. }
  1156. $this->addToolBarModulesListButton();
  1157. }
  1158. /**
  1159. * Load class object using identifier in $_GET (if possible)
  1160. * otherwise return an empty object, or die
  1161. *
  1162. * @param boolean $opt Return an empty object if load fail
  1163. * @return object|boolean
  1164. */
  1165. protected function loadObject($opt = false)
  1166. {
  1167. if (!isset($this->className) || empty($this->className))
  1168. return true;
  1169. $id = (int)Tools::getValue($this->identifier);
  1170. if ($id && Validate::isUnsignedId($id))
  1171. {
  1172. if (!$this->object)
  1173. $this->object = new $this->className($id);
  1174. if (Validate::isLoadedObject($this->object))
  1175. return $this->object;
  1176. // throw exception
  1177. $this->errors[] = Tools::displayError('The object cannot be loaded (or found)');
  1178. return false;
  1179. }
  1180. elseif ($opt)
  1181. {
  1182. if (!$this->object)
  1183. $this->object = new $this->className();
  1184. return $this->object;
  1185. }
  1186. else
  1187. {
  1188. $this->errors[] = Tools::displayError('The object cannot be loaded (the identifier is missing or invalid)');
  1189. return false;
  1190. }
  1191. }
  1192. /**
  1193. * Check if the token is valid, else display a warning page
  1194. */
  1195. public function checkAccess()
  1196. {
  1197. if (!$this->checkToken())
  1198. {
  1199. // If this is an XSS attempt, then we should only display a simple, secure page
  1200. // ${1} in the replacement string of the regexp is required,
  1201. // because the token may begin with a number and mix up with it (e.g. $17)
  1202. $url = preg_replace('/([&?]token=)[^&]*(&.*)?$/', '${1}'.$this->token.'$2', $_SERVER['REQUEST_URI']);
  1203. if (false === strpos($url, '?token=') && false === strpos($url, '&token='))
  1204. $url .= '&token='.$this->token;
  1205. if (strpos($url, '?') === false)
  1206. $url = str_replace('&token', '?controller=AdminDashboard&token', $url);
  1207. $this->context->smarty->assign('url', htmlentities($url));
  1208. return false;
  1209. }
  1210. return true;
  1211. }
  1212. protected function filterToField($key, $filter)
  1213. {
  1214. if (!isset($this->fields_list))
  1215. return false;
  1216. foreach ($this->fields_list as $field)
  1217. if (array_key_exists('filter_key', $field) && $field['filter_key'] == $key)
  1218. return $field;
  1219. if (array_key_exists($filter, $this->fields_list))
  1220. return $this->fields_list[$filter];
  1221. return false;
  1222. }
  1223. public function displayNoSmarty()
  1224. {
  1225. }
  1226. public function displayAjax()
  1227. {
  1228. if ($this->json)
  1229. {
  1230. $this->context->smarty->assign(array(
  1231. 'json' => true,
  1232. 'status' => $this->status,
  1233. ));
  1234. }
  1235. $this->layout = 'layout-ajax.tpl';
  1236. $this->display_header = false;
  1237. $this->display_footer = false;
  1238. return $this->display();
  1239. }
  1240. protected function redirect()
  1241. {
  1242. header('Location: '.$this->redirect_after);
  1243. exit;
  1244. }
  1245. public function display()
  1246. {
  1247. $this->context->smarty->assign(array(
  1248. 'display_header' => $this->display_header,
  1249. 'display_footer' => $this->display_footer,
  1250. ));
  1251. // Use page title from meta_title if it has been set else from the breadcrumbs array
  1252. if (!$this->meta_title)
  1253. $this->meta_title = strip_tags(is_array($this->toolbar_title) ? implode(' '.Configuration::get('PS_NAVIGATION_PIPE').' ', $this->toolbar_title) : $this->toolbar_title);
  1254. $this->context->smarty->assign('meta_title', $this->meta_title);
  1255. $template_dirs = $this->context->smarty->getTemplateDir();
  1256. // Check if header/footer have been overriden
  1257. $dir = $this->context->smarty->getTemplateDir(0).'controllers'.DIRECTORY_SEPARATOR.trim($this->override_folder, '\\/').DIRECTORY_SEPARATOR;
  1258. $module_list_dir = $this->context->smarty->getTemplateDir(0).'helpers'.DIRECTORY_SEPARATOR.'modules_list'.DIRECTORY_SEPARATOR;
  1259. $header_tpl = file_exists($dir.'header.tpl') ? $dir.'header.tpl' : 'header.tpl';
  1260. $page_header_toolbar = file_exists($dir.'page_header_toolbar.tpl') ? $dir.'page_header_toolbar.tpl' : 'page_header_toolbar.tpl';
  1261. $footer_tpl = file_exists($dir.'footer.tpl') ? $dir.'footer.tpl' : 'footer.tpl';
  1262. $modal_module_list = file_exists($module_list_dir.'modal.tpl') ? $module_list_dir.'modal.tpl' : 'modal.tpl';
  1263. $tpl_action = $this->tpl_folder.$this->display.'.tpl';
  1264. // Check if action template has been overriden
  1265. foreach ($template_dirs as $template_dir)
  1266. if (file_exists($template_dir.DIRECTORY_SEPARATOR.$tpl_action) && $this->display != 'view' && $this->display != 'options')
  1267. {
  1268. if (method_exists($this, $this->display.Tools::toCamelCase($this->className)))
  1269. $this->{$this->display.Tools::toCamelCase($this->className)}();
  1270. $this->context->smarty->assign('content', $this->context->smarty->fetch($tpl_action));
  1271. break;
  1272. }
  1273. if (!$this->ajax)
  1274. {
  1275. $template = $this->createTemplate($this->template);
  1276. $page = $template->fetch();
  1277. }
  1278. else
  1279. $page = $this->content;
  1280. if ($conf = Tools::getValue('conf'))
  1281. $this->context->smarty->assign('conf', $this->json ? Tools::jsonEncode($this->_conf[(int)$conf]) : $this->_conf[(int)$conf]);
  1282. foreach (array('errors', 'warnings', 'informations', 'confirmations') as $type)
  1283. {
  1284. if (!is_array($this->$type))
  1285. $this->$type = (array)$this->$type;
  1286. $this->context->smarty->assign($type, $this->json ? Tools::jsonEncode(array_unique($this->$type)) : array_unique($this->$type));
  1287. }
  1288. if ($this->show_page_header_toolbar && !$this->lite_display)
  1289. $this->context->smarty->assign(array(
  1290. 'page_header_toolbar' => $this->context->smarty->fetch($page_header_toolbar),
  1291. 'modal_module_list' => $this->context->smarty->fetch($modal_module_list),
  1292. )
  1293. );
  1294. $this->context->smarty->assign(array(
  1295. 'page' => $this->json ? Tools::jsonEncode($page) : $page,
  1296. 'header' => $this->context->smarty->fetch($header_tpl),
  1297. 'footer' => $this->context->smarty->fetch($footer_tpl),
  1298. )
  1299. );
  1300. $this->smartyOutputContent($this->layout);
  1301. }
  1302. /**
  1303. * add a warning message to display at the top of the page
  1304. *
  1305. * @param string $msg
  1306. */
  1307. protected function displayWarning($msg)
  1308. {
  1309. $this->warnings[] = $msg;
  1310. }
  1311. /**
  1312. * add a info message to display at the top of the page
  1313. *
  1314. * @param string $msg
  1315. */
  1316. protected function displayInformation($msg)
  1317. {
  1318. $this->informations[] = $msg;
  1319. }
  1320. /**
  1321. * Assign smarty variables for the header
  1322. */
  1323. public function initHeader()
  1324. {
  1325. // Multishop
  1326. $is_multishop = Shop::isFeatureActive();
  1327. // Quick access
  1328. $quick_access = QuickAccess::getQuickAccesses($this->context->language->id);
  1329. foreach ($quick_access as $index => $quick)
  1330. {
  1331. if ($quick['link'] == '../' && Shop::getContext() == Shop::CONTEXT_SHOP)
  1332. {
  1333. $url = $this->context->shop->getBaseURL();
  1334. if (!$url)
  1335. {
  1336. unset($quick_access[$index]);
  1337. continue;
  1338. }
  1339. $quick_access[$index]['link'] = $url;
  1340. }
  1341. else
  1342. {
  1343. preg_match('/controller=(.+)(&.+)?$/', $quick['link'], $admin_tab);
  1344. if (isset($admin_tab[1]))
  1345. {
  1346. if (strpos($admin_tab[1], '&'))
  1347. $admin_tab[1] = substr($admin_tab[1], 0, strpos($admin_tab[1], '&'));
  1348. $token = Tools::getAdminToken($admin_tab[1].(int)Tab::getIdFromClassName($admin_tab[1]).(int)$this->context->employee->id);
  1349. $quick_access[$index]['link'] .= '&token='.$token;
  1350. }
  1351. }
  1352. }
  1353. $name = $this->l('New Bookmark');
  1354. if (isset($this->context->smarty->tpl_vars['breadcrumbs2']) && $this->context->smarty->tpl_vars['breadcrumbs2']->value['tab']['name'])
  1355. {
  1356. if ($this->context->smarty->tpl_vars['breadcrumbs2']->value['action']['name'])
  1357. $name = $this->context->smarty->tpl_vars['breadcrumbs2']->value['tab']['name'].' > '.$this->context->smarty->tpl_vars['breadcrumbs2']->value['action']['name'];
  1358. else
  1359. $name = $this->context->smarty->tpl_vars['breadcrumbs2']->value['tab']['name'];
  1360. }
  1361. elseif (isset($this->context->smarty->tpl_vars['breadcrumbs2']) && is_string($this->context->smarty->tpl_vars['breadcrumbs2']->value))
  1362. $name = $this->context->smarty->tpl_vars['breadcrumbs2']->value;
  1363. $link = preg_replace('/&token=[a-z0-9]{32}/', '', basename($_SERVER['REQUEST_URI']));
  1364. $quick_access[] = array(
  1365. 'name' => $this->l('Bookmark this page'),
  1366. 'link' => $this->context->link->getAdminLink('AdminQuickAccesses').'&new_window=0&name_'.(int)Configuration::get('PS_LANG_DEFAULT').'='.urlencode($name).'&link='.urlencode($link).'&submitAddquick_access=1',
  1367. 'new_window' => 0
  1368. );
  1369. // Tab list
  1370. $tabs = Tab::getTabs($this->context->language->id, 0);
  1371. $current_id = Tab::getCurrentParentId();
  1372. foreach ($tabs as $index => $tab)
  1373. {
  1374. if (!Tab::checkTabRights($tab['id_tab'])
  1375. || ($tab['class_name'] == 'AdminStock' && Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') == 0)
  1376. || $tab['class_name'] == 'AdminCarrierWizard')
  1377. {
  1378. unset($tabs[$index]);
  1379. continue;
  1380. }
  1381. $img_cache_url = 'themes/'.$this->context->employee->bo_theme.'/img/t/'.$tab['class_name'].'.png';
  1382. $img_exists_cache = Tools::file_exists_cache(_PS_ADMIN_DIR_.$img_cache_url);
  1383. // retrocompatibility : change png to gif if icon not exists
  1384. if (!$img_exists_cache)
  1385. $img_exists_cache = Tools::file_exists_cache(_PS_ADMIN_DIR_.str_replace('.png', '.gif', $img_cache_url));
  1386. if ($img_exists_cache)
  1387. $path_img = $img = $img_exists_cache;
  1388. else
  1389. {
  1390. $path_img = _PS_IMG_DIR_.'t/'.$tab['class_name'].'.png';
  1391. // Relative link will always work, whatever the base uri set in the admin
  1392. $img = '../img/t/'.$tab['class_name'].'.png';
  1393. }
  1394. if (trim($tab['module']) != '')
  1395. {
  1396. $path_img = _PS_MODULE_DIR_.$tab['module'].'/'.$tab['class_name'].'.png';
  1397. // Relative link will always work, whatever the base uri set in the admin
  1398. $img = '../modules/'.$tab['module'].'/'.$tab['class_name'].'.png';
  1399. }
  1400. // retrocompatibility
  1401. if (!file_exists($path_img))
  1402. $img = str_replace('png', 'gif', $img);
  1403. // tab[class_name] does not contains the "Controller" suffix
  1404. $tabs[$index]['current'] = ($tab['class_name'].'Controller' == get_class($this)) || ($current_id == $tab['id_tab']);
  1405. $tabs[$index]['img'] = $img;
  1406. $tabs[$index]['href'] = $this->context->link->getAdminLink($tab['class_name']);
  1407. $sub_tabs = Tab::getTabs($this->context->language->id, $tab['id_tab']);
  1408. foreach ($sub_tabs as $index2 => $sub_tab)
  1409. {
  1410. //check if module is enable and
  1411. if (isset($sub_tab['module']) && !empty($sub_tab['module']))
  1412. {
  1413. $module = Module::getInstanceByName($sub_tab['module']);
  1414. if (is_object($module) && !$module->isEnabledForShopContext())
  1415. {
  1416. unset($sub_tabs[$index2]);
  1417. continue;
  1418. }
  1419. }
  1420. if (Tab::checkTabRights($sub_tab['id_tab']) === true && (bool)$sub_tab['active'] && $sub_tab['class_name'] != 'AdminCarrierWizard')
  1421. // class_name is the name of the class controller
  1422. {
  1423. $sub_tabs[$index2]['href'] = $this->context->link->getAdminLink($sub_tab['class_name']);
  1424. $sub_tabs[$index2]['current'] = ($sub_tab['class_name'].'Controller' == get_class($this) || $sub_tab['class_name'] == Tools::getValue('controller'));
  1425. }
  1426. elseif ($sub_tab['class_name'] == 'AdminCarrierWizard' && $sub_tab['class_name'].'Controller' == get_class($this))
  1427. {
  1428. foreach ($sub_tabs as $i => $tab) {
  1429. if($tab['class_name'] == 'AdminCarriers')
  1430. break;
  1431. }
  1432. $sub_tabs[$i]['current'] = true;
  1433. unset($sub_tabs[$index2]);
  1434. }
  1435. else
  1436. unset($sub_tabs[$index2]);
  1437. }
  1438. $tabs[$index]['sub_tabs'] = $sub_tabs;
  1439. }
  1440. if (Validate::isLoadedObject($this->context->employee))
  1441. {
  1442. $accesses = Profile::getProfileAccesses($this->context->employee->id_profile, 'class_name');
  1443. /* Hooks are volontary out the initialize array (need those variables already assigned) */
  1444. $bo_color = empty($this->context->employee->bo_color) ? '#FFFFFF' : $this->context->employee->bo_color;
  1445. $this->context->smarty->assign(array(
  1446. 'autorefresh_notifications' => Configuration::get('PS_ADMINREFRESH_NOTIFICATION'),
  1447. 'help_box' => Configuration::get('PS_HELPBOX'),
  1448. 'round_mode' => Configuration::get('PS_PRICE_ROUND_MODE'),
  1449. 'brightness' => Tools::getBrightness($bo_color) < 128 ? 'white' : '#383838',
  1450. 'bo_width' => (int)$this->context->employee->bo_width,
  1451. 'bo_color' => isset($this->context->employee->bo_color) ? Tools::htmlentitiesUTF8($this->context->employee->bo_color) : null,
  1452. 'show_new_orders' => Configuration::get('PS_SHOW_NEW_ORDERS') && isset($accesses['AdminOrders']) && $accesses['AdminOrders']['view'],
  1453. 'show_new_customers' => Configuration::get('PS_SHOW_NEW_CUSTOMERS') && isset($accesses['AdminCustomers']) && $accesses['AdminCustomers']['view'],
  1454. 'show_new_messages' => Configuration::get('PS_SHOW_NEW_MESSAGES') && isset($accesses['AdminCustomerThreads'])&& $accesses['AdminCustomerThreads']['view'],
  1455. 'employee' => $this->context->employee,
  1456. 'search_type' => Tools::getValue('bo_search_type'),
  1457. 'bo_query' => Tools::safeOutput(Tools::stripslashes(Tools::getValue('bo_query'))),
  1458. 'quick_access' => $quick_access,
  1459. 'multi_shop' => Shop::isFeatureActive(),
  1460. 'shop_list' => Helper::renderShopList(),
  1461. 'shop' => $this->context->shop,
  1462. 'shop_group' => new ShopGroup((int)Shop::getContextShopGroupID()),
  1463. 'current_parent_id' => (int)Tab::getCurrentParentId(),
  1464. 'tabs' => $tabs,
  1465. 'is_multishop' => $is_multishop,
  1466. 'multishop_context' => $this->multishop_context,
  1467. 'default_tab_link' => $this->context->link->getAdminLink(Tab::getClassNameById((int)Context::getContext()->employee->default_tab)),
  1468. 'collapse_menu' => isset($this->context->cookie->collapse_menu) ? (int)$this->context->cookie->collapse_menu : 0
  1469. ));
  1470. }
  1471. else
  1472. $this->context->smarty->assign('default_tab_link', $this->context->link->getAdminLink('AdminDashboard'));
  1473. $this->context->smarty->assign(array(
  1474. 'img_dir' => _PS_IMG_,
  1475. 'iso' => $this->context->language->iso_code,
  1476. 'class_name' => $this->className,
  1477. 'iso_user' => $this->context->language->iso_code,
  1478. 'country_iso_code' => $this->context->country->iso_code,
  1479. 'version' => _PS_VERSION_,
  1480. 'lang_iso' => $this->context->language->iso_code,
  1481. 'full_language_code' => $this->context->language->language_code,
  1482. 'link' => $this->context->link,
  1483. 'shop_name' => Configuration::get('PS_SHOP_NAME'),
  1484. 'base_url' => $this->context->shop->getBaseURL(),
  1485. 'tab' => isset($tab) ? $tab : null, // Deprecated, this tab is declared in the foreach, so it's the last tab in the foreach
  1486. 'current_parent_id' => (int)Tab::getCurrentParentId(),
  1487. 'tabs' => $tabs,
  1488. 'install_dir_exists' => file_exists(_PS_ADMIN_DIR_.'/../install'),
  1489. 'pic_dir' => _THEME_PROD_PIC_DIR_,
  1490. 'controller_name' => htmlentities(Tools::getValue('controller')),
  1491. 'currentIndex' => self::$currentIndex,
  1492. 'bootstrap' => $this->bootstrap,
  1493. 'default_language' => (int)Configuration::get('PS_LANG_DEFAULT')
  1494. ));
  1495. $module = Module::getInstanceByName('themeconfigurator');
  1496. $lang = '';
  1497. if (Configuration::get('PS_REWRITING_SETTINGS') && count(Language::getLanguages(true)) > 1)
  1498. $lang = Language::getIsoById($this->context->employee->id_lang).'/';
  1499. if (is_object($module) && $module->active && (int)Configuration::get('PS_TC_ACTIVE') == 1 && $this->context->shop->getBaseURL())
  1500. $this->context->smarty->assign('base_url_tc', $this->context->shop->getBaseUrl()
  1501. .(Configuration::get('PS_REWRITING_SETTINGS') ? '' : 'index.php')
  1502. .$lang
  1503. .'?live_configurator_token='.$module->getLiveConfiguratorToken()
  1504. .'&id_employee='.(int)$this->context->employee->id
  1505. .'&id_shop='.(int)$this->context->shop->id
  1506. .(Configuration::get('PS_TC_THEME') != '' ? '&theme='.Configuration::get('PS_TC_THEME') : '')
  1507. .(Configuration::get('PS_TC_FONT') != '' ? '&theme_font='.Configuration::get('PS_TC_FONT') : ''));
  1508. }
  1509. /**
  1510. * Declare an action to use for each row in the list
  1511. */
  1512. public function addRowAction($action)
  1513. {
  1514. $action = strtolower($action);
  1515. $this->actions[] = $action;
  1516. }
  1517. /**
  1518. * Add an action to use for each row in the list
  1519. */
  1520. public function addRowActionSkipList($action, $list)
  1521. {
  1522. $action = strtolower($action);
  1523. $list = (array)$list;
  1524. if (array_key_exists($action, $this->list_skip_actions))
  1525. $this->list_skip_actions[$action] = array_merge($this->list_skip_actions[$action], $list);
  1526. else
  1527. $this->list_skip_actions[$action] = $list;
  1528. }
  1529. /**
  1530. * Assign smarty variables for all default views, list and form, then call other init functions
  1531. */
  1532. public function initContent()
  1533. {
  1534. if (!$this->viewAccess())
  1535. {
  1536. $this->errors[] = Tools::displayError('You do not have permission to view this.');
  1537. return;
  1538. }
  1539. $this->getLanguages();
  1540. $this->initToolbar();
  1541. $this->initTabModuleList();
  1542. $this->initPageHeaderToolbar();
  1543. if ($this->display == 'edit' || $this->display == 'add')
  1544. {
  1545. if (!$this->loadObject(true))
  1546. return;
  1547. $this->content .= $this->renderForm();
  1548. }
  1549. elseif ($this->display == 'view')
  1550. {
  1551. // Some controllers use the view action without an object
  1552. if ($this->className)
  1553. $this->loadObject(true);
  1554. $this->content .= $this->renderView();
  1555. }
  1556. elseif ($this->display == 'details')
  1557. {
  1558. $this->content .= $this->renderDetails();
  1559. }
  1560. elseif (!$this->ajax)
  1561. {
  1562. $this->content .= $this->renderModulesList();
  1563. $this->content .= $this->renderKpis();
  1564. $this->content .= $this->renderList();
  1565. $this->content .= $this->renderOptions();
  1566. // if we have to display the required fields form
  1567. if ($this->required_database)
  1568. $this->content .= $this->displayRequiredFields();
  1569. }
  1570. $this->context->smarty->assign(array(
  1571. 'content' => $this->content,
  1572. 'lite_display' => $this->lite_display,
  1573. 'url_post' => self::$currentIndex.'&token='.$this->token,
  1574. 'show_page_header_toolbar' => $this->show_page_header_toolbar,
  1575. 'page_header_toolbar_title' => $this->page_header_toolbar_title,
  1576. 'title' => $this->page_header_toolbar_title,
  1577. 'toolbar_btn' => $this->page_header_toolbar_btn,
  1578. 'page_header_toolbar_btn' => $this->page_header_toolbar_btn
  1579. ));
  1580. }
  1581. /**
  1582. * init tab modules list and add button in toolbar
  1583. */
  1584. protected function initTabModuleList()
  1585. {
  1586. if (!$this->isFresh(Module::CACHE_FILE_MUST_HAVE_MODULES_LIST, 86400))
  1587. @file_put_contents(_PS_ROOT_DIR_.Module::CACHE_FILE_MUST_HAVE_MODULES_LIST, Tools::addonsRequest('must-have'));
  1588. if (!$this->isFresh(Module::CACHE_FILE_TAB_MODULES_LIST, 604800))
  1589. $this->refresh(Module::CACHE_FILE_TAB_MODULES_LIST, 'http://'.Tab::TAB_MODULE_LIST_URL);
  1590. $this->tab_modules_list = Tab::getTabModulesList($this->id);
  1591. if (is_array($this->tab_modules_list['default_list']) && count($this->tab_modules_list['default_list']))
  1592. $this->filter_modules_list = $this->tab_modules_list['default_list'];
  1593. elseif (is_array($this->tab_modules_list['slider_list']) && count($this->tab_modules_list['slider_list']))
  1594. {
  1595. $this->addToolBarModulesListButton();
  1596. $this->addPageHeaderToolBarModulesListButton();
  1597. $this->context->smarty->assign(array(
  1598. 'tab_modules_list' => implode(',', $this->tab_modules_list['slider_list']),
  1599. 'admin_module_ajax_url' => $this->context->link->getAdminLink('AdminModules'),
  1600. 'back_tab_modules_list' => $this->context->link->getAdminLink(Tools::getValue('controller')),
  1601. 'tab_modules_open' => (int)Tools::getValue('tab_modules_open')
  1602. ));
  1603. }
  1604. }
  1605. protected function addPageHeaderToolBarModulesListButton()
  1606. {
  1607. $this->filterTabModuleList();
  1608. if (is_array($this->tab_modules_list['slider_list']) && count($this->tab_modules_list['slider_list']))
  1609. $this->page_header_toolbar_btn['modules-list'] = array(
  1610. 'href' => '#',
  1611. 'desc' => $this->l('Recommended Modules')
  1612. );
  1613. }
  1614. protected function addToolBarModulesListButton()
  1615. {
  1616. $this->filterTabModuleList();
  1617. if (is_array($this->tab_modules_list['slider_list']) && count($this->tab_modules_list['slider_list']))
  1618. $this->toolbar_btn['modules-list'] = array(
  1619. 'href' => '#',
  1620. 'desc' => $this->l('Recommended Modules')
  1621. );
  1622. }
  1623. protected function filterTabModuleList()
  1624. {
  1625. if (!$this->isFresh(Module::CACHE_FILE_DEFAULT_COUNTRY_MODULES_LIST, 86400))
  1626. file_put_contents(_PS_ROOT_DIR_.Module::CACHE_FILE_DEFAULT_COUNTRY_MODULES_LIST, Tools::addonsRequest('native'));
  1627. if (!$this->isFresh(Module::CACHE_FILE_ALL_COUNTRY_MODULES_LIST, 86400))
  1628. file_put_contents(_PS_ROOT_DIR_.Module::CACHE_FILE_ALL_COUNTRY_MODULES_LIST, Tools::addonsRequest('native_all'));
  1629. if (!$this->isFresh(Module::CACHE_FILE_MUST_HAVE_MODULES_LIST, 86400))
  1630. @file_put_contents(_PS_ROOT_DIR_.Module::CACHE_FILE_MUST_HAVE_MODULES_LIST, Tools::addonsRequest('must-have'));
  1631. libxml_use_internal_errors(true);
  1632. $country_module_list = file_get_contents(_PS_ROOT_DIR_.Module::CACHE_FILE_DEFAULT_COUNTRY_MODULES_LIST);
  1633. $must_have_module_list = file_get_contents(_PS_ROOT_DIR_.Module::CACHE_FILE_MUST_HAVE_MODULES_LIST);
  1634. $all_module_list = array();
  1635. if (!empty($country_module_list) && $country_module_list_xml = simplexml_load_string($country_module_list))
  1636. {
  1637. $country_module_list_array = array();
  1638. if (is_object($country_module_list_xml->module))
  1639. foreach ($country_module_list_xml->module as $k => $m)
  1640. $all_module_list[] = (string)$m->name;
  1641. }
  1642. if (!empty($must_have_module_list) && $must_have_module_list_xml = simplexml_load_string($must_have_module_list))
  1643. {
  1644. $must_have_module_list_array = array();
  1645. if (is_object($country_module_list_xml->module))
  1646. foreach ($must_have_module_list_xml->module as $l => $mo)
  1647. $all_module_list[] = (string)$mo->name;
  1648. }
  1649. $this->tab_modules_list['slider_list'] = array_intersect($this->tab_modules_list['slider_list'], $all_module_list);
  1650. }
  1651. /**
  1652. * initialize the invalid doom page of death
  1653. *
  1654. * @return void
  1655. */
  1656. public function initCursedPage()
  1657. {
  1658. $this->layout = 'invalid_token.tpl';
  1659. }
  1660. /**
  1661. * Assign smarty variables for the footer
  1662. */
  1663. public function initFooter()
  1664. {
  1665. //RTL Support
  1666. //rtl.js overrides inline styles
  1667. //iso_code.css overrides default fonts for every language (optional)
  1668. if ($this->context->language->is_rtl)
  1669. {
  1670. $this->addJS(_PS_JS_DIR_.'rtl.js');
  1671. $this->addCSS(__PS_BASE_URI__.$this->admin_webpath.'/themes/'.$this->bo_theme.'/css/'.$this->context->language->iso_code.'.css', 'all', false);
  1672. }
  1673. // We assign js and css files on the last step before display template, because controller can add many js and css files
  1674. $this->context->smarty->assign('css_files', $this->css_files);
  1675. $this->context->smarty->assign('js_files', array_unique($this->js_files));
  1676. $this->context->smarty->assign(array(
  1677. 'ps_version' => _PS_VERSION_,
  1678. 'timer_start' => $this->timer_start,
  1679. 'iso_is_fr' => strtoupper($this->context->language->iso_code) == 'FR',
  1680. 'modals' => $this->renderModal(),
  1681. ));
  1682. }
  1683. public function initModal()
  1684. {
  1685. if ($this->logged_on_addons)
  1686. {
  1687. $this->context->smarty->assign(array(
  1688. 'logged_on_addons' => 1,
  1689. 'username_addons' => $this->context->cookie->username_addons
  1690. ));
  1691. }
  1692. // Iso needed to generate Addons login
  1693. $language = new Language($this->context->employee->id_lang);
  1694. $iso_code_caps = strtoupper($language->iso_code);
  1695. $this->context->smarty->assign(array(
  1696. 'check_url_fopen' => (ini_get('allow_url_fopen') ? 'ok' : 'ko'),
  1697. 'check_openssl' => (extension_loaded('openssl') ? 'ok' : 'ko'),
  1698. 'add_permission' => 1,
  1699. 'addons_register_link' => "//addons.prestashop.com/".$language->iso_code."/login?email=".urlencode($this->context->employee->email)."&firstname=".urlencode($this->context->employee->firstname)."&lastname=".urlencode($this->context->employee->lastname)."&website=".urlencode($this->context->shop->getBaseURL())."&utm_source=back-office&utm_medium=connect-to-addons&utm_campaign=back-office-".$iso_code_caps."#createnow",
  1700. 'addons_forgot_password_link' => "//addons.prestashop.com/".$language->iso_code."/forgot-your-password"
  1701. ));
  1702. $this->modals[] = array(
  1703. 'modal_id' => "modal_addons_connect",
  1704. 'modal_class' => "modal-md",
  1705. 'modal_title' => '<i class="icon-puzzle-piece"></i> <a target="_blank" href="http://addons.prestashop.com/?utm_source=backoffice_modules">PrestaShop Addons</a>',
  1706. 'modal_content' => $this->context->smarty->fetch('controllers/modules/login_addons.tpl'),
  1707. );
  1708. }
  1709. public function renderModal()
  1710. {
  1711. $modal_render = '';
  1712. if (is_array($this->modals) && count($this->modals))
  1713. {
  1714. foreach ($this->modals as $modal)
  1715. {
  1716. $this->context->smarty->assign($modal);
  1717. $modal_render .= $this->context->smarty->fetch('modal.tpl');
  1718. }
  1719. }
  1720. return $modal_render;
  1721. }
  1722. public function renderModulesList()
  1723. {
  1724. // Load cache file modules list (natives and partners modules)
  1725. $xmlModules = false;
  1726. if (file_exists(_PS_ROOT_DIR_.Module::CACHE_FILE_MODULES_LIST))
  1727. $xmlModules = @simplexml_load_file(_PS_ROOT_DIR_.Module::CACHE_FILE_MODULES_LIST);
  1728. if ($xmlModules)
  1729. foreach ($xmlModules->children() as $xmlModule)
  1730. foreach ($xmlModule->children() as $module)
  1731. foreach ($module->attributes() as $key => $value)
  1732. {
  1733. if ($xmlModule->attributes() == 'native' && $key == 'name')
  1734. $this->list_natives_modules[] = (string)$value;
  1735. if ($xmlModule->attributes() == 'partner' && $key == 'name')
  1736. $this->list_partners_modules[] = (string)$value;
  1737. }
  1738. if ($this->getModulesList($this->filter_modules_list))
  1739. {
  1740. foreach ($this->modules_list as $key => $module)
  1741. {
  1742. if (in_array($module->name, $this->list_partners_modules))
  1743. $this->modules_list[$key]->type = 'addonsPartner';
  1744. if (isset($module->description_full) && trim($module->description_full) != '')
  1745. $module->show_quick_view = true;
  1746. }
  1747. $helper = new Helper();
  1748. return $helper->renderModulesList($this->modules_list);
  1749. }
  1750. }
  1751. /**
  1752. * Function used to render the list to display for this controller
  1753. */
  1754. public function renderList()
  1755. {
  1756. if (!($this->fields_list && is_array($this->fields_list)))
  1757. return false;
  1758. $this->getList($this->context->language->id);
  1759. // If list has 'active' field, we automatically create bulk action
  1760. if (isset($this->fields_list) && is_array($this->fields_list) && array_key_exists('active', $this->fields_list)
  1761. && !empty($this->fields_list['active']))
  1762. {
  1763. if (!is_array($this->bulk_actions))
  1764. $this->bulk_actions = array();
  1765. $this->bulk_actions = array_merge(array(
  1766. 'enableSelection' => array(
  1767. 'text' => $this->l('Enable selection'),
  1768. 'icon' => 'icon-power-off text-success'
  1769. ),
  1770. 'disableSelection' => array(
  1771. 'text' => $this->l('Disable selection'),
  1772. 'icon' => 'icon-power-off text-danger'
  1773. ),
  1774. 'divider' => array(
  1775. 'text' => 'divider'
  1776. )
  1777. ), $this->bulk_actions);
  1778. }
  1779. $helper = new HelperList();
  1780. // Empty list is ok
  1781. if (!is_array($this->_list))
  1782. {
  1783. $this->displayWarning($this->l('Bad SQL query', 'Helper').'<br />'.htmlspecialchars($this->_list_error));
  1784. return false;
  1785. }
  1786. $this->setHelperDisplay($helper);
  1787. $helper->tpl_vars = $this->tpl_list_vars;
  1788. $helper->tpl_delete_link_vars = $this->tpl_delete_link_vars;
  1789. // For compatibility reasons, we have to check standard actions in class attributes
  1790. foreach ($this->actions_available as $action)
  1791. {
  1792. if (!in_array($action, $this->actions) && isset($this->$action) && $this->$action)
  1793. $this->actions[] = $action;
  1794. }
  1795. $helper->is_cms = $this->is_cms;
  1796. $list = $helper->generateList($this->_list, $this->fields_list);
  1797. return $list;
  1798. }
  1799. /**
  1800. * Override to render the view page
  1801. */
  1802. public function renderView()
  1803. {
  1804. $helper = new HelperView($this);
  1805. $this->setHelperDisplay($helper);
  1806. $helper->tpl_vars = $this->tpl_view_vars;
  1807. if (!is_null($this->base_tpl_view))
  1808. $helper->base_tpl = $this->base_tpl_view;
  1809. $view = $helper->generateView();
  1810. return $view;
  1811. }
  1812. /**
  1813. * Override to render the view page
  1814. */
  1815. public function renderDetails()
  1816. {
  1817. return $this->renderList();
  1818. }
  1819. /**
  1820. * Function used to render the form for this controller
  1821. */
  1822. public function renderForm()
  1823. {
  1824. if (!$this->default_form_language)
  1825. $this->getLanguages();
  1826. if (Tools::getValue('submitFormAjax'))
  1827. $this->content .= $this->context->smarty->fetch('form_submit_ajax.tpl');
  1828. if ($this->fields_form && is_array($this->fields_form))
  1829. {
  1830. if (!$this->multiple_fieldsets)
  1831. $this->fields_form = array(array('form' => $this->fields_form));
  1832. // For add a fields via an override of $fields_form, use $fields_form_override
  1833. if (is_array($this->fields_form_override) && !empty($this->fields_form_override))
  1834. $this->fields_form[0]['form']['input'] = array_merge($this->fields_form[0]['form']['input'], $this->fields_form_override);
  1835. $fields_value = $this->getFieldsValue($this->object);
  1836. Hook::exec('action'.$this->controller_name.'FormModifier', array(
  1837. 'fields' => &$this->fields_form,
  1838. 'fields_value' => &$fields_value,
  1839. 'form_vars' => &$this->tpl_form_vars,
  1840. ));
  1841. $helper = new HelperForm($this);
  1842. $this->setHelperDisplay($helper);
  1843. $helper->fields_value = $fields_value;
  1844. $helper->submit_action = $this->submit_action;
  1845. $helper->tpl_vars = $this->tpl_form_vars;
  1846. $helper->show_cancel_button = (isset($this->show_form_cancel_button)) ? $this->show_form_cancel_button : ($this->display == 'add' || $this->display == 'edit');
  1847. $back = Tools::safeOutput(Tools::getValue('back', ''));
  1848. if (empty($back))
  1849. $back = self::$currentIndex.'&token='.$this->token;
  1850. if (!Validate::isCleanHtml($back))
  1851. die(Tools::displayError());
  1852. $helper->back_url = $back;
  1853. !is_null($this->base_tpl_form) ? $helper->base_tpl = $this->base_tpl_form : '';
  1854. if ($this->tabAccess['view'])
  1855. {
  1856. if (Tools::getValue('back'))
  1857. $helper->tpl_vars['back'] = Tools::safeOutput(Tools::getValue('back'));
  1858. else
  1859. $helper->tpl_vars['back'] = Tools::safeOutput(Tools::getValue(self::$currentIndex.'&token='.$this->token));
  1860. }
  1861. $form = $helper->generateForm($this->fields_form);
  1862. return $form;
  1863. }
  1864. }
  1865. public function renderKpis()
  1866. {
  1867. }
  1868. /**
  1869. * Function used to render the options for this controller
  1870. */
  1871. public function renderOptions()
  1872. {
  1873. Hook::exec('action'.$this->controller_name.'OptionsModifier', array(
  1874. 'options' => &$this->fields_options,
  1875. 'option_vars' => &$this->tpl_option_vars,
  1876. ));
  1877. if ($this->fields_options && is_array($this->fields_options))
  1878. {
  1879. if (isset($this->display) && $this->display != 'options' && $this->display != 'list')
  1880. $this->show_toolbar = false;
  1881. else
  1882. $this->display = 'options';
  1883. unset($this->toolbar_btn);
  1884. $this->initToolbar();
  1885. $helper = new HelperOptions($this);
  1886. $this->setHelperDisplay($helper);
  1887. $helper->id = $this->id;
  1888. $helper->tpl_vars = $this->tpl_option_vars;
  1889. $options = $helper->generateOptions($this->fields_options);
  1890. return $options;
  1891. }
  1892. }
  1893. /**
  1894. * this function set various display option for helper list
  1895. *
  1896. * @param Helper $helper
  1897. * @return void
  1898. */
  1899. public function setHelperDisplay(Helper $helper)
  1900. {
  1901. if (empty($this->toolbar_title))
  1902. $this->initToolbarTitle();
  1903. // tocheck
  1904. if ($this->object && $this->object->id)
  1905. $helper->id = $this->object->id;
  1906. // @todo : move that in Helper
  1907. $helper->title = is_array($this->toolbar_title) ? implode(' '.Configuration::get('PS_NAVIGATION_PIPE').' ', $this->toolbar_title) : $this->toolbar_title;
  1908. $helper->toolbar_btn = $this->toolbar_btn;
  1909. $helper->show_toolbar = $this->show_toolbar;
  1910. $helper->toolbar_scroll = $this->toolbar_scroll;
  1911. $helper->override_folder = $this->tpl_folder;
  1912. $helper->actions = $this->actions;
  1913. $helper->simple_header = $this->list_simple_header;
  1914. $helper->bulk_actions = $this->bulk_actions;
  1915. $helper->currentIndex = self::$currentIndex;
  1916. $helper->className = $this->className;
  1917. $helper->table = $this->table;
  1918. $helper->name_controller = Tools::getValue('controller');
  1919. $helper->orderBy = $this->_orderBy;
  1920. $helper->orderWay = $this->_orderWay;
  1921. $helper->listTotal = $this->_listTotal;
  1922. $helper->shopLink = $this->shopLink;
  1923. $helper->shopLinkType = $this->shopLinkType;
  1924. $helper->identifier = $this->identifier;
  1925. $helper->token = $this->token;
  1926. $helper->languages = $this->_languages;
  1927. $helper->specificConfirmDelete = $this->specificConfirmDelete;
  1928. $helper->imageType = $this->imageType;
  1929. $helper->no_link = $this->list_no_link;
  1930. $helper->colorOnBackground = $this->colorOnBackground;
  1931. $helper->ajax_params = (isset($this->ajax_params) ? $this->ajax_params : null);
  1932. $helper->default_form_language = $this->default_form_language;
  1933. $helper->allow_employee_form_lang = $this->allow_employee_form_lang;
  1934. $helper->multiple_fieldsets = $this->multiple_fieldsets;
  1935. $helper->row_hover = $this->row_hover;
  1936. $helper->position_identifier = $this->position_identifier;
  1937. $helper->position_group_identifier = $this->position_group_identifier;
  1938. $helper->controller_name = $this->controller_name;
  1939. $helper->list_id = isset($this->list_id) ? $this->list_id : $this->table;
  1940. $helper->bootstrap = $this->bootstrap;
  1941. // For each action, try to add the corresponding skip elements list
  1942. $helper->list_skip_actions = $this->list_skip_actions;
  1943. $this->helper = $helper;
  1944. }
  1945. // @deprecated 1.6.0
  1946. public function setDeprecatedMedia(){}
  1947. public function setMedia()
  1948. {
  1949. //Bootstrap + Specific Admin Theme
  1950. $this->addCSS(__PS_BASE_URI__.$this->admin_webpath.'/themes/'.$this->bo_theme.'/css/'.$this->bo_css, 'all', 0);
  1951. $this->addCSS(__PS_BASE_URI__.$this->admin_webpath.'/themes/'.$this->bo_theme.'/css/overrides.css', 'all', 99);
  1952. $this->addJquery();
  1953. $this->addjQueryPlugin(array('scrollTo', 'alerts', 'chosen', 'autosize', 'fancybox', 'storageapi' ));
  1954. $this->addjQueryPlugin('growl', null, false);
  1955. $this->addJqueryUI(array('ui.slider', 'ui.datepicker'));
  1956. $this->addJS(array(
  1957. _PS_JS_DIR_.'admin.js',
  1958. _PS_JS_DIR_.'tools.js',
  1959. _PS_JS_DIR_.'jquery/plugins/timepicker/jquery-ui-timepicker-addon.js'
  1960. ));
  1961. //loads specific javascripts for the admin theme
  1962. $this->addJS(__PS_BASE_URI__.$this->admin_webpath.'/themes/'.$this->bo_theme.'/js/vendor/bootstrap.min.js');
  1963. $this->addJS(__PS_BASE_URI__.$this->admin_webpath.'/themes/'.$this->bo_theme.'/js/vendor/modernizr.min.js');
  1964. $this->addJS(__PS_BASE_URI__.$this->admin_webpath.'/themes/'.$this->bo_theme.'/js/modernizr-loads.js');
  1965. $this->addJS(__PS_BASE_URI__.$this->admin_webpath.'/themes/'.$this->bo_theme.'/js/vendor/moment-with-langs.min.js');
  1966. if (!$this->lite_display)
  1967. $this->addJS(__PS_BASE_URI__.$this->admin_webpath.'/themes/'.$this->bo_theme.'/js/help.js');
  1968. if (!Tools::getValue('submitFormAjax'))
  1969. $this->addJs(_PS_JS_DIR_.'notifications.js');
  1970. // Execute Hook AdminController SetMedia
  1971. Hook::exec('actionAdminControllerSetMedia');
  1972. }
  1973. /**
  1974. * non-static method which uses AdminController::translate()
  1975. *
  1976. * @param mixed $string term or expression in english
  1977. * @param string $class name of the class
  1978. * @param boolan $addslashes if set to true, the return value will pass through addslashes(). Otherwise, stripslashes().
  1979. * @param boolean $htmlentities if set to true(default), the return value will pass through htmlentities($string, ENT_QUOTES, 'utf-8')
  1980. * @return string the translation if available, or the english default text.
  1981. */
  1982. protected function l($string, $class = null, $addslashes = false, $htmlentities = true)
  1983. {
  1984. if ($class === null || $class == 'AdminTab')
  1985. $class = substr(get_class($this), 0, -10);
  1986. // classname has changed, from AdminXXX to AdminXXXController, so we remove 10 characters and we keep same keys
  1987. elseif (strtolower(substr($class, -10)) == 'controller')
  1988. $class = substr($class, 0, -10);
  1989. return Translate::getAdminTranslation($string, $class, $addslashes, $htmlentities);
  1990. }
  1991. /**
  1992. * Init context and dependencies, handles POST and GET
  1993. */
  1994. public function init()
  1995. {
  1996. // Has to be removed for the next Prestashop version
  1997. global $currentIndex;
  1998. parent::init();
  1999. if (Tools::getValue('ajax'))
  2000. $this->ajax = '1';
  2001. /* Server Params */
  2002. $protocol_link = (Tools::usingSecureMode() && Configuration::get('PS_SSL_ENABLED')) ? 'https://' : 'http://';
  2003. $protocol_content = (Tools::usingSecureMode() && Configuration::get('PS_SSL_ENABLED')) ? 'https://' : 'http://';
  2004. $this->context->link = new Link($protocol_link, $protocol_content);
  2005. if (isset($_GET['logout']))
  2006. $this->context->employee->logout();
  2007. if (isset(Context::getContext()->cookie->last_activity))
  2008. {
  2009. if ($this->context->cookie->last_activity + 900 < time())
  2010. $this->context->employee->logout();
  2011. else
  2012. $this->context->cookie->last_activity = time();
  2013. }
  2014. if ($this->controller_name != 'AdminLogin' && (!isset($this->context->employee) || !$this->context->employee->isLoggedBack()))
  2015. {
  2016. if (isset($this->context->employee))
  2017. $this->context->employee->logout();
  2018. Tools::redirectAdmin($this->context->link->getAdminLink('AdminLogin').((!isset($_GET['logout']) && $this->controller_name != 'AdminNotFound' && Tools::getValue('controller')) ? '&redirect='.$this->controller_name : ''));
  2019. }
  2020. // Set current index
  2021. $current_index = 'index.php'.(($controller = Tools::getValue('controller')) ? '?controller='.$controller : '');
  2022. if ($back = Tools::getValue('back'))
  2023. $current_index .= '&back='.urlencode($back);
  2024. self::$currentIndex = $current_index;
  2025. $currentIndex = $current_index;
  2026. if ((int)Tools::getValue('liteDisplaying'))
  2027. {
  2028. $this->display_header = false;
  2029. $this->display_footer = false;
  2030. $this->content_only = false;
  2031. $this->lite_display = true;
  2032. }
  2033. if ($this->ajax && method_exists($this, 'ajaxPreprocess'))
  2034. $this->ajaxPreProcess();
  2035. $this->context->smarty->assign(array(
  2036. 'table' => $this->table,
  2037. 'current' => self::$currentIndex,
  2038. 'token' => $this->token,
  2039. 'host_mode' => defined('_PS_HOST_MODE_') ? 1 : 0,
  2040. 'stock_management' => (int)Configuration::get('PS_STOCK_MANAGEMENT')
  2041. ));
  2042. if ($this->display_header)
  2043. $this->context->smarty->assign('displayBackOfficeHeader', Hook::exec('displayBackOfficeHeader', array()));
  2044. $this->context->smarty->assign(array(
  2045. 'displayBackOfficeTop' => Hook::exec('displayBackOfficeTop', array()),
  2046. 'submit_form_ajax' => (int)Tools::getValue('submitFormAjax')
  2047. ));
  2048. $this->initProcess();
  2049. $this->initBreadcrumbs();
  2050. $this->initModal();
  2051. }
  2052. public function initShopContext()
  2053. {
  2054. if (!$this->context->employee->isLoggedBack())
  2055. return;
  2056. // Change shop context ?
  2057. if (Shop::isFeatureActive() && Tools::getValue('setShopContext') !== false)
  2058. {
  2059. $this->context->cookie->shopContext = Tools::getValue('setShopContext');
  2060. $url = parse_url($_SERVER['REQUEST_URI']);
  2061. $query = (isset($url['query'])) ? $url['query'] : '';
  2062. parse_str($query, $parse_query);
  2063. unset($parse_query['setShopContext'], $parse_query['conf']);
  2064. $this->redirect_after = $url['path'].'?'.http_build_query($parse_query, '', '&');
  2065. }
  2066. elseif (!Shop::isFeatureActive())
  2067. $this->context->cookie->shopContext = 's-'.Configuration::get('PS_SHOP_DEFAULT');
  2068. else if (Shop::getTotalShops(false, null) < 2)
  2069. $this->context->cookie->shopContext = 's-'.$this->context->employee->getDefaultShopID();
  2070. $shop_id = '';
  2071. Shop::setContext(Shop::CONTEXT_ALL);
  2072. if ($this->context->cookie->shopContext)
  2073. {
  2074. $split = explode('-', $this->context->cookie->shopContext);
  2075. if (count($split) == 2)
  2076. {
  2077. if ($split[0] == 'g')
  2078. {
  2079. if ($this->context->employee->hasAuthOnShopGroup($split[1]))
  2080. Shop::setContext(Shop::CONTEXT_GROUP, $split[1]);
  2081. else
  2082. {
  2083. $shop_id = $this->context->employee->getDefaultShopID();
  2084. Shop::setContext(Shop::CONTEXT_SHOP, $shop_id);
  2085. }
  2086. }
  2087. else if (Shop::getShop($split[1]) && $this->context->employee->hasAuthOnShop($split[1]))
  2088. {
  2089. $shop_id = $split[1];
  2090. Shop::setContext(Shop::CONTEXT_SHOP, $shop_id);
  2091. }
  2092. else
  2093. {
  2094. $shop_id = $this->context->employee->getDefaultShopID();
  2095. Shop::setContext(Shop::CONTEXT_SHOP, $shop_id);
  2096. }
  2097. }
  2098. }
  2099. // Check multishop context and set right context if need
  2100. if (!($this->multishop_context & Shop::getContext()))
  2101. {
  2102. if (Shop::getContext() == Shop::CONTEXT_SHOP && !($this->multishop_context & Shop::CONTEXT_SHOP))
  2103. Shop::setContext(Shop::CONTEXT_GROUP, Shop::getContextShopGroupID());
  2104. if (Shop::getContext() == Shop::CONTEXT_GROUP && !($this->multishop_context & Shop::CONTEXT_GROUP))
  2105. Shop::setContext(Shop::CONTEXT_ALL);
  2106. }
  2107. // Replace existing shop if necessary
  2108. if (!$shop_id)
  2109. $this->context->shop = new Shop(Configuration::get('PS_SHOP_DEFAULT'));
  2110. elseif ($this->context->shop->id != $shop_id)
  2111. $this->context->shop = new Shop($shop_id);
  2112. // Replace current default country
  2113. $this->context->country = new Country((int)Configuration::get('PS_COUNTRY_DEFAULT'));
  2114. }
  2115. /**
  2116. * Retrieve GET and POST value and translate them to actions
  2117. */
  2118. public function initProcess()
  2119. {
  2120. if (!isset($this->list_id))
  2121. $this->list_id = $this->table;
  2122. // Manage list filtering
  2123. if (Tools::isSubmit('submitFilter'.$this->list_id)
  2124. || $this->context->cookie->{'submitFilter'.$this->list_id} !== false
  2125. || Tools::getValue($this->list_id.'Orderby')
  2126. || Tools::getValue($this->list_id.'Orderway'))
  2127. $this->filter = true;
  2128. $this->id_object = (int)Tools::getValue($this->identifier);
  2129. /* Delete object image */
  2130. if (isset($_GET['deleteImage']))
  2131. {
  2132. if ($this->tabAccess['delete'] === '1')
  2133. $this->action = 'delete_image';
  2134. else
  2135. $this->errors[] = Tools::displayError('You do not have permission to delete this.');
  2136. }
  2137. /* Delete object */
  2138. elseif (isset($_GET['delete'.$this->table]))
  2139. {
  2140. if ($this->tabAccess['delete'] === '1')
  2141. $this->action = 'delete';
  2142. else
  2143. $this->errors[] = Tools::displayError('You do not have permission to delete this.');
  2144. }
  2145. /* Change object statuts (active, inactive) */
  2146. elseif ((isset($_GET['status'.$this->table]) || isset($_GET['status'])) && Tools::getValue($this->identifier))
  2147. {
  2148. if ($this->tabAccess['edit'] === '1')
  2149. $this->action = 'status';
  2150. else
  2151. $this->errors[] = Tools::displayError('You do not have permission to edit this.');
  2152. }
  2153. /* Move an object */
  2154. elseif (isset($_GET['position']))
  2155. {
  2156. if ($this->tabAccess['edit'] == '1')
  2157. $this->action = 'position';
  2158. else
  2159. $this->errors[] = Tools::displayError('You do not have permission to edit this.');
  2160. }
  2161. elseif (Tools::isSubmit('submitAdd'.$this->table)
  2162. || Tools::isSubmit('submitAdd'.$this->table.'AndStay')
  2163. || Tools::isSubmit('submitAdd'.$this->table.'AndPreview')
  2164. || Tools::isSubmit('submitAdd'.$this->table.'AndBackToParent'))
  2165. {
  2166. // case 1: updating existing entry
  2167. if ($this->id_object)
  2168. {
  2169. if ($this->tabAccess['edit'] === '1')
  2170. {
  2171. $this->action = 'save';
  2172. if (Tools::isSubmit('submitAdd'.$this->table.'AndStay'))
  2173. $this->display = 'edit';
  2174. else
  2175. $this->display = 'list';
  2176. }
  2177. else
  2178. $this->errors[] = Tools::displayError('You do not have permission to edit this.');
  2179. }
  2180. // case 2: creating new entry
  2181. else
  2182. {
  2183. if ($this->tabAccess['add'] === '1')
  2184. {
  2185. $this->action = 'save';
  2186. if (Tools::isSubmit('submitAdd'.$this->table.'AndStay'))
  2187. $this->display = 'edit';
  2188. else
  2189. $this->display = 'list';
  2190. }
  2191. else
  2192. $this->errors[] = Tools::displayError('You do not have permission to add this.');
  2193. }
  2194. }
  2195. elseif (isset($_GET['add'.$this->table]))
  2196. {
  2197. if ($this->tabAccess['add'] === '1')
  2198. {
  2199. $this->action = 'new';
  2200. $this->display = 'add';
  2201. }
  2202. else
  2203. $this->errors[] = Tools::displayError('You do not have permission to add this.');
  2204. }
  2205. elseif (isset($_GET['update'.$this->table]) && isset($_GET[$this->identifier]))
  2206. {
  2207. $this->display = 'edit';
  2208. if ($this->tabAccess['edit'] !== '1')
  2209. $this->errors[] = Tools::displayError('You do not have permission to edit this.');
  2210. }
  2211. elseif (isset($_GET['view'.$this->table]))
  2212. {
  2213. if ($this->tabAccess['view'] === '1')
  2214. {
  2215. $this->display = 'view';
  2216. $this->action = 'view';
  2217. }
  2218. else
  2219. $this->errors[] = Tools::displayError('You do not have permission to view this.');
  2220. }
  2221. elseif (isset($_GET['details'.$this->table]))
  2222. {
  2223. if ($this->tabAccess['view'] === '1')
  2224. {
  2225. $this->display = 'details';
  2226. $this->action = 'details';
  2227. }
  2228. else
  2229. $this->errors[] = Tools::displayError('You do not have permission to view this.');
  2230. }
  2231. elseif (isset($_GET['export'.$this->table]))
  2232. {
  2233. if ($this->tabAccess['view'] === '1')
  2234. $this->action = 'export';
  2235. }
  2236. /* Cancel all filters for this tab */
  2237. elseif (isset($_POST['submitReset'.$this->list_id]))
  2238. $this->action = 'reset_filters';
  2239. /* Submit options list */
  2240. elseif (Tools::isSubmit('submitOptions'.$this->table) || Tools::isSubmit('submitOptions'))
  2241. {
  2242. $this->display = 'options';
  2243. if ($this->tabAccess['edit'] === '1')
  2244. $this->action = 'update_options';
  2245. else
  2246. $this->errors[] = Tools::displayError('You do not have permission to edit this.');
  2247. }
  2248. elseif (Tools::getValue('action') && method_exists($this, 'process'.ucfirst(Tools::toCamelCase(Tools::getValue('action')))))
  2249. $this->action = Tools::getValue('action');
  2250. elseif (Tools::isSubmit('submitFields') && $this->required_database && $this->tabAccess['add'] === '1' && $this->tabAccess['delete'] === '1')
  2251. $this->action = 'update_fields';
  2252. elseif (is_array($this->bulk_actions))
  2253. {
  2254. $submit_bulk_actions = array_merge(array(
  2255. 'enableSelection' => array(
  2256. 'text' => $this->l('Enable selection'),
  2257. 'icon' => 'icon-power-off text-success'
  2258. ),
  2259. 'disableSelection' => array(
  2260. 'text' => $this->l('Disable selection'),
  2261. 'icon' => 'icon-power-off text-danger'
  2262. )
  2263. ), $this->bulk_actions);
  2264. foreach ($submit_bulk_actions as $bulk_action => $params)
  2265. {
  2266. if (Tools::isSubmit('submitBulk'.$bulk_action.$this->table) || Tools::isSubmit('submitBulk'.$bulk_action))
  2267. {
  2268. if ($this->tabAccess['edit'] === '1')
  2269. {
  2270. $this->action = 'bulk'.$bulk_action;
  2271. $this->boxes = Tools::getValue($this->table.'Box');
  2272. }
  2273. else
  2274. $this->errors[] = Tools::displayError('You do not have permission to edit this.');
  2275. break;
  2276. }
  2277. elseif (Tools::isSubmit('submitBulk'))
  2278. {
  2279. if ($this->tabAccess['edit'] === '1')
  2280. {
  2281. $this->action = 'bulk'.Tools::getValue('select_submitBulk');
  2282. $this->boxes = Tools::getValue($this->table.'Box');
  2283. }
  2284. else
  2285. $this->errors[] = Tools::displayError('You do not have permission to edit this.');
  2286. break;
  2287. }
  2288. }
  2289. }
  2290. elseif (!empty($this->fields_options) && empty($this->fields_list))
  2291. $this->display = 'options';
  2292. }
  2293. /**
  2294. * Get the current objects' list form the database
  2295. *
  2296. * @param integer $id_lang Language used for display
  2297. * @param string $order_by ORDER BY clause
  2298. * @param string $_orderWay Order way (ASC, DESC)
  2299. * @param integer $start Offset in LIMIT clause
  2300. * @param integer $limit Row count in LIMIT clause
  2301. */
  2302. public function getList($id_lang, $order_by = null, $order_way = null, $start = 0, $limit = null, $id_lang_shop = false)
  2303. {
  2304. Hook::exec('action'.$this->controller_name.'ListingFieldsModifier', array(
  2305. 'select' => &$this->_select,
  2306. 'join' => &$this->_join,
  2307. 'where' => &$this->_where,
  2308. 'group_by' => &$this->_groupBy,
  2309. 'order_by' => &$this->_orderBy,
  2310. 'order_way' => &$this->_orderWay,
  2311. 'fields' => &$this->fields_list,
  2312. ));
  2313. if (!isset($this->list_id))
  2314. $this->list_id = $this->table;
  2315. /* Manage default params values */
  2316. $use_limit = true;
  2317. if ($limit === false)
  2318. $use_limit = false;
  2319. elseif (empty($limit))
  2320. {
  2321. if (isset($this->context->cookie->{$this->list_id.'_pagination'}) && $this->context->cookie->{$this->list_id.'_pagination'})
  2322. $limit = $this->context->cookie->{$this->list_id.'_pagination'};
  2323. else
  2324. $limit = $this->_default_pagination;
  2325. }
  2326. if (!Validate::isTableOrIdentifier($this->table))
  2327. throw new PrestaShopException(sprintf('Table name %s is invalid:', $this->table));
  2328. $prefix = str_replace(array('admin', 'controller'), '', Tools::strtolower(get_class($this)));
  2329. if (empty($order_by))
  2330. {
  2331. if ($this->context->cookie->{$prefix.$this->list_id.'Orderby'})
  2332. $order_by = $this->context->cookie->{$prefix.$this->list_id.'Orderby'};
  2333. elseif ($this->_orderBy)
  2334. $order_by = $this->_orderBy;
  2335. else
  2336. $order_by = $this->_defaultOrderBy;
  2337. }
  2338. if (empty($order_way))
  2339. {
  2340. if ($this->context->cookie->{$prefix.$this->list_id.'Orderway'})
  2341. $order_way = $this->context->cookie->{$prefix.$this->list_id.'Orderway'};
  2342. elseif ($this->_orderWay)
  2343. $order_way = $this->_orderWay;
  2344. else
  2345. $order_way = $this->_defaultOrderWay;
  2346. }
  2347. $limit = (int)Tools::getValue($this->list_id.'_pagination', $limit);
  2348. if (in_array($limit, $this->_pagination) && $limit != $this->_default_pagination)
  2349. $this->context->cookie->{$this->list_id.'_pagination'} = $limit;
  2350. else
  2351. unset($this->context->cookie->{$this->list_id.'_pagination'});
  2352. /* Check params validity */
  2353. if (!Validate::isOrderBy($order_by) || !Validate::isOrderWay($order_way)
  2354. || !is_numeric($start) || !is_numeric($limit)
  2355. || !Validate::isUnsignedId($id_lang))
  2356. throw new PrestaShopException('get list params is not valid');
  2357. if (!isset($this->fields_list[$order_by]['order_key']) && isset($this->fields_list[$order_by]['filter_key']))
  2358. $this->fields_list[$order_by]['order_key'] = $this->fields_list[$order_by]['filter_key'];
  2359. if (isset($this->fields_list[$order_by]) && isset($this->fields_list[$order_by]['order_key']))
  2360. $order_by = $this->fields_list[$order_by]['order_key'];
  2361. /* Determine offset from current page */
  2362. $start = 0;
  2363. if ((int)Tools::getValue('submitFilter'.$this->list_id))
  2364. $start = ((int)Tools::getValue('submitFilter'.$this->list_id) - 1) * $limit;
  2365. elseif (empty($start) && isset($this->context->cookie->{$this->list_id.'_start'}) && Tools::isSubmit('export'.$this->table))
  2366. $start = $this->context->cookie->{$this->list_id.'_start'};
  2367. // Either save or reset the offset in the cookie
  2368. if ($start)
  2369. $this->context->cookie->{$this->list_id.'_start'} = $start;
  2370. elseif (isset($this->context->cookie->{$this->list_id.'_start'}))
  2371. unset($this->context->cookie->{$this->list_id.'_start'});
  2372. /* Cache */
  2373. $this->_lang = (int)$id_lang;
  2374. $this->_orderBy = $order_by;
  2375. if (preg_match('/[.!]/', $order_by))
  2376. {
  2377. $order_by_split = preg_split('/[.!]/', $order_by);
  2378. $order_by = bqSQL($order_by_split[0]).'.`'.bqSQL($order_by_split[1]).'`';
  2379. }
  2380. elseif ($order_by)
  2381. $order_by = '`'.bqSQL($order_by).'`';
  2382. $this->_orderWay = Tools::strtoupper($order_way);
  2383. /* SQL table : orders, but class name is Order */
  2384. $sql_table = $this->table == 'order' ? 'orders' : $this->table;
  2385. // Add SQL shop restriction
  2386. $select_shop = $join_shop = $where_shop = '';
  2387. if ($this->shopLinkType)
  2388. {
  2389. $select_shop = ', shop.name as shop_name ';
  2390. $join_shop = ' LEFT JOIN '._DB_PREFIX_.$this->shopLinkType.' shop
  2391. ON a.id_'.$this->shopLinkType.' = shop.id_'.$this->shopLinkType;
  2392. $where_shop = Shop::addSqlRestriction($this->shopShareDatas, 'a', $this->shopLinkType);
  2393. }
  2394. if ($this->multishop_context && Shop::isTableAssociated($this->table) && !empty($this->className))
  2395. {
  2396. if (Shop::getContext() != Shop::CONTEXT_ALL || !$this->context->employee->isSuperAdmin())
  2397. {
  2398. $test_join = !preg_match('#`?'.preg_quote(_DB_PREFIX_.$this->table.'_shop').'`? *sa#', $this->_join);
  2399. if (Shop::isFeatureActive() && $test_join && Shop::isTableAssociated($this->table))
  2400. {
  2401. $this->_where .= ' AND a.'.$this->identifier.' IN (
  2402. SELECT sa.'.$this->identifier.'
  2403. FROM `'._DB_PREFIX_.$this->table.'_shop` sa
  2404. WHERE sa.id_shop IN ('.implode(', ', Shop::getContextListShopID()).')
  2405. )';
  2406. }
  2407. }
  2408. }
  2409. /* Query in order to get results with all fields */
  2410. $lang_join = '';
  2411. if ($this->lang)
  2412. {
  2413. $lang_join = 'LEFT JOIN `'._DB_PREFIX_.$this->table.'_lang` b ON (b.`'.$this->identifier.'` = a.`'.$this->identifier.'` AND b.`id_lang` = '.(int)$id_lang;
  2414. if ($id_lang_shop)
  2415. {
  2416. if (!Shop::isFeatureActive())
  2417. $lang_join .= ' AND b.`id_shop` = 1';
  2418. elseif (Shop::getContext() == Shop::CONTEXT_SHOP)
  2419. $lang_join .= ' AND b.`id_shop` = '.(int)$id_lang_shop;
  2420. else
  2421. $lang_join .= ' AND b.`id_shop` = a.id_shop_default';
  2422. }
  2423. $lang_join .= ')';
  2424. }
  2425. $having_clause = '';
  2426. if (isset($this->_filterHaving) || isset($this->_having))
  2427. {
  2428. $having_clause = ' HAVING ';
  2429. if (isset($this->_filterHaving))
  2430. $having_clause .= ltrim($this->_filterHaving, ' AND ');
  2431. if (isset($this->_having))
  2432. $having_clause .= $this->_having.' ';
  2433. }
  2434. do
  2435. {
  2436. $this->_listsql = '
  2437. SELECT SQL_CALC_FOUND_ROWS
  2438. '.($this->_tmpTableFilter ? ' * FROM (SELECT ' : '');
  2439. if ($this->explicitSelect)
  2440. {
  2441. foreach ($this->fields_list as $key => $array_value)
  2442. {
  2443. // Add it only if it is not already in $this->_select
  2444. if (isset($this->_select) && preg_match('/[\s]`?'.preg_quote($key, '/').'`?\s*,/', $this->_select))
  2445. continue;
  2446. if (isset($array_value['filter_key']))
  2447. $this->_listsql .= str_replace('!', '.', $array_value['filter_key']).' as '.$key.',';
  2448. elseif ($key == 'id_'.$this->table)
  2449. $this->_listsql .= 'a.`'.bqSQL($key).'`,';
  2450. elseif ($key != 'image' && !preg_match('/'.preg_quote($key, '/').'/i', $this->_select))
  2451. $this->_listsql .= '`'.bqSQL($key).'`,';
  2452. }
  2453. $this->_listsql = rtrim($this->_listsql, ',');
  2454. }
  2455. else
  2456. $this->_listsql .= ($this->lang ? 'b.*,' : '').' a.*';
  2457. $this->_listsql .= '
  2458. '.(isset($this->_select) ? ', '.rtrim($this->_select, ', ') : '').$select_shop.'
  2459. FROM `'._DB_PREFIX_.$sql_table.'` a
  2460. '.$lang_join.'
  2461. '.(isset($this->_join) ? $this->_join.' ' : '').'
  2462. '.$join_shop.'
  2463. WHERE 1 '.(isset($this->_where) ? $this->_where.' ' : '').($this->deleted ? 'AND a.`deleted` = 0 ' : '').
  2464. (isset($this->_filter) ? $this->_filter : '').$where_shop.'
  2465. '.(isset($this->_group) ? $this->_group.' ' : '').'
  2466. '.$having_clause.'
  2467. ORDER BY '.((str_replace('`', '', $order_by) == $this->identifier) ? 'a.' : '').$order_by.' '.pSQL($order_way).
  2468. ($this->_tmpTableFilter ? ') tmpTable WHERE 1'.$this->_tmpTableFilter : '').
  2469. (($use_limit === true) ? ' LIMIT '.(int)$start.','.(int)$limit : '');
  2470. $this->_list = Db::getInstance()->executeS($this->_listsql, true, false);
  2471. if ($this->_list === false)
  2472. {
  2473. $this->_list_error = Db::getInstance()->getMsgError();
  2474. break;
  2475. }
  2476. $this->_listTotal = Db::getInstance()->getValue('SELECT FOUND_ROWS() AS `'._DB_PREFIX_.$this->table.'`', false);
  2477. if ($use_limit === true)
  2478. {
  2479. $start = (int)$start - (int)$limit;
  2480. if ($start < 0)
  2481. break;
  2482. }
  2483. else
  2484. {
  2485. break;
  2486. }
  2487. } while (empty($this->_list));
  2488. Hook::exec('action'.$this->controller_name.'ListingResultsModifier', array(
  2489. 'list' => &$this->_list,
  2490. 'list_total' => &$this->_listTotal,
  2491. ));
  2492. }
  2493. public function getModulesList($filter_modules_list)
  2494. {
  2495. if (!is_array($filter_modules_list) && !is_null($filter_modules_list))
  2496. $filter_modules_list = array($filter_modules_list);
  2497. if (!count($filter_modules_list))
  2498. return false; //if there is no modules to display just return false;
  2499. $all_modules = Module::getModulesOnDisk(true);
  2500. $this->modules_list = array();
  2501. foreach ($all_modules as $module)
  2502. {
  2503. $perm = true;
  2504. if ($module->id)
  2505. $perm &= Module::getPermissionStatic($module->id, 'configure');
  2506. else
  2507. {
  2508. $id_admin_module = Tab::getIdFromClassName('AdminModules');
  2509. $access = Profile::getProfileAccess($this->context->employee->id_profile, $id_admin_module);
  2510. if (!$access['edit'])
  2511. $perm &= false;
  2512. }
  2513. if (in_array($module->name, $filter_modules_list) && $perm)
  2514. {
  2515. $this->fillModuleData($module, 'array');
  2516. $this->modules_list[array_search($module->name, $filter_modules_list)] = $module;
  2517. }
  2518. }
  2519. ksort($this->modules_list);
  2520. if (count($this->modules_list))
  2521. return true;
  2522. return false; //no module found on disk just return false;
  2523. }
  2524. public function getLanguages()
  2525. {
  2526. $cookie = $this->context->cookie;
  2527. $this->allow_employee_form_lang = (int)Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG');
  2528. if ($this->allow_employee_form_lang && !$cookie->employee_form_lang)
  2529. $cookie->employee_form_lang = (int)Configuration::get('PS_LANG_DEFAULT');
  2530. $lang_exists = false;
  2531. $this->_languages = Language::getLanguages(false);
  2532. foreach ($this->_languages as $lang)
  2533. if (isset($cookie->employee_form_lang) && $cookie->employee_form_lang == $lang['id_lang'])
  2534. $lang_exists = true;
  2535. $this->default_form_language = $lang_exists ? (int)$cookie->employee_form_lang : (int)Configuration::get('PS_LANG_DEFAULT');
  2536. foreach ($this->_languages as $k => $language)
  2537. $this->_languages[$k]['is_default'] = ((int)($language['id_lang'] == $this->default_form_language));
  2538. return $this->_languages;
  2539. }
  2540. /**
  2541. * Return the list of fields value
  2542. *
  2543. * @param object $obj Object
  2544. * @return array
  2545. */
  2546. public function getFieldsValue($obj)
  2547. {
  2548. foreach ($this->fields_form as $fieldset)
  2549. if (isset($fieldset['form']['input']))
  2550. foreach ($fieldset['form']['input'] as $input)
  2551. if (!isset($this->fields_value[$input['name']]))
  2552. if (isset($input['type']) && $input['type'] == 'shop')
  2553. {
  2554. if ($obj->id)
  2555. {
  2556. $result = Shop::getShopById((int)$obj->id, $this->identifier, $this->table);
  2557. foreach ($result as $row)
  2558. $this->fields_value['shop'][$row['id_'.$input['type']]][] = $row['id_shop'];
  2559. }
  2560. }
  2561. elseif (isset($input['lang']) && $input['lang'])
  2562. foreach ($this->_languages as $language)
  2563. {
  2564. $fieldValue = $this->getFieldValue($obj, $input['name'], $language['id_lang']);
  2565. if (empty($fieldValue))
  2566. {
  2567. if (isset($input['default_value']) && is_array($input['default_value']) && isset($input['default_value'][$language['id_lang']]))
  2568. $fieldValue = $input['default_value'][$language['id_lang']];
  2569. elseif (isset($input['default_value']))
  2570. $fieldValue = $input['default_value'];
  2571. }
  2572. $this->fields_value[$input['name']][$language['id_lang']] = $fieldValue;
  2573. }
  2574. else
  2575. {
  2576. $fieldValue = $this->getFieldValue($obj, $input['name']);
  2577. if ($fieldValue === false && isset($input['default_value']))
  2578. $fieldValue = $input['default_value'];
  2579. $this->fields_value[$input['name']] = $fieldValue;
  2580. }
  2581. return $this->fields_value;
  2582. }
  2583. /**
  2584. * Return field value if possible (both classical and multilingual fields)
  2585. *
  2586. * Case 1 : Return value if present in $_POST / $_GET
  2587. * Case 2 : Return object value
  2588. *
  2589. * @param object $obj Object
  2590. * @param string $key Field name
  2591. * @param integer $id_lang Language id (optional)
  2592. * @return string
  2593. */
  2594. public function getFieldValue($obj, $key, $id_lang = null)
  2595. {
  2596. if ($id_lang)
  2597. $default_value = (isset($obj->id) && $obj->id && isset($obj->{$key}[$id_lang])) ? $obj->{$key}[$id_lang] : false;
  2598. else
  2599. $default_value = isset($obj->{$key}) ? $obj->{$key} : false;
  2600. return Tools::getValue($key.($id_lang ? '_'.$id_lang : ''), $default_value);
  2601. }
  2602. /**
  2603. * Manage page display (form, list...)
  2604. *
  2605. * @param string $className Allow to validate a different class than the current one
  2606. */
  2607. public function validateRules($class_name = false)
  2608. {
  2609. if (!$class_name)
  2610. $class_name = $this->className;
  2611. $object = new $class_name();
  2612. if (method_exists($this, 'getValidationRules'))
  2613. $definition = $this->getValidationRules();
  2614. else
  2615. $definition = ObjectModel::getDefinition($class_name);
  2616. $default_language = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
  2617. foreach ($definition['fields'] as $field => $def)
  2618. {
  2619. $skip = array();
  2620. if (in_array($field, array('passwd', 'no-picture')))
  2621. $skip = array('required');
  2622. if (isset($def['lang']) && $def['lang'])
  2623. {
  2624. if (isset($def['required']) && $def['required'])
  2625. {
  2626. $value = Tools::getValue($field.'_'.$default_language->id);
  2627. if (empty($value))
  2628. $this->errors[$field.'_'.$default_language->id] = sprintf(
  2629. Tools::displayError('The field %1$s is required at least in %2$s.'),
  2630. $object->displayFieldName($field, $class_name),
  2631. $default_language->name
  2632. );
  2633. }
  2634. foreach (Language::getLanguages(false) as $language)
  2635. {
  2636. $value = Tools::getValue($field.'_'.$language['id_lang']);
  2637. if (!empty($value))
  2638. if (($error = $object->validateField($field, $value, $language['id_lang'], $skip, true)) !== true)
  2639. $this->errors[$field.'_'.$language['id_lang']] = $error;
  2640. }
  2641. }
  2642. else
  2643. if (($error = $object->validateField($field, Tools::getValue($field), null, $skip, true)) !== true)
  2644. $this->errors[$field] = $error;
  2645. }
  2646. /* Overload this method for custom checking */
  2647. $this->_childValidation();
  2648. /* Checking for multilingual fields validity */
  2649. if (isset($rules['validateLang']) && is_array($rules['validateLang']))
  2650. foreach ($rules['validateLang'] as $field_lang => $function)
  2651. foreach ($languages as $language)
  2652. if (($value = Tools::getValue($field_lang.'_'.$language['id_lang'])) !== false && !empty($value))
  2653. {
  2654. if (Tools::strtolower($function) == 'iscleanhtml' && Configuration::get('PS_ALLOW_HTML_IFRAME'))
  2655. $res = Validate::$function($value, true);
  2656. else
  2657. $res = Validate::$function($value);
  2658. if (!$res)
  2659. $this->errors[$field_lang.'_'.$language['id_lang']] = sprintf(
  2660. Tools::displayError('The %1$s field (%2$s) is invalid.'),
  2661. call_user_func(array($class_name, 'displayFieldName'), $field_lang, $class_name),
  2662. $language['name']
  2663. );
  2664. }
  2665. }
  2666. /**
  2667. * Overload this method for custom checking
  2668. */
  2669. protected function _childValidation()
  2670. {
  2671. }
  2672. /**
  2673. * Display object details
  2674. */
  2675. public function viewDetails()
  2676. {
  2677. }
  2678. /**
  2679. * Called before deletion
  2680. *
  2681. * @param object $object Object
  2682. * @return boolean
  2683. */
  2684. protected function beforeDelete($object)
  2685. {
  2686. return false;
  2687. }
  2688. /**
  2689. * Called before deletion
  2690. *
  2691. * @param object $object Object
  2692. * @return boolean
  2693. */
  2694. protected function afterDelete($object, $oldId)
  2695. {
  2696. return true;
  2697. }
  2698. protected function afterAdd($object)
  2699. {
  2700. return true;
  2701. }
  2702. protected function afterUpdate($object)
  2703. {
  2704. return true;
  2705. }
  2706. /**
  2707. * Check rights to view the current tab
  2708. *
  2709. * @return boolean
  2710. */
  2711. protected function afterImageUpload()
  2712. {
  2713. return true;
  2714. }
  2715. /**
  2716. * Copy datas from $_POST to object
  2717. *
  2718. * @param object &$object Object
  2719. * @param string $table Object table
  2720. */
  2721. protected function copyFromPost(&$object, $table)
  2722. {
  2723. /* Classical fields */
  2724. foreach ($_POST as $key => $value)
  2725. if (array_key_exists($key, $object) && $key != 'id_'.$table)
  2726. {
  2727. /* Do not take care of password field if empty */
  2728. if ($key == 'passwd' && Tools::getValue('id_'.$table) && empty($value))
  2729. continue;
  2730. /* Automatically encrypt password in MD5 */
  2731. if ($key == 'passwd' && !empty($value))
  2732. $value = Tools::encrypt($value);
  2733. $object->{$key} = $value;
  2734. }
  2735. /* Multilingual fields */
  2736. $languages = Language::getLanguages(false);
  2737. $class_vars = get_class_vars(get_class($object));
  2738. $fields = array();
  2739. if (isset($class_vars['definition']['fields']))
  2740. $fields = $class_vars['definition']['fields'];
  2741. foreach ($fields as $field => $params) {
  2742. if (array_key_exists('lang', $params) && $params['lang']) {
  2743. foreach ($languages as $language) {
  2744. if (isset($_POST[$field.'_'.(int)$language['id_lang']])) {
  2745. $object->{$field}[(int)$language['id_lang']] = $_POST[$field.'_'.(int)$language['id_lang']];
  2746. }
  2747. }
  2748. }
  2749. }
  2750. }
  2751. /**
  2752. * Returns an array with selected shops and type (group or boutique shop)
  2753. *
  2754. * @param string $table
  2755. * @return array
  2756. */
  2757. protected function getSelectedAssoShop($table)
  2758. {
  2759. if (!Shop::isFeatureActive() || !Shop::isTableAssociated($table))
  2760. return array();
  2761. $shops = Shop::getShops(true, null, true);
  2762. if (count($shops) == 1 && isset($shops[0]))
  2763. return array($shops[0], 'shop');
  2764. $assos = array();
  2765. if (Tools::isSubmit('checkBoxShopAsso_'.$table))
  2766. foreach (Tools::getValue('checkBoxShopAsso_'.$table) as $id_shop => $value)
  2767. $assos[] = (int)$id_shop;
  2768. else if (Shop::getTotalShops(false) == 1)// if we do not have the checkBox multishop, we can have an admin with only one shop and being in multishop
  2769. $assos[] = (int)Shop::getContextShopID();
  2770. return $assos;
  2771. }
  2772. /**
  2773. * Update the associations of shops
  2774. *
  2775. * @param int $id_object
  2776. */
  2777. protected function updateAssoShop($id_object)
  2778. {
  2779. if (!Shop::isFeatureActive())
  2780. return;
  2781. if (!Shop::isTableAssociated($this->table))
  2782. return;
  2783. $assos_data = $this->getSelectedAssoShop($this->table, $id_object);
  2784. // Get list of shop id we want to exclude from asso deletion
  2785. $exclude_ids = $assos_data;
  2786. foreach (Db::getInstance()->executeS('SELECT id_shop FROM '._DB_PREFIX_.'shop') as $row)
  2787. if (!$this->context->employee->hasAuthOnShop($row['id_shop']))
  2788. $exclude_ids[] = $row['id_shop'];
  2789. Db::getInstance()->delete($this->table.'_shop', '`'.$this->identifier.'` = '.(int)$id_object.($exclude_ids ? ' AND id_shop NOT IN ('.implode(', ', $exclude_ids).')' : ''));
  2790. $insert = array();
  2791. foreach ($assos_data as $id_shop)
  2792. $insert[] = array(
  2793. $this->identifier => (int)$id_object,
  2794. 'id_shop' => (int)$id_shop,
  2795. );
  2796. return Db::getInstance()->insert($this->table.'_shop', $insert, false, true, Db::INSERT_IGNORE);
  2797. }
  2798. protected function validateField($value, $field)
  2799. {
  2800. if (isset($field['validation']))
  2801. {
  2802. $valid_method_exists = method_exists('Validate', $field['validation']);
  2803. if ((!isset($field['empty']) || !$field['empty'] || (isset($field['empty']) && $field['empty'] && $value)) && $valid_method_exists)
  2804. {
  2805. if (!Validate::$field['validation']($value))
  2806. {
  2807. $this->errors[] = Tools::displayError($field['title'].' : Incorrect value');
  2808. return false;
  2809. }
  2810. }
  2811. }
  2812. return true;
  2813. }
  2814. /**
  2815. * Can be overriden
  2816. */
  2817. public function beforeUpdateOptions()
  2818. {
  2819. }
  2820. /**
  2821. * Overload this method for custom checking
  2822. *
  2823. * @param integer $id Object id used for deleting images
  2824. * @return boolean
  2825. */
  2826. protected function postImage($id)
  2827. {
  2828. if (isset($this->fieldImageSettings['name']) && isset($this->fieldImageSettings['dir']))
  2829. return $this->uploadImage($id, $this->fieldImageSettings['name'], $this->fieldImageSettings['dir'].'/');
  2830. elseif (!empty($this->fieldImageSettings))
  2831. foreach ($this->fieldImageSettings as $image)
  2832. if (isset($image['name']) && isset($image['dir']))
  2833. $this->uploadImage($id, $image['name'], $image['dir'].'/');
  2834. return !count($this->errors) ? true : false;
  2835. }
  2836. protected function uploadImage($id, $name, $dir, $ext = false, $width = null, $height = null)
  2837. {
  2838. if (isset($_FILES[$name]['tmp_name']) && !empty($_FILES[$name]['tmp_name']))
  2839. {
  2840. // Delete old image
  2841. if (Validate::isLoadedObject($object = $this->loadObject()))
  2842. $object->deleteImage();
  2843. else
  2844. return false;
  2845. // Check image validity
  2846. $max_size = isset($this->max_image_size) ? $this->max_image_size : 0;
  2847. if ($error = ImageManager::validateUpload($_FILES[$name], Tools::getMaxUploadSize($max_size)))
  2848. $this->errors[] = $error;
  2849. $tmp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS');
  2850. if (!$tmp_name)
  2851. return false;
  2852. if (!move_uploaded_file($_FILES[$name]['tmp_name'], $tmp_name))
  2853. return false;
  2854. // Evaluate the memory required to resize the image: if it's too much, you can't resize it.
  2855. if (!ImageManager::checkImageMemoryLimit($tmp_name))
  2856. $this->errors[] = Tools::displayError('Due to memory limit restrictions, this image cannot be loaded. Please increase your memory_limit value via your server\'s configuration settings. ');
  2857. // Copy new image
  2858. if (empty($this->errors) && !ImageManager::resize($tmp_name, _PS_IMG_DIR_.$dir.$id.'.'.$this->imageType, (int)$width, (int)$height, ($ext ? $ext : $this->imageType)))
  2859. $this->errors[] = Tools::displayError('An error occurred while uploading the image.');
  2860. if (count($this->errors))
  2861. return false;
  2862. if ($this->afterImageUpload())
  2863. {
  2864. unlink($tmp_name);
  2865. return true;
  2866. }
  2867. return false;
  2868. }
  2869. return true;
  2870. }
  2871. /**
  2872. * Delete multiple items
  2873. *
  2874. * @return boolean true if succcess
  2875. */
  2876. protected function processBulkDelete()
  2877. {
  2878. if (is_array($this->boxes) && !empty($this->boxes))
  2879. {
  2880. $object = new $this->className();
  2881. if (isset($object->noZeroObject))
  2882. {
  2883. $objects_count = count(call_user_func(array($this->className, $object->noZeroObject)));
  2884. // Check if all object will be deleted
  2885. if ($objects_count <= 1 || count($this->boxes) == $objects_count)
  2886. $this->errors[] = Tools::displayError('You need at least one object.').
  2887. ' <b>'.$this->table.'</b><br />'.
  2888. Tools::displayError('You cannot delete all of the items.');
  2889. }
  2890. else
  2891. {
  2892. $result = true;
  2893. foreach ($this->boxes as $id)
  2894. {
  2895. $to_delete = new $this->className($id);
  2896. $delete_ok = true;
  2897. if ($this->deleted)
  2898. {
  2899. $to_delete->deleted = 1;
  2900. if (!$to_delete->update())
  2901. {
  2902. $result = false;
  2903. $delete_ok = false;
  2904. }
  2905. }
  2906. else
  2907. if (!$to_delete->delete())
  2908. {
  2909. $result = false;
  2910. $delete_ok = false;
  2911. }
  2912. if ($delete_ok)
  2913. PrestaShopLogger::addLog(sprintf($this->l('%s deletion', 'AdminTab', false, false), $this->className), 1, null, $this->className, (int)$to_delete->id, true, (int)$this->context->employee->id);
  2914. else
  2915. $this->errors[] = sprintf(Tools::displayError('Can\'t delete #%d'), $id);
  2916. }
  2917. if ($result)
  2918. $this->redirect_after = self::$currentIndex.'&conf=2&token='.$this->token;
  2919. $this->errors[] = Tools::displayError('An error occurred while deleting this selection.');
  2920. }
  2921. }
  2922. else
  2923. $this->errors[] = Tools::displayError('You must select at least one element to delete.');
  2924. if (isset($result))
  2925. return $result;
  2926. else
  2927. return false;
  2928. }
  2929. protected function ajaxProcessOpenHelp()
  2930. {
  2931. $help_class_name = $_GET['controller'];
  2932. $popupContent = "<!doctype html>
  2933. <html>
  2934. <head>
  2935. <meta charset='UTF-8'>
  2936. <title>PrestaShop Help</title>
  2937. <link href='//help.prestashop.com/css/help.css' rel='stylesheet'>
  2938. <link href='//fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet'>
  2939. <script src='"._PS_JS_DIR_."jquery/jquery-1.11.0.min.js'></script>
  2940. <script src='"._PS_JS_DIR_."jquery/plugins/jquery.storageapi.js'></script>
  2941. <script src='"._PS_JS_DIR_."admin.js'></script>
  2942. <script src='"._PS_JS_DIR_."tools.js'></script>
  2943. <script>
  2944. help_class_name='".addslashes($help_class_name)."';
  2945. iso_user = '".addslashes($this->context->language->iso_code)."'
  2946. </script>
  2947. <script src='themes/default/js/help.js'></script>
  2948. <script>
  2949. $(function(){
  2950. initHelp();
  2951. });
  2952. </script>
  2953. </head>
  2954. <body><div id='help-container' class='help-popup'></div></body>
  2955. </html>";
  2956. die($popupContent);
  2957. }
  2958. /**
  2959. * Enable multiple items
  2960. *
  2961. * @return boolean true if succcess
  2962. */
  2963. protected function processBulkEnableSelection()
  2964. {
  2965. return $this->processBulkStatusSelection(1);
  2966. }
  2967. /**
  2968. * Disable multiple items
  2969. *
  2970. * @return boolean true if succcess
  2971. */
  2972. protected function processBulkDisableSelection()
  2973. {
  2974. return $this->processBulkStatusSelection(0);
  2975. }
  2976. /**
  2977. * Toggle status of multiple items
  2978. *
  2979. * @return boolean true if succcess
  2980. */
  2981. protected function processBulkStatusSelection($status)
  2982. {
  2983. $result = true;
  2984. if (is_array($this->boxes) && !empty($this->boxes))
  2985. {
  2986. foreach ($this->boxes as $id)
  2987. {
  2988. $object = new $this->className((int)$id);
  2989. $object->active = (int)$status;
  2990. $result &= $object->update();
  2991. }
  2992. }
  2993. return $result;
  2994. }
  2995. protected function processBulkAffectZone()
  2996. {
  2997. $result = false;
  2998. if (is_array($this->boxes) && !empty($this->boxes))
  2999. {
  3000. $object = new $this->className();
  3001. $result = $object->affectZoneToSelection(Tools::getValue($this->table.'Box'), Tools::getValue('zone_to_affect'));
  3002. if ($result)
  3003. $this->redirect_after = self::$currentIndex.'&conf=28&token='.$this->token;
  3004. $this->errors[] = Tools::displayError('An error occurred while affecting a zone to the selection.');
  3005. }
  3006. else
  3007. $this->errors[] = Tools::displayError('You must select at least one element to affect a new zone.');
  3008. return $result;
  3009. }
  3010. /**
  3011. * Called before Add
  3012. *
  3013. * @param object $object Object
  3014. * @return boolean
  3015. */
  3016. protected function beforeAdd($object)
  3017. {
  3018. return true;
  3019. }
  3020. /**
  3021. * prepare the view to display the required fields form
  3022. */
  3023. public function displayRequiredFields()
  3024. {
  3025. if (!$this->tabAccess['add'] || !$this->tabAccess['delete'] === '1' || !$this->required_database)
  3026. return;
  3027. $helper = new Helper();
  3028. $helper->currentIndex = self::$currentIndex;
  3029. $helper->token = $this->token;
  3030. return $helper->renderRequiredFields($this->className, $this->identifier, $this->required_fields);
  3031. }
  3032. /**
  3033. * Create a template from the override file, else from the base file.
  3034. *
  3035. * @param string $tpl_name filename
  3036. * @return Template
  3037. */
  3038. public function createTemplate($tpl_name)
  3039. {
  3040. // Use override tpl if it exists
  3041. // If view access is denied, we want to use the default template that will be used to display an error
  3042. if ($this->viewAccess() && $this->override_folder)
  3043. {
  3044. if (file_exists($this->context->smarty->getTemplateDir(1).DIRECTORY_SEPARATOR.$this->override_folder.$tpl_name))
  3045. return $this->context->smarty->createTemplate($this->override_folder.$tpl_name, $this->context->smarty);
  3046. elseif (file_exists($this->context->smarty->getTemplateDir(0).'controllers'.DIRECTORY_SEPARATOR.$this->override_folder.$tpl_name))
  3047. return $this->context->smarty->createTemplate('controllers'.DIRECTORY_SEPARATOR.$this->override_folder.$tpl_name, $this->context->smarty);
  3048. }
  3049. return $this->context->smarty->createTemplate($this->context->smarty->getTemplateDir(0).$tpl_name, $this->context->smarty);
  3050. }
  3051. /**
  3052. * Shortcut to set up a json success payload
  3053. *
  3054. * @param $message success message
  3055. */
  3056. public function jsonConfirmation($message)
  3057. {
  3058. $this->json = true;
  3059. $this->confirmations[] = $message;
  3060. if ($this->status === '')
  3061. $this->status = 'ok';
  3062. }
  3063. /**
  3064. * Shortcut to set up a json error payload
  3065. *
  3066. * @param $message error message
  3067. */
  3068. public function jsonError($message)
  3069. {
  3070. $this->json = true;
  3071. $this->errors[] = $message;
  3072. if ($this->status === '')
  3073. $this->status = 'error';
  3074. }
  3075. public function isFresh($file, $timeout = 604800)
  3076. {
  3077. if (file_exists(_PS_ROOT_DIR_.$file) && filesize(_PS_ROOT_DIR_.$file) > 0)
  3078. return ((time() - filemtime(_PS_ROOT_DIR_.$file)) < $timeout);
  3079. return false;
  3080. }
  3081. protected static $is_prestashop_up = true;
  3082. public function refresh($file_to_refresh, $external_file)
  3083. {
  3084. if (self::$is_prestashop_up && $content = Tools::file_get_contents($external_file))
  3085. return (bool)file_put_contents(_PS_ROOT_DIR_.$file_to_refresh, $content);
  3086. self::$is_prestashop_up = false;
  3087. return false;
  3088. }
  3089. public function fillModuleData(&$module, $output_type = 'link', $back = null)
  3090. {
  3091. $obj = null;
  3092. if ($module->onclick_option)
  3093. $obj = new $module->name();
  3094. // Fill module data
  3095. $module->logo = '../../img/questionmark.png';
  3096. if (@filemtime(_PS_ROOT_DIR_.DIRECTORY_SEPARATOR.basename(_PS_MODULE_DIR_).DIRECTORY_SEPARATOR.$module->name
  3097. .DIRECTORY_SEPARATOR.'logo.gif'))
  3098. $module->logo = 'logo.gif';
  3099. if (@filemtime(_PS_ROOT_DIR_.DIRECTORY_SEPARATOR.basename(_PS_MODULE_DIR_).DIRECTORY_SEPARATOR.$module->name
  3100. .DIRECTORY_SEPARATOR.'logo.png'))
  3101. $module->logo = 'logo.png';
  3102. $link_admin_modules = $this->context->link->getAdminLink('AdminModules', true);
  3103. $module->options['install_url'] = $link_admin_modules.'&install='.urlencode($module->name).'&tab_module='.$module->tab.'&module_name='.$module->name.'&anchor='.ucfirst($module->name);
  3104. $module->options['update_url'] = $link_admin_modules.'&update='.urlencode($module->name).'&tab_module='.$module->tab.'&module_name='.$module->name.'&anchor='.ucfirst($module->name);
  3105. $module->options['uninstall_url'] = $link_admin_modules.'&uninstall='.urlencode($module->name).'&tab_module='.$module->tab.'&module_name='.$module->name.'&anchor='.ucfirst($module->name);
  3106. $module->optionsHtml = $this->displayModuleOptions($module, $output_type, $back);
  3107. $module->options['uninstall_onclick'] = ((!$module->onclick_option) ?
  3108. ((empty($module->confirmUninstall)) ? 'return confirm(\''.$this->l('Do you really want to uninstall this module?').'\');' : 'return confirm(\''.addslashes($module->confirmUninstall).'\');') :
  3109. $obj->onclickOption('uninstall', $module->options['uninstall_url']));
  3110. if ((Tools::getValue('module_name') == $module->name || in_array($module->name, explode('|', Tools::getValue('modules_list')))) && (int)Tools::getValue('conf') > 0)
  3111. $module->message = $this->_conf[(int)Tools::getValue('conf')];
  3112. if ((Tools::getValue('module_name') == $module->name || in_array($module->name, explode('|', Tools::getValue('modules_list')))) && (int)Tools::getValue('conf') > 0)
  3113. unset($obj);
  3114. }
  3115. /**
  3116. * Display modules list
  3117. *
  3118. * @param $module
  3119. * @param $output_type (link or select)
  3120. * @param $back
  3121. *
  3122. * @return string
  3123. */
  3124. protected $translationsTab = array();
  3125. public function displayModuleOptions($module, $output_type = 'link', $back = null)
  3126. {
  3127. if (!isset($module->enable_device))
  3128. $module->enable_device = Context::DEVICE_COMPUTER | Context::DEVICE_TABLET | Context::DEVICE_MOBILE;
  3129. $this->translationsTab['confirm_uninstall_popup'] = (isset($module->confirmUninstall) ? $module->confirmUninstall : $this->l('Do you really want to uninstall this module?'));
  3130. if (!isset($this->translationsTab['Disable this module']))
  3131. {
  3132. $this->translationsTab['Disable this module'] = $this->l('Disable this module');
  3133. $this->translationsTab['Enable this module for all shops'] = $this->l('Enable this module for all shops');
  3134. $this->translationsTab['Disable'] = $this->l('Disable');
  3135. $this->translationsTab['Enable'] = $this->l('Enable');
  3136. $this->translationsTab['Disable on mobiles'] = $this->l('Disable on mobiles');
  3137. $this->translationsTab['Disable on tablets'] = $this->l('Disable on tablets');
  3138. $this->translationsTab['Disable on computers'] = $this->l('Disable on computers');
  3139. $this->translationsTab['Display on mobiles'] = $this->l('Display on mobiles');
  3140. $this->translationsTab['Display on tablets'] = $this->l('Display on tablets');
  3141. $this->translationsTab['Display on computers'] = $this->l('Display on computers');
  3142. $this->translationsTab['Reset'] = $this->l('Reset');
  3143. $this->translationsTab['Configure'] = $this->l('Configure');
  3144. $this->translationsTab['Delete'] = $this->l('Delete');
  3145. $this->translationsTab['Install'] = $this->l('Install');
  3146. $this->translationsTab['Uninstall'] = $this->l('Uninstall');
  3147. $this->translationsTab['Would you like to delete the content related to this module ?'] = $this->l('Would you like to delete the content related to this module ?');
  3148. $this->translationsTab['This action will permanently remove the module from the server. Are you sure you want to do this?'] = $this->l('This action will permanently remove the module from the server. Are you sure you want to do this?');
  3149. $this->translationsTab['Remove from Favorites'] = $this->l('Remove from Favorites');
  3150. $this->translationsTab['Mark as Favorite'] = $this->l('Mark as Favorite');
  3151. }
  3152. $link_admin_modules = $this->context->link->getAdminLink('AdminModules', true);
  3153. $modules_options = array();
  3154. $configure_module = array(
  3155. 'href' => $link_admin_modules.'&configure='.urlencode($module->name).'&tab_module='.$module->tab.'&module_name='.urlencode($module->name),
  3156. 'onclick' => $module->onclick_option && isset($module->onclick_option_content['configure']) ? $module->onclick_option_content['configure'] : '',
  3157. 'title' => '',
  3158. 'text' => $this->translationsTab['Configure'],
  3159. 'cond' => $module->id && isset($module->is_configurable) && $module->is_configurable,
  3160. 'icon' => 'wrench',
  3161. );
  3162. $desactive_module = array(
  3163. 'href' => $link_admin_modules.'&module_name='.urlencode($module->name).'&'.($module->active ? 'enable=0' : 'enable=1').'&tab_module='.$module->tab,
  3164. 'onclick' => $module->active && $module->onclick_option && isset($module->onclick_option_content['desactive']) ? $module->onclick_option_content['desactive'] : '' ,
  3165. 'title' => Shop::isFeatureActive() ? htmlspecialchars($module->active ? $this->translationsTab['Disable this module'] : $this->translationsTab['Enable this module for all shops']) : '',
  3166. 'text' => $module->active ? $this->translationsTab['Disable'] : $this->translationsTab['Enable'],
  3167. 'cond' => $module->id,
  3168. 'icon' => 'off',
  3169. );
  3170. $link_reset_module = $link_admin_modules.'&module_name='.urlencode($module->name).'&reset&tab_module='.$module->tab;
  3171. $is_reset_ready = false;
  3172. if (Validate::isModuleName($module->name))
  3173. if (method_exists(Module::getInstanceByName($module->name), 'reset'))
  3174. $is_reset_ready = true;
  3175. $reset_module = array(
  3176. 'href' => $link_reset_module,
  3177. 'onclick' => $module->onclick_option && isset($module->onclick_option_content['reset']) ? $module->onclick_option_content['reset'] : '',
  3178. 'title' => '',
  3179. 'text' => $this->translationsTab['Reset'],
  3180. 'cond' => $module->id && $module->active,
  3181. 'icon' => 'undo',
  3182. 'class' => ($is_reset_ready ? 'reset_ready' : '')
  3183. );
  3184. $delete_module = array(
  3185. 'href' => $link_admin_modules.'&delete='.urlencode($module->name).'&tab_module='.$module->tab.'&module_name='.urlencode($module->name),
  3186. 'onclick' => $module->onclick_option && isset($module->onclick_option_content['delete']) ? $module->onclick_option_content['delete'] : 'return confirm(\''.$this->translationsTab['This action will permanently remove the module from the server. Are you sure you want to do this?'].'\');',
  3187. 'title' => '',
  3188. 'text' => $this->translationsTab['Delete'],
  3189. 'cond' => true,
  3190. 'icon' => 'trash',
  3191. 'class' => 'text-danger'
  3192. );
  3193. $display_mobile = array(
  3194. 'href' => $link_admin_modules.'&module_name='.urlencode($module->name).'&'.($module->enable_device & Context::DEVICE_MOBILE ? 'disable_device' : 'enable_device').'='.Context::DEVICE_MOBILE.'&tab_module='.$module->tab,
  3195. 'onclick' => '',
  3196. 'title' => htmlspecialchars($module->enable_device & Context::DEVICE_MOBILE ? $this->translationsTab['Disable on mobiles'] : $this->translationsTab['Display on mobiles']),
  3197. 'text' => $module->enable_device & Context::DEVICE_MOBILE ? $this->translationsTab['Disable on mobiles'] : $this->translationsTab['Display on mobiles'],
  3198. 'cond' => $module->id,
  3199. 'icon' => 'mobile'
  3200. );
  3201. $display_tablet = array(
  3202. 'href' => $link_admin_modules.'&module_name='.urlencode($module->name).'&'.($module->enable_device & Context::DEVICE_TABLET ? 'disable_device' : 'enable_device').'='.Context::DEVICE_TABLET.'&tab_module='.$module->tab,
  3203. 'onclick' => '',
  3204. 'title' => htmlspecialchars($module->enable_device & Context::DEVICE_TABLET ? $this->translationsTab['Disable on tablets'] : $this->translationsTab['Display on tablets']),
  3205. 'text' => $module->enable_device & Context::DEVICE_TABLET ? $this->translationsTab['Disable on tablets'] : $this->translationsTab['Display on tablets'],
  3206. 'cond' => $module->id,
  3207. 'icon' => 'tablet'
  3208. );
  3209. $display_computer = array(
  3210. 'href' => $link_admin_modules.'&module_name='.urlencode($module->name).'&'.($module->enable_device & Context::DEVICE_COMPUTER ? 'disable_device' : 'enable_device').'='.Context::DEVICE_COMPUTER.'&tab_module='.$module->tab,
  3211. 'onclick' => '',
  3212. 'title' => htmlspecialchars($module->enable_device & Context::DEVICE_COMPUTER ? $this->translationsTab['Disable on computers'] : $this->translationsTab['Display on computers']),
  3213. 'text' => $module->enable_device & Context::DEVICE_COMPUTER ? $this->translationsTab['Disable on computers'] : $this->translationsTab['Display on computers'],
  3214. 'cond' => $module->id,
  3215. 'icon' => 'desktop'
  3216. );
  3217. $install = array(
  3218. 'href' => $link_admin_modules.'&install='.urlencode($module->name).'&tab_module='.$module->tab.'&module_name='.$module->name.'&anchor='.ucfirst($module->name).(!is_null($back) ? '&back='.urlencode($back) : ''),
  3219. 'onclick' => '',
  3220. 'title' => $this->translationsTab['Install'],
  3221. 'text' => $this->translationsTab['Install'],
  3222. 'cond' => $module->id,
  3223. 'icon' => 'plus-sign-alt'
  3224. );
  3225. $uninstall = array(
  3226. 'href' => $link_admin_modules.'&uninstall='.urlencode($module->name).'&tab_module='.$module->tab.'&module_name='.$module->name.'&anchor='.ucfirst($module->name).(!is_null($back) ? '&back='.urlencode($back) : ''),
  3227. 'onclick' => (isset($module->onclick_option_content['uninstall']) ? $module->onclick_option_content['uninstall'] : 'return confirm(\''.$this->translationsTab['confirm_uninstall_popup'].'\');'),
  3228. 'title' => $this->translationsTab['Uninstall'],
  3229. 'text' => $this->translationsTab['Uninstall'],
  3230. 'cond' => $module->id,
  3231. 'icon' => 'minus-sign-alt'
  3232. );
  3233. $remove_from_favorite = array(
  3234. 'href' => '#',
  3235. 'class' => 'action_unfavorite toggle_favorite',
  3236. 'onclick' =>'',
  3237. 'title' => $this->translationsTab['Remove from Favorites'],
  3238. 'text' => $this->translationsTab['Remove from Favorites'],
  3239. 'cond' => $module->id,
  3240. 'icon' => 'star',
  3241. 'data-value' => '0',
  3242. 'data-module' => $module->name
  3243. );
  3244. $mark_as_favorite = array(
  3245. 'href' => '#',
  3246. 'class' => 'action_favorite toggle_favorite',
  3247. 'onclick' => '',
  3248. 'title' => $this->translationsTab['Mark as Favorite'],
  3249. 'text' => $this->translationsTab['Mark as Favorite'],
  3250. 'cond' => $module->id,
  3251. 'icon' => 'star',
  3252. 'data-value' => '1',
  3253. 'data-module' => $module->name
  3254. );
  3255. $update = array(
  3256. 'href' => $module->options['update_url'],
  3257. 'onclick' => '',
  3258. 'title' => 'Update it!',
  3259. 'text' => 'Update it!',
  3260. 'icon' => 'refresh',
  3261. 'cond' => $module->id,
  3262. );
  3263. $divider = array(
  3264. 'href' => '#',
  3265. 'onclick' => '',
  3266. 'title' => 'divider',
  3267. 'text' => 'divider',
  3268. 'cond' => $module->id,
  3269. );
  3270. if (isset($module->version_addons) && $module->version_addons)
  3271. $modules_options[] = $update;
  3272. if ($module->active)
  3273. {
  3274. $modules_options[] = $configure_module;
  3275. $modules_options[] = $desactive_module;
  3276. $modules_options[] = $display_mobile;
  3277. $modules_options[] = $display_tablet;
  3278. $modules_options[] = $display_computer;
  3279. }
  3280. else
  3281. {
  3282. $modules_options[] = $desactive_module;
  3283. $modules_options[] = $configure_module;
  3284. }
  3285. $modules_options[] = $reset_module;
  3286. if ($output_type == 'select')
  3287. {
  3288. if (!$module->id)
  3289. $modules_options[] = $install;
  3290. else
  3291. $modules_options[] = $uninstall;
  3292. }
  3293. else if ($output_type == 'array')
  3294. if ($module->id)
  3295. $modules_options[] = $uninstall;
  3296. if (isset($module->preferences) && isset($module->preferences['favorite']) && $module->preferences['favorite'] == 1)
  3297. {
  3298. $remove_from_favorite['style'] = '';
  3299. $mark_as_favorite['style'] = 'display:none;';
  3300. $modules_options[] = $remove_from_favorite;
  3301. $modules_options[] = $mark_as_favorite;
  3302. }
  3303. else
  3304. {
  3305. $mark_as_favorite['style'] = '';
  3306. $remove_from_favorite['style'] = 'display:none;';
  3307. $modules_options[] = $remove_from_favorite;
  3308. $modules_options[] = $mark_as_favorite;
  3309. }
  3310. if ($module->id == 0)
  3311. {
  3312. $install['cond'] = 1;
  3313. $install['flag_install'] = 1;
  3314. $modules_options[] = $install;
  3315. }
  3316. $modules_options[] = $divider;
  3317. $modules_options[] = $delete_module;
  3318. $return = '';
  3319. foreach ($modules_options as $option_name => $option)
  3320. {
  3321. if ($option['cond'])
  3322. {
  3323. if ($output_type == 'link')
  3324. {
  3325. $return .= '<li><a class="'.$option_name.' action_module';
  3326. $return .='" href="'.$option['href'].(!is_null($back) ? '&back='.urlencode($back) : '').'"';
  3327. $return .=' onclick="'.$option['onclick'].'" title="'.$option['title'].'"><i class="icon-'.(isset($option['icon']) && $option['icon'] ? $option['icon']:'cog' ).'"></i>&nbsp;'.$option['text'].'</a></li>';
  3328. }
  3329. elseif ($output_type == 'array')
  3330. {
  3331. if (!is_array($return))
  3332. $return = array();
  3333. $html = '<a class="';
  3334. $is_install = isset($option['flag_install']) ? true : false;
  3335. if (isset($option['class']))
  3336. $html .= $option['class'];
  3337. if ($is_install)
  3338. $html .= ' btn btn-success';
  3339. if (!$is_install && count($return) == 0)
  3340. $html .= ' btn btn-default';
  3341. $html .= '"';
  3342. if (isset($option['data-value']))
  3343. $html .= ' data-value="'.$option['data-value'].'"';
  3344. if (isset($option['data-module']))
  3345. $html .= ' data-module="'.$option['data-module'].'"';
  3346. if (isset($option['style']))
  3347. $html .= ' style="'.$option['style'].'"';
  3348. $html .= ' href="'.htmlentities($option['href']).(!is_null($back) ? '&back='.urlencode($back) : '').'" onclick="'.$option['onclick'].'" title="'.$option['title'].'"><i class="icon-'.(isset($option['icon']) && $option['icon'] ? $option['icon']:'cog' ).'"></i> '.$option['text'].'</a>';
  3349. $return[] = $html;
  3350. }
  3351. elseif ($output_type == 'select')
  3352. $return .= '<option id="'.$option_name.'" data-href="'.htmlentities($option['href']).(!is_null($back) ? '&back='.urlencode($back) : '').'" data-onclick="'.$option['onclick'].'">'.$option['text'].'</option>';
  3353. }
  3354. }
  3355. if ($output_type == 'select')
  3356. $return = '<select id="select_'.$module->name.'">'.$return.'</select>';
  3357. return $return;
  3358. }
  3359. public function ajaxProcessGetModuleQuickView()
  3360. {
  3361. $modules = Module::getModulesOnDisk();
  3362. foreach ($modules as $module)
  3363. if ($module->name == Tools::getValue('module'))
  3364. break;
  3365. $url = $module->url;
  3366. if (isset($module->type) && ($module->type == 'addonsPartner' || $module->type == 'addonsNative'))
  3367. $url = $this->context->link->getAdminLink('AdminModules').'&install='.urlencode($module->name).'&tab_module='.$module->tab.'&module_name='.$module->name.'&anchor='.ucfirst($module->name);
  3368. $this->context->smarty->assign(array(
  3369. 'displayName' => $module->displayName,
  3370. 'image' => $module->image,
  3371. 'nb_rates' => (int)$module->nb_rates[0],
  3372. 'avg_rate' => (int)$module->avg_rate[0],
  3373. 'badges' => $module->badges,
  3374. 'compatibility' => $module->compatibility,
  3375. 'description_full' => $module->description_full,
  3376. 'additional_description' => $module->additional_description,
  3377. 'is_addons_partner' => (isset($module->type) && ($module->type == 'addonsPartner' || $module->type == 'addonsNative')),
  3378. 'url' => $url,
  3379. 'price' => $module->price
  3380. ));
  3381. // Fetch the translations in the right place - they are not defined by our current controller!
  3382. Context::getContext()->override_controller_name_for_translations = 'AdminModules';
  3383. $this->smartyOutputContent('controllers/modules/quickview.tpl');
  3384. die(1);
  3385. }
  3386. }