PageRenderTime 63ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/classes/controller/AdminController.php

https://github.com/cokarmando/PrestaShop
PHP | 2979 lines | 2125 code | 357 blank | 497 comment | 583 complexity | eeaf6d4c756876622106026044b04d10 MD5 | raw file
  1. <?php
  2. /*
  3. * 2007-2013 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-2013 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. protected $meta_title;
  40. public $template = 'content.tpl';
  41. /** @var string Associated table name */
  42. public $table;
  43. /** @var string Object identifier inside the associated table */
  44. protected $identifier = false;
  45. /** @var string Tab name */
  46. public $className;
  47. /** @var array tabAccess */
  48. public $tabAccess;
  49. /** @var integer Tab id */
  50. public $id = -1;
  51. public $required_database = false;
  52. /** @var string Security token */
  53. public $token;
  54. /** @var string shop | group_shop */
  55. public $shopLinkType;
  56. /** @var string Default ORDER BY clause when $_orderBy is not defined */
  57. protected $_defaultOrderBy = false;
  58. protected $_defaultOrderWay = 'ASC';
  59. public $tpl_form_vars = array();
  60. public $tpl_list_vars = array();
  61. public $tpl_delete_link_vars = array();
  62. public $tpl_option_vars = array();
  63. public $tpl_view_vars = array();
  64. public $tpl_required_fields_vars = array();
  65. public $base_tpl_view = null;
  66. public $base_tpl_form = null;
  67. /** @var bool if you want more fieldsets in the form */
  68. public $multiple_fieldsets = false;
  69. public $fields_value = false;
  70. /** @var array Errors displayed after post processing */
  71. public $errors = array();
  72. /** @var define if the header of the list contains filter and sorting links or not */
  73. protected $list_simple_header;
  74. /** @var array list to be generated */
  75. protected $fields_list;
  76. /** @var array modules list filters */
  77. protected $filter_modules_list = null;
  78. /** @var array modules list filters */
  79. protected $modules_list = array();
  80. /** @var array edit form to be generated */
  81. protected $fields_form;
  82. /** @var override of $fields_form */
  83. protected $fields_form_override;
  84. /** @var array list of option forms to be generated */
  85. protected $fields_options;
  86. protected $shopLink;
  87. /** @var string SQL query */
  88. protected $_listsql = '';
  89. /** @var array Cache for query results */
  90. protected $_list = array();
  91. /** @var define if the header of the list contains filter and sorting links or not */
  92. protected $toolbar_title;
  93. /** @var array list of toolbar buttons */
  94. protected $toolbar_btn = null;
  95. /** @var boolean scrolling toolbar */
  96. protected $toolbar_scroll = true;
  97. /** @var boolean set to false to hide toolbar and page title */
  98. protected $show_toolbar = true;
  99. /** @var boolean set to true to show toolbar and page title for options */
  100. protected $show_toolbar_options = false;
  101. /** @var integer Number of results in list */
  102. protected $_listTotal = 0;
  103. /** @var boolean Automatically join language table if true */
  104. public $lang = false;
  105. /** @var array WHERE clause determined by filter fields */
  106. protected $_filter;
  107. /** @var array Temporary SQL table WHERE clause determinated by filter fields */
  108. protected $_tmpTableFilter = '';
  109. /** @var array Number of results in list per page (used in select field) */
  110. protected $_pagination = array(20, 50, 100, 300);
  111. /** @var string ORDER BY clause determined by field/arrows in list header */
  112. protected $_orderBy;
  113. /** @var string Order way (ASC, DESC) determined by arrows in list header */
  114. protected $_orderWay;
  115. /** @var array list of available actions for each list row - default actions are view, edit, delete, duplicate */
  116. protected $actions_available = array('view', 'edit', 'delete', 'duplicate');
  117. /** @var array list of required actions for each list row */
  118. protected $actions = array();
  119. /** @var array list of row ids associated with a given action for witch this action have to not be available */
  120. protected $list_skip_actions = array();
  121. /* @var boolean don't show header & footer */
  122. protected $lite_display = false;
  123. /** @var bool boolean List content lines are clickable if true */
  124. protected $list_no_link = false;
  125. protected $allow_export = false;
  126. /** @var array $cache_lang cache for traduction */
  127. public static $cache_lang = array();
  128. /** @var array required_fields to display in the Required Fields form */
  129. public $required_fields = array();
  130. /** @var Helper */
  131. protected $helper;
  132. /**
  133. * @var array actions to execute on multiple selections
  134. * Usage:
  135. * array(
  136. * 'actionName' => array(
  137. * 'text' => $this->l('Message displayed on the submit button (mandatory)'),
  138. * 'confirm' => $this->l('If set, this confirmation message will pop-up (optional)')),
  139. * 'anotherAction' => array(...)
  140. * );
  141. *
  142. * If your action is named 'actionName', you need to have a method named bulkactionName() that will be executed when the button is clicked.
  143. */
  144. protected $bulk_actions;
  145. /**
  146. * @var array ids of the rows selected
  147. */
  148. protected $boxes;
  149. /** @var string Do not automatically select * anymore but select only what is necessary */
  150. protected $explicitSelect = false;
  151. /** @var string Add fields into data query to display list */
  152. protected $_select;
  153. /** @var string Join tables into data query to display list */
  154. protected $_join;
  155. /** @var string Add conditions into data query to display list */
  156. protected $_where;
  157. /** @var string Group rows into data query to display list */
  158. protected $_group;
  159. /** @var string Having rows into data query to display list */
  160. protected $_having;
  161. protected $is_cms = false;
  162. /** @var string identifier to use for changing positions in lists (can be omitted if positions cannot be changed) */
  163. protected $position_identifier;
  164. /** @var boolean Table records are not deleted but marked as deleted if set to true */
  165. protected $deleted = false;
  166. /**
  167. * @var bool is a list filter set
  168. */
  169. protected $filter;
  170. protected $noLink;
  171. protected $specificConfirmDelete = null;
  172. protected $colorOnBackground;
  173. /** @var bool If true, activates color on hover */
  174. protected $row_hover = true;
  175. /** @string Action to perform : 'edit', 'view', 'add', ... */
  176. protected $action;
  177. protected $display;
  178. protected $_includeContainer = true;
  179. protected $tab_modules_list = array('default_list' => array(), 'slider_list' => array());
  180. public $tpl_folder;
  181. protected $bo_theme;
  182. /** @var bool Redirect or not ater a creation */
  183. protected $_redirect = true;
  184. /** @var array Name and directory where class image are located */
  185. public $fieldImageSettings = array();
  186. /** @var string Image type */
  187. public $imageType = 'jpg';
  188. /** @var instanciation of the class associated with the AdminController */
  189. protected $object;
  190. /** @var current object ID */
  191. protected $id_object;
  192. /**
  193. * @var current controller name without suffix
  194. */
  195. public $controller_name;
  196. public $multishop_context = -1;
  197. public $multishop_context_group = true;
  198. /**
  199. * Current breadcrumb position as an array of tab names
  200. */
  201. protected $breadcrumbs;
  202. public function __construct()
  203. {
  204. global $timer_start;
  205. $this->timer_start = $timer_start;
  206. // Has to be remove for the next Prestashop version
  207. global $token;
  208. $this->controller_type = 'admin';
  209. $this->controller_name = get_class($this);
  210. if (strpos($this->controller_name, 'Controller'))
  211. $this->controller_name = substr($this->controller_name, 0, -10);
  212. parent::__construct();
  213. if ($this->multishop_context == -1)
  214. $this->multishop_context = Shop::CONTEXT_ALL | Shop::CONTEXT_GROUP | Shop::CONTEXT_SHOP;
  215. $this->bo_theme = ((Validate::isLoadedObject($this->context->employee) && $this->context->employee->bo_theme) ? $this->context->employee->bo_theme : 'default');
  216. if (!file_exists(_PS_BO_ALL_THEMES_DIR_.$this->bo_theme.DIRECTORY_SEPARATOR.'template'))
  217. $this->bo_theme = 'default';
  218. $this->context->smarty->setTemplateDir(array(
  219. _PS_BO_ALL_THEMES_DIR_.$this->bo_theme.DIRECTORY_SEPARATOR.'template',
  220. _PS_OVERRIDE_DIR_.'controllers'.DIRECTORY_SEPARATOR.'admin'.DIRECTORY_SEPARATOR.'templates'
  221. ));
  222. $this->id = Tab::getIdFromClassName($this->controller_name);
  223. $this->token = Tools::getAdminToken($this->controller_name.(int)$this->id.(int)$this->context->employee->id);
  224. $token = $this->token;
  225. $this->_conf = array(
  226. 1 => $this->l('Deletion successful'), 2 => $this->l('The selection has been successfully deleted.'),
  227. 3 => $this->l('Creation successful'), 4 => $this->l('Update successful'),
  228. 5 => $this->l('The status has been updated successfully.'), 6 => $this->l('The settings have been updated successfully.'),
  229. 7 => $this->l('The image was successfully deleted.'), 8 => $this->l('The module was downloaded successfully.'),
  230. 9 => $this->l('The thumbnails were successfully regenerated.'), 10 => $this->l('Message sent to the customer.'),
  231. 11 => $this->l('Comment added'), 12 => $this->l('Module(s) installed successfully.'),
  232. 13 => $this->l('Module(s) uninstalled successfully.'), 14 => $this->l('The translation was successfully copied.'),
  233. 15 => $this->l('The translations have been successfully added.'), 16 => $this->l('The module transplanted successfully to the hook.'),
  234. 17 => $this->l('The module was successfully removed from the hook.'), 18 => $this->l('Upload successful'),
  235. 19 => $this->l('Duplication was completed successfully.'), 20 => $this->l('The translation was added successfully, but the language has not been created.'),
  236. 21 => $this->l('Module reset successfully.'), 22 => $this->l('Module deleted successfully.'),
  237. 23 => $this->l('Localization pack imported successfully.'), 24 => $this->l('Localization pack imported successfully.'),
  238. 25 => $this->l('The selcted images have successfully been moved.'),
  239. 26 => $this->l('Your cover selection has been saved.'),
  240. 27 => $this->l('The image shop association has been modified.'),
  241. 28 => $this->l('A zone has been assigned to the selection successfully.'),
  242. 29 => $this->l('Upgrade successful'),
  243. 30 => $this->l('A partial refund was successfully created.'),
  244. 31 => $this->l('The discount was successfully generated.')
  245. );
  246. if (!$this->identifier) $this->identifier = 'id_'.$this->table;
  247. if (!$this->_defaultOrderBy) $this->_defaultOrderBy = $this->identifier;
  248. $this->tabAccess = Profile::getProfileAccess($this->context->employee->id_profile, $this->id);
  249. // Fix for AdminHome
  250. if ($this->controller_name == 'AdminHome')
  251. $_POST['token'] = $this->token;
  252. if (!Shop::isFeatureActive())
  253. $this->shopLinkType = '';
  254. //$this->base_template_folder = _PS_BO_ALL_THEMES_DIR_.$this->bo_theme.'/template';
  255. $this->override_folder = Tools::toUnderscoreCase(substr($this->controller_name, 5)).'/';
  256. // Get the name of the folder containing the custom tpl files
  257. $this->tpl_folder = Tools::toUnderscoreCase(substr($this->controller_name, 5)).'/';
  258. $this->initShopContext();
  259. $this->context->currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));
  260. }
  261. /**
  262. * Set breadcrumbs array for the controller page
  263. */
  264. public function initBreadcrumbs()
  265. {
  266. $tabs = array();
  267. $tabs = Tab::recursiveTab($this->id, $tabs);
  268. $tabs = array_reverse($tabs);
  269. foreach ($tabs as $tab)
  270. $this->breadcrumbs[] = $tab['name'];
  271. }
  272. /**
  273. * set default toolbar_title to admin breadcrumb
  274. *
  275. * @return void
  276. */
  277. public function initToolbarTitle()
  278. {
  279. $bread_extended = array_unique($this->breadcrumbs);
  280. switch ($this->display)
  281. {
  282. case 'edit':
  283. $bread_extended[] = $this->l('Edit');
  284. break;
  285. case 'add':
  286. $bread_extended[] = $this->l('Add new');
  287. break;
  288. case 'view':
  289. $bread_extended[] = $this->l('View');
  290. break;
  291. }
  292. $this->toolbar_title = $bread_extended;
  293. }
  294. /**
  295. * Check rights to view the current tab
  296. *
  297. * @param bool $disable
  298. * @return boolean
  299. */
  300. public function viewAccess($disable = false)
  301. {
  302. if ($disable)
  303. return true;
  304. if ($this->tabAccess['view'] === '1')
  305. return true;
  306. return false;
  307. }
  308. /**
  309. * Check for security token
  310. */
  311. public function checkToken()
  312. {
  313. $token = Tools::getValue('token');
  314. return (!empty($token) && $token === $this->token);
  315. }
  316. public function ajaxProcessHelpAccess()
  317. {
  318. $this->json = true;
  319. $item = Tools::getValue('item');
  320. $iso_user = Tools::getValue('isoUser');
  321. $country = Tools::getValue('country');
  322. $version = Tools::getValue('version');
  323. if (isset($item) && isset($iso_user) && isset($country))
  324. {
  325. $helper = new HelperHelpAccess($item, $iso_user, $country, $version);
  326. $this->content = $helper->generate();
  327. }
  328. else
  329. $this->content = 'none';
  330. $this->display = 'content';
  331. }
  332. /**
  333. * Set the filters used for the list display
  334. */
  335. public function processFilter()
  336. {
  337. $prefix = str_replace(array('admin', 'controller'), '', Tools::strtolower(get_class($this)));
  338. // Filter memorization
  339. if (isset($_POST) && !empty($_POST) && isset($this->table))
  340. foreach ($_POST as $key => $value)
  341. {
  342. if (stripos($key, $this->table.'Filter_') === 0)
  343. $this->context->cookie->{$prefix.$key} = !is_array($value) ? $value : serialize($value);
  344. elseif(stripos($key, 'submitFilter') === 0)
  345. $this->context->cookie->$key = !is_array($value) ? $value : serialize($value);
  346. }
  347. if (isset($_GET) && !empty($_GET) && isset($this->table))
  348. foreach ($_GET as $key => $value)
  349. if (stripos($key, $this->table.'OrderBy') === 0 || stripos($key, $this->table.'Orderway') === 0)
  350. $this->context->cookie->{$prefix.$key} = $value;
  351. $filters = $this->context->cookie->getFamily($prefix.$this->table.'Filter_');
  352. foreach ($filters as $key => $value)
  353. {
  354. /* Extracting filters from $_POST on key filter_ */
  355. if ($value != null && !strncmp($key, $prefix.$this->table.'Filter_', 7 + Tools::strlen($prefix.$this->table)))
  356. {
  357. $key = Tools::substr($key, 7 + Tools::strlen($prefix.$this->table));
  358. /* Table alias could be specified using a ! eg. alias!field */
  359. $tmp_tab = explode('!', $key);
  360. $filter = count($tmp_tab) > 1 ? $tmp_tab[1] : $tmp_tab[0];
  361. if ($field = $this->filterToField($key, $filter))
  362. {
  363. $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))
  364. $value = Tools::unSerialize($value);
  365. $key = isset($tmp_tab[1]) ? $tmp_tab[0].'.`'.$tmp_tab[1].'`' : '`'.$tmp_tab[0].'`';
  366. // Assignement by reference
  367. if (array_key_exists('tmpTableFilter', $field))
  368. $sql_filter = & $this->_tmpTableFilter;
  369. elseif (array_key_exists('havingFilter', $field))
  370. $sql_filter = & $this->_filterHaving;
  371. else
  372. $sql_filter = & $this->_filter;
  373. /* Only for date filtering (from, to) */
  374. if (is_array($value))
  375. {
  376. if (isset($value[0]) && !empty($value[0]))
  377. {
  378. if (!Validate::isDate($value[0]))
  379. $this->errors[] = Tools::displayError('The \'From\' date format is invalid (YYYY-MM-DD)');
  380. else
  381. $sql_filter .= ' AND '.pSQL($key).' >= \''.pSQL(Tools::dateFrom($value[0])).'\'';
  382. }
  383. if (isset($value[1]) && !empty($value[1]))
  384. {
  385. if (!Validate::isDate($value[1]))
  386. $this->errors[] = Tools::displayError('The \'To\' date format is invalid (YYYY-MM-DD)');
  387. else
  388. $sql_filter .= ' AND '.pSQL($key).' <= \''.pSQL(Tools::dateTo($value[1])).'\'';
  389. }
  390. }
  391. else
  392. {
  393. $sql_filter .= ' AND ';
  394. $check_key = ($key == $this->identifier || $key == '`'.$this->identifier.'`');
  395. if ($type == 'int' || $type == 'bool')
  396. $sql_filter .= (($check_key || $key == '`active`') ? 'a.' : '').pSQL($key).' = '.(int)$value.' ';
  397. elseif ($type == 'decimal')
  398. $sql_filter .= ($check_key ? 'a.' : '').pSQL($key).' = '.(float)$value.' ';
  399. elseif ($type == 'select')
  400. $sql_filter .= ($check_key ? 'a.' : '').pSQL($key).' = \''.pSQL($value).'\' ';
  401. else
  402. $sql_filter .= ($check_key ? 'a.' : '').pSQL($key).' LIKE \'%'.pSQL($value).'%\' ';
  403. }
  404. }
  405. }
  406. }
  407. }
  408. /**
  409. * @todo uses redirectAdmin only if !$this->ajax
  410. */
  411. public function postProcess()
  412. {
  413. if ($this->ajax)
  414. {
  415. // from ajax-tab.php
  416. $action = Tools::getValue('action');
  417. // no need to use displayConf() here
  418. if (!empty($action) && method_exists($this, 'ajaxProcess'.Tools::toCamelCase($action)))
  419. return $this->{'ajaxProcess'.Tools::toCamelCase($action)}();
  420. elseif (method_exists($this, 'ajaxProcess'))
  421. return $this->ajaxProcess();
  422. }
  423. else
  424. {
  425. // Process list filtering
  426. if ($this->filter)
  427. $this->processFilter();
  428. // If the method named after the action exists, call "before" hooks, then call action method, then call "after" hooks
  429. if (!empty($this->action) && method_exists($this, 'process'.ucfirst(Tools::toCamelCase($this->action))))
  430. {
  431. // Hook before action
  432. Hook::exec('actionAdmin'.ucfirst($this->action).'Before', array('controller' => $this));
  433. Hook::exec('action'.get_class($this).ucfirst($this->action).'Before', array('controller' => $this));
  434. // Call process
  435. $return = $this->{'process'.Tools::toCamelCase($this->action)}();
  436. // Hook After Action
  437. Hook::exec('actionAdmin'.ucfirst($this->action).'After', array('controller' => $this, 'return' => $return));
  438. Hook::exec('action'.get_class($this).ucfirst($this->action).'After', array('controller' => $this, 'return' => $return));
  439. return $return;
  440. }
  441. }
  442. }
  443. /**
  444. * Object Delete images
  445. */
  446. public function processDeleteImage()
  447. {
  448. if (Validate::isLoadedObject($object = $this->loadObject()))
  449. {
  450. if (($object->deleteImage()))
  451. {
  452. $redirect = self::$currentIndex.'&add'.$this->table.'&'.$this->identifier.'='.Tools::getValue($this->identifier).'&conf=7&token='.$this->token;
  453. if (!$this->ajax)
  454. $this->redirect_after = $redirect;
  455. else
  456. $this->content = 'ok';
  457. }
  458. }
  459. $this->errors[] = Tools::displayError('An error occurred while attempting to delet the image. (cannot load object).');
  460. return $object;
  461. }
  462. public function processExport()
  463. {
  464. // clean buffer
  465. if (ob_get_level() && ob_get_length() > 0)
  466. ob_clean();
  467. $this->getList($this->context->language->id);
  468. if (!count($this->_list))
  469. return;
  470. header('Content-type: text/csv');
  471. header('Content-Type: application/force-download; charset=UTF-8');
  472. header('Cache-Control: no-store, no-cache');
  473. header('Content-disposition: attachment; filename="'.$this->table.'_'.date('Y-m-d_His').'.csv"');
  474. $headers = array();
  475. foreach ($this->fields_list as $datas)
  476. $headers[] = Tools::htmlentitiesDecodeUTF8($datas['title']);
  477. $content = array();
  478. foreach ($this->_list as $i => $row)
  479. {
  480. $content[$i] = array();
  481. foreach ($this->fields_list as $key => $value)
  482. if (isset($row[$key]))
  483. $content[$i][] = Tools::htmlentitiesDecodeUTF8($row[$key]);
  484. }
  485. $this->context->smarty->assign(array(
  486. 'export_precontent' => "\xEF\xBB\xBF",
  487. 'export_headers' => $headers,
  488. 'export_content' => $content
  489. )
  490. );
  491. $this->layout = 'layout-export.tpl';
  492. }
  493. /**
  494. * Object Delete
  495. */
  496. public function processDelete()
  497. {
  498. if (Validate::isLoadedObject($object = $this->loadObject()))
  499. {
  500. $res = true;
  501. // check if request at least one object with noZeroObject
  502. if (isset($object->noZeroObject) && count(call_user_func(array($this->className, $object->noZeroObject))) <= 1)
  503. {
  504. $this->errors[] = Tools::displayError('You need at least one object.').
  505. ' <b>'.$this->table.'</b><br />'.
  506. Tools::displayError('You cannot delete all of the items.');
  507. }
  508. 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
  509. $this->errors[] = Tools::displayError('You cannot delete this item.');
  510. else
  511. {
  512. if ($this->deleted)
  513. {
  514. if (!empty($this->fieldImageSettings))
  515. $res = $object->deleteImage();
  516. if (!$res)
  517. $this->errors[] = Tools::displayError('Unable to delete associated images.');
  518. $object->deleted = 1;
  519. if ($object->update())
  520. $this->redirect_after = self::$currentIndex.'&conf=1&token='.$this->token;
  521. }
  522. elseif ($object->delete())
  523. $this->redirect_after = self::$currentIndex.'&conf=1&token='.$this->token;
  524. $this->errors[] = Tools::displayError('An error occurred during deletion.');
  525. }
  526. }
  527. else
  528. {
  529. $this->errors[] = Tools::displayError('An error occurred while deleting the object.').
  530. ' <b>'.$this->table.'</b> '.
  531. Tools::displayError('(cannot load object)');
  532. }
  533. return $object;
  534. }
  535. /**
  536. * Call the right method for creating or updating object
  537. *
  538. * @return mixed
  539. */
  540. public function processSave()
  541. {
  542. if ($this->id_object)
  543. {
  544. $this->object = $this->loadObject();
  545. return $this->processUpdate();
  546. }
  547. else
  548. return $this->processAdd();
  549. }
  550. /**
  551. * Object creation
  552. */
  553. public function processAdd()
  554. {
  555. /* Checking fields validity */
  556. $this->validateRules();
  557. if (count($this->errors) <= 0)
  558. {
  559. $this->object = new $this->className();
  560. $this->copyFromPost($this->object, $this->table);
  561. $this->beforeAdd($this->object);
  562. if (method_exists($this->object, 'add') && !$this->object->add())
  563. {
  564. $this->errors[] = Tools::displayError('An error occurred while creating an object.').
  565. ' <b>'.$this->table.' ('.Db::getInstance()->getMsgError().')</b>';
  566. }
  567. /* voluntary do affectation here */
  568. elseif (($_POST[$this->identifier] = $this->object->id) && $this->postImage($this->object->id) && !count($this->errors) && $this->_redirect)
  569. {
  570. $parent_id = (int)Tools::getValue('id_parent', 1);
  571. $this->afterAdd($this->object);
  572. $this->updateAssoShop($this->object->id);
  573. // Save and stay on same form
  574. if (empty($this->redirect_after) && $this->redirect_after !== false && Tools::isSubmit('submitAdd'.$this->table.'AndStay'))
  575. $this->redirect_after = self::$currentIndex.'&'.$this->identifier.'='.$this->object->id.'&conf=3&update'.$this->table.'&token='.$this->token;
  576. // Save and back to parent
  577. if (empty($this->redirect_after) && $this->redirect_after !== false && Tools::isSubmit('submitAdd'.$this->table.'AndBackToParent'))
  578. $this->redirect_after = self::$currentIndex.'&'.$this->identifier.'='.$parent_id.'&conf=3&token='.$this->token;
  579. // Default behavior (save and back)
  580. if (empty($this->redirect_after) && $this->redirect_after !== false)
  581. $this->redirect_after = self::$currentIndex.($parent_id ? '&'.$this->identifier.'='.$this->object->id : '').'&conf=3&token='.$this->token;
  582. }
  583. }
  584. $this->errors = array_unique($this->errors);
  585. if (!empty($this->errors))
  586. {
  587. // if we have errors, we stay on the form instead of going back to the list
  588. $this->display = 'edit';
  589. return false;
  590. }
  591. return $this->object;
  592. }
  593. /**
  594. * Object update
  595. */
  596. public function processUpdate()
  597. {
  598. /* Checking fields validity */
  599. $this->validateRules();
  600. if (empty($this->errors))
  601. {
  602. $id = (int)Tools::getValue($this->identifier);
  603. /* Object update */
  604. if (isset($id) && !empty($id))
  605. {
  606. $object = new $this->className($id);
  607. if (Validate::isLoadedObject($object))
  608. {
  609. /* Specific to objects which must not be deleted */
  610. if ($this->deleted && $this->beforeDelete($object))
  611. {
  612. // Create new one with old objet values
  613. $object_new = $object->duplicateObject();
  614. if (Validate::isLoadedObject($object_new))
  615. {
  616. // Update old object to deleted
  617. $object->deleted = 1;
  618. $object->update();
  619. // Update new object with post values
  620. $this->copyFromPost($object_new, $this->table);
  621. $result = $object_new->update();
  622. if (Validate::isLoadedObject($object_new))
  623. $this->afterDelete($object_new, $object->id);
  624. }
  625. }
  626. else
  627. {
  628. $this->copyFromPost($object, $this->table);
  629. $result = $object->update();
  630. $this->afterUpdate($object);
  631. }
  632. if ($object->id)
  633. $this->updateAssoShop($object->id);
  634. if (!$result)
  635. {
  636. $this->errors[] = Tools::displayError('An error occurred while updating an object.').
  637. ' <b>'.$this->table.'</b> ('.Db::getInstance()->getMsgError().')';
  638. }
  639. elseif ($this->postImage($object->id) && !count($this->errors) && $this->_redirect)
  640. {
  641. $parent_id = (int)Tools::getValue('id_parent', 1);
  642. // Specific back redirect
  643. if ($back = Tools::getValue('back'))
  644. $this->redirect_after = urldecode($back).'&conf=4';
  645. // Specific scene feature
  646. // @todo change stay_here submit name (not clear for redirect to scene ... )
  647. if (Tools::getValue('stay_here') == 'on' || Tools::getValue('stay_here') == 'true' || Tools::getValue('stay_here') == '1')
  648. $this->redirect_after = self::$currentIndex.'&'.$this->identifier.'='.$object->id.'&conf=4&updatescene&token='.$this->token;
  649. // Save and stay on same form
  650. // @todo on the to following if, we may prefer to avoid override redirect_after previous value
  651. if (Tools::isSubmit('submitAdd'.$this->table.'AndStay'))
  652. $this->redirect_after = self::$currentIndex.'&'.$this->identifier.'='.$object->id.'&conf=4&update'.$this->table.'&token='.$this->token;
  653. // Save and back to parent
  654. if (Tools::isSubmit('submitAdd'.$this->table.'AndBackToParent'))
  655. $this->redirect_after = self::$currentIndex.'&'.$this->identifier.'='.$parent_id.'&conf=4&token='.$this->token;
  656. // Default behavior (save and back)
  657. if (empty($this->redirect_after))
  658. $this->redirect_after = self::$currentIndex.($parent_id ? '&'.$this->identifier.'='.$object->id : '').'&conf=4&token='.$this->token;
  659. }
  660. }
  661. else
  662. $this->errors[] = Tools::displayError('An error occurred while updating an object.').
  663. ' <b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)');
  664. }
  665. }
  666. $this->errors = array_unique($this->errors);
  667. if (!empty($this->errors))
  668. {
  669. // if we have errors, we stay on the form instead of going back to the list
  670. $this->display = 'edit';
  671. return false;
  672. }
  673. if (isset($object))
  674. return $object;
  675. return;
  676. }
  677. /**
  678. * Change object required fields
  679. */
  680. public function processUpdateFields()
  681. {
  682. if (!is_array($fields = Tools::getValue('fieldsBox')))
  683. $fields = array();
  684. $object = new $this->className();
  685. if (!$object->addFieldsRequiredDatabase($fields))
  686. $this->errors[] = Tools::displayError('An error occurred when attempting to update the required fields.');
  687. else
  688. $this->redirect_after = self::$currentIndex.'&conf=4&token='.$this->token;
  689. return $object;
  690. }
  691. /**
  692. * Change object status (active, inactive)
  693. */
  694. public function processStatus()
  695. {
  696. if (Validate::isLoadedObject($object = $this->loadObject()))
  697. {
  698. if ($object->toggleStatus())
  699. {
  700. $id_category = (($id_category = (int)Tools::getValue('id_category')) && Tools::getValue('id_product')) ? '&id_category='.$id_category : '';
  701. $this->redirect_after = self::$currentIndex.'&conf=5'.$id_category.'&token='.$this->token;
  702. }
  703. else
  704. $this->errors[] = Tools::displayError('An error occurred while updating the status.');
  705. }
  706. else
  707. $this->errors[] = Tools::displayError('An error occurred while updating the status for an object.').
  708. ' <b>'.$this->table.'</b> '.
  709. Tools::displayError('(cannot load object)');
  710. return $object;
  711. }
  712. /**
  713. * Change object position
  714. */
  715. public function processPosition()
  716. {
  717. if (!Validate::isLoadedObject($object = $this->loadObject()))
  718. {
  719. $this->errors[] = Tools::displayError('An error occurred while updating the status for an object.').
  720. ' <b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)');
  721. }
  722. elseif (!$object->updatePosition((int)Tools::getValue('way'), (int)Tools::getValue('position')))
  723. $this->errors[] = Tools::displayError('Failed to update the position.');
  724. else
  725. {
  726. $id_identifier_str = ($id_identifier = (int)Tools::getValue($this->identifier)) ? '&'.$this->identifier.'='.$id_identifier : '';
  727. $redirect = self::$currentIndex.'&'.$this->table.'Orderby=position&'.$this->table.'Orderway=asc&conf=5'.$id_identifier_str.'&token='.$this->token;
  728. $this->redirect_after = $redirect;
  729. }
  730. return $object;
  731. }
  732. /**
  733. * Cancel all filters for this tab
  734. */
  735. public function processResetFilters()
  736. {
  737. $prefix = str_replace(array('admin', 'controller'), '', Tools::strtolower(get_class($this)));
  738. $filters = $this->context->cookie->getFamily($prefix.$this->table.'Filter_');
  739. foreach ($filters as $cookie_key => $filter)
  740. if (strncmp($cookie_key, $prefix.$this->table.'Filter_', 7 + Tools::strlen($prefix.$this->table)) == 0)
  741. {
  742. $key = substr($cookie_key, 7 + Tools::strlen($prefix.$this->table));
  743. /* Table alias could be specified using a ! eg. alias!field */
  744. $tmp_tab = explode('!', $key);
  745. $key = (count($tmp_tab) > 1 ? $tmp_tab[1] : $tmp_tab[0]);
  746. if (is_array($this->fields_list) && array_key_exists($key, $this->fields_list))
  747. unset($this->context->cookie->$cookie_key);
  748. }
  749. if (isset($this->context->cookie->{'submitFilter'.$this->table}))
  750. unset($this->context->cookie->{'submitFilter'.$this->table});
  751. if (isset($this->context->cookie->{$prefix.$this->table.'Orderby'}))
  752. unset($this->context->cookie->{$prefix.$this->table.'Orderby'});
  753. if (isset($this->context->cookie->{$prefix.$this->table.'Orderway'}))
  754. unset($this->context->cookie->{$prefix.$this->table.'Orderway'});
  755. unset($_POST);
  756. $this->_filter = false;
  757. unset($this->_filterHaving);
  758. unset($this->_having);
  759. }
  760. /**
  761. * Update options and preferences
  762. */
  763. protected function processUpdateOptions()
  764. {
  765. $this->beforeUpdateOptions();
  766. $languages = Language::getLanguages(false);
  767. $hide_multishop_checkbox = (Shop::getTotalShops(false, null) < 2) ? true : false;
  768. foreach ($this->fields_options as $category_data)
  769. {
  770. if (!isset($category_data['fields']))
  771. continue;
  772. $fields = $category_data['fields'];
  773. foreach ($fields as $field => $values)
  774. {
  775. if (isset($values['type']) && $values['type'] == 'selectLang')
  776. {
  777. foreach ($languages as $lang)
  778. if (Tools::getValue($field.'_'.strtoupper($lang['iso_code'])))
  779. $fields[$field.'_'.strtoupper($lang['iso_code'])] = array(
  780. 'type' => 'select',
  781. 'cast' => 'strval',
  782. 'identifier' => 'mode',
  783. 'list' => $values['list']
  784. );
  785. }
  786. }
  787. // Validate fields
  788. foreach ($fields as $field => $values)
  789. {
  790. // We don't validate fields with no visibility
  791. if (!$hide_multishop_checkbox && Shop::isFeatureActive() && isset($values['visibility']) && $values['visibility'] > Shop::getContext())
  792. continue;
  793. // Check if field is required
  794. if (isset($values['required']) && $values['required'] && !empty($_POST['multishopOverrideOption'][$field]))
  795. if (isset($values['type']) && $values['type'] == 'textLang')
  796. {
  797. foreach ($languages as $language)
  798. if (($value = Tools::getValue($field.'_'.$language['id_lang'])) == false && (string)$value != '0')
  799. $this->errors[] = sprintf(Tools::displayError('field %s is required.'), $values['title']);
  800. }
  801. elseif (($value = Tools::getValue($field)) == false && (string)$value != '0')
  802. $this->errors[] = sprintf(Tools::displayError('field %s is required.'), $values['title']);
  803. // Check field validator
  804. if (isset($values['type']) && $values['type'] == 'textLang')
  805. {
  806. foreach ($languages as $language)
  807. if (Tools::getValue($field.'_'.$language['id_lang']) && isset($values['validation']))
  808. if (!Validate::$values['validation'](Tools::getValue($field.'_'.$language['id_lang'])))
  809. $this->errors[] = sprintf(Tools::displayError('field %s is invalid.'), $values['title']);
  810. }
  811. elseif (Tools::getValue($field) && isset($values['validation']))
  812. if (!Validate::$values['validation'](Tools::getValue($field)))
  813. $this->errors[] = sprintf(Tools::displayError('field %s is invalid.'), $values['title']);
  814. // Set default value
  815. if (Tools::getValue($field) === false && isset($values['default']))
  816. $_POST[$field] = $values['default'];
  817. }
  818. if (!count($this->errors))
  819. {
  820. foreach ($fields as $key => $options)
  821. {
  822. if (!$hide_multishop_checkbox && Shop::isFeatureActive() && isset($options['visibility']) && $options['visibility'] > Shop::getContext())
  823. continue;
  824. if (!$hide_multishop_checkbox && Shop::isFeatureActive() && Shop::getContext() != Shop::CONTEXT_ALL && empty($options['no_multishop_checkbox']) && empty($_POST['multishopOverrideOption'][$key]))
  825. {
  826. Configuration::deleteFromContext($key);
  827. continue;
  828. }
  829. // check if a method updateOptionFieldName is available
  830. $method_name = 'updateOption'.Tools::toCamelCase($key, true);
  831. if (method_exists($this, $method_name))
  832. $this->$method_name(Tools::getValue($key));
  833. elseif (isset($options['type']) && in_array($options['type'], array('textLang', 'textareaLang')))
  834. {
  835. $list = array();
  836. foreach ($languages as $language)
  837. {
  838. $key_lang = Tools::getValue($key.'_'.$language['id_lang']);
  839. $val = (isset($options['cast']) ? $options['cast']($key_lang) : $key_lang);
  840. if ($this->validateField($val, $options))
  841. {
  842. if (Validate::isCleanHtml($val))
  843. $list[$language['id_lang']] = $val;
  844. else
  845. $this->errors[] = Tools::displayError('Can not add configuration '.$key.' for lang '.Language::getIsoById((int)$language['id_lang']));
  846. }
  847. }
  848. Configuration::updateValue($key, $list);
  849. }
  850. else
  851. {
  852. $val = (isset($options['cast']) ? $options['cast'](Tools::getValue($key)) : Tools::getValue($key));
  853. if ($this->validateField($val, $options))
  854. {
  855. if (Validate::isCleanHtml($val))
  856. Configuration::updateValue($key, $val);
  857. else
  858. $this->errors[] = Tools::displayError('Can not add configuration '.$key);
  859. }
  860. }
  861. }
  862. }
  863. }
  864. $this->display = 'list';
  865. if (empty($this->errors))
  866. $this->confirmations[] = $this->_conf[6];
  867. }
  868. /**
  869. * assign default action in toolbar_btn smarty var, if they are not set.
  870. * uses override to specifically add, modify or remove items
  871. *
  872. */
  873. public function initToolbar()
  874. {
  875. switch ($this->display)
  876. {
  877. case 'add':
  878. case 'edit':
  879. // Default save button - action dynamically handled in javascript
  880. $this->toolbar_btn['save'] = array(
  881. 'href' => '#',
  882. 'desc' => $this->l('Save')
  883. );
  884. //no break
  885. case 'view':
  886. // Default cancel button - like old back link
  887. $back = Tools::safeOutput(Tools::getValue('back', ''));
  888. if (empty($back))
  889. $back = self::$currentIndex.'&token='.$this->token;
  890. if (!Validate::isCleanHtml($back))
  891. die(Tools::displayError());
  892. if (!$this->lite_display)
  893. $this->toolbar_btn['back'] = array(
  894. 'href' => $back,
  895. 'desc' => $this->l('Back to list')
  896. );
  897. break;
  898. case 'options':
  899. $this->toolbar_btn['save'] = array(
  900. 'href' => '#',
  901. 'desc' => $this->l('Save')
  902. );
  903. break;
  904. case 'view':
  905. break;
  906. default: // list
  907. $this->toolbar_btn['new'] = array(
  908. 'href' => self::$currentIndex.'&amp;add'.$this->table.'&amp;token='.$this->token,
  909. 'desc' => $this->l('Add new')
  910. );
  911. if ($this->allow_export)
  912. $this->toolbar_btn['export'] = array(
  913. 'href' => self::$currentIndex.'&amp;export'.$this->table.'&amp;token='.$this->token,
  914. 'desc' => $this->l('Export')
  915. );
  916. }
  917. $this->addToolBarModulesListButton();
  918. }
  919. /**
  920. * Load class object using identifier in $_GET (if possible)
  921. * otherwise return an empty object, or die
  922. *
  923. * @param boolean $opt Return an empty object if load fail
  924. * @return object
  925. */
  926. protected function loadObject($opt = false)
  927. {
  928. $id = (int)Tools::getValue($this->identifier);
  929. if ($id && Validate::isUnsignedId($id))
  930. {
  931. if (!$this->object)
  932. $this->object = new $this->className($id);
  933. if (Validate::isLoadedObject($this->object))
  934. return $this->object;
  935. // throw exception
  936. $this->errors[] = Tools::displayError('The object cannot be loaded (or found)');
  937. return false;
  938. }
  939. elseif ($opt)
  940. {
  941. if (!$this->object)
  942. $this->object = new $this->className();
  943. return $this->object;
  944. }
  945. else
  946. {
  947. $this->errors[] = Tools::displayError('The object cannot be loaded (ithe dentifier is missing or invalid)');
  948. return false;
  949. }
  950. return $this->object;
  951. }
  952. /**
  953. * Check if the token is valid, else display a warning page
  954. */
  955. public function checkAccess()
  956. {
  957. if (!$this->checkToken())
  958. {
  959. // If this is an XSS attempt, then we should only display a simple, secure page
  960. // ${1} in the replacement string of the regexp is required,
  961. // because the token may begin with a number and mix up with it (e.g. $17)
  962. $url = preg_replace('/([&?]token=)[^&]*(&.*)?$/', '${1}'.$this->token.'$2', $_SERVER['REQUEST_URI']);
  963. if (false === strpos($url, '?token=') && false === strpos($url, '&token='))
  964. $url .= '&token='.$this->token;
  965. if (strpos($url, '?') === false)
  966. $url = str_replace('&token', '?controller=AdminHome&token', $url);
  967. $this->context->smarty->assign('url', htmlentities($url));
  968. return false;
  969. }
  970. return true;
  971. }
  972. protected function filterToField($key, $filter)
  973. {
  974. foreach ($this->fields_list as $field)
  975. if (array_key_exists('filter_key', $field) && $field['filter_key'] == $key)
  976. return $field;
  977. if (array_key_exists($filter, $this->fields_list))
  978. return $this->fields_list[$filter];
  979. return false;
  980. }
  981. public function displayNoSmarty()
  982. {
  983. }
  984. public function displayAjax()
  985. {
  986. if ($this->json)
  987. {
  988. $this->context->smarty->assign(array(
  989. 'json' => true,
  990. 'status' => $this->status,
  991. ));
  992. }
  993. $this->layout = 'layout-ajax.tpl';
  994. return $this->display();
  995. }
  996. protected function redirect()
  997. {
  998. header('Location: '.$this->redirect_after);
  999. exit;
  1000. }
  1001. public function display()
  1002. {
  1003. $this->context->smarty->assign(array(
  1004. 'display_header' => $this->display_header,
  1005. 'display_footer' => $this->display_footer,
  1006. )
  1007. );
  1008. // Use page title from meta_title if it has been set else from the breadcrumbs array
  1009. if (!$this->meta_title)
  1010. $this->meta_title = isset($this->breadcrumbs[1]) ? $this->breadcrumbs[1] : $this->breadcrumbs[0];
  1011. $this->context->smarty->assign('meta_title', $this->meta_title);
  1012. $tpl_action = $this->tpl_folder.$this->display.'.tpl';
  1013. // Check if action template has been override
  1014. foreach ($this->context->smarty->getTemplateDir() as $template_dir)
  1015. if (file_exists($template_dir.DIRECTORY_SEPARATOR.$tpl_action) && $this->display != 'view' && $this->display != 'options')
  1016. {
  1017. if (method_exists($this, $this->display.Tools::toCamelCase($this->className)))
  1018. $this->{$this->display.Tools::toCamelCase($this->className)}();
  1019. $this->context->smarty->assign('content', $this->context->smarty->fetch($tpl_action));
  1020. break;
  1021. }
  1022. if (!$this->ajax)
  1023. {
  1024. $template = $this->createTemplate($this->template);
  1025. $page = $template->fetch();
  1026. }
  1027. else
  1028. $page = $this->content;
  1029. if ($conf = Tools::getValue('conf'))
  1030. if ($this->json)
  1031. $this->context->smarty->assign('conf', Tools::jsonEncode($this->_conf[(int)$conf]));
  1032. else
  1033. $this->context->smarty->assign('conf', $this->_conf[(int)$conf]);
  1034. $notifications_type = array('errors', 'warnings', 'informations', 'confirmations');
  1035. foreach($notifications_type as $type)
  1036. if ($this->json)
  1037. $this->context->smarty->assign($type, Tools::jsonEncode(array_unique($this->$type)));
  1038. else
  1039. $this->context->smarty->assign($type, array_unique($this->$type));
  1040. if ($this->json)
  1041. $this->context->smarty->assign('page', Tools::jsonEncode($page));
  1042. else
  1043. $this->context->smarty->assign('page', $page);
  1044. $this->smartyOutputContent($this->layout);
  1045. }
  1046. /**
  1047. * add a warning message to display at the top of the page
  1048. *
  1049. * @param string $msg
  1050. */
  1051. protected function displayWarning($msg)
  1052. {
  1053. $this->warnings[] = $msg;
  1054. }
  1055. /**
  1056. * add a info message to display at the top of the page
  1057. *
  1058. * @param string $msg
  1059. */
  1060. protected function displayInformation($msg)
  1061. {
  1062. $this->informations[] = $msg;
  1063. }
  1064. /**
  1065. * Assign smarty variables for the header
  1066. */
  1067. public function initHeader()
  1068. {
  1069. // Multishop
  1070. $is_multishop = Shop::isFeatureActive();
  1071. // Quick access
  1072. $quick_access = QuickAccess::getQuickAccesses($this->context->language->id);
  1073. foreach ($quick_access as $index => $quick)
  1074. {
  1075. if ($quick['link'] == '../' && Shop::getContext() == Shop::CONTEXT_SHOP)
  1076. {
  1077. $url = $this->context->shop->getBaseURL();
  1078. if (!$url)
  1079. {
  1080. unset($quick_access[$index]);
  1081. continue;
  1082. }
  1083. $quick_access[$index]['link'] = $url;
  1084. }
  1085. else
  1086. {
  1087. preg_match('/controller=(.+)(&.+)?$/', $quick['link'], $admin_tab);
  1088. if (isset($admin_tab[1]))
  1089. {
  1090. if (strpos($admin_tab[1], '&'))
  1091. $admin_tab[1] = substr($admin_tab[1], 0, strpos($admin_tab[1], '&'));
  1092. $token = Tools::getAdminToken($admin_tab[1].(int)Tab::getIdFromClassName($admin_tab[1]).(int)$this->context->employee->id);
  1093. $quick_access[$index]['link'] .= '&token='.$token;
  1094. }
  1095. }
  1096. }
  1097. // Tab list
  1098. $tabs = Tab::getTabs($this->context->language->id, 0);
  1099. $current_id = Tab::getCurrentParentId();
  1100. foreach ($tabs as $index => $tab)
  1101. {
  1102. if ($tab['class_name'] == 'AdminStock' && Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') == 0)
  1103. {
  1104. unset($tabs[$index]);
  1105. continue;
  1106. }
  1107. $img_cache_url = 'themes/'.$this->context->employee->bo_theme.'/img/t/'.$tab['class_name'].'.png';
  1108. $img_exists_cache = Tools::file_exists_cache(_PS_ADMIN_DIR_.$img_cache_url);
  1109. // retrocompatibility : change png to gif if icon not exists
  1110. if (!$img_exists_cache)
  1111. $img_exists_cache = Tools::file_exists_cache(_PS_ADMIN_DIR_.str_replace('.png', '.gif', $img_cache_url));
  1112. if ($img_exists_cache)
  1113. $path_img = $img = $img_exists_cache;
  1114. else
  1115. {
  1116. $path_img = _PS_IMG_DIR_.'t/'.$tab['class_name'].'.png';
  1117. // Relative link will always work, whatever the base uri set in the admin
  1118. $img = '../img/t/'.$tab['class_name'].'.png';
  1119. }
  1120. if (trim($tab['module']) != '')
  1121. {
  1122. $path_img = _PS_MODULE_DIR_.$tab['module'].'/'.$tab['class_name'].'.png';
  1123. // Relative link will always work, whatever the base uri set in the admin
  1124. $img = '../modules/'.$tab['module'].'/'.$tab['class_name'].'.png';
  1125. }
  1126. // retrocompatibility
  1127. if (!file_exists($path_img))
  1128. $img = str_replace('png', 'gif', $img);
  1129. // tab[class_name] does not contains the "Controller" suffix
  1130. $tabs[$index]['current'] = ($tab['class_name'].'Controller' == get_class($this)) || ($current_id == $tab['id_tab']);
  1131. $tabs[$index]['img'] = $img;
  1132. $tabs[$index]['href'] = $this->context->link->getAdminLink($tab['class_name']);
  1133. $sub_tabs = Tab::getTabs($this->context->language->id, $tab['id_tab']);
  1134. foreach ($sub_tabs as $index2 => $sub_tab)
  1135. {
  1136. // class_name is the name of the class controller
  1137. if (Tab::checkTabRights($sub_tab['id_tab']) === true
  1138. && (bool)$sub_tab['active'])
  1139. $sub_tabs[$index2]['href'] = $this->context->link->getAdminLink($sub_tab['class_name']);
  1140. else
  1141. unset($sub_tabs[$index2]);
  1142. }
  1143. $tabs[$index]['sub_tabs'] = $sub_tabs;
  1144. // If there are no subtabs, we don't want to display the parent tab in menu
  1145. if (empty($sub_tabs))
  1146. unset($tabs[$index]);
  1147. }
  1148. if (Validate::isLoadedObject($this->context->employee))
  1149. {
  1150. $accesses = Profile::getProfileAccesses($this->context->employee->id_profile, 'class_name');
  1151. /* Hooks are volontary out the initialize array (need those variables already assigned) */
  1152. $bo_color = empty($this->context->employee->bo_color) ? '#FFFFFF' : $this->context->employee->bo_color;
  1153. $this->context->smarty->assign(array(
  1154. 'autorefresh_notifications' => Configuration::get('PS_ADMIN_REFRESH_NOTIFICATION'),
  1155. 'help_box' => Configuration::get('PS_HELPBOX'),
  1156. 'round_mode' => Configuration::get('PS_PRICE_ROUND_MODE'),
  1157. 'brightness' => Tools::getBrightness($bo_color) < 128 ? 'white' : '#383838',
  1158. 'bo_width' => (int)$this->context->employee->bo_width,
  1159. 'bo_color' => isset($this->context->employee->bo_color) ? Tools::htmlentitiesUTF8($this->context->employee->bo_color) : null,
  1160. 'show_new_orders' => Configuration::get('PS_SHOW_NEW_ORDERS') && $accesses['AdminOrders']['view'],
  1161. 'show_new_customers' => Configuration::get('PS_SHOW_NEW_CUSTOMERS') && $accesses['AdminCustomers']['view'],
  1162. 'show_new_messages' => Configuration::get('PS_SHOW_NEW_MESSAGES') && $accesses['AdminCustomerThreads']['view'],
  1163. 'first_name' => Tools::substr($this->context->employee->firstname, 0, 1),
  1164. 'last_name' => htmlentities($this->context->employee->lastname, ENT_COMPAT, 'UTF-8'),
  1165. 'employee' => $this->context->employee,
  1166. 'search_type' => Tools::getValue('bo_search_type'),
  1167. 'bo_query' => Tools::safeOutput(Tools::stripslashes(Tools::getValue('bo_query'))),
  1168. 'quick_access' => $quick_access,
  1169. 'multi_shop' => Shop::isFeatureActive(),
  1170. 'shop_list' => Helper::renderShopList(),
  1171. 'shop' => $this->context->shop,
  1172. 'shop_group' => new ShopGroup((int)Shop::getContextShopGroupID()),
  1173. 'current_parent_id' => (int)Tab::getCurrentParentId(),
  1174. 'tabs' => $tabs,
  1175. 'is_multishop' => $is_multishop,
  1176. 'multishop_context' => $this->multishop_context,
  1177. ));
  1178. }
  1179. $this->context->smarty->assign(array(
  1180. 'img_dir' => _PS_IMG_,
  1181. 'iso' => $this->context->language->iso_code,
  1182. 'class_name' => $this->className,
  1183. 'iso_user' => $this->context->language->iso_code,
  1184. 'country_iso_code' => $this->context->country->iso_code,
  1185. 'version' => _PS_VERSION_,
  1186. 'lang_iso' => $this->context->language->iso_code,
  1187. 'link' => $this->context->link,
  1188. 'shop_name' => Configuration::get('PS_SHOP_NAME'),
  1189. 'base_url' => $this->context->shop->getBaseURL(),
  1190. 'tab' => $tab, // Deprecated, this tab is declared in the foreach, so it's the last tab in the foreach
  1191. 'current_parent_id' => (int)Tab::getCurrentParentId(),
  1192. 'tabs' => $tabs,
  1193. 'install_dir_exists' => file_exists(_PS_ADMIN_DIR_.'/../install'),
  1194. 'pic_dir' => _THEME_PROD_PIC_DIR_,
  1195. 'controller_name' => htmlentities(Tools::getValue('controller')),
  1196. 'currentIndex' => self::$currentIndex
  1197. ));
  1198. }
  1199. /**
  1200. * Declare an action to use for each row in the list
  1201. */
  1202. public function addRowAction($action)
  1203. {
  1204. $action = strtolower($action);
  1205. $this->actions[] = $action;
  1206. }
  1207. /**
  1208. * Add an action to use for each row in the list
  1209. */
  1210. public function addRowActionSkipList($action, $list)
  1211. {
  1212. $action = strtolower($action);
  1213. $list = (array)$list;
  1214. if (array_key_exists($action, $this->list_skip_actions))
  1215. $this->list_skip_actions[$action] = array_merge($this->list_skip_actions[$action], $list);
  1216. else
  1217. $this->list_skip_actions[$action] = $list;
  1218. }
  1219. /**
  1220. * Assign smarty variables for all default views, list and form, then call other init functions
  1221. */
  1222. public function initContent()
  1223. {
  1224. if (!$this->viewAccess())
  1225. {
  1226. $this->errors[] = Tools::displayError('You do not have permission to view this.');
  1227. return;
  1228. }
  1229. $this->getLanguages();
  1230. // toolbar (save, cancel, new, ..)
  1231. $this->initToolbar();
  1232. $this->initTabModuleList();
  1233. if ($this->display == 'edit' || $this->display == 'add')
  1234. {
  1235. if (!$this->loadObject(true))
  1236. return;
  1237. $this->content .= $this->renderForm();
  1238. }
  1239. elseif ($this->display == 'view')
  1240. {
  1241. // Some controllers use the view action without an object
  1242. if ($this->className)
  1243. $this->loadObject(true);
  1244. $this->content .= $this->renderView();
  1245. }
  1246. elseif (!$this->ajax)
  1247. {
  1248. $this->content .= $this->renderModulesList();
  1249. $this->content .= $this->renderList();
  1250. $this->content .= $this->renderOptions();
  1251. // if we have to display the required fields form
  1252. if ($this->required_database)
  1253. $this->content .= $this->displayRequiredFields();
  1254. }
  1255. $this->context->smarty->assign(array(
  1256. 'content' => $this->content,
  1257. 'url_post' => self::$currentIndex.'&token='.$this->token,
  1258. ));
  1259. }
  1260. /**
  1261. * init tab modules list and add button in toolbar
  1262. */
  1263. protected function initTabModuleList()
  1264. {
  1265. if (!$this->isFresh(Module::CACHE_FILE_TAB_MODULES_LIST, 604800))
  1266. $this->refresh(Module::CACHE_FILE_TAB_MODULES_LIST, 'http://'.Tab::TAB_MODULE_LIST_URL);
  1267. $this->tab_modules_list = Tab::getTabModulesList($this->id);
  1268. if (is_array($this->tab_modules_list['default_list']) && count($this->tab_modules_list['default_list']))
  1269. $this->filter_modules_list = $this->tab_modules_list['default_list'];
  1270. elseif (is_array($this->tab_modules_list['slider_list']) && count($this->tab_modules_list['slider_list']))
  1271. {
  1272. $this->addToolBarModulesListButton();
  1273. $this->context->smarty->assign(array(
  1274. 'tab_modules_list' => implode(',', $this->tab_modules_list['slider_list']),
  1275. 'admin_module_ajax_url' => $this->context->link->getAdminLink('AdminModules'),
  1276. 'back_tab_modules_list' => $this->context->link->getAdminLink(Tools::getValue('controller')),
  1277. 'tab_modules_open' => (int)Tools::getValue('tab_modules_open')
  1278. ));
  1279. }
  1280. }
  1281. protected function addToolBarModulesListButton()
  1282. {
  1283. if (is_array($this->tab_modules_list['slider_list']) && count($this->tab_modules_list['slider_list']))
  1284. $this->toolbar_btn['modules-list'] = array(
  1285. 'href' => '#',
  1286. 'desc' => $this->l('Modules List')
  1287. );
  1288. }
  1289. /**
  1290. * initialize the invalid doom page of death
  1291. *
  1292. * @return void
  1293. */
  1294. public function initCursedPage()
  1295. {
  1296. $this->layout = 'invalid_token.tpl';
  1297. }
  1298. /**
  1299. * Assign smarty variables for the footer
  1300. */
  1301. public function initFooter()
  1302. {
  1303. // We assign js and css files on the last step before display template, because controller can add many js and css files
  1304. $this->context->smarty->assign('css_files', $this->css_files);
  1305. $this->context->smarty->assign('js_files', array_unique($this->js_files));
  1306. $this->context->smarty->assign(array(
  1307. 'ps_version' => _PS_VERSION_,
  1308. 'timer_start' => $this->timer_start,
  1309. 'iso_is_fr' => strtoupper($this->context->language->iso_code) == 'FR',
  1310. ));
  1311. }
  1312. public function renderModulesList()
  1313. {
  1314. if ($this->getModulesList($this->filter_modules_list))
  1315. {
  1316. $helper = new Helper();
  1317. return $helper->renderModulesList($this->modules_list);
  1318. }
  1319. }
  1320. /**
  1321. * Function used to render the list to display for this controller
  1322. */
  1323. public function renderList()
  1324. {
  1325. if (!($this->fields_list && is_array($this->fields_list)))
  1326. return false;
  1327. $this->getList($this->context->language->id);
  1328. $helper = new HelperList();
  1329. // Empty list is ok
  1330. if (!is_array($this->_list))
  1331. {
  1332. $this->displayWarning($this->l('Bad SQL query', 'Helper').'<br />'.htmlspecialchars($this->_list_error));
  1333. return false;
  1334. }
  1335. $this->setHelperDisplay($helper);
  1336. $helper->tpl_vars = $this->tpl_list_vars;
  1337. $helper->tpl_delete_link_vars = $this->tpl_delete_link_vars;
  1338. // For compatibility reasons, we have to check standard actions in class attributes
  1339. foreach ($this->actions_available as $action)
  1340. {
  1341. if (!in_array($action, $this->actions) && isset($this->$action) && $this->$action)
  1342. $this->actions[] = $action;
  1343. }
  1344. $helper->is_cms = $this->is_cms;
  1345. $list = $helper->generateList($this->_list, $this->fields_list);
  1346. return $list;
  1347. }
  1348. /**
  1349. * Override to render the view page
  1350. */
  1351. public function renderView()
  1352. {
  1353. $helper = new HelperView($this);
  1354. $this->setHelperDisplay($helper);
  1355. $helper->tpl_vars = $this->tpl_view_vars;
  1356. if (!is_null($this->base_tpl_view))
  1357. $helper->base_tpl = $this->base_tpl_view;
  1358. $view = $helper->generateView();
  1359. return $view;
  1360. }
  1361. /**
  1362. * Function used to render the form for this controller
  1363. */
  1364. public function renderForm()
  1365. {
  1366. if (!$this->default_form_language)
  1367. $this->getLanguages();
  1368. if (Tools::getValue('submitFormAjax'))
  1369. $this->content .= $this->context->smarty->fetch('form_submit_ajax.tpl');
  1370. if ($this->fields_form && is_array($this->fields_form))
  1371. {
  1372. if (!$this->multiple_fieldsets)
  1373. $this->fields_form = array(array('form' => $this->fields_form));
  1374. // For add a fields via an override of $fields_form, use $fields_form_override
  1375. if (is_array($this->fields_form_override) && !empty($this->fields_form_override))
  1376. $this->fields_form[0]['form']['input'][] = $this->fields_form_override;
  1377. $helper = new HelperForm($this);
  1378. $this->setHelperDisplay($helper);
  1379. $helper->fields_value = $this->getFieldsValue($this->object);
  1380. $helper->tpl_vars = $this->tpl_form_vars;
  1381. !is_null($this->base_tpl_form) ? $helper->base_tpl = $this->base_tpl_form : '';
  1382. if ($this->tabAccess['view'])
  1383. {
  1384. if (Tools::getValue('back'))
  1385. $helper->tpl_vars['back'] = Tools::safeOutput(Tools::getValue('back'));
  1386. else
  1387. $helper->tpl_vars['back'] = Tools::safeOutput(Tools::getValue(self::$currentIndex.'&token='.$this->token));
  1388. }
  1389. $form = $helper->generateForm($this->fields_form);
  1390. return $form;
  1391. }
  1392. }
  1393. /**
  1394. * Function used to render the options for this controller
  1395. */
  1396. public function renderOptions()
  1397. {
  1398. if ($this->fields_options && is_array($this->fields_options))
  1399. {
  1400. if (isset($this->display) && $this->display != 'options' && $this->display != 'list')
  1401. $this->show_toolbar = false;
  1402. else
  1403. $this->display = 'options';
  1404. unset($this->toolbar_btn);
  1405. $this->initToolbar();
  1406. $helper = new HelperOptions($this);
  1407. $this->setHelperDisplay($helper);
  1408. $helper->id = $this->id;
  1409. $helper->tpl_vars = $this->tpl_option_vars;
  1410. $options = $helper->generateOptions($this->fields_options);
  1411. return $options;
  1412. }
  1413. }
  1414. /**
  1415. * this function set various display option for helper list
  1416. *
  1417. * @param Helper $helper
  1418. * @return void
  1419. */
  1420. public function setHelperDisplay(Helper $helper)
  1421. {
  1422. if (empty($this->toolbar_title))
  1423. $this->initToolbarTitle();
  1424. // tocheck
  1425. if ($this->object && $this->object->id)
  1426. $helper->id = $this->object->id;
  1427. // @todo : move that in Helper
  1428. $helper->title = $this->toolbar_title;
  1429. $helper->toolbar_btn = $this->toolbar_btn;
  1430. $helper->show_toolbar = $this->show_toolbar;
  1431. $helper->toolbar_scroll = $this->toolbar_scroll;
  1432. $helper->override_folder = $this->tpl_folder;
  1433. $helper->actions = $this->actions;
  1434. $helper->simple_header = $this->list_simple_header;
  1435. $helper->bulk_actions = $this->bulk_actions;
  1436. $helper->currentIndex = self::$currentIndex;
  1437. $helper->className = $this->className;
  1438. $helper->table = $this->table;
  1439. $helper->name_controller = Tools::getValue('controller');
  1440. $helper->orderBy = $this->_orderBy;
  1441. $helper->orderWay = $this->_orderWay;
  1442. $helper->listTotal = $this->_listTotal;
  1443. $helper->shopLink = $this->shopLink;
  1444. $helper->shopLinkType = $this->shopLinkType;
  1445. $helper->identifier = $this->identifier;
  1446. $helper->token = $this->token;
  1447. $helper->languages = $this->_languages;
  1448. $helper->specificConfirmDelete = $this->specificConfirmDelete;
  1449. $helper->imageType = $this->imageType;
  1450. $helper->no_link = $this->list_no_link;
  1451. $helper->colorOnBackground = $this->colorOnBackground;
  1452. $helper->ajax_params = (isset($this->ajax_params) ? $this->ajax_params : null);
  1453. $helper->default_form_language = $this->default_form_language;
  1454. $helper->allow_employee_form_lang = $this->allow_employee_form_lang;
  1455. $helper->multiple_fieldsets = $this->multiple_fieldsets;
  1456. $helper->row_hover = $this->row_hover;
  1457. $helper->position_identifier = $this->position_identifier;
  1458. $helper->controller_name = $this->controller_name;
  1459. // For each action, try to add the corresponding skip elements list
  1460. $helper->list_skip_actions = $this->list_skip_actions;
  1461. $this->helper = $helper;
  1462. }
  1463. public function setMedia()
  1464. {
  1465. $this->addCSS(_PS_CSS_DIR_.'admin.css', 'all');
  1466. $admin_webpath = str_ireplace(_PS_ROOT_DIR_, '', _PS_ADMIN_DIR_);
  1467. $admin_webpath = preg_replace('/^'.preg_quote(DIRECTORY_SEPARATOR, '/').'/', '', $admin_webpath);
  1468. $this->addCSS(__PS_BASE_URI__.$admin_webpath.'/themes/'.$this->bo_theme.'/css/admin.css', 'all');
  1469. if ($this->context->language->is_rtl)
  1470. $this->addCSS(_THEME_CSS_DIR_.'rtl.css');
  1471. $this->addJquery();
  1472. $this->addjQueryPlugin(array('cluetip', 'hoverIntent', 'scrollTo', 'alerts', 'chosen'));
  1473. $this->addJS(array(
  1474. _PS_JS_DIR_.'admin.js',
  1475. _PS_JS_DIR_.'toggle.js',
  1476. _PS_JS_DIR_.'tools.js',
  1477. _PS_JS_DIR_.'ajax.js',
  1478. _PS_JS_DIR_.'toolbar.js'
  1479. ));
  1480. if (!Tools::getValue('submitFormAjax'))
  1481. {
  1482. $this->addJs(_PS_JS_DIR_.'notifications.js');
  1483. if (Configuration::get('PS_HELPBOX'))
  1484. $this->addJS(_PS_JS_DIR_.'helpAccess.js');
  1485. }
  1486. // Execute Hook AdminController SetMedia
  1487. Hook::exec('actionAdminControllerSetMedia', array());
  1488. }
  1489. /**
  1490. * non-static method which uses AdminController::translate()
  1491. *
  1492. * @param mixed $string term or expression in english
  1493. * @param string $class name of the class
  1494. * @param boolan $addslashes if set to true, the return value will pass through addslashes(). Otherwise, stripslashes().
  1495. * @param boolean $htmlentities if set to true(default), the return value will pass through htmlentities($string, ENT_QUOTES, 'utf-8')
  1496. * @return string the translation if available, or the english default text.
  1497. */
  1498. protected function l($string, $class = 'AdminTab', $addslashes = false, $htmlentities = true)
  1499. {
  1500. // classname has changed, from AdminXXX to AdminXXXController
  1501. // So we remove 10 characters and we keep same keys
  1502. if (strtolower(substr($class, -10)) == 'controller')
  1503. $class = substr($class, 0, -10);
  1504. elseif ($class == 'AdminTab')
  1505. $class = substr(get_class($this), 0, -10);
  1506. return Translate::getAdminTranslation($string, $class, $addslashes, $htmlentities);
  1507. }
  1508. /**
  1509. * Init context and dependencies, handles POST and GET
  1510. */
  1511. public function init()
  1512. {
  1513. // Has to be removed for the next Prestashop version
  1514. global $currentIndex;
  1515. parent::init();
  1516. if (Tools::getValue('ajax'))
  1517. $this->ajax = '1';
  1518. /* Server Params */
  1519. $protocol_link = (Tools::usingSecureMode() && Configuration::get('PS_SSL_ENABLED')) ? 'https://' : 'http://';
  1520. $protocol_content = (Tools::usingSecureMode() && Configuration::get('PS_SSL_ENABLED')) ? 'https://' : 'http://';
  1521. $this->context->link = new Link($protocol_link, $protocol_content);
  1522. if (isset($_GET['logout']))
  1523. $this->context->employee->logout();
  1524. if ($this->controller_name != 'AdminLogin' && (!isset($this->context->employee) || !$this->context->employee->isLoggedBack()))
  1525. Tools::redirectAdmin($this->context->link->getAdminLink('AdminLogin').(!isset($_GET['logout']) ? '&redirect='.$this->controller_name : ''));
  1526. // Set current index
  1527. $current_index = 'index.php'.(($controller = Tools::getValue('controller')) ? '?controller='.$controller : '');
  1528. if ($back = Tools::getValue('back'))
  1529. $current_index .= '&back='.urlencode($back);
  1530. self::$currentIndex = $current_index;
  1531. $currentIndex = $current_index;
  1532. if ((int)Tools::getValue('liteDisplaying'))
  1533. {
  1534. $this->display_header = false;
  1535. $this->display_footer = false;
  1536. $this->content_only = false;
  1537. $this->lite_display = true;
  1538. }
  1539. if ($this->ajax && method_exists($this, 'ajaxPreprocess'))
  1540. $this->ajaxPreProcess();
  1541. $this->context->smarty->assign(array(
  1542. 'table' => $this->table,
  1543. 'current' => self::$currentIndex,
  1544. 'token' => $this->token,
  1545. 'stock_management' => (int)Configuration::get('PS_STOCK_MANAGEMENT')
  1546. ));
  1547. if ($this->display_header)
  1548. $this->context->smarty->assign('displayBackOfficeHeader', Hook::exec('displayBackOfficeHeader', array()));
  1549. $this->context->smarty->assign(
  1550. array(
  1551. 'displayBackOfficeTop' => Hook::exec('displayBackOfficeTop', array()),
  1552. 'submit_form_ajax' => (int)Tools::getValue('submitFormAjax')
  1553. )
  1554. );
  1555. $this->initProcess();
  1556. }
  1557. public function initShopContext()
  1558. {
  1559. if (!$this->context->employee->isLoggedBack())
  1560. return;
  1561. // Change shop context ?
  1562. if (Shop::isFeatureActive() && Tools::getValue('setShopContext') !== false)
  1563. {
  1564. $this->context->cookie->shopContext = Tools::getValue('setShopContext');
  1565. $url = parse_url($_SERVER['REQUEST_URI']);
  1566. $query = (isset($url['query'])) ? $url['query'] : '';
  1567. parse_str($query, $parse_query);
  1568. unset($parse_query['setShopContext'], $parse_query['conf']);
  1569. $this->redirect_after = $url['path'].'?'.http_build_query($parse_query, '', '&');
  1570. }
  1571. elseif (!Shop::isFeatureActive())
  1572. $this->context->cookie->shopContext = 's-'.Configuration::get('PS_SHOP_DEFAULT');
  1573. else if (Shop::getTotalShops(false, null) < 2)
  1574. $this->context->cookie->shopContext = 's-'.$this->context->employee->getDefaultShopID();
  1575. $shop_id = '';
  1576. Shop::setContext(Shop::CONTEXT_ALL);
  1577. if ($this->context->cookie->shopContext)
  1578. {
  1579. $split = explode('-', $this->context->cookie->shopContext);
  1580. if (count($split) == 2)
  1581. {
  1582. if ($split[0] == 'g')
  1583. {
  1584. if ($this->context->employee->hasAuthOnShopGroup($split[1]))
  1585. Shop::setContext(Shop::CONTEXT_GROUP, $split[1]);
  1586. else
  1587. {
  1588. $shop_id = $this->context->employee->getDefaultShopID();
  1589. Shop::setContext(Shop::CONTEXT_SHOP, $shop_id);
  1590. }
  1591. }
  1592. else if (Shop::getShop($split[1]) && $this->context->employee->hasAuthOnShop($split[1]))
  1593. {
  1594. $shop_id = $split[1];
  1595. Shop::setContext(Shop::CONTEXT_SHOP, $shop_id);
  1596. }
  1597. else
  1598. {
  1599. $shop_id = $this->context->employee->getDefaultShopID();
  1600. Shop::setContext(Shop::CONTEXT_SHOP, $shop_id);
  1601. }
  1602. }
  1603. }
  1604. // Check multishop context and set right context if need
  1605. if (!($this->multishop_context & Shop::getContext()))
  1606. {
  1607. if (Shop::getContext() == Shop::CONTEXT_SHOP && !($this->multishop_context & Shop::CONTEXT_SHOP))
  1608. Shop::setContext(Shop::CONTEXT_GROUP, Shop::getContextShopGroupID());
  1609. if (Shop::getContext() == Shop::CONTEXT_GROUP && !($this->multishop_context & Shop::CONTEXT_GROUP))
  1610. Shop::setContext(Shop::CONTEXT_ALL);
  1611. }
  1612. // Replace existing shop if necessary
  1613. if (!$shop_id)
  1614. $this->context->shop = new Shop(Configuration::get('PS_SHOP_DEFAULT'));
  1615. elseif ($this->context->shop->id != $shop_id)
  1616. $this->context->shop = new Shop($shop_id);
  1617. $this->initBreadcrumbs();
  1618. }
  1619. /**
  1620. * Retrieve GET and POST value and translate them to actions
  1621. */
  1622. public function initProcess()
  1623. {
  1624. // Manage list filtering
  1625. if (Tools::isSubmit('submitFilter'.$this->table)
  1626. || $this->context->cookie->{'submitFilter'.$this->table} !== false
  1627. || Tools::getValue($this->table.'Orderby')
  1628. || Tools::getValue($this->table.'Orderway'))
  1629. $this->filter = true;
  1630. $this->id_object = (int)Tools::getValue($this->identifier);
  1631. /* Delete object image */
  1632. if (isset($_GET['deleteImage']))
  1633. {
  1634. if ($this->tabAccess['delete'] === '1')
  1635. $this->action = 'delete_image';
  1636. else
  1637. $this->errors[] = Tools::displayError('You do not have permission to delete this.');
  1638. }
  1639. /* Delete object */
  1640. elseif (isset($_GET['delete'.$this->table]))
  1641. {
  1642. if ($this->tabAccess['delete'] === '1')
  1643. $this->action = 'delete';
  1644. else
  1645. $this->errors[] = Tools::displayError('You do not have permission to delete this.');
  1646. }
  1647. /* Change object statuts (active, inactive) */
  1648. elseif ((isset($_GET['status'.$this->table]) || isset($_GET['status'])) && Tools::getValue($this->identifier))
  1649. {
  1650. if ($this->tabAccess['edit'] === '1')
  1651. $this->action = 'status';
  1652. else
  1653. $this->errors[] = Tools::displayError('You do not have permission to edit this.');
  1654. }
  1655. /* Move an object */
  1656. elseif (isset($_GET['position']))
  1657. {
  1658. if ($this->tabAccess['edit'] == '1')
  1659. $this->action = 'position';
  1660. else
  1661. $this->errors[] = Tools::displayError('You do not have permission to edit this.');
  1662. }
  1663. elseif (Tools::getValue('submitAdd'.$this->table)
  1664. || Tools::getValue('submitAdd'.$this->table.'AndStay')
  1665. || Tools::getValue('submitAdd'.$this->table.'AndPreview'))
  1666. {
  1667. // case 1: updating existing entry
  1668. if ($this->id_object)
  1669. {
  1670. if ($this->tabAccess['edit'] === '1')
  1671. {
  1672. $this->action = 'save';
  1673. if (Tools::getValue('submitAdd'.$this->table.'AndStay'))
  1674. $this->display = 'edit';
  1675. else
  1676. $this->display = 'list';
  1677. }
  1678. else
  1679. $this->errors[] = Tools::displayError('You do not have permission to edit this.');
  1680. }
  1681. // case 2: creating new entry
  1682. else
  1683. {
  1684. if ($this->tabAccess['add'] === '1')
  1685. {
  1686. $this->action = 'save';
  1687. if (Tools::getValue('submitAdd'.$this->table.'AndStay'))
  1688. $this->display = 'edit';
  1689. else
  1690. $this->display = 'list';
  1691. }
  1692. else
  1693. $this->errors[] = Tools::displayError('You do not have permission to add this.');
  1694. }
  1695. }
  1696. elseif (isset($_GET['add'.$this->table]))
  1697. {
  1698. if ($this->tabAccess['add'] === '1')
  1699. {
  1700. $this->action = 'new';
  1701. $this->display = 'add';
  1702. }
  1703. else
  1704. $this->errors[] = Tools::displayError('You do not have permission to add this.');
  1705. }
  1706. elseif (isset($_GET['update'.$this->table]) && isset($_GET[$this->identifier]))
  1707. {
  1708. $this->display = 'edit';
  1709. if ($this->tabAccess['edit'] !== '1')
  1710. $this->errors[] = Tools::displayError('You do not have permission to edit this.');
  1711. }
  1712. elseif (isset($_GET['view'.$this->table]))
  1713. {
  1714. if ($this->tabAccess['view'] === '1')
  1715. {
  1716. $this->display = 'view';
  1717. $this->action = 'view';
  1718. }
  1719. else
  1720. $this->errors[] = Tools::displayError('You do not have permission to view this.');
  1721. }
  1722. elseif (isset($_GET['export'.$this->table]))
  1723. {
  1724. if ($this->tabAccess['view'] === '1')
  1725. $this->action = 'export';
  1726. }
  1727. /* Cancel all filters for this tab */
  1728. elseif (isset($_POST['submitReset'.$this->table]))
  1729. $this->action = 'reset_filters';
  1730. /* Submit options list */
  1731. elseif (Tools::getValue('submitOptions'.$this->table) || Tools::getValue('submitOptions'))
  1732. {
  1733. $this->display = 'options';
  1734. if ($this->tabAccess['edit'] === '1')
  1735. $this->action = 'update_options';
  1736. else
  1737. $this->errors[] = Tools::displayError('You do not have permission to edit this.');
  1738. }
  1739. elseif (Tools::isSubmit('submitFields') && $this->required_database && $this->tabAccess['add'] === '1' && $this->tabAccess['delete'] === '1')
  1740. $this->action = 'update_fields';
  1741. elseif (is_array($this->bulk_actions))
  1742. foreach ($this->bulk_actions as $bulk_action => $params)
  1743. {
  1744. if (Tools::isSubmit('submitBulk'.$bulk_action.$this->table) || Tools::isSubmit('submitBulk'.$bulk_action))
  1745. {
  1746. if ($this->tabAccess['edit'] === '1')
  1747. {
  1748. $this->action = 'bulk'.$bulk_action;
  1749. $this->boxes = Tools::getValue($this->table.'Box');
  1750. }
  1751. else
  1752. $this->errors[] = Tools::displayError('You do not have permission to edit this.');
  1753. break;
  1754. }
  1755. elseif (Tools::isSubmit('submitBulk'))
  1756. {
  1757. if ($this->tabAccess['edit'] === '1')
  1758. {
  1759. $this->action = 'bulk'.Tools::getValue('select_submitBulk');
  1760. $this->boxes = Tools::getValue($this->table.'Box');
  1761. }
  1762. else
  1763. $this->errors[] = Tools::displayError('You do not have permission to edit this.');
  1764. break;
  1765. }
  1766. }
  1767. elseif (!empty($this->fields_options) && empty($this->fields_list))
  1768. $this->display = 'options';
  1769. }
  1770. /**
  1771. * Get the current objects' list form the database
  1772. *
  1773. * @param integer $id_lang Language used for display
  1774. * @param string $order_by ORDER BY clause
  1775. * @param string $_orderWay Order way (ASC, DESC)
  1776. * @param integer $start Offset in LIMIT clause
  1777. * @param integer $limit Row count in LIMIT clause
  1778. */
  1779. public function getList($id_lang, $order_by = null, $order_way = null, $start = 0, $limit = null, $id_lang_shop = false)
  1780. {
  1781. /* Manage default params values */
  1782. $use_limit = true;
  1783. if ($limit === false)
  1784. $use_limit = false;
  1785. elseif (empty($limit))
  1786. {
  1787. if (isset($this->context->cookie->{$this->table.'_pagination'}) && $this->context->cookie->{$this->table.'_pagination'})
  1788. $limit = $this->context->cookie->{$this->table.'_pagination'};
  1789. else
  1790. $limit = $this->_pagination[1];
  1791. }
  1792. if (!Validate::isTableOrIdentifier($this->table))
  1793. throw new PrestaShopException(sprintf('Table name %s is invalid:', $this->table));
  1794. $prefix = str_replace(array('admin', 'controller'), '', Tools::strtolower(get_class($this)));
  1795. if (empty($order_by))
  1796. {
  1797. if ($this->context->cookie->{$prefix.$this->table.'Orderby'})
  1798. $order_by = $this->context->cookie->{$prefix.$this->table.'Orderby'};
  1799. elseif ($this->_orderBy)
  1800. $order_by = $this->_orderBy;
  1801. else
  1802. $order_by = $this->_defaultOrderBy;
  1803. }
  1804. if (empty($order_way))
  1805. {
  1806. if ($this->context->cookie->{$prefix.$this->table.'Orderway'})
  1807. $order_way = $this->context->cookie->{$prefix.$this->table.'Orderway'};
  1808. elseif ($this->_orderWay)
  1809. $order_way = $this->_orderWay;
  1810. else
  1811. $order_way = $this->_defaultOrderWay;
  1812. }
  1813. $limit = (int)Tools::getValue('pagination', $limit);
  1814. $this->context->cookie->{$this->table.'_pagination'} = $limit;
  1815. /* Check params validity */
  1816. if (!Validate::isOrderBy($order_by) || !Validate::isOrderWay($order_way)
  1817. || !is_numeric($start) || !is_numeric($limit)
  1818. || !Validate::isUnsignedId($id_lang))
  1819. throw new PrestaShopException('get list params is not valid');
  1820. if (isset($this->fields_list[$order_by]) && isset($this->fields_list[$order_by]['filter_key']))
  1821. $order_by = $this->fields_list[$order_by]['filter_key'];
  1822. /* Determine offset from current page */
  1823. if ((isset($_POST['submitFilter'.$this->table]) ||
  1824. isset($_POST['submitFilter'.$this->table.'_x']) ||
  1825. isset($_POST['submitFilter'.$this->table.'_y'])) &&
  1826. !empty($_POST['submitFilter'.$this->table]) &&
  1827. is_numeric($_POST['submitFilter'.$this->table]))
  1828. $start = ((int)$_POST['submitFilter'.$this->table] - 1) * $limit;
  1829. /* Cache */
  1830. $this->_lang = (int)$id_lang;
  1831. if (preg_match('/[.!]/', $order_by))
  1832. {
  1833. $order_by_split = preg_split('/[.!]/', $order_by);
  1834. $order_by = pSQL($order_by_split[0]).'.`'.pSQL($order_by_split[1]).'`';
  1835. $this->_orderBy = (isset($order_by_split) && isset($order_by_split[1])) ? $order_by_split[1] : $order_by;
  1836. }
  1837. else
  1838. $this->_orderBy = $order_by;
  1839. $this->_orderWay = Tools::strtoupper($order_way);
  1840. /* SQL table : orders, but class name is Order */
  1841. $sql_table = $this->table == 'order' ? 'orders' : $this->table;
  1842. // Add SQL shop restriction
  1843. $select_shop = $join_shop = $where_shop = '';
  1844. if ($this->shopLinkType)
  1845. {
  1846. $select_shop = ', shop.name as shop_name ';
  1847. $join_shop = ' LEFT JOIN '._DB_PREFIX_.$this->shopLinkType.' shop
  1848. ON a.id_'.$this->shopLinkType.' = shop.id_'.$this->shopLinkType;
  1849. $where_shop = Shop::addSqlRestriction($this->shopShareDatas, 'a', $this->shopLinkType);
  1850. }
  1851. if ($this->multishop_context && Shop::isTableAssociated($this->table) && !empty($this->className))
  1852. {
  1853. if (Shop::getContext() != Shop::CONTEXT_ALL || !$this->context->employee->isSuperAdmin())
  1854. {
  1855. $test_join = !preg_match('#`?'.preg_quote(_DB_PREFIX_.$this->table.'_shop').'`? *sa#', $this->_join);
  1856. if (Shop::isFeatureActive() && $test_join && Shop::isTableAssociated($this->table))
  1857. {
  1858. $this->_where .= ' AND a.'.$this->identifier.' IN (
  1859. SELECT sa.'.$this->identifier.'
  1860. FROM `'._DB_PREFIX_.$this->table.'_shop` sa
  1861. WHERE sa.id_shop IN ('.implode(', ', Shop::getContextListShopID()).')
  1862. )';
  1863. }
  1864. }
  1865. }
  1866. /* Query in order to get results with all fields */
  1867. $lang_join = '';
  1868. if ($this->lang)
  1869. {
  1870. $lang_join = 'LEFT JOIN `'._DB_PREFIX_.$this->table.'_lang` b ON (b.`'.$this->identifier.'` = a.`'.$this->identifier.'` AND b.`id_lang` = '.(int)$id_lang;
  1871. if ($id_lang_shop)
  1872. {
  1873. if (!Shop::isFeatureActive())
  1874. $lang_join .= ' AND b.`id_shop` = 1';
  1875. elseif (Shop::getContext() == Shop::CONTEXT_SHOP)
  1876. $lang_join .= ' AND b.`id_shop` = '.(int)$id_lang_shop;
  1877. else
  1878. $lang_join .= ' AND b.`id_shop` = a.id_shop_default';
  1879. }
  1880. $lang_join .= ')';
  1881. }
  1882. $having_clause = '';
  1883. if (isset($this->_filterHaving) || isset($this->_having))
  1884. {
  1885. $having_clause = ' HAVING ';
  1886. if (isset($this->_filterHaving))
  1887. $having_clause .= ltrim($this->_filterHaving, ' AND ');
  1888. if (isset($this->_having))
  1889. $having_clause .= $this->_having.' ';
  1890. }
  1891. $this->_listsql = '
  1892. SELECT SQL_CALC_FOUND_ROWS
  1893. '.($this->_tmpTableFilter ? ' * FROM (SELECT ' : '');
  1894. if ($this->explicitSelect)
  1895. {
  1896. foreach ($this->fields_list as $key => $array_value)
  1897. {
  1898. // Add it only if it is not already in $this->_select
  1899. if (isset($this->_select) && preg_match('/[\s]`?'.preg_quote($key, '/').'`?\s*,/', $this->_select))
  1900. continue;
  1901. if (isset($array_value['filter_key']))
  1902. $this->_listsql .= str_replace('!', '.', $array_value['filter_key']).' as '.$key.',';
  1903. elseif ($key == 'id_'.$this->table)
  1904. $this->_listsql .= 'a.`'.bqSQL($key).'`,';
  1905. elseif ($key != 'image' && !preg_match('/'.preg_quote($key, '/').'/i', $this->_select))
  1906. $this->_listsql .= '`'.bqSQL($key).'`,';
  1907. }
  1908. $this->_listsql = rtrim($this->_listsql, ',');
  1909. }
  1910. else
  1911. $this->_listsql .= ($this->lang ? 'b.*,' : '').' a.*';
  1912. $this->_listsql .= '
  1913. '.(isset($this->_select) ? ', '.$this->_select : '').$select_shop.'
  1914. FROM `'._DB_PREFIX_.$sql_table.'` a
  1915. '.$lang_join.'
  1916. '.(isset($this->_join) ? $this->_join.' ' : '').'
  1917. '.$join_shop.'
  1918. WHERE 1 '.(isset($this->_where) ? $this->_where.' ' : '').($this->deleted ? 'AND a.`deleted` = 0 ' : '').
  1919. (isset($this->_filter) ? $this->_filter : '').$where_shop.'
  1920. '.(isset($this->_group) ? $this->_group.' ' : '').'
  1921. '.$having_clause.'
  1922. ORDER BY '.(($order_by == $this->identifier) ? 'a.' : '').pSQL($order_by).' '.pSQL($order_way).
  1923. ($this->_tmpTableFilter ? ') tmpTable WHERE 1'.$this->_tmpTableFilter : '').
  1924. (($use_limit === true) ? ' LIMIT '.(int)$start.','.(int)$limit : '');
  1925. if (!($this->_list = Db::getInstance()->executeS($this->_listsql)))
  1926. $this->_list_error = Db::getInstance()->getMsgError();
  1927. else
  1928. $this->_listTotal = Db::getInstance()->getValue('SELECT FOUND_ROWS() AS `'._DB_PREFIX_.$this->table.'`');
  1929. }
  1930. public function getModulesList($filter_modules_list)
  1931. {
  1932. if (!is_array($filter_modules_list) && !is_null($filter_modules_list))
  1933. $filter_modules_list = array($filter_modules_list);
  1934. if (!count($filter_modules_list))
  1935. return false; //if there is no modules to display just return false;
  1936. $all_modules = Module::getModulesOnDisk(true);
  1937. $this->modules_list = array();
  1938. foreach($all_modules as $module)
  1939. {
  1940. $perm = true;
  1941. if ($module->id)
  1942. $perm &= Module::getPermissionStatic($module->id, 'configure');
  1943. else
  1944. {
  1945. $id_admin_module = Tab::getIdFromClassName('AdminModules');
  1946. $access = Profile::getProfileAccess($this->context->employee->id_profile, $id_admin_module);
  1947. if (!$access['edit'])
  1948. $perm &= false;
  1949. }
  1950. if (in_array($module->name, $filter_modules_list) && $perm)
  1951. {
  1952. $this->fillModuleData($module, 'select');
  1953. $this->modules_list[] = $module;
  1954. }
  1955. }
  1956. if (count($this->modules_list))
  1957. return true;
  1958. return false; //no module found on disk just return false;
  1959. }
  1960. public function getLanguages()
  1961. {
  1962. $cookie = $this->context->cookie;
  1963. $this->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
  1964. if ($this->allow_employee_form_lang && !$cookie->employee_form_lang)
  1965. $cookie->employee_form_lang = (int)Configuration::get('PS_LANG_DEFAULT');
  1966. $use_lang_from_cookie = false;
  1967. $this->_languages = Language::getLanguages(false);
  1968. if ($this->allow_employee_form_lang)
  1969. foreach ($this->_languages as $lang)
  1970. if ($cookie->employee_form_lang == $lang['id_lang'])
  1971. $use_lang_from_cookie = true;
  1972. if (!$use_lang_from_cookie)
  1973. $this->default_form_language = (int)Configuration::get('PS_LANG_DEFAULT');
  1974. else
  1975. $this->default_form_language = (int)$cookie->employee_form_lang;
  1976. foreach ($this->_languages as $k => $language)
  1977. $this->_languages[$k]['is_default'] = (int)($language['id_lang'] == $this->default_form_language);
  1978. return $this->_languages;
  1979. }
  1980. /**
  1981. * Return the list of fields value
  1982. *
  1983. * @param object $obj Object
  1984. * @return array
  1985. */
  1986. public function getFieldsValue($obj)
  1987. {
  1988. foreach ($this->fields_form as $fieldset)
  1989. if (isset($fieldset['form']['input']))
  1990. foreach ($fieldset['form']['input'] as $input)
  1991. if (!isset($this->fields_value[$input['name']]))
  1992. if (isset($input['type']) && $input['type'] == 'shop')
  1993. {
  1994. if ($obj->id)
  1995. {
  1996. $result = Shop::getShopById((int)$obj->id, $this->identifier, $this->table);
  1997. foreach ($result as $row)
  1998. $this->fields_value['shop'][$row['id_'.$input['type']]][] = $row['id_shop'];
  1999. }
  2000. }
  2001. elseif (isset($input['lang']) && $input['lang'])
  2002. foreach ($this->_languages as $language)
  2003. {
  2004. $fieldValue = $this->getFieldValue($obj, $input['name'], $language['id_lang']);
  2005. if (empty($fieldValue))
  2006. {
  2007. if (isset($input['default_value']) && is_array($input['default_value']) && isset($input['default_value'][$language['id_lang']]))
  2008. $fieldValue = $input['default_value'][$language['id_lang']];
  2009. elseif (isset($input['default_value']))
  2010. $fieldValue = $input['default_value'];
  2011. }
  2012. $this->fields_value[$input['name']][$language['id_lang']] = $fieldValue;
  2013. }
  2014. else
  2015. {
  2016. $fieldValue = $this->getFieldValue($obj, $input['name']);
  2017. if ($fieldValue === false && isset($input['default_value']))
  2018. $fieldValue = $input['default_value'];
  2019. $this->fields_value[$input['name']] = $fieldValue;
  2020. }
  2021. return $this->fields_value;
  2022. }
  2023. /**
  2024. * Return field value if possible (both classical and multilingual fields)
  2025. *
  2026. * Case 1 : Return value if present in $_POST / $_GET
  2027. * Case 2 : Return object value
  2028. *
  2029. * @param object $obj Object
  2030. * @param string $key Field name
  2031. * @param integer $id_lang Language id (optional)
  2032. * @return string
  2033. */
  2034. public function getFieldValue($obj, $key, $id_lang = null)
  2035. {
  2036. if ($id_lang)
  2037. $default_value = ($obj->id && isset($obj->{$key}[$id_lang])) ? $obj->{$key}[$id_lang] : false;
  2038. else
  2039. $default_value = isset($obj->{$key}) ? $obj->{$key} : false;
  2040. return Tools::getValue($key.($id_lang ? '_'.$id_lang : ''), $default_value);
  2041. }
  2042. /**
  2043. * Manage page display (form, list...)
  2044. *
  2045. * @param string $className Allow to validate a different class than the current one
  2046. */
  2047. public function validateRules($class_name = false)
  2048. {
  2049. if (!$class_name)
  2050. $class_name = $this->className;
  2051. /* Class specific validation rules */
  2052. if (!empty($class_name))
  2053. $rules = call_user_func(array($class_name, 'getValidationRules'), $class_name);
  2054. if (isset($rules) && count($rules) && (count($rules['requiredLang']) || count($rules['sizeLang']) || count($rules['validateLang'])))
  2055. {
  2056. /* Language() instance determined by default language */
  2057. $default_language = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
  2058. /* All availables languages */
  2059. $languages = Language::getLanguages(false);
  2060. }
  2061. /* Checking for required fields */
  2062. if (isset($rules['required']) && is_array($rules['required']))
  2063. foreach ($rules['required'] as $field)
  2064. if (($value = Tools::getValue($field)) == false && (string)$value != '0')
  2065. if (!Tools::getValue($this->identifier) || ($field != 'passwd' && $field != 'no-picture'))
  2066. $this->errors[] = sprintf(
  2067. Tools::displayError('The %s field is required.'),
  2068. call_user_func(array($class_name, 'displayFieldName'), $field, $class_name)
  2069. );
  2070. /* Checking for multilingual required fields */
  2071. if (isset($rules['requiredLang']) && is_array($rules['requiredLang']))
  2072. foreach ($rules['requiredLang'] as $field_lang)
  2073. if (($empty = Tools::getValue($field_lang.'_'.$default_language->id)) === false || $empty !== '0' && empty($empty))
  2074. $this->errors[] = sprintf(
  2075. Tools::displayError('The field %1$s is required at least in %2$s.'),
  2076. call_user_func(array($class_name, 'displayFieldName'), $field_lang, $class_name),
  2077. $default_language->name
  2078. );
  2079. /* Checking for maximum fields sizes */
  2080. if (isset($rules['size']) && is_array($rules['size']))
  2081. foreach ($rules['size'] as $field => $max_length)
  2082. if (Tools::getValue($field) !== false && Tools::strlen(Tools::getValue($field)) > $max_length)
  2083. $this->errors[] = sprintf(
  2084. Tools::displayError('The %1$s field is too long (%2$d chars max).'),
  2085. call_user_func(array($class_name, 'displayFieldName'), $field, $class_name),
  2086. $max_length
  2087. );
  2088. /* Checking for maximum multilingual fields size */
  2089. if (isset($rules['sizeLang']) && is_array($rules['sizeLang']))
  2090. foreach ($rules['sizeLang'] as $field_lang => $max_length)
  2091. foreach ($languages as $language)
  2092. {
  2093. $field_lang_value = Tools::getValue($field_lang.'_'.$language['id_lang']);
  2094. if ($field_lang_value !== false && Tools::strlen($field_lang_value) > $max_length)
  2095. $this->errors[] = sprintf(
  2096. Tools::displayError('The field %1$s (%2$s) is too long (%3$d chars max, html chars including).'),
  2097. call_user_func(array($class_name, 'displayFieldName'), $field_lang, $class_name),
  2098. $language['name'],
  2099. $max_length
  2100. );
  2101. }
  2102. /* Overload this method for custom checking */
  2103. $this->_childValidation();
  2104. /* Checking for fields validity */
  2105. if (isset($rules['validate']) && is_array($rules['validate']))
  2106. foreach ($rules['validate'] as $field => $function)
  2107. if (($value = Tools::getValue($field)) !== false && ($field != 'passwd'))
  2108. if (!Validate::$function($value) && !empty($value))
  2109. $this->errors[] = sprintf(
  2110. Tools::displayError('The %s field is invalid.'),
  2111. call_user_func(array($class_name, 'displayFieldName'), $field, $class_name)
  2112. );
  2113. /* Checking for passwd_old validity */
  2114. if (($value = Tools::getValue('passwd')) != false)
  2115. {
  2116. if ($class_name == 'Employee' && !Validate::isPasswdAdmin($value))
  2117. $this->errors[] = sprintf(
  2118. Tools::displayError('The %s field is invalid.'),
  2119. call_user_func(array($class_name, 'displayFieldName'), 'passwd', $class_name)
  2120. );
  2121. elseif ($class_name == 'Customer' && !Validate::isPasswd($value))
  2122. $this->errors[] = sprintf(
  2123. Tools::displayError('The %s field is invalid.'),
  2124. call_user_func(array($class_name, 'displayFieldName'), 'passwd', $class_name)
  2125. );
  2126. }
  2127. /* Checking for multilingual fields validity */
  2128. if (isset($rules['validateLang']) && is_array($rules['validateLang']))
  2129. foreach ($rules['validateLang'] as $field_lang => $function)
  2130. foreach ($languages as $language)
  2131. if (($value = Tools::getValue($field_lang.'_'.$language['id_lang'])) !== false && !empty($value))
  2132. if (!Validate::$function($value))
  2133. $this->errors[] = sprintf(
  2134. Tools::displayError('The %1$s field (%2$s) is invalid.'),
  2135. call_user_func(array($class_name, 'displayFieldName'), $field_lang, $class_name),
  2136. $language['name']
  2137. );
  2138. }
  2139. /**
  2140. * Overload this method for custom checking
  2141. */
  2142. protected function _childValidation()
  2143. {
  2144. }
  2145. /**
  2146. * Display object details
  2147. */
  2148. public function viewDetails()
  2149. {
  2150. }
  2151. /**
  2152. * Called before deletion
  2153. *
  2154. * @param object $object Object
  2155. * @return boolean
  2156. */
  2157. protected function beforeDelete($object)
  2158. {
  2159. return false;
  2160. }
  2161. /**
  2162. * Called before deletion
  2163. *
  2164. * @param object $object Object
  2165. * @return boolean
  2166. */
  2167. protected function afterDelete($object, $oldId)
  2168. {
  2169. return true;
  2170. }
  2171. protected function afterAdd($object)
  2172. {
  2173. return true;
  2174. }
  2175. protected function afterUpdate($object)
  2176. {
  2177. return true;
  2178. }
  2179. /**
  2180. * Check rights to view the current tab
  2181. *
  2182. * @return boolean
  2183. */
  2184. protected function afterImageUpload()
  2185. {
  2186. return true;
  2187. }
  2188. /**
  2189. * Copy datas from $_POST to object
  2190. *
  2191. * @param object &$object Object
  2192. * @param string $table Object table
  2193. */
  2194. protected function copyFromPost(&$object, $table)
  2195. {
  2196. /* Classical fields */
  2197. foreach ($_POST as $key => $value)
  2198. if (key_exists($key, $object) && $key != 'id_'.$table)
  2199. {
  2200. /* Do not take care of password field if empty */
  2201. if ($key == 'passwd' && Tools::getValue('id_'.$table) && empty($value))
  2202. continue;
  2203. /* Automatically encrypt password in MD5 */
  2204. if ($key == 'passwd' && !empty($value))
  2205. $value = Tools::encrypt($value);
  2206. $object->{$key} = $value;
  2207. }
  2208. /* Multilingual fields */
  2209. $rules = call_user_func(array(get_class($object), 'getValidationRules'), get_class($object));
  2210. if (count($rules['validateLang']))
  2211. {
  2212. $languages = Language::getLanguages(false);
  2213. foreach ($languages as $language)
  2214. foreach (array_keys($rules['validateLang']) as $field)
  2215. if (isset($_POST[$field.'_'.(int)$language['id_lang']]))
  2216. $object->{$field}[(int)$language['id_lang']] = $_POST[$field.'_'.(int)$language['id_lang']];
  2217. }
  2218. }
  2219. /**
  2220. * Returns an array with selected shops and type (group or boutique shop)
  2221. *
  2222. * @param string $table
  2223. * @return array
  2224. */
  2225. protected function getSelectedAssoShop($table)
  2226. {
  2227. if (!Shop::isFeatureActive() || !Shop::isTableAssociated($table))
  2228. return array();
  2229. $shops = Shop::getShops(true, null, true);
  2230. if (count($shops) == 1 && isset($shops[0]))
  2231. return array($shops[0], 'shop');
  2232. $assos = array();
  2233. if (Tools::isSubmit('checkBoxShopAsso_'.$table))
  2234. foreach (Tools::getValue('checkBoxShopAsso_'.$table) as $id_shop => $value)
  2235. $assos[] = (int)$id_shop;
  2236. 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
  2237. $assos[] = (int)Shop::getContextShopID();
  2238. return $assos;
  2239. }
  2240. /**
  2241. * Update the associations of shops
  2242. *
  2243. * @param int $id_object
  2244. */
  2245. protected function updateAssoShop($id_object)
  2246. {
  2247. if (!Shop::isFeatureActive())
  2248. return;
  2249. if (!Shop::isTableAssociated($this->table))
  2250. return;
  2251. $assos_data = $this->getSelectedAssoShop($this->table, $id_object);
  2252. // Get list of shop id we want to exclude from asso deletion
  2253. $exclude_ids = $assos_data;
  2254. foreach (Db::getInstance()->executeS('SELECT id_shop FROM '._DB_PREFIX_.'shop') as $row)
  2255. if (!$this->context->employee->hasAuthOnShop($row['id_shop']))
  2256. $exclude_ids[] = $row['id_shop'];
  2257. Db::getInstance()->delete($this->table.'_shop', '`'.$this->identifier.'` = '.(int)$id_object.($exclude_ids ? ' AND id_shop NOT IN ('.implode(', ', $exclude_ids).')' : ''));
  2258. $insert = array();
  2259. foreach ($assos_data as $id_shop)
  2260. $insert[] = array(
  2261. $this->identifier => $id_object,
  2262. 'id_shop' => (int)$id_shop,
  2263. );
  2264. return Db::getInstance()->insert($this->table.'_shop', $insert, false, true, Db::INSERT_IGNORE);
  2265. }
  2266. protected function validateField($value, $field)
  2267. {
  2268. if (isset($field['validation']))
  2269. {
  2270. $valid_method_exists = method_exists('Validate', $field['validation']);
  2271. if ((!isset($field['empty']) || !$field['empty'] || (isset($field['empty']) && $field['empty'] && $value)) && $valid_method_exists)
  2272. {
  2273. if (!Validate::$field['validation']($value))
  2274. {
  2275. $this->errors[] = Tools::displayError($field['title'].' : Incorrect value');
  2276. return false;
  2277. }
  2278. }
  2279. }
  2280. return true;
  2281. }
  2282. /**
  2283. * Can be overriden
  2284. */
  2285. public function beforeUpdateOptions()
  2286. {
  2287. }
  2288. /**
  2289. * Overload this method for custom checking
  2290. *
  2291. * @param integer $id Object id used for deleting images
  2292. * @return boolean
  2293. */
  2294. protected function postImage($id)
  2295. {
  2296. if (isset($this->fieldImageSettings['name']) && isset($this->fieldImageSettings['dir']))
  2297. return $this->uploadImage($id, $this->fieldImageSettings['name'], $this->fieldImageSettings['dir'].'/');
  2298. elseif (!empty($this->fieldImageSettings))
  2299. foreach ($this->fieldImageSettings as $image)
  2300. if (isset($image['name']) && isset($image['dir']))
  2301. $this->uploadImage($id, $image['name'], $image['dir'].'/');
  2302. return !count($this->errors) ? true : false;
  2303. }
  2304. protected function uploadImage($id, $name, $dir, $ext = false, $width = null, $height = null)
  2305. {
  2306. if (isset($_FILES[$name]['tmp_name']) && !empty($_FILES[$name]['tmp_name']))
  2307. {
  2308. // Delete old image
  2309. if (Validate::isLoadedObject($object = $this->loadObject()))
  2310. $object->deleteImage();
  2311. else
  2312. return false;
  2313. // Check image validity
  2314. $max_size = isset($this->max_image_size) ? $this->max_image_size : 0;
  2315. if ($error = ImageManager::validateUpload($_FILES[$name], Tools::getMaxUploadSize($max_size)))
  2316. $this->errors[] = $error;
  2317. $tmp_name = tempnam(_PS_TMP_IMG_DIR_, 'PS');
  2318. if (!$tmp_name)
  2319. return false;
  2320. if (!move_uploaded_file($_FILES[$name]['tmp_name'], $tmp_name))
  2321. return false;
  2322. // Evaluate the memory required to resize the image: if it's too much, you can't resize it.
  2323. if (!ImageManager::checkImageMemoryLimit($tmp_name))
  2324. $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. ');
  2325. // Copy new image
  2326. if (empty($this->errors) && !ImageManager::resize($tmp_name, _PS_IMG_DIR_.$dir.$id.'.'.$this->imageType, (int)$width, (int)$height, ($ext ? $ext : $this->imageType)))
  2327. $this->errors[] = Tools::displayError('An error occurred while uploading the image.');
  2328. if (count($this->errors))
  2329. return false;
  2330. if ($this->afterImageUpload())
  2331. {
  2332. unlink($tmp_name);
  2333. return true;
  2334. }
  2335. return false;
  2336. }
  2337. return true;
  2338. }
  2339. /**
  2340. * Delete multiple items
  2341. *
  2342. * @return boolean true if succcess
  2343. */
  2344. protected function processBulkDelete()
  2345. {
  2346. if (is_array($this->boxes) && !empty($this->boxes))
  2347. {
  2348. $object = new $this->className();
  2349. if (isset($object->noZeroObject))
  2350. {
  2351. $objects_count = count(call_user_func(array($this->className, $object->noZeroObject)));
  2352. // Check if all object will be deleted
  2353. if ($objects_count <= 1 || count($this->boxes) == $objects_count)
  2354. $this->errors[] = Tools::displayError('You need at least one object.').
  2355. ' <b>'.$this->table.'</b><br />'.
  2356. Tools::displayError('You cannot delete all of the items.');
  2357. }
  2358. else
  2359. {
  2360. $result = true;
  2361. if ($this->deleted)
  2362. {
  2363. foreach ($this->boxes as $id)
  2364. {
  2365. $to_delete = new $this->className($id);
  2366. $to_delete->deleted = 1;
  2367. $result = $result && $to_delete->update();
  2368. }
  2369. }
  2370. else
  2371. $result = $object->deleteSelection(Tools::getValue($this->table.'Box'));
  2372. if ($result)
  2373. $this->redirect_after = self::$currentIndex.'&conf=2&token='.$this->token;
  2374. $this->errors[] = Tools::displayError('An error occurred while deleting this selection.');
  2375. }
  2376. }
  2377. else
  2378. $this->errors[] = Tools::displayError('You must select at least one element to delete.');
  2379. if (isset($result))
  2380. return $result;
  2381. else
  2382. return false;
  2383. }
  2384. /**
  2385. * Enable multiple items
  2386. *
  2387. * @return boolean true if succcess
  2388. */
  2389. protected function processBulkEnableSelection()
  2390. {
  2391. return $this->processBulkStatusSelection(1);
  2392. }
  2393. /**
  2394. * Disable multiple items
  2395. *
  2396. * @return boolean true if succcess
  2397. */
  2398. protected function processBulkDisableSelection()
  2399. {
  2400. return $this->processBulkStatusSelection(0);
  2401. }
  2402. /**
  2403. * Toggle status of multiple items
  2404. *
  2405. * @return boolean true if succcess
  2406. */
  2407. protected function processBulkStatusSelection($status)
  2408. {
  2409. $result = true;
  2410. if (is_array($this->boxes) && !empty($this->boxes))
  2411. {
  2412. foreach ($this->boxes as $id)
  2413. {
  2414. $object = new $this->className((int)$id);
  2415. $object->active = (int)$status;
  2416. $result &= $object->update();
  2417. }
  2418. }
  2419. return $result;
  2420. }
  2421. protected function processBulkAffectZone()
  2422. {
  2423. $result = false;
  2424. if (is_array($this->boxes) && !empty($this->boxes))
  2425. {
  2426. $object = new $this->className();
  2427. $result = $object->affectZoneToSelection(Tools::getValue($this->table.'Box'), Tools::getValue('zone_to_affect'));
  2428. if ($result)
  2429. $this->redirect_after = self::$currentIndex.'&conf=28&token='.$this->token;
  2430. $this->errors[] = Tools::displayError('An error occurred while affecting a zone to the selection.');
  2431. }
  2432. else
  2433. $this->errors[] = Tools::displayError('You must select at least one element to affect a new zone.');
  2434. return $result;
  2435. }
  2436. /**
  2437. * Called before Add
  2438. *
  2439. * @param object $object Object
  2440. * @return boolean
  2441. */
  2442. protected function beforeAdd($object)
  2443. {
  2444. return true;
  2445. }
  2446. /**
  2447. * prepare the view to display the required fields form
  2448. */
  2449. public function displayRequiredFields()
  2450. {
  2451. if (!$this->tabAccess['add'] || !$this->tabAccess['delete'] === '1' || !$this->required_database)
  2452. return;
  2453. $helper = new Helper();
  2454. $helper->currentIndex = self::$currentIndex;
  2455. $helper->token = $this->token;
  2456. return $helper->renderRequiredFields($this->className, $this->identifier, $this->required_fields);
  2457. }
  2458. /**
  2459. * Create a template from the override file, else from the base file.
  2460. *
  2461. * @param string $tpl_name filename
  2462. * @return Template
  2463. */
  2464. public function createTemplate($tpl_name)
  2465. {
  2466. // Use override tpl if it exists
  2467. // If view access is denied, we want to use the default template that will be used to display an error
  2468. if ($this->viewAccess() && $this->override_folder)
  2469. {
  2470. if (file_exists($this->context->smarty->getTemplateDir(1).DIRECTORY_SEPARATOR.$this->override_folder.$tpl_name))
  2471. return $this->context->smarty->createTemplate($this->override_folder.$tpl_name, $this->context->smarty);
  2472. else if (file_exists($this->context->smarty->getTemplateDir(0).'controllers'.DIRECTORY_SEPARATOR.$this->override_folder.$tpl_name))
  2473. return $this->context->smarty->createTemplate('controllers'.DIRECTORY_SEPARATOR.$this->override_folder.$tpl_name, $this->context->smarty);
  2474. }
  2475. return $this->context->smarty->createTemplate($this->context->smarty->getTemplateDir(0).$tpl_name, $this->context->smarty);
  2476. }
  2477. /**
  2478. * Shortcut to set up a json success payload
  2479. *
  2480. * @param $message success message
  2481. */
  2482. public function jsonConfirmation($message)
  2483. {
  2484. $this->json = true;
  2485. $this->confirmations[] = $message;
  2486. if ($this->status === '')
  2487. $this->status = 'ok';
  2488. }
  2489. /**
  2490. * Shortcut to set up a json error payload
  2491. *
  2492. * @param $message error message
  2493. */
  2494. public function jsonError($message)
  2495. {
  2496. $this->json = true;
  2497. $this->errors[] = $message;
  2498. if ($this->status === '')
  2499. $this->status = 'error';
  2500. }
  2501. public function isFresh($file, $timeout = 604800000)
  2502. {
  2503. if (file_exists(_PS_ROOT_DIR_.$file))
  2504. {
  2505. if (filesize(_PS_ROOT_DIR_.$file) < 1)
  2506. return false;
  2507. return ((time() - filemtime(_PS_ROOT_DIR_.$file)) < $timeout);
  2508. }
  2509. else
  2510. return false;
  2511. }
  2512. public function refresh($file_to_refresh, $external_file)
  2513. {
  2514. $content = Tools::file_get_contents($external_file);
  2515. if ($content)
  2516. return (bool)file_put_contents(_PS_ROOT_DIR_.$file_to_refresh, $content);
  2517. return false;
  2518. }
  2519. public function fillModuleData(&$module, $output_type = 'link', $back = null)
  2520. {
  2521. $obj = null;
  2522. if ($module->onclick_option)
  2523. $obj = new $module->name();
  2524. // Fill module data
  2525. $module->logo = '../../img/questionmark.png';
  2526. if (file_exists('../modules/'.$module->name.'/logo.gif'))
  2527. $module->logo = 'logo.gif';
  2528. if (file_exists('../modules/'.$module->name.'/logo.png'))
  2529. $module->logo = 'logo.png';
  2530. $module->optionsHtml = $this->displayModuleOptions($module, $output_type);
  2531. $link_admin_modules = $this->context->link->getAdminLink('AdminModules', true);
  2532. $module->options['install_url'] = $link_admin_modules.'&install='.urlencode($module->name).'&tab_module='.$module->tab.'&module_name='.$module->name.'&anchor=anchor'.ucfirst($module->name);
  2533. $module->options['update_url'] = $link_admin_modules.'&update='.urlencode($module->name).'&tab_module='.$module->tab.'&module_name='.$module->name.'&anchor=anchor'.ucfirst($module->name);
  2534. $module->options['uninstall_url'] = $link_admin_modules.'&uninstall='.urlencode($module->name).'&tab_module='.$module->tab.'&module_name='.$module->name.'&anchor=anchor'.ucfirst($module->name);
  2535. $module->options['uninstall_onclick'] = ((!$module->onclick_option) ?
  2536. ((empty($module->confirmUninstall)) ? '' : 'return confirm(\''.addslashes($module->confirmUninstall).'\');') :
  2537. $obj->onclickOption('uninstall', $module->options['uninstall_url']));
  2538. if ((Tools::getValue('module_name') == $module->name || in_array($module->name, explode('|', Tools::getValue('modules_list')))) && (int)Tools::getValue('conf') > 0)
  2539. $module->message = $this->_conf[(int)Tools::getValue('conf')];
  2540. if ((Tools::getValue('module_name') == $module->name || in_array($module->name, explode('|', Tools::getValue('modules_list')))) && (int)Tools::getValue('conf') > 0)
  2541. unset($obj);
  2542. }
  2543. /**
  2544. * Display modules list
  2545. *
  2546. * @param $module
  2547. * @param $output_type (link or select)
  2548. * @param $back
  2549. *
  2550. * @return string
  2551. */
  2552. protected $translationsTab = array();
  2553. public function displayModuleOptions($module, $output_type = 'link', $back = null)
  2554. {
  2555. if (!isset($this->translationsTab['Disable this module']))
  2556. {
  2557. $this->translationsTab['Disable this module'] = $this->l('Disable this module');
  2558. $this->translationsTab['Enable this module for all shops'] = $this->l('Enable this module for all shops');
  2559. $this->translationsTab['Disable'] = $this->l('Disable');
  2560. $this->translationsTab['Enable'] = $this->l('Enable');
  2561. $this->translationsTab['Reset'] = $this->l('Reset');
  2562. $this->translationsTab['Configure'] = $this->l('Configure');
  2563. $this->translationsTab['Delete'] = $this->l('Delete');
  2564. $this->translationsTab['Install'] = $this->l('Install');
  2565. $this->translationsTab['Uninstall'] = $this->l('Uninstall');
  2566. $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?');
  2567. }
  2568. $link_admin_modules = $this->context->link->getAdminLink('AdminModules', true);
  2569. $modules_options = array(
  2570. 'configure-module' => array(
  2571. 'href' => $link_admin_modules.'&configure='.urlencode($module->name).'&tab_module='.$module->tab.'&module_name='.urlencode($module->name),
  2572. 'onclick' => $module->onclick_option && isset($module->onclick_option_content['configure']) ? $module->onclick_option_content['configure'] : '',
  2573. 'title' => '',
  2574. 'text' => $this->translationsTab['Configure'],
  2575. 'cond' => $module->id && isset($module->is_configurable) && $module->is_configurable,
  2576. ),
  2577. 'desactive-module' => array(
  2578. 'href' => $link_admin_modules.'&module_name='.urlencode($module->name).'&'.($module->active ? 'enable=0' : 'enable=1').'&tab_module='.$module->tab,
  2579. 'onclick' => $module->active && $module->onclick_option && isset($module->onclick_option_content['desactive']) ? $module->onclick_option_content['desactive'] : '' ,
  2580. 'title' => Shop::isFeatureActive() ? htmlspecialchars($module->active ? $this->translationsTab['Disable this module'] : $this->translationsTab['Enable this module for all shops']) : '',
  2581. 'text' => $module->active ? $this->translationsTab['Disable'] : $this->translationsTab['Enable'],
  2582. 'cond' => $module->id,
  2583. ),
  2584. 'reset-module' => array(
  2585. 'href' => $link_admin_modules.'&module_name='.urlencode($module->name).'&reset&tab_module='.$module->tab,
  2586. 'onclick' => $module->onclick_option && isset($module->onclick_option_content['reset']) ? $module->onclick_option_content['reset'] : '',
  2587. 'title' => '',
  2588. 'text' => $this->translationsTab['Reset'],
  2589. 'cond' => $module->id && $module->active,
  2590. ),
  2591. 'delete-module' => array(
  2592. 'href' => $link_admin_modules.'&delete='.urlencode($module->name).'&tab_module='.$module->tab.'&module_name='.urlencode($module->name),
  2593. '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?'].'\');',
  2594. 'title' => '',
  2595. 'text' => $this->translationsTab['Delete'],
  2596. 'cond' => true,
  2597. ),
  2598. );
  2599. $return = '';
  2600. foreach ($modules_options as $option_name => $option)
  2601. {
  2602. if ($option['cond'])
  2603. {
  2604. if ($output_type == 'link')
  2605. $return .= '<span class="'.$option_name.'">
  2606. <a class="action_module" href="'.$option['href'].(!is_null($back) ? '&back='.urlencode($back) : '').'" onclick="'.$option['onclick'].'" title="'.$option['title'].'">'.$option['text'].'</a>
  2607. </span>';
  2608. elseif ($output_type == 'select')
  2609. $return .= '<option id="'.$option_name.'" data-href="'.$option['href'].(!is_null($back) ? '&back='.urlencode($back) : '').'" data-onclick="'.$option['onclick'].'">'.$option['text'].'</option>';
  2610. }
  2611. }
  2612. if ($output_type == 'select')
  2613. {
  2614. if (!$module->id)
  2615. $return = '<option data-onclick="" data-href="'.$link_admin_modules.'&install='.urlencode($module->name).'&tab_module='.$module->tab.'&module_name='.$module->name.'&anchor=anchor'.ucfirst($module->name).(!is_null($back) ? '&back='.urlencode($back) : '').'" >'.$this->translationsTab['Install'].'</option>'.$return;
  2616. else
  2617. $return .= '<option data-onclick="" data-href="'.$link_admin_modules.'&uninstall='.urlencode($module->name).'&tab_module='.$module->tab.'&module_name='.$module->name.'&anchor=anchor'.ucfirst($module->name).(!is_null($back) ? '&back='.urlencode($back) : '').'" >'.$this->translationsTab['Uninstall'].'</option>';
  2618. $return = '<select id="select_'.$module->name.'">'.$return.'</select>';
  2619. }
  2620. return $return;
  2621. }
  2622. }