PageRenderTime 136ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/classes/controller/AdminController.php

https://bitbucket.org/enurkov/prestashop
PHP | 2810 lines | 1984 code | 337 blank | 489 comment | 537 complexity | 14f3db9c3194db499b585cca91460c9a MD5 | raw file

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

  1. <?php
  2. /*
  3. * 2007-2012 PrestaShop
  4. *
  5. * NOTICE OF LICENSE
  6. *
  7. * This source file is subject to the Open Software License (OSL 3.0)
  8. * that is bundled with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://opensource.org/licenses/osl-3.0.php
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@prestashop.com so we can send you a copy immediately.
  14. *
  15. * DISCLAIMER
  16. *
  17. * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
  18. * versions in the future. If you wish to customize PrestaShop for your
  19. * needs please refer to http://www.prestashop.com for more information.
  20. *
  21. * @author PrestaShop SA <contact@prestashop.com>
  22. * @copyright 2007-2012 PrestaShop SA
  23. * @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. protected $addons_url = 'api.addons.prestashop.com';
  36. public $_languages = array();
  37. public $default_form_language;
  38. public $allow_employee_form_lang;
  39. public $layout = 'layout.tpl';
  40. protected $meta_title;
  41. public $template = 'content.tpl';
  42. /** @var string Associated table name */
  43. public $table;
  44. /** @var string Object identifier inside the associated table */
  45. protected $identifier = false;
  46. /** @var string Tab name */
  47. public $className;
  48. /** @var array tabAccess */
  49. public $tabAccess;
  50. /** @var integer Tab id */
  51. public $id = -1;
  52. public $required_database = false;
  53. /** @var string Security token */
  54. public $token;
  55. /** @var string shop | group_shop */
  56. public $shopLinkType;
  57. /** @var string Default ORDER BY clause when $_orderBy is not defined */
  58. protected $_defaultOrderBy = false;
  59. protected $_defaultOrderWay = 'ASC';
  60. public $tpl_form_vars = array();
  61. public $tpl_list_vars = array();
  62. public $tpl_delete_link_vars = array();
  63. public $tpl_option_vars = array();
  64. public $tpl_view_vars = array();
  65. public $tpl_required_fields_vars = array();
  66. public $base_tpl_view = null;
  67. public $base_tpl_form = null;
  68. /** @var bool if you want more fieldsets in the form */
  69. public $multiple_fieldsets = false;
  70. public $fields_value = false;
  71. /** @var array Errors displayed after post processing */
  72. public $errors = array();
  73. /** @var define if the header of the list contains filter and sorting links or not */
  74. protected $list_simple_header;
  75. /** @var array list to be generated */
  76. protected $fields_list;
  77. /** @var array edit form to be generated */
  78. protected $fields_form;
  79. /** @var override of $fields_form */
  80. protected $fields_form_override;
  81. /** @var array list of option forms to be generated */
  82. protected $fields_options;
  83. protected $shopLink;
  84. /** @var string SQL query */
  85. protected $_listsql = '';
  86. /** @var array Cache for query results */
  87. protected $_list = array();
  88. /** @var define if the header of the list contains filter and sorting links or not */
  89. protected $toolbar_title;
  90. /** @var array list of toolbar buttons */
  91. protected $toolbar_btn = null;
  92. /** @var boolean scrolling toolbar */
  93. protected $toolbar_scroll = true;
  94. /** @var boolean set to false to hide toolbar and page title */
  95. protected $show_toolbar = true;
  96. /** @var boolean set to true to show toolbar and page title for options */
  97. protected $show_toolbar_options = false;
  98. /** @var integer Number of results in list */
  99. protected $_listTotal = 0;
  100. /** @var boolean Automatically join language table if true */
  101. public $lang = false;
  102. /** @var array WHERE clause determined by filter fields */
  103. protected $_filter;
  104. /** @var array Temporary SQL table WHERE clause determinated by filter fields */
  105. protected $_tmpTableFilter = '';
  106. /** @var array Number of results in list per page (used in select field) */
  107. protected $_pagination = array(20, 50, 100, 300);
  108. /** @var string ORDER BY clause determined by field/arrows in list header */
  109. protected $_orderBy;
  110. /** @var string Order way (ASC, DESC) determined by arrows in list header */
  111. protected $_orderWay;
  112. /** @var array list of available actions for each list row - default actions are view, edit, delete, duplicate */
  113. protected $actions_available = array('view', 'edit', 'delete', 'duplicate');
  114. /** @var array list of required actions for each list row */
  115. protected $actions = array();
  116. /** @var array list of row ids associated with a given action for witch this action have to not be available */
  117. protected $list_skip_actions = array();
  118. /* @var boolean don't show header & footer */
  119. protected $lite_display = false;
  120. /** @var bool boolean List content lines are clickable if true */
  121. protected $list_no_link = false;
  122. /** @var array $cache_lang cache for traduction */
  123. public static $cache_lang = array();
  124. /** @var array required_fields to display in the Required Fields form */
  125. public $required_fields = array();
  126. /**
  127. * @var array actions to execute on multiple selections
  128. * Usage:
  129. * array(
  130. * 'actionName' => array(
  131. * 'text' => $this->l('Message displayed on the submit button (mandatory)'),
  132. * 'confirm' => $this->l('If set, this confirmation message will pop-up (optional)')),
  133. * 'anotherAction' => array(...)
  134. * );
  135. *
  136. * If your action is named 'actionName', you need to have a method named bulkactionName() that will be executed when the button is clicked.
  137. */
  138. protected $bulk_actions;
  139. /**
  140. * @var array ids of the rows selected
  141. */
  142. protected $boxes;
  143. /** @var string Do not automatically select * anymore but select only what is necessary */
  144. protected $explicitSelect = false;
  145. /** @var string Add fields into data query to display list */
  146. protected $_select;
  147. /** @var string Join tables into data query to display list */
  148. protected $_join;
  149. /** @var string Add conditions into data query to display list */
  150. protected $_where;
  151. /** @var string Group rows into data query to display list */
  152. protected $_group;
  153. /** @var string Having rows into data query to display list */
  154. protected $_having;
  155. protected $is_cms = false;
  156. /** @var string identifier to use for changing positions in lists (can be omitted if positions cannot be changed) */
  157. protected $position_identifier;
  158. /** @var boolean Table records are not deleted but marked as deleted if set to true */
  159. protected $deleted = false;
  160. /**
  161. * @var bool is a list filter set
  162. */
  163. protected $filter;
  164. protected $noLink;
  165. protected $specificConfirmDelete = null;
  166. protected $colorOnBackground;
  167. /** @var bool If true, activates color on hover */
  168. protected $row_hover = true;
  169. /** @string Action to perform : 'edit', 'view', 'add', ... */
  170. protected $action;
  171. protected $display;
  172. protected $_includeContainer = true;
  173. public $tpl_folder;
  174. protected $bo_theme;
  175. /** @var bool Redirect or not ater a creation */
  176. protected $_redirect = true;
  177. /** @var array Name and directory where class image are located */
  178. public $fieldImageSettings = array();
  179. /** @var string Image type */
  180. public $imageType = 'jpg';
  181. /** @var instanciation of the class associated with the AdminController */
  182. protected $object;
  183. /** @var current object ID */
  184. protected $id_object;
  185. /**
  186. * @var current controller name without suffix
  187. */
  188. public $controller_name;
  189. public $multishop_context = -1;
  190. public $multishop_context_group = true;
  191. /**
  192. * Current breadcrumb position as an array of tab names
  193. */
  194. protected $breadcrumbs;
  195. public function __construct()
  196. {
  197. global $timer_start;
  198. $this->timer_start = $timer_start;
  199. // Has to be remove for the next Prestashop version
  200. global $token;
  201. $this->controller_type = 'admin';
  202. $this->controller_name = get_class($this);
  203. if (strpos($this->controller_name, 'Controller'))
  204. $this->controller_name = substr($this->controller_name, 0, -10);
  205. parent::__construct();
  206. if ($this->multishop_context == -1)
  207. $this->multishop_context = Shop::CONTEXT_ALL | Shop::CONTEXT_GROUP | Shop::CONTEXT_SHOP;
  208. $this->bo_theme = ((Validate::isLoadedObject($this->context->employee) && $this->context->employee->bo_theme) ? $this->context->employee->bo_theme : 'default');
  209. if (!file_exists(_PS_BO_ALL_THEMES_DIR_.$this->bo_theme.DIRECTORY_SEPARATOR.'template'))
  210. $this->bo_theme = 'default';
  211. $this->context->smarty->setTemplateDir(array(
  212. _PS_BO_ALL_THEMES_DIR_.$this->bo_theme.DIRECTORY_SEPARATOR.'template',
  213. _PS_OVERRIDE_DIR_.'controllers'.DIRECTORY_SEPARATOR.'admin'.DIRECTORY_SEPARATOR.'templates'
  214. ));
  215. $this->id = Tab::getIdFromClassName($this->controller_name);
  216. $this->token = Tools::getAdminToken($this->controller_name.(int)$this->id.(int)$this->context->employee->id);
  217. $token = $this->token;
  218. $this->_conf = array(
  219. 1 => $this->l('Deletion successful'), 2 => $this->l('Selection successfully deleted'),
  220. 3 => $this->l('Creation successful'), 4 => $this->l('Update successful'),
  221. 5 => $this->l('Status update successful'), 6 => $this->l('Settings update successful'),
  222. 7 => $this->l('Image successfully deleted'), 8 => $this->l('Module downloaded successfully'),
  223. 9 => $this->l('Thumbnails successfully regenerated'), 10 => $this->l('Message sent to the customer'),
  224. 11 => $this->l('Comment added'), 12 => $this->l('Module(s) installed successfully'),
  225. 13 => $this->l('Module(s) uninstalled successfully'), 14 => $this->l('Language successfully copied'),
  226. 15 => $this->l('Translations successfully added'), 16 => $this->l('Module transplanted successfully to hook'),
  227. 17 => $this->l('Module removed successfully from hook'), 18 => $this->l('Upload successful'),
  228. 19 => $this->l('Duplication completed successfully'), 20 => $this->l('Translation added successfully but the language has not been created'),
  229. 21 => $this->l('Module reset successfully'), 22 => $this->l('Module deleted successfully'),
  230. 23 => $this->l('Localization pack imported successfully'), 24 => $this->l('Localization pack imported successfully'),
  231. 25 => $this->l('Images successfully moved'),
  232. 26 => $this->l('Cover selection saved'),
  233. 27 => $this->l('Image shop association modified'),
  234. 28 => $this->l('Zone assigned to the selection successfully'),
  235. 29 => $this->l('Upgrade successful'),
  236. 30 => $this->l('Partial refund successfully created'),
  237. 31 => $this->l('The discount successfully generated')
  238. );
  239. if (!$this->identifier) $this->identifier = 'id_'.$this->table;
  240. if (!$this->_defaultOrderBy) $this->_defaultOrderBy = $this->identifier;
  241. $this->tabAccess = Profile::getProfileAccess($this->context->employee->id_profile, $this->id);
  242. // Fix for AdminHome
  243. if ($this->controller_name == 'AdminHome')
  244. $_POST['token'] = $this->token;
  245. if (!Shop::isFeatureActive())
  246. $this->shopLinkType = '';
  247. //$this->base_template_folder = _PS_BO_ALL_THEMES_DIR_.$this->bo_theme.'/template';
  248. $this->override_folder = Tools::toUnderscoreCase(substr($this->controller_name, 5)).'/';
  249. // Get the name of the folder containing the custom tpl files
  250. $this->tpl_folder = Tools::toUnderscoreCase(substr($this->controller_name, 5)).'/';
  251. $this->initShopContext();
  252. $this->context->currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));
  253. }
  254. /**
  255. * Set breadcrumbs array for the controller page
  256. */
  257. public function initBreadcrumbs()
  258. {
  259. $tabs = array();
  260. $tabs = Tab::recursiveTab($this->id, $tabs);
  261. $tabs = array_reverse($tabs);
  262. foreach ($tabs as $tab)
  263. $this->breadcrumbs[] = $tab['name'];
  264. }
  265. /**
  266. * set default toolbar_title to admin breadcrumb
  267. *
  268. * @return void
  269. */
  270. public function initToolbarTitle()
  271. {
  272. $bread_extended = array_unique($this->breadcrumbs);
  273. switch ($this->display)
  274. {
  275. case 'edit':
  276. $bread_extended[] = $this->l('Edit');
  277. break;
  278. case 'add':
  279. $bread_extended[] = $this->l('Add new');
  280. break;
  281. case 'view':
  282. $bread_extended[] = $this->l('View');
  283. break;
  284. }
  285. $this->toolbar_title = $bread_extended;
  286. }
  287. /**
  288. * Check rights to view the current tab
  289. *
  290. * @param bool $disable
  291. * @return boolean
  292. */
  293. public function viewAccess($disable = false)
  294. {
  295. if ($disable)
  296. return true;
  297. if ($this->tabAccess['view'] === '1')
  298. return true;
  299. return false;
  300. }
  301. /**
  302. * Check for security token
  303. */
  304. public function checkToken()
  305. {
  306. $token = Tools::getValue('token');
  307. return (!empty($token) && $token === $this->token);
  308. }
  309. public function ajaxProcessHelpAccess()
  310. {
  311. $this->json = true;
  312. $item = Tools::getValue('item');
  313. $iso_user = Tools::getValue('isoUser');
  314. $country = Tools::getValue('country');
  315. $version = Tools::getValue('version');
  316. if (isset($item) && isset($iso_user) && isset($country))
  317. {
  318. $helper = new HelperHelpAccess($item, $iso_user, $country, $version);
  319. $this->content = $helper->generate();
  320. }
  321. else
  322. $this->content = 'none';
  323. $this->display = 'content';
  324. }
  325. /**
  326. * Set the filters used for the list display
  327. */
  328. public function processFilter()
  329. {
  330. // Filter memorization
  331. if (isset($_POST) && !empty($_POST) && isset($this->table))
  332. foreach ($_POST as $key => $value)
  333. {
  334. if (is_array($this->table))
  335. {
  336. foreach ($this->table as $table)
  337. if (stripos($key, $table.'Filter_') === 0 || stripos($key, 'submitFilter') === 0)
  338. $this->context->cookie->$key = !is_array($value) ? $value : serialize($value);
  339. }
  340. elseif (stripos($key, $this->table.'Filter_') === 0 || stripos($key, 'submitFilter') === 0)
  341. $this->context->cookie->$key = !is_array($value) ? $value : serialize($value);
  342. }
  343. if (isset($_GET) && !empty($_GET) && isset($this->table))
  344. foreach ($_GET as $key => $value)
  345. {
  346. if (is_array($this->table))
  347. {
  348. foreach ($this->table as $table)
  349. if (stripos($key, $table.'OrderBy') === 0 || stripos($key, $table.'Orderway') === 0)
  350. $this->context->cookie->$key = $value;
  351. }
  352. elseif (stripos($key, $this->table.'OrderBy') === 0 || stripos($key, $this->table.'Orderway') === 0)
  353. $this->context->cookie->$key = $value;
  354. }
  355. $filters = $this->context->cookie->getFamily($this->table.'Filter_');
  356. foreach ($filters as $key => $value)
  357. {
  358. /* Extracting filters from $_POST on key filter_ */
  359. if ($value != null && !strncmp($key, $this->table.'Filter_', 7 + Tools::strlen($this->table)))
  360. {
  361. $key = Tools::substr($key, 7 + Tools::strlen($this->table));
  362. /* Table alias could be specified using a ! eg. alias!field */
  363. $tmp_tab = explode('!', $key);
  364. $filter = count($tmp_tab) > 1 ? $tmp_tab[1] : $tmp_tab[0];
  365. if ($field = $this->filterToField($key, $filter))
  366. {
  367. $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))
  368. $value = Tools::unSerialize($value);
  369. $key = isset($tmp_tab[1]) ? $tmp_tab[0].'.`'.$tmp_tab[1].'`' : '`'.$tmp_tab[0].'`';
  370. // Assignement by reference
  371. if (array_key_exists('tmpTableFilter', $field))
  372. $sql_filter = & $this->_tmpTableFilter;
  373. elseif (array_key_exists('havingFilter', $field))
  374. $sql_filter = & $this->_filterHaving;
  375. else
  376. $sql_filter = & $this->_filter;
  377. /* Only for date filtering (from, to) */
  378. if (is_array($value))
  379. {
  380. if (isset($value[0]) && !empty($value[0]))
  381. {
  382. if (!Validate::isDate($value[0]))
  383. $this->errors[] = Tools::displayError('\'From:\' date format is invalid (YYYY-MM-DD)');
  384. else
  385. $sql_filter .= ' AND '.pSQL($key).' >= \''.pSQL(Tools::dateFrom($value[0])).'\'';
  386. }
  387. if (isset($value[1]) && !empty($value[1]))
  388. {
  389. if (!Validate::isDate($value[1]))
  390. $this->errors[] = Tools::displayError('\'To:\' date format is invalid (YYYY-MM-DD)');
  391. else
  392. $sql_filter .= ' AND '.pSQL($key).' <= \''.pSQL(Tools::dateTo($value[1])).'\'';
  393. }
  394. }
  395. else
  396. {
  397. $sql_filter .= ' AND ';
  398. $check_key = ($key == $this->identifier || $key == '`'.$this->identifier.'`');
  399. if ($type == 'int' || $type == 'bool')
  400. $sql_filter .= (($check_key || $key == '`active`') ? 'a.' : '').pSQL($key).' = '.(int)$value.' ';
  401. elseif ($type == 'decimal')
  402. $sql_filter .= ($check_key ? 'a.' : '').pSQL($key).' = '.(float)$value.' ';
  403. elseif ($type == 'select')
  404. $sql_filter .= ($check_key ? 'a.' : '').pSQL($key).' = \''.pSQL($value).'\' ';
  405. else
  406. $sql_filter .= ($check_key ? 'a.' : '').pSQL($key).' LIKE \'%'.pSQL($value).'%\' ';
  407. }
  408. }
  409. }
  410. }
  411. }
  412. /**
  413. * @todo uses redirectAdmin only if !$this->ajax
  414. */
  415. public function postProcess()
  416. {
  417. if ($this->ajax)
  418. {
  419. // from ajax-tab.php
  420. $action = Tools::getValue('action');
  421. // no need to use displayConf() here
  422. if (!empty($action) && method_exists($this, 'ajaxProcess'.Tools::toCamelCase($action)))
  423. return $this->{'ajaxProcess'.Tools::toCamelCase($action)}();
  424. elseif (method_exists($this, 'ajaxProcess'))
  425. return $this->ajaxProcess();
  426. }
  427. else
  428. {
  429. // Process list filtering
  430. if ($this->filter)
  431. $this->processFilter();
  432. // If the method named after the action exists, call "before" hooks, then call action method, then call "after" hooks
  433. if (!empty($this->action) && method_exists($this, 'process'.ucfirst(Tools::toCamelCase($this->action))))
  434. {
  435. // Hook before action
  436. Hook::exec('actionAdmin'.ucfirst($this->action).'Before', array('controller' => $this));
  437. Hook::exec('action'.get_class($this).ucfirst($this->action).'Before', array('controller' => $this));
  438. // Call process
  439. $return = $this->{'process'.Tools::toCamelCase($this->action)}();
  440. // Hook After Action
  441. Hook::exec('actionAdmin'.ucfirst($this->action).'After', array('controller' => $this, 'return' => $return));
  442. Hook::exec('action'.get_class($this).ucfirst($this->action).'After', array('controller' => $this, 'return' => $return));
  443. return $return;
  444. }
  445. }
  446. }
  447. /**
  448. * Object Delete images
  449. */
  450. public function processDeleteImage()
  451. {
  452. if (Validate::isLoadedObject($object = $this->loadObject()))
  453. {
  454. if (($object->deleteImage()))
  455. {
  456. $redirect = self::$currentIndex.'&add'.$this->table.'&'.$this->identifier.'='.Tools::getValue($this->identifier).'&conf=7&token='.$this->token;
  457. if (!$this->ajax)
  458. $this->redirect_after = $redirect;
  459. else
  460. $this->content = 'ok';
  461. }
  462. }
  463. $this->errors[] = Tools::displayError('An error occurred during image deletion (cannot load object).');
  464. return $object;
  465. }
  466. /**
  467. * Object Delete
  468. */
  469. public function processDelete()
  470. {
  471. if (Validate::isLoadedObject($object = $this->loadObject()))
  472. {
  473. $res = true;
  474. // check if request at least one object with noZeroObject
  475. if (isset($object->noZeroObject) && count(call_user_func(array($this->className, $object->noZeroObject))) <= 1)
  476. {
  477. $this->errors[] = Tools::displayError('You need at least one object.').
  478. ' <b>'.$this->table.'</b><br />'.
  479. Tools::displayError('You cannot delete all of the items.');
  480. }
  481. 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
  482. $this->errors[] = Tools::displayError('You cannot delete this item.');
  483. else
  484. {
  485. if ($this->deleted)
  486. {
  487. if (!empty($this->fieldImageSettings))
  488. $res = $object->deleteImage();
  489. if (!$res)
  490. $this->errors[] = Tools::displayError('Unable to delete associated images');
  491. $object->deleted = 1;
  492. if ($object->update())
  493. $this->redirect_after = self::$currentIndex.'&conf=1&token='.$this->token;
  494. }
  495. elseif ($object->delete())
  496. $this->redirect_after = self::$currentIndex.'&conf=1&token='.$this->token;
  497. $this->errors[] = Tools::displayError('An error occurred during deletion.');
  498. }
  499. }
  500. else
  501. {
  502. $this->errors[] = Tools::displayError('An error occurred while deleting object.').
  503. ' <b>'.$this->table.'</b> '.
  504. Tools::displayError('(cannot load object)');
  505. }
  506. return $object;
  507. }
  508. /**
  509. * Call the right method for creating or updating object
  510. *
  511. * @return mixed
  512. */
  513. public function processSave()
  514. {
  515. if ($this->id_object)
  516. {
  517. $this->object = $this->loadObject();
  518. return $this->processUpdate();
  519. }
  520. else
  521. return $this->processAdd();
  522. }
  523. /**
  524. * Object creation
  525. */
  526. public function processAdd()
  527. {
  528. /* Checking fields validity */
  529. $this->validateRules();
  530. if (count($this->errors) <= 0)
  531. {
  532. $this->object = new $this->className();
  533. $this->copyFromPost($this->object, $this->table);
  534. $this->beforeAdd($this->object);
  535. if (method_exists($this->object, 'add') && !$this->object->add())
  536. {
  537. $this->errors[] = Tools::displayError('An error occurred while creating object.').
  538. ' <b>'.$this->table.' ('.Db::getInstance()->getMsgError().')</b>';
  539. }
  540. /* voluntary do affectation here */
  541. elseif (($_POST[$this->identifier] = $this->object->id) && $this->postImage($this->object->id) && !count($this->errors) && $this->_redirect)
  542. {
  543. $parent_id = (int)Tools::getValue('id_parent', 1);
  544. $this->afterAdd($this->object);
  545. $this->updateAssoShop($this->object->id);
  546. // Save and stay on same form
  547. if (empty($this->redirect_after) && $this->redirect_after !== false && Tools::isSubmit('submitAdd'.$this->table.'AndStay'))
  548. $this->redirect_after = self::$currentIndex.'&'.$this->identifier.'='.$this->object->id.'&conf=3&update'.$this->table.'&token='.$this->token;
  549. // Save and back to parent
  550. if (empty($this->redirect_after) && $this->redirect_after !== false && Tools::isSubmit('submitAdd'.$this->table.'AndBackToParent'))
  551. $this->redirect_after = self::$currentIndex.'&'.$this->identifier.'='.$parent_id.'&conf=3&token='.$this->token;
  552. // Default behavior (save and back)
  553. if (empty($this->redirect_after) && $this->redirect_after !== false)
  554. $this->redirect_after = self::$currentIndex.($parent_id ? '&'.$this->identifier.'='.$this->object->id : '').'&conf=3&token='.$this->token;
  555. }
  556. }
  557. $this->errors = array_unique($this->errors);
  558. if (!empty($this->errors))
  559. {
  560. // if we have errors, we stay on the form instead of going back to the list
  561. $this->display = 'edit';
  562. return false;
  563. }
  564. return $this->object;
  565. }
  566. /**
  567. * Object update
  568. */
  569. public function processUpdate()
  570. {
  571. /* Checking fields validity */
  572. $this->validateRules();
  573. if (empty($this->errors))
  574. {
  575. $id = (int)Tools::getValue($this->identifier);
  576. /* Object update */
  577. if (isset($id) && !empty($id))
  578. {
  579. $object = new $this->className($id);
  580. if (Validate::isLoadedObject($object))
  581. {
  582. /* Specific to objects which must not be deleted */
  583. if ($this->deleted && $this->beforeDelete($object))
  584. {
  585. // Create new one with old objet values
  586. $object_new = $object->duplicateObject();
  587. if (Validate::isLoadedObject($object_new))
  588. {
  589. // Update old object to deleted
  590. $object->deleted = 1;
  591. $object->update();
  592. // Update new object with post values
  593. $this->copyFromPost($object_new, $this->table);
  594. $result = $object_new->update();
  595. if (Validate::isLoadedObject($object_new))
  596. $this->afterDelete($object_new, $object->id);
  597. }
  598. }
  599. else
  600. {
  601. $this->copyFromPost($object, $this->table);
  602. $result = $object->update();
  603. $this->afterUpdate($object);
  604. }
  605. if ($object->id)
  606. $this->updateAssoShop($object->id);
  607. if (!$result)
  608. {
  609. $this->errors[] = Tools::displayError('An error occurred while updating object.').
  610. ' <b>'.$this->table.'</b> ('.Db::getInstance()->getMsgError().')';
  611. }
  612. elseif ($this->postImage($object->id) && !count($this->errors) && $this->_redirect)
  613. {
  614. $parent_id = (int)Tools::getValue('id_parent', 1);
  615. // Specific back redirect
  616. if ($back = Tools::getValue('back'))
  617. $this->redirect_after = urldecode($back).'&conf=4';
  618. // Specific scene feature
  619. // @todo change stay_here submit name (not clear for redirect to scene ... )
  620. if (Tools::getValue('stay_here') == 'on' || Tools::getValue('stay_here') == 'true' || Tools::getValue('stay_here') == '1')
  621. $this->redirect_after = self::$currentIndex.'&'.$this->identifier.'='.$object->id.'&conf=4&updatescene&token='.$this->token;
  622. // Save and stay on same form
  623. // @todo on the to following if, we may prefer to avoid override redirect_after previous value
  624. if (Tools::isSubmit('submitAdd'.$this->table.'AndStay'))
  625. $this->redirect_after = self::$currentIndex.'&'.$this->identifier.'='.$object->id.'&conf=4&update'.$this->table.'&token='.$this->token;
  626. // Save and back to parent
  627. if (Tools::isSubmit('submitAdd'.$this->table.'AndBackToParent'))
  628. $this->redirect_after = self::$currentIndex.'&'.$this->identifier.'='.$parent_id.'&conf=4&token='.$this->token;
  629. // Default behavior (save and back)
  630. if (empty($this->redirect_after))
  631. $this->redirect_after = self::$currentIndex.($parent_id ? '&'.$this->identifier.'='.$object->id : '').'&conf=4&token='.$this->token;
  632. }
  633. }
  634. else
  635. $this->errors[] = Tools::displayError('An error occurred while updating object.').
  636. ' <b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)');
  637. }
  638. }
  639. $this->errors = array_unique($this->errors);
  640. if (!empty($this->errors))
  641. {
  642. // if we have errors, we stay on the form instead of going back to the list
  643. $this->display = 'edit';
  644. return false;
  645. }
  646. if (isset($object))
  647. return $object;
  648. return;
  649. }
  650. /**
  651. * Change object required fields
  652. */
  653. public function processUpdateFields()
  654. {
  655. if (!is_array($fields = Tools::getValue('fieldsBox')))
  656. $fields = array();
  657. $object = new $this->className();
  658. if (!$object->addFieldsRequiredDatabase($fields))
  659. $this->errors[] = Tools::displayError('Error in updating required fields');
  660. else
  661. $this->redirect_after = self::$currentIndex.'&conf=4&token='.$this->token;
  662. return $object;
  663. }
  664. /**
  665. * Change object status (active, inactive)
  666. */
  667. public function processStatus()
  668. {
  669. if (Validate::isLoadedObject($object = $this->loadObject()))
  670. {
  671. if ($object->toggleStatus())
  672. {
  673. $id_category = (($id_category = (int)Tools::getValue('id_category')) && Tools::getValue('id_product')) ? '&id_category='.$id_category : '';
  674. $this->redirect_after = self::$currentIndex.'&conf=5'.$id_category.'&token='.$this->token;
  675. }
  676. else
  677. $this->errors[] = Tools::displayError('An error occurred while updating status.');
  678. }
  679. else
  680. $this->errors[] = Tools::displayError('An error occurred while updating status for object.').
  681. ' <b>'.$this->table.'</b> '.
  682. Tools::displayError('(cannot load object)');
  683. return $object;
  684. }
  685. /**
  686. * Change object position
  687. */
  688. public function processPosition()
  689. {
  690. if (!Validate::isLoadedObject($object = $this->loadObject()))
  691. {
  692. $this->errors[] = Tools::displayError('An error occurred while updating status for object.').
  693. ' <b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)');
  694. }
  695. elseif (!$object->updatePosition((int)Tools::getValue('way'), (int)Tools::getValue('position')))
  696. $this->errors[] = Tools::displayError('Failed to update the position.');
  697. else
  698. {
  699. $id_identifier_str = ($id_identifier = (int)Tools::getValue($this->identifier)) ? '&'.$this->identifier.'='.$id_identifier : '';
  700. $redirect = self::$currentIndex.'&'.$this->table.'Orderby=position&'.$this->table.'Orderway=asc&conf=5'.$id_identifier_str.'&token='.$this->token;
  701. $this->redirect_after = $redirect;
  702. }
  703. return $object;
  704. }
  705. /**
  706. * Cancel all filters for this tab
  707. */
  708. public function processResetFilters()
  709. {
  710. $filters = $this->context->cookie->getFamily($this->table.'Filter_');
  711. foreach ($filters as $cookie_key => $filter)
  712. if (strncmp($cookie_key, $this->table.'Filter_', 7 + Tools::strlen($this->table)) == 0)
  713. {
  714. $key = substr($cookie_key, 7 + Tools::strlen($this->table));
  715. /* Table alias could be specified using a ! eg. alias!field */
  716. $tmp_tab = explode('!', $key);
  717. $key = (count($tmp_tab) > 1 ? $tmp_tab[1] : $tmp_tab[0]);
  718. if (is_array($this->fields_list) && array_key_exists($key, $this->fields_list))
  719. unset($this->context->cookie->$cookie_key);
  720. }
  721. if (isset($this->context->cookie->{'submitFilter'.$this->table}))
  722. unset($this->context->cookie->{'submitFilter'.$this->table});
  723. if (isset($this->context->cookie->{$this->table.'Orderby'}))
  724. unset($this->context->cookie->{$this->table.'Orderby'});
  725. if (isset($this->context->cookie->{$this->table.'Orderway'}))
  726. unset($this->context->cookie->{$this->table.'Orderway'});
  727. unset($_POST);
  728. $this->_filter = false;
  729. unset($this->_filterHaving);
  730. unset($this->_having);
  731. }
  732. /**
  733. * Update options and preferences
  734. */
  735. protected function processUpdateOptions()
  736. {
  737. $this->beforeUpdateOptions();
  738. $languages = Language::getLanguages(false);
  739. $hide_multishop_checkbox = (Shop::getTotalShops(false, null) < 2) ? true : false;
  740. foreach ($this->fields_options as $category_data)
  741. {
  742. if (!isset($category_data['fields']))
  743. continue;
  744. $fields = $category_data['fields'];
  745. foreach ($fields as $field => $values)
  746. {
  747. if (isset($values['type']) && $values['type'] == 'selectLang')
  748. {
  749. foreach ($languages as $lang)
  750. if (Tools::getValue($field.'_'.strtoupper($lang['iso_code'])))
  751. $fields[$field.'_'.strtoupper($lang['iso_code'])] = array(
  752. 'type' => 'select',
  753. 'cast' => 'strval',
  754. 'identifier' => 'mode',
  755. 'list' => $values['list']
  756. );
  757. }
  758. }
  759. // Validate fields
  760. foreach ($fields as $field => $values)
  761. {
  762. // We don't validate fields with no visibility
  763. if (!$hide_multishop_checkbox && Shop::isFeatureActive() && isset($values['visibility']) && $values['visibility'] > Shop::getContext())
  764. continue;
  765. // Check if field is required
  766. if (isset($values['required']) && $values['required'] && !empty($_POST['multishopOverrideOption'][$field]))
  767. if (isset($values['type']) && $values['type'] == 'textLang')
  768. {
  769. foreach ($languages as $language)
  770. if (($value = Tools::getValue($field.'_'.$language['id_lang'])) == false && (string)$value != '0')
  771. $this->errors[] = sprintf(Tools::displayError('field %s is required.'), $values['title']);
  772. }
  773. elseif (($value = Tools::getValue($field)) == false && (string)$value != '0')
  774. $this->errors[] = sprintf(Tools::displayError('field %s is required.'), $values['title']);
  775. // Check field validator
  776. if (isset($values['type']) && $values['type'] == 'textLang')
  777. {
  778. foreach ($languages as $language)
  779. if (Tools::getValue($field.'_'.$language['id_lang']) && isset($values['validation']))
  780. if (!Validate::$values['validation'](Tools::getValue($field.'_'.$language['id_lang'])))
  781. $this->errors[] = sprintf(Tools::displayError('field %s is invalid.'), $values['title']);
  782. }
  783. elseif (Tools::getValue($field) && isset($values['validation']))
  784. if (!Validate::$values['validation'](Tools::getValue($field)))
  785. $this->errors[] = sprintf(Tools::displayError('field %s is invalid.'), $values['title']);
  786. // Set default value
  787. if (Tools::getValue($field) === false && isset($values['default']))
  788. $_POST[$field] = $values['default'];
  789. }
  790. if (!count($this->errors))
  791. {
  792. foreach ($fields as $key => $options)
  793. {
  794. if (!$hide_multishop_checkbox && Shop::isFeatureActive() && isset($options['visibility']) && $options['visibility'] > Shop::getContext())
  795. continue;
  796. if (!$hide_multishop_checkbox && Shop::isFeatureActive() && Shop::getContext() != Shop::CONTEXT_ALL && empty($options['no_multishop_checkbox']) && empty($_POST['multishopOverrideOption'][$key]))
  797. {
  798. Configuration::deleteFromContext($key);
  799. continue;
  800. }
  801. // check if a method updateOptionFieldName is available
  802. $method_name = 'updateOption'.Tools::toCamelCase($key, true);
  803. if (method_exists($this, $method_name))
  804. $this->$method_name(Tools::getValue($key));
  805. elseif (isset($options['type']) && in_array($options['type'], array('textLang', 'textareaLang')))
  806. {
  807. $list = array();
  808. foreach ($languages as $language)
  809. {
  810. $key_lang = Tools::getValue($key.'_'.$language['id_lang']);
  811. $val = (isset($options['cast']) ? $options['cast']($key_lang) : $key_lang);
  812. if ($this->validateField($val, $options))
  813. {
  814. if (Validate::isCleanHtml($val))
  815. $list[$language['id_lang']] = $val;
  816. else
  817. $this->errors[] = Tools::displayError('Can not add configuration '.$key.' for lang '.Language::getIsoById((int)$language['id_lang']));
  818. }
  819. }
  820. Configuration::updateValue($key, $list);
  821. }
  822. else
  823. {
  824. $val = (isset($options['cast']) ? $options['cast'](Tools::getValue($key)) : Tools::getValue($key));
  825. if ($this->validateField($val, $options))
  826. {
  827. if (Validate::isCleanHtml($val))
  828. Configuration::updateValue($key, $val);
  829. else
  830. $this->errors[] = Tools::displayError('Can not add configuration '.$key);
  831. }
  832. }
  833. }
  834. }
  835. }
  836. $this->display = 'list';
  837. if (empty($this->errors))
  838. $this->confirmations[] = $this->_conf[6];
  839. }
  840. /**
  841. * assign default action in toolbar_btn smarty var, if they are not set.
  842. * uses override to specifically add, modify or remove items
  843. *
  844. */
  845. public function initToolbar()
  846. {
  847. switch ($this->display)
  848. {
  849. case 'add':
  850. case 'edit':
  851. // Default save button - action dynamically handled in javascript
  852. $this->toolbar_btn['save'] = array(
  853. 'href' => '#',
  854. 'desc' => $this->l('Save')
  855. );
  856. //no break
  857. case 'view':
  858. // Default cancel button - like old back link
  859. $back = Tools::safeOutput(Tools::getValue('back', ''));
  860. if (empty($back))
  861. $back = self::$currentIndex.'&token='.$this->token;
  862. if (!Validate::isCleanHtml($back))
  863. die(Tools::displayError());
  864. if (!$this->lite_display)
  865. $this->toolbar_btn['back'] = array(
  866. 'href' => $back,
  867. 'desc' => $this->l('Back to list')
  868. );
  869. break;
  870. case 'options':
  871. $this->toolbar_btn['save'] = array(
  872. 'href' => '#',
  873. 'desc' => $this->l('Save')
  874. );
  875. break;
  876. case 'view':
  877. break;
  878. default: // list
  879. $this->toolbar_btn['new'] = array(
  880. 'href' => self::$currentIndex.'&amp;add'.$this->table.'&amp;token='.$this->token,
  881. 'desc' => $this->l('Add new')
  882. );
  883. }
  884. }
  885. /**
  886. * Load class object using identifier in $_GET (if possible)
  887. * otherwise return an empty object, or die
  888. *
  889. * @param boolean $opt Return an empty object if load fail
  890. * @return object
  891. */
  892. protected function loadObject($opt = false)
  893. {
  894. $id = (int)Tools::getValue($this->identifier);
  895. if ($id && Validate::isUnsignedId($id))
  896. {
  897. if (!$this->object)
  898. $this->object = new $this->className($id);
  899. if (Validate::isLoadedObject($this->object))
  900. return $this->object;
  901. // throw exception
  902. $this->errors[] = Tools::displayError('Object cannot be loaded (not found)');
  903. return false;
  904. }
  905. elseif ($opt)
  906. {
  907. if (!$this->object)
  908. $this->object = new $this->className();
  909. return $this->object;
  910. }
  911. else
  912. {
  913. $this->errors[] = Tools::displayError('Object cannot be loaded (identifier missing or invalid)');
  914. return false;
  915. }
  916. return $this->object;
  917. }
  918. /**
  919. * Check if the token is valid, else display a warning page
  920. */
  921. public function checkAccess()
  922. {
  923. if (!$this->checkToken())
  924. {
  925. // If this is an XSS attempt, then we should only display a simple, secure page
  926. // ${1} in the replacement string of the regexp is required,
  927. // because the token may begin with a number and mix up with it (e.g. $17)
  928. $url = preg_replace('/([&?]token=)[^&]*(&.*)?$/', '${1}'.$this->token.'$2', $_SERVER['REQUEST_URI']);
  929. if (false === strpos($url, '?token=') && false === strpos($url, '&token='))
  930. $url .= '&token='.$this->token;
  931. if (strpos($url, '?') === false)
  932. $url = str_replace('&token', '?controller=AdminHome&token', $url);
  933. $this->context->smarty->assign('url', htmlentities($url));
  934. return false;
  935. }
  936. return true;
  937. }
  938. protected function filterToField($key, $filter)
  939. {
  940. foreach ($this->fields_list as $field)
  941. if (array_key_exists('filter_key', $field) && $field['filter_key'] == $key)
  942. return $field;
  943. if (array_key_exists($filter, $this->fields_list))
  944. return $this->fields_list[$filter];
  945. return false;
  946. }
  947. public function displayNoSmarty()
  948. {
  949. }
  950. public function displayAjax()
  951. {
  952. if ($this->json)
  953. {
  954. $this->context->smarty->assign(array(
  955. 'json' => true,
  956. 'status' => $this->status,
  957. ));
  958. }
  959. $this->layout = 'layout-ajax.tpl';
  960. return $this->display();
  961. }
  962. protected function redirect()
  963. {
  964. header('Location: '.$this->redirect_after);
  965. exit;
  966. }
  967. public function display()
  968. {
  969. $this->context->smarty->assign(array(
  970. 'display_header' => $this->display_header,
  971. 'display_footer' => $this->display_footer,
  972. )
  973. );
  974. // Use page title from meta_title if it has been set else from the breadcrumbs array
  975. if (!$this->meta_title)
  976. $this->meta_title = isset($this->breadcrumbs[1]) ? $this->breadcrumbs[1] : $this->breadcrumbs[0];
  977. $this->context->smarty->assign('meta_title', $this->meta_title);
  978. $tpl_action = $this->tpl_folder.$this->display.'.tpl';
  979. // Check if action template has been override
  980. foreach ($this->context->smarty->getTemplateDir() as $template_dir)
  981. if (file_exists($template_dir.DIRECTORY_SEPARATOR.$tpl_action) && $this->display != 'view' && $this->display != 'options')
  982. {
  983. if (method_exists($this, $this->display.Tools::toCamelCase($this->className)))
  984. $this->{$this->display.Tools::toCamelCase($this->className)}();
  985. $this->context->smarty->assign('content', $this->context->smarty->fetch($tpl_action));
  986. break;
  987. }
  988. if (!$this->ajax)
  989. {
  990. $template = $this->createTemplate($this->template);
  991. $page = $template->fetch();
  992. }
  993. else
  994. $page = $this->content;
  995. if ($conf = Tools::getValue('conf'))
  996. if ($this->json)
  997. $this->context->smarty->assign('conf', Tools::jsonEncode($this->_conf[(int)$conf]));
  998. else
  999. $this->context->smarty->assign('conf', $this->_conf[(int)$conf]);
  1000. if ($this->json)
  1001. $this->context->smarty->assign('errors', Tools::jsonEncode($this->errors));
  1002. else
  1003. $this->context->smarty->assign('errors', $this->errors);
  1004. if ($this->json)
  1005. $this->context->smarty->assign('warnings', Tools::jsonEncode($this->warnings));
  1006. else
  1007. $this->context->smarty->assign('warnings', $this->warnings);
  1008. if ($this->json)
  1009. $this->context->smarty->assign('informations', Tools::jsonEncode($this->informations));
  1010. else
  1011. $this->context->smarty->assign('informations', $this->informations);
  1012. if ($this->json)
  1013. $this->context->smarty->assign('confirmations', Tools::jsonEncode($this->confirmations));
  1014. else
  1015. $this->context->smarty->assign('confirmations', $this->confirmations);
  1016. if ($this->json)
  1017. $this->context->smarty->assign('page', Tools::jsonEncode($page));
  1018. else
  1019. $this->context->smarty->assign('page', $page);
  1020. $this->smartyOutputContent($this->layout);
  1021. }
  1022. /**
  1023. * add a warning message to display at the top of the page
  1024. *
  1025. * @param string $msg
  1026. */
  1027. protected function displayWarning($msg)
  1028. {
  1029. $this->warnings[] = $msg;
  1030. }
  1031. /**
  1032. * add a info message to display at the top of the page
  1033. *
  1034. * @param string $msg
  1035. */
  1036. protected function displayInformation($msg)
  1037. {
  1038. $this->informations[] = $msg;
  1039. }
  1040. /**
  1041. * Assign smarty variables for the header
  1042. */
  1043. public function initHeader()
  1044. {
  1045. // Multishop
  1046. $is_multishop = Shop::isFeatureActive();
  1047. // Quick access
  1048. $quick_access = QuickAccess::getQuickAccesses($this->context->language->id);
  1049. foreach ($quick_access as $index => $quick)
  1050. {
  1051. if ($quick['link'] == '../' && Shop::getContext() == Shop::CONTEXT_SHOP)
  1052. {
  1053. $url = $this->context->shop->getBaseURL();
  1054. if (!$url)
  1055. {
  1056. unset($quick_access[$index]);
  1057. continue;
  1058. }
  1059. $quick_access[$index]['link'] = $url;
  1060. }
  1061. else
  1062. {
  1063. preg_match('/controller=(.+)(&.+)?$/', $quick['link'], $admin_tab);
  1064. if (isset($admin_tab[1]))
  1065. {
  1066. if (strpos($admin_tab[1], '&'))
  1067. $admin_tab[1] = substr($admin_tab[1], 0, strpos($admin_tab[1], '&'));
  1068. $token = Tools::getAdminToken($admin_tab[1].(int)Tab::getIdFromClassName($admin_tab[1]).(int)$this->context->employee->id);
  1069. $quick_access[$index]['link'] .= '&token='.$token;
  1070. }
  1071. }
  1072. }
  1073. // Tab list
  1074. $tabs = Tab::getTabs($this->context->language->id, 0);
  1075. $current_id = Tab::getCurrentParentId();
  1076. foreach ($tabs as $index => $tab)
  1077. {
  1078. if ($tab['class_name'] == 'AdminStock' && Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') == 0)
  1079. {
  1080. unset($tabs[$index]);
  1081. continue;
  1082. }
  1083. $img_cache_url = 'themes/'.$this->context->employee->bo_theme.'/img/t/'.$tab['class_name'].'.png';
  1084. $img_exists_cache = Tools::file_exists_cache(_PS_ADMIN_DIR_.$img_cache_url);
  1085. // retrocompatibility : change png to gif if icon not exists
  1086. if (!$img_exists_cache)
  1087. $img_exists_cache = Tools::file_exists_cache(_PS_ADMIN_DIR_.str_replace('.png', '.gif', $img_cache_url));
  1088. if ($img_exists_cache)
  1089. $path_img = $img = $img_exists_cache;
  1090. else
  1091. {
  1092. $path_img = _PS_IMG_DIR_.'t/'.$tab['class_name'].'.png';
  1093. // Relative link will always work, whatever the base uri set in the admin
  1094. $img = '../img/t/'.$tab['class_name'].'.png';
  1095. }
  1096. if (trim($tab['module']) != '')
  1097. {
  1098. $path_img = _PS_MODULE_DIR_.$tab['module'].'/'.$tab['class_name'].'.png';
  1099. // Relative link will always work, whatever the base uri set in the admin
  1100. $img = '../modules/'.$tab['module'].'/'.$tab['class_name'].'.png';
  1101. }
  1102. // retrocompatibility
  1103. if (!file_exists($path_img))
  1104. $img = str_replace('png', 'gif', $img);
  1105. // tab[class_name] does not contains the "Controller" suffix
  1106. $tabs[$index]['current'] = ($tab['class_name'].'Controller' == get_class($this)) || ($current_id == $tab['id_tab']);
  1107. $tabs[$index]['img'] = $img;
  1108. $tabs[$index]['href'] = $this->context->link->getAdminLink($tab['class_name']);
  1109. $sub_tabs = Tab::getTabs($this->context->language->id, $tab['id_tab']);
  1110. foreach ($sub_tabs as $index2 => $sub_tab)
  1111. {
  1112. // class_name is the name of the class controller
  1113. if (Tab::checkTabRights($sub_tab['id_tab']) === true
  1114. && (bool)$sub_tab['active'])
  1115. $sub_tabs[$index2]['href'] = $this->context->link->getAdminLink($sub_tab['class_name']);
  1116. else
  1117. unset($sub_tabs[$index2]);
  1118. }
  1119. $tabs[$index]['sub_tabs'] = $sub_tabs;
  1120. // If there are no subtabs, we don't want to display the parent tab in menu
  1121. if (empty($sub_tabs))
  1122. unset($tabs[$index]);
  1123. }
  1124. if (Validate::isLoadedObject($this->context->employee))
  1125. {
  1126. $accesses = Profile::getProfileAccesses($this->context->employee->id_profile, 'class_name');
  1127. /* Hooks are volontary out the initialize array (need those variables already assigned) */
  1128. $bo_color = empty($this->context->employee->bo_color) ? '#FFFFFF' : $this->context->employee->bo_color;
  1129. $this->context->smarty->assign(array(
  1130. 'autorefresh_notifications' => Configuration::get('PS_ADMIN_REFRESH_NOTIFICATION'),
  1131. 'help_box' => Configuration::get('PS_HELPBOX'),
  1132. 'round_mode' => Configuration::get('PS_PRICE_ROUND_MODE'),
  1133. 'brightness' => Tools::getBrightness($bo_color) < 128 ? 'white' : '#383838',
  1134. 'bo_width' => (int)$this->context->employee->bo_width,
  1135. 'bo_color' => isset($this->context->employee->bo_color) ? Tools::htmlentitiesUTF8($this->context->employee->bo_color) : null,
  1136. 'show_new_orders' => Configuration::get('PS_SHOW_NEW_ORDERS') && $accesses['AdminOrders']['view'],
  1137. 'show_new_customers' => Configuration::get('PS_SHOW_NEW_CUSTOMERS') && $accesses['AdminCustomers']['view'],
  1138. 'show_new_messages' => Configuration::get('PS_SHOW_NEW_MESSAGES') && $accesses['AdminCustomerThreads']['view'],
  1139. 'first_name' => Tools::substr($this->context->employee->firstname, 0, 1),
  1140. 'last_name' => htmlentities($this->context->employee->lastname, ENT_COMPAT, 'UTF-8'),
  1141. 'employee' => $this->context->employee,
  1142. 'search_type' => Tools::getValue('bo_search_type'),
  1143. 'bo_query' => Tools::safeOutput(Tools::stripslashes(Tools::getValue('bo_query'))),
  1144. 'quick_access' => $quick_access,
  1145. 'multi_shop' => Shop::isFeatureActive(),
  1146. 'shop_list' => Helper::renderShopList(),
  1147. 'shop' => $this->context->shop,
  1148. 'shop_group' => new ShopGroup((int)Shop::getContextShopGroupID()),
  1149. 'current_parent_id' => (int)Tab::getCurrentParentId(),
  1150. 'tabs' => $tabs,
  1151. 'is_multishop' => $is_multishop,
  1152. 'multishop_context' => $this->multishop_context,
  1153. ));
  1154. }
  1155. $this->context->smarty->assign(array(
  1156. 'img_dir' => _PS_IMG_,
  1157. 'iso' => $this->context->language->iso_code,
  1158. 'class_name' => $this->className,
  1159. 'iso_user' => $this->context->language->iso_code,
  1160. 'country_iso_code' => $this->context->country->iso_code,
  1161. 'version' => _PS_VERSION_,
  1162. 'lang_iso' => $this->context->language->iso_code,
  1163. 'link' => $this->context->link,
  1164. 'shop_name' => Configuration::get('PS_SHOP_NAME'),
  1165. 'base_url' => $this->context->shop->getBaseURL(),
  1166. 'tab' => $tab, // Deprecated, this tab is declared in the foreach, so it's the last tab in the foreach
  1167. 'current_parent_id' => (int)Tab::getCurrentParentId(),
  1168. 'tabs' => $tabs,
  1169. 'install_dir_exists' => file_exists(_PS_ADMIN_DIR_.'/../install'),
  1170. 'pic_dir' => _THEME_PROD_PIC_DIR_,
  1171. 'controller_name' => htmlentities(Tools::getValue('controller')),
  1172. 'currentIndex' => self::$currentIndex
  1173. ));
  1174. }
  1175. /**
  1176. * Declare an action to use for each row in the list
  1177. */
  1178. public function addRowAction($action)
  1179. {
  1180. $action = strtolower($action);
  1181. $this->actions[] = $action;
  1182. }
  1183. /**
  1184. * Add an action to use for each row in the list
  1185. */
  1186. public function addRowActionSkipList($action, $list)
  1187. {
  1188. $action = strtolower($action);
  1189. $list = (array)$list;
  1190. if (array_key_exists($action, $this->list_skip_actions))
  1191. $this->list_skip_actions[$action] = array_merge($this->list_skip_actions[$action], $list);
  1192. else
  1193. $this->list_skip_actions[$action] = $list;
  1194. }
  1195. /**
  1196. * Assign smarty variables for all default views, list and form, then call other init functions
  1197. */
  1198. public function initContent()
  1199. {
  1200. if (!$this->viewAccess())
  1201. {
  1202. $this->errors[] = Tools::displayError('You do not have permission to view here.');
  1203. return;
  1204. }
  1205. $this->getLanguages();
  1206. // toolbar (save, cancel, new, ..)
  1207. $this->initToolbar();
  1208. if ($this->display == 'edit' || $this->display == 'add')
  1209. {
  1210. if (!$this->loadObject(true))
  1211. return;
  1212. $this->content .= $this->renderForm();
  1213. }
  1214. elseif ($this->display == 'view')
  1215. {
  1216. // Some controllers use the view action without an object
  1217. if ($this->className)
  1218. $this->loadObject(true);
  1219. $this->content .= $this->renderView();
  1220. }
  1221. elseif (!$this->ajax)
  1222. {
  1223. $this->content .= $this->renderList();
  1224. $this->content .= $this->renderOptions();
  1225. // if we have to display the required fields form
  1226. if ($this->required_database)
  1227. $this->content .= $this->displayRequiredFields();
  1228. }
  1229. $this->context->smarty->assign(array(
  1230. 'content' => $this->content,
  1231. 'url_post' => self::$currentIndex.'&token='.$this->token,
  1232. ));
  1233. }
  1234. /**
  1235. * initialize the invalid doom page of death
  1236. *
  1237. * @return void
  1238. */
  1239. public function initCursedPage()
  1240. {
  1241. $this->layout = 'invalid_token.tpl';
  1242. }
  1243. /**
  1244. * Assign smarty variables for the footer
  1245. */
  1246. public function initFooter()
  1247. {
  1248. // We assign js and css files on the last step before display template, because controller can add many js and css files
  1249. $this->context->smarty->assign('css_files', $this->css_files);
  1250. $this->context->smarty->assign('js_files', array_unique($this->js_files));
  1251. $this->context->smarty->assign(array(
  1252. 'ps_version' => _PS_VERSION_,
  1253. 'timer_start' => $this->timer_start,
  1254. 'iso_is_fr' => strtoupper($this->context->language->iso_code) == 'FR',
  1255. ));
  1256. }
  1257. /**
  1258. * Function used to render the list to display for this controller
  1259. */
  1260. public function renderList()
  1261. {
  1262. if (!($this->fields_list && is_array($this->fields_list)))
  1263. return false;
  1264. $this->getList($this->context->language->id);
  1265. // Empty list is ok
  1266. if (!is_array($this->_list))
  1267. return false;
  1268. $helper = new HelperList();
  1269. $this->setHelperDisplay($helper);
  1270. $helper->tpl_vars = $this->tpl_list_vars;
  1271. $helper->tpl_delete_link_vars = $this->tpl_delete_link_vars;
  1272. // For compatibility reasons, we have to check standard actions in class attributes
  1273. foreach ($this->actions_available as $action)
  1274. {
  1275. if (!in_array($action, $this->actions) && isset($this->$action) && $this->$action)
  1276. $this->actions[] = $action;
  1277. }
  1278. $list = $helper->generateList($this->_list, $this->fields_list);
  1279. return $list;
  1280. }
  1281. /**
  1282. * Override to render the view page
  1283. */
  1284. public function renderView()
  1285. {
  1286. $helper = new HelperView($this);
  1287. $this->setHelperDisplay($helper);
  1288. $helper->tpl_vars = $this->tpl_view_vars;
  1289. if (!is_null($this->base_tpl_view))
  1290. $helper->base_tpl = $this->base_tpl_view;
  1291. $view = $helper->generateView();
  1292. return $view;
  1293. }
  1294. /**
  1295. * Function used to render the form for this controller
  1296. */
  1297. public function renderForm()
  1298. {
  1299. if (!$this->default_form_language)
  1300. $this->getLanguages();
  1301. if (Tools::getValue('submitFormAjax'))
  1302. $this->content .= $this->context->smarty->fetch('form_submit_ajax.tpl');
  1303. if ($this->fields_form && is_array($this->fields_form))
  1304. {
  1305. if (!$this->multiple_fieldsets)
  1306. $this->fields_form = array(array('form' => $this->fields_form));
  1307. // For add a fields via an override of $fields_form, use $fields_form_override
  1308. if (is_array($this->fields_form_override) && !empty($this->fields_form_override))
  1309. $this->fields_form[0]['form'][

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