PageRenderTime 57ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/classes/controller/AdminController.php

https://github.com/MyBB-Services/PrestaShop
PHP | 2998 lines | 2144 code | 357 blank | 497 comment | 591 complexity | 22cf7d021f3c320aa4def3e78288c487 MD5 | raw file

Large files files are truncated, but you can click here to view the full 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. try {
  414. if ($this->ajax)
  415. {
  416. // from ajax-tab.php
  417. $action = Tools::getValue('action');
  418. // no need to use displayConf() here
  419. if (!empty($action) && method_exists($this, 'ajaxProcess'.Tools::toCamelCase($action)))
  420. return $this->{'ajaxProcess'.Tools::toCamelCase($action)}();
  421. elseif (method_exists($this, 'ajaxProcess'))
  422. return $this->ajaxProcess();
  423. }
  424. else
  425. {
  426. // Process list filtering
  427. if ($this->filter)
  428. $this->processFilter();
  429. // If the method named after the action exists, call "before" hooks, then call action method, then call "after" hooks
  430. if (!empty($this->action) && method_exists($this, 'process'.ucfirst(Tools::toCamelCase($this->action))))
  431. {
  432. // Hook before action
  433. Hook::exec('actionAdmin'.ucfirst($this->action).'Before', array('controller' => $this));
  434. Hook::exec('action'.get_class($this).ucfirst($this->action).'Before', array('controller' => $this));
  435. // Call process
  436. $return = $this->{'process'.Tools::toCamelCase($this->action)}();
  437. // Hook After Action
  438. Hook::exec('actionAdmin'.ucfirst($this->action).'After', array('controller' => $this, 'return' => $return));
  439. Hook::exec('action'.get_class($this).ucfirst($this->action).'After', array('controller' => $this, 'return' => $return));
  440. return $return;
  441. }
  442. }
  443. } catch (PrestaShopException $e) {
  444. $this->errors[] = $e->getMessage();
  445. };
  446. return false;
  447. }
  448. /**
  449. * Object Delete images
  450. */
  451. public function processDeleteImage()
  452. {
  453. if (Validate::isLoadedObject($object = $this->loadObject()))
  454. {
  455. if (($object->deleteImage()))
  456. {
  457. $redirect = self::$currentIndex.'&add'.$this->table.'&'.$this->identifier.'='.Tools::getValue($this->identifier).'&conf=7&token='.$this->token;
  458. if (!$this->ajax)
  459. $this->redirect_after = $redirect;
  460. else
  461. $this->content = 'ok';
  462. }
  463. }
  464. $this->errors[] = Tools::displayError('An error occurred while attempting to delet the image. (cannot load object).');
  465. return $object;
  466. }
  467. public function processExport()
  468. {
  469. // clean buffer
  470. if (ob_get_level() && ob_get_length() > 0)
  471. ob_clean();
  472. $this->getList($this->context->language->id);
  473. if (!count($this->_list))
  474. return;
  475. header('Content-type: text/csv');
  476. header('Content-Type: application/force-download; charset=UTF-8');
  477. header('Cache-Control: no-store, no-cache');
  478. header('Content-disposition: attachment; filename="'.$this->table.'_'.date('Y-m-d_His').'.csv"');
  479. $headers = array();
  480. foreach ($this->fields_list as $datas)
  481. $headers[] = Tools::htmlentitiesDecodeUTF8($datas['title']);
  482. $content = array();
  483. foreach ($this->_list as $i => $row)
  484. {
  485. $content[$i] = array();
  486. $path_to_image = false;
  487. foreach ($this->fields_list as $key => $params)
  488. {
  489. $field_value = isset($row[$key]) ? Tools::htmlentitiesDecodeUTF8($row[$key]) : '';
  490. if ($key == 'image')
  491. {
  492. if ($params['image'] != 'p' || Configuration::get('PS_LEGACY_IMAGES'))
  493. $path_to_image = Tools::getShopDomain(true)._PS_IMG_.$params['image'].'/'.$row['id_'.$this->table].(isset($row['id_image']) ? '-'.(int)$row['id_image'] : '').'.'.$this->imageType;
  494. else
  495. $path_to_image = Tools::getShopDomain(true)._PS_IMG_.$params['image'].'/'.Image::getImgFolderStatic($row['id_image']).(int)$row['id_image'].'.'.$this->imageType;
  496. if ($path_to_image)
  497. $field_value = $path_to_image;
  498. }
  499. $content[$i][] = $field_value;
  500. }
  501. }
  502. $this->context->smarty->assign(array(
  503. 'export_precontent' => "\xEF\xBB\xBF",
  504. 'export_headers' => $headers,
  505. 'export_content' => $content
  506. )
  507. );
  508. $this->layout = 'layout-export.tpl';
  509. }
  510. /**
  511. * Object Delete
  512. */
  513. public function processDelete()
  514. {
  515. if (Validate::isLoadedObject($object = $this->loadObject()))
  516. {
  517. $res = true;
  518. // check if request at least one object with noZeroObject
  519. if (isset($object->noZeroObject) && count(call_user_func(array($this->className, $object->noZeroObject))) <= 1)
  520. {
  521. $this->errors[] = Tools::displayError('You need at least one object.').
  522. ' <b>'.$this->table.'</b><br />'.
  523. Tools::displayError('You cannot delete all of the items.');
  524. }
  525. 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
  526. $this->errors[] = Tools::displayError('You cannot delete this item.');
  527. else
  528. {
  529. if ($this->deleted)
  530. {
  531. if (!empty($this->fieldImageSettings))
  532. $res = $object->deleteImage();
  533. if (!$res)
  534. $this->errors[] = Tools::displayError('Unable to delete associated images.');
  535. $object->deleted = 1;
  536. if ($object->update())
  537. $this->redirect_after = self::$currentIndex.'&conf=1&token='.$this->token;
  538. }
  539. elseif ($object->delete())
  540. $this->redirect_after = self::$currentIndex.'&conf=1&token='.$this->token;
  541. $this->errors[] = Tools::displayError('An error occurred during deletion.');
  542. }
  543. }
  544. else
  545. {
  546. $this->errors[] = Tools::displayError('An error occurred while deleting the object.').
  547. ' <b>'.$this->table.'</b> '.
  548. Tools::displayError('(cannot load object)');
  549. }
  550. return $object;
  551. }
  552. /**
  553. * Call the right method for creating or updating object
  554. *
  555. * @return mixed
  556. */
  557. public function processSave()
  558. {
  559. if ($this->id_object)
  560. {
  561. $this->object = $this->loadObject();
  562. return $this->processUpdate();
  563. }
  564. else
  565. return $this->processAdd();
  566. }
  567. /**
  568. * Object creation
  569. */
  570. public function processAdd()
  571. {
  572. /* Checking fields validity */
  573. $this->validateRules();
  574. if (count($this->errors) <= 0)
  575. {
  576. $this->object = new $this->className();
  577. $this->copyFromPost($this->object, $this->table);
  578. $this->beforeAdd($this->object);
  579. if (method_exists($this->object, 'add') && !$this->object->add())
  580. {
  581. $this->errors[] = Tools::displayError('An error occurred while creating an object.').
  582. ' <b>'.$this->table.' ('.Db::getInstance()->getMsgError().')</b>';
  583. }
  584. /* voluntary do affectation here */
  585. elseif (($_POST[$this->identifier] = $this->object->id) && $this->postImage($this->object->id) && !count($this->errors) && $this->_redirect)
  586. {
  587. $parent_id = (int)Tools::getValue('id_parent', 1);
  588. $this->afterAdd($this->object);
  589. $this->updateAssoShop($this->object->id);
  590. // Save and stay on same form
  591. if (empty($this->redirect_after) && $this->redirect_after !== false && Tools::isSubmit('submitAdd'.$this->table.'AndStay'))
  592. $this->redirect_after = self::$currentIndex.'&'.$this->identifier.'='.$this->object->id.'&conf=3&update'.$this->table.'&token='.$this->token;
  593. // Save and back to parent
  594. if (empty($this->redirect_after) && $this->redirect_after !== false && Tools::isSubmit('submitAdd'.$this->table.'AndBackToParent'))
  595. $this->redirect_after = self::$currentIndex.'&'.$this->identifier.'='.$parent_id.'&conf=3&token='.$this->token;
  596. // Default behavior (save and back)
  597. if (empty($this->redirect_after) && $this->redirect_after !== false)
  598. $this->redirect_after = self::$currentIndex.($parent_id ? '&'.$this->identifier.'='.$this->object->id : '').'&conf=3&token='.$this->token;
  599. }
  600. }
  601. $this->errors = array_unique($this->errors);
  602. if (!empty($this->errors))
  603. {
  604. // if we have errors, we stay on the form instead of going back to the list
  605. $this->display = 'edit';
  606. return false;
  607. }
  608. return $this->object;
  609. }
  610. /**
  611. * Object update
  612. */
  613. public function processUpdate()
  614. {
  615. /* Checking fields validity */
  616. $this->validateRules();
  617. if (empty($this->errors))
  618. {
  619. $id = (int)Tools::getValue($this->identifier);
  620. /* Object update */
  621. if (isset($id) && !empty($id))
  622. {
  623. $object = new $this->className($id);
  624. if (Validate::isLoadedObject($object))
  625. {
  626. /* Specific to objects which must not be deleted */
  627. if ($this->deleted && $this->beforeDelete($object))
  628. {
  629. // Create new one with old objet values
  630. $object_new = $object->duplicateObject();
  631. if (Validate::isLoadedObject($object_new))
  632. {
  633. // Update old object to deleted
  634. $object->deleted = 1;
  635. $object->update();
  636. // Update new object with post values
  637. $this->copyFromPost($object_new, $this->table);
  638. $result = $object_new->update();
  639. if (Validate::isLoadedObject($object_new))
  640. $this->afterDelete($object_new, $object->id);
  641. }
  642. }
  643. else
  644. {
  645. $this->copyFromPost($object, $this->table);
  646. $result = $object->update();
  647. $this->afterUpdate($object);
  648. }
  649. if ($object->id)
  650. $this->updateAssoShop($object->id);
  651. if (!$result)
  652. {
  653. $this->errors[] = Tools::displayError('An error occurred while updating an object.').
  654. ' <b>'.$this->table.'</b> ('.Db::getInstance()->getMsgError().')';
  655. }
  656. elseif ($this->postImage($object->id) && !count($this->errors) && $this->_redirect)
  657. {
  658. $parent_id = (int)Tools::getValue('id_parent', 1);
  659. // Specific back redirect
  660. if ($back = Tools::getValue('back'))
  661. $this->redirect_after = urldecode($back).'&conf=4';
  662. // Specific scene feature
  663. // @todo change stay_here submit name (not clear for redirect to scene ... )
  664. if (Tools::getValue('stay_here') == 'on' || Tools::getValue('stay_here') == 'true' || Tools::getValue('stay_here') == '1')
  665. $this->redirect_after = self::$currentIndex.'&'.$this->identifier.'='.$object->id.'&conf=4&updatescene&token='.$this->token;
  666. // Save and stay on same form
  667. // @todo on the to following if, we may prefer to avoid override redirect_after previous value
  668. if (Tools::isSubmit('submitAdd'.$this->table.'AndStay'))
  669. $this->redirect_after = self::$currentIndex.'&'.$this->identifier.'='.$object->id.'&conf=4&update'.$this->table.'&token='.$this->token;
  670. // Save and back to parent
  671. if (Tools::isSubmit('submitAdd'.$this->table.'AndBackToParent'))
  672. $this->redirect_after = self::$currentIndex.'&'.$this->identifier.'='.$parent_id.'&conf=4&token='.$this->token;
  673. // Default behavior (save and back)
  674. if (empty($this->redirect_after))
  675. $this->redirect_after = self::$currentIndex.($parent_id ? '&'.$this->identifier.'='.$object->id : '').'&conf=4&token='.$this->token;
  676. }
  677. }
  678. else
  679. $this->errors[] = Tools::displayError('An error occurred while updating an object.').
  680. ' <b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)');
  681. }
  682. }
  683. $this->errors = array_unique($this->errors);
  684. if (!empty($this->errors))
  685. {
  686. // if we have errors, we stay on the form instead of going back to the list
  687. $this->display = 'edit';
  688. return false;
  689. }
  690. if (isset($object))
  691. return $object;
  692. return;
  693. }
  694. /**
  695. * Change object required fields
  696. */
  697. public function processUpdateFields()
  698. {
  699. if (!is_array($fields = Tools::getValue('fieldsBox')))
  700. $fields = array();
  701. $object = new $this->className();
  702. if (!$object->addFieldsRequiredDatabase($fields))
  703. $this->errors[] = Tools::displayError('An error occurred when attempting to update the required fields.');
  704. else
  705. $this->redirect_after = self::$currentIndex.'&conf=4&token='.$this->token;
  706. return $object;
  707. }
  708. /**
  709. * Change object status (active, inactive)
  710. */
  711. public function processStatus()
  712. {
  713. if (Validate::isLoadedObject($object = $this->loadObject()))
  714. {
  715. if ($object->toggleStatus())
  716. {
  717. $id_category = (($id_category = (int)Tools::getValue('id_category')) && Tools::getValue('id_product')) ? '&id_category='.$id_category : '';
  718. $this->redirect_after = self::$currentIndex.'&conf=5'.$id_category.'&token='.$this->token;
  719. }
  720. else
  721. $this->errors[] = Tools::displayError('An error occurred while updating the status.');
  722. }
  723. else
  724. $this->errors[] = Tools::displayError('An error occurred while updating the status for an object.').
  725. ' <b>'.$this->table.'</b> '.
  726. Tools::displayError('(cannot load object)');
  727. return $object;
  728. }
  729. /**
  730. * Change object position
  731. */
  732. public function processPosition()
  733. {
  734. if (!Validate::isLoadedObject($object = $this->loadObject()))
  735. {
  736. $this->errors[] = Tools::displayError('An error occurred while updating the status for an object.').
  737. ' <b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)');
  738. }
  739. elseif (!$object->updatePosition((int)Tools::getValue('way'), (int)Tools::getValue('position')))
  740. $this->errors[] = Tools::displayError('Failed to update the position.');
  741. else
  742. {
  743. $id_identifier_str = ($id_identifier = (int)Tools::getValue($this->identifier)) ? '&'.$this->identifier.'='.$id_identifier : '';
  744. $redirect = self::$currentIndex.'&'.$this->table.'Orderby=position&'.$this->table.'Orderway=asc&conf=5'.$id_identifier_str.'&token='.$this->token;
  745. $this->redirect_after = $redirect;
  746. }
  747. return $object;
  748. }
  749. /**
  750. * Cancel all filters for this tab
  751. */
  752. public function processResetFilters()
  753. {
  754. $prefix = str_replace(array('admin', 'controller'), '', Tools::strtolower(get_class($this)));
  755. $filters = $this->context->cookie->getFamily($prefix.$this->table.'Filter_');
  756. foreach ($filters as $cookie_key => $filter)
  757. if (strncmp($cookie_key, $prefix.$this->table.'Filter_', 7 + Tools::strlen($prefix.$this->table)) == 0)
  758. {
  759. $key = substr($cookie_key, 7 + Tools::strlen($prefix.$this->table));
  760. /* Table alias could be specified using a ! eg. alias!field */
  761. $tmp_tab = explode('!', $key);
  762. $key = (count($tmp_tab) > 1 ? $tmp_tab[1] : $tmp_tab[0]);
  763. if (is_array($this->fields_list) && array_key_exists($key, $this->fields_list))
  764. unset($this->context->cookie->$cookie_key);
  765. }
  766. if (isset($this->context->cookie->{'submitFilter'.$this->table}))
  767. unset($this->context->cookie->{'submitFilter'.$this->table});
  768. if (isset($this->context->cookie->{$prefix.$this->table.'Orderby'}))
  769. unset($this->context->cookie->{$prefix.$this->table.'Orderby'});
  770. if (isset($this->context->cookie->{$prefix.$this->table.'Orderway'}))
  771. unset($this->context->cookie->{$prefix.$this->table.'Orderway'});
  772. unset($_POST);
  773. $this->_filter = false;
  774. unset($this->_filterHaving);
  775. unset($this->_having);
  776. }
  777. /**
  778. * Update options and preferences
  779. */
  780. protected function processUpdateOptions()
  781. {
  782. $this->beforeUpdateOptions();
  783. $languages = Language::getLanguages(false);
  784. $hide_multishop_checkbox = (Shop::getTotalShops(false, null) < 2) ? true : false;
  785. foreach ($this->fields_options as $category_data)
  786. {
  787. if (!isset($category_data['fields']))
  788. continue;
  789. $fields = $category_data['fields'];
  790. foreach ($fields as $field => $values)
  791. {
  792. if (isset($values['type']) && $values['type'] == 'selectLang')
  793. {
  794. foreach ($languages as $lang)
  795. if (Tools::getValue($field.'_'.strtoupper($lang['iso_code'])))
  796. $fields[$field.'_'.strtoupper($lang['iso_code'])] = array(
  797. 'type' => 'select',
  798. 'cast' => 'strval',
  799. 'identifier' => 'mode',
  800. 'list' => $values['list']
  801. );
  802. }
  803. }
  804. // Validate fields
  805. foreach ($fields as $field => $values)
  806. {
  807. // We don't validate fields with no visibility
  808. if (!$hide_multishop_checkbox && Shop::isFeatureActive() && isset($values['visibility']) && $values['visibility'] > Shop::getContext())
  809. continue;
  810. // Check if field is required
  811. if (isset($values['required']) && $values['required'] && !empty($_POST['multishopOverrideOption'][$field]))
  812. if (isset($values['type']) && $values['type'] == 'textLang')
  813. {
  814. foreach ($languages as $language)
  815. if (($value = Tools::getValue($field.'_'.$language['id_lang'])) == false && (string)$value != '0')
  816. $this->errors[] = sprintf(Tools::displayError('field %s is required.'), $values['title']);
  817. }
  818. elseif (($value = Tools::getValue($field)) == false && (string)$value != '0')
  819. $this->errors[] = sprintf(Tools::displayError('field %s is required.'), $values['title']);
  820. // Check field validator
  821. if (isset($values['type']) && $values['type'] == 'textLang')
  822. {
  823. foreach ($languages as $language)
  824. if (Tools::getValue($field.'_'.$language['id_lang']) && isset($values['validation']))
  825. if (!Validate::$values['validation'](Tools::getValue($field.'_'.$language['id_lang'])))
  826. $this->errors[] = sprintf(Tools::displayError('field %s is invalid.'), $values['title']);
  827. }
  828. elseif (Tools::getValue($field) && isset($values['validation']))
  829. if (!Validate::$values['validation'](Tools::getValue($field)))
  830. $this->errors[] = sprintf(Tools::displayError('field %s is invalid.'), $values['title']);
  831. // Set default value
  832. if (Tools::getValue($field) === false && isset($values['default']))
  833. $_POST[$field] = $values['default'];
  834. }
  835. if (!count($this->errors))
  836. {
  837. foreach ($fields as $key => $options)
  838. {
  839. if (!$hide_multishop_checkbox && Shop::isFeatureActive() && isset($options['visibility']) && $options['visibility'] > Shop::getContext())
  840. continue;
  841. if (!$hide_multishop_checkbox && Shop::isFeatureActive() && Shop::getContext() != Shop::CONTEXT_ALL && empty($options['no_multishop_checkbox']) && empty($_POST['multishopOverrideOption'][$key]))
  842. {
  843. Configuration::deleteFromContext($key);
  844. continue;
  845. }
  846. // check if a method updateOptionFieldName is available
  847. $method_name = 'updateOption'.Tools::toCamelCase($key, true);
  848. if (method_exists($this, $method_name))
  849. $this->$method_name(Tools::getValue($key));
  850. elseif (isset($options['type']) && in_array($options['type'], array('textLang', 'textareaLang')))
  851. {
  852. $list = array();
  853. foreach ($languages as $language)
  854. {
  855. $key_lang = Tools::getValue($key.'_'.$language['id_lang']);
  856. $val = (isset($options['cast']) ? $options['cast']($key_lang) : $key_lang);
  857. if ($this->validateField($val, $options))
  858. {
  859. if (Validate::isCleanHtml($val))
  860. $list[$language['id_lang']] = $val;
  861. else
  862. $this->errors[] = Tools::displayError('Can not add configuration '.$key.' for lang '.Language::getIsoById((int)$language['id_lang']));
  863. }
  864. }
  865. Configuration::updateValue($key, $list);
  866. }
  867. else
  868. {
  869. $val = (isset($options['cast']) ? $options['cast'](Tools::getValue($key)) : Tools::getValue($key));
  870. if ($this->validateField($val, $options))
  871. {
  872. if (Validate::isCleanHtml($val))
  873. Configuration::updateValue($key, $val);
  874. else
  875. $this->errors[] = Tools::displayError('Can not add configuration '.$key);
  876. }
  877. }
  878. }
  879. }
  880. }
  881. $this->display = 'list';
  882. if (empty($this->errors))
  883. $this->confirmations[] = $this->_conf[6];
  884. }
  885. /**
  886. * assign default action in toolbar_btn smarty var, if they are not set.
  887. * uses override to specifically add, modify or remove items
  888. *
  889. */
  890. public function initToolbar()
  891. {
  892. switch ($this->display)
  893. {
  894. case 'add':
  895. case 'edit':
  896. // Default save button - action dynamically handled in javascript
  897. $this->toolbar_btn['save'] = array(
  898. 'href' => '#',
  899. 'desc' => $this->l('Save')
  900. );
  901. //no break
  902. case 'view':
  903. // Default cancel button - like old back link
  904. $back = Tools::safeOutput(Tools::getValue('back', ''));
  905. if (empty($back))
  906. $back = self::$currentIndex.'&token='.$this->token;
  907. if (!Validate::isCleanHtml($back))
  908. die(Tools::displayError());
  909. if (!$this->lite_display)
  910. $this->toolbar_btn['back'] = array(
  911. 'href' => $back,
  912. 'desc' => $this->l('Back to list')
  913. );
  914. break;
  915. case 'options':
  916. $this->toolbar_btn['save'] = array(
  917. 'href' => '#',
  918. 'desc' => $this->l('Save')
  919. );
  920. break;
  921. case 'view':
  922. break;
  923. default: // list
  924. $this->toolbar_btn['new'] = array(
  925. 'href' => self::$currentIndex.'&amp;add'.$this->table.'&amp;token='.$this->token,
  926. 'desc' => $this->l('Add new')
  927. );
  928. if ($this->allow_export)
  929. $this->toolbar_btn['export'] = array(
  930. 'href' => self::$currentIndex.'&amp;export'.$this->table.'&amp;token='.$this->token,
  931. 'desc' => $this->l('Export')
  932. );
  933. }
  934. $this->addToolBarModulesListButton();
  935. }
  936. /**
  937. * Load class object using identifier in $_GET (if possible)
  938. * otherwise return an empty object, or die
  939. *
  940. * @param boolean $opt Return an empty object if load fail
  941. * @return object
  942. */
  943. protected function loadObject($opt = false)
  944. {
  945. $id = (int)Tools::getValue($this->identifier);
  946. if ($id && Validate::isUnsignedId($id))
  947. {
  948. if (!$this->object)
  949. $this->object = new $this->className($id);
  950. if (Validate::isLoadedObject($this->object))
  951. return $this->object;
  952. // throw exception
  953. $this->errors[] = Tools::displayError('The object cannot be loaded (or found)');
  954. return false;
  955. }
  956. elseif ($opt)
  957. {
  958. if (!$this->object)
  959. $this->object = new $this->className();
  960. return $this->object;
  961. }
  962. else
  963. {
  964. $this->errors[] = Tools::displayError('The object cannot be loaded (the dentifier is missing or invalid)');
  965. return false;
  966. }
  967. return $this->object;
  968. }
  969. /**
  970. * Check if the token is valid, else display a warning page
  971. */
  972. public function checkAccess()
  973. {
  974. if (!$this->checkToken())
  975. {
  976. // If this is an XSS attempt, then we should only display a simple, secure page
  977. // ${1} in the replacement string of the regexp is required,
  978. // because the token may begin with a number and mix up with it (e.g. $17)
  979. $url = preg_replace('/([&?]token=)[^&]*(&.*)?$/', '${1}'.$this->token.'$2', $_SERVER['REQUEST_URI']);
  980. if (false === strpos($url, '?token=') && false === strpos($url, '&token='))
  981. $url .= '&token='.$this->token;
  982. if (strpos($url, '?') === false)
  983. $url = str_replace('&token', '?controller=AdminHome&token', $url);
  984. $this->context->smarty->assign('url', htmlentities($url));
  985. return false;
  986. }
  987. return true;
  988. }
  989. protected function filterToField($key, $filter)
  990. {
  991. foreach ($this->fields_list as $field)
  992. if (array_key_exists('filter_key', $field) && $field['filter_key'] == $key)
  993. return $field;
  994. if (array_key_exists($filter, $this->fields_list))
  995. return $this->fields_list[$filter];
  996. return false;
  997. }
  998. public function displayNoSmarty()
  999. {
  1000. }
  1001. public function displayAjax()
  1002. {
  1003. if ($this->json)
  1004. {
  1005. $this->context->smarty->assign(array(
  1006. 'json' => true,
  1007. 'status' => $this->status,
  1008. ));
  1009. }
  1010. $this->layout = 'layout-ajax.tpl';
  1011. return $this->display();
  1012. }
  1013. protected function redirect()
  1014. {
  1015. header('Location: '.$this->redirect_after);
  1016. exit;
  1017. }
  1018. public function display()
  1019. {
  1020. $this->context->smarty->assign(array(
  1021. 'display_header' => $this->display_header,
  1022. 'display_footer' => $this->display_footer,
  1023. )
  1024. );
  1025. // Use page title from meta_title if it has been set else from the breadcrumbs array
  1026. if (!$this->meta_title)
  1027. $this->meta_title = isset($this->breadcrumbs[1]) ? $this->breadcrumbs[1] : $this->breadcrumbs[0];
  1028. $this->context->smarty->assign('meta_title', $this->meta_title);
  1029. $tpl_action = $this->tpl_folder.$this->display.'.tpl';
  1030. // Check if action template has been override
  1031. foreach ($this->context->smarty->getTemplateDir() as $template_dir)
  1032. if (file_exists($template_dir.DIRECTORY_SEPARATOR.$tpl_action) && $this->display != 'view' && $this->display != 'options')
  1033. {
  1034. if (method_exists($this, $this->display.Tools::toCamelCase($this->className)))
  1035. $this->{$this->display.Tools::toCamelCase($this->className)}();
  1036. $this->context->smarty->assign('content', $this->context->smarty->fetch($tpl_action));
  1037. break;
  1038. }
  1039. if (!$this->ajax)
  1040. {
  1041. $template = $this->createTemplate($this->template);
  1042. $page = $template->fetch();
  1043. }
  1044. else
  1045. $page = $this->content;
  1046. if ($conf = Tools::getValue('conf'))
  1047. if ($this->json)
  1048. $this->context->smarty->assign('conf', Tools::jsonEncode($this->_conf[(int)$conf]));
  1049. else
  1050. $this->context->smarty->assign('conf', $this->_conf[(int)$conf]);
  1051. $notifications_type = array('errors', 'warnings', 'informations', 'confirmations');
  1052. foreach($notifications_type as $type)
  1053. if ($this->json)
  1054. $this->context->smarty->assign($type, Tools::jsonEncode(array_unique($this->$type)));
  1055. else
  1056. $this->context->smarty->assign($type, array_unique($this->$type));
  1057. if ($this->json)
  1058. $this->context->smarty->assign('page', Tools::jsonEncode($page));
  1059. else
  1060. $this->context->smarty->assign('page', $page);
  1061. $this->smartyOutputContent($this->layout);
  1062. }
  1063. /**
  1064. * add a warning message to display at the top of the page
  1065. *
  1066. * @param string $msg
  1067. */
  1068. protected function displayWarning($msg)
  1069. {
  1070. $this->warnings[] = $msg;
  1071. }
  1072. /**
  1073. * add a info message to display at the top of the page
  1074. *
  1075. * @param string $msg
  1076. */
  1077. protected function displayInformation($msg)
  1078. {
  1079. $this->informations[] = $msg;
  1080. }
  1081. /**
  1082. * Assign smarty variables for the header
  1083. */
  1084. public function initHeader()
  1085. {
  1086. // Multishop
  1087. $is_multishop = Shop::isFeatureActive();
  1088. // Quick access
  1089. $quick_access = QuickAccess::getQuickAccesses($this->context->language->id);
  1090. foreach ($quick_access as $index => $quick)
  1091. {
  1092. if ($quick['link'] == '../' && Shop::getContext() == Shop::CONTEXT_SHOP)
  1093. {
  1094. $url = $this->context->shop->getBaseURL();
  1095. if (!$url)
  1096. {
  1097. unset($quick_access[$index]);
  1098. continue;
  1099. }
  1100. $quick_access[$index]['link'] = $url;
  1101. }
  1102. else
  1103. {
  1104. preg_match('/controller=(.+)(&.+)?$/', $quick['link'], $admin_tab);
  1105. if (isset($admin_tab[1]))
  1106. {
  1107. if (strpos($admin_tab[1], '&'))
  1108. $admin_tab[1] = substr($admin_tab[1], 0, strpos($admin_tab[1], '&'));
  1109. $token = Tools::getAdminToken($admin_tab[1].(int)Tab::getIdFromClassName($admin_tab[1]).(int)$this->context->employee->id);
  1110. $quick_access[$index]['link'] .= '&token='.$token;
  1111. }
  1112. }
  1113. }
  1114. // Tab list
  1115. $tabs = Tab::getTabs($this->context->language->id, 0);
  1116. $current_id = Tab::getCurrentParentId();
  1117. foreach ($tabs as $index => $tab)
  1118. {
  1119. if ($tab['class_name'] == 'AdminStock' && Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT') == 0)
  1120. {
  1121. unset($tabs[$index]);
  1122. continue;
  1123. }
  1124. $img_cache_url = 'themes/'.$this->context->employee->bo_theme.'/img/t/'.$tab['class_name'].'.png';
  1125. $img_exists_cache = Tools::file_exists_cache(_PS_ADMIN_DIR_.$img_cache_url);
  1126. // retrocompatibility : change png to gif if icon not exists
  1127. if (!$img_exists_cache)
  1128. $img_exists_cache = Tools::file_exists_cache(_PS_ADMIN_DIR_.str_replace('.png', '.gif', $img_cache_url));
  1129. if ($img_exists_cache)
  1130. $path_img = $img = $img_exists_cache;
  1131. else
  1132. {
  1133. $path_img = _PS_IMG_DIR_.'t/'.$tab['class_name'].'.png';
  1134. // Relative link will always work, whatever the base uri set in the admin
  1135. $img = '../img/t/'.$tab['class_name'].'.png';
  1136. }
  1137. if (trim($tab['module']) != '')
  1138. {
  1139. $path_img = _PS_MODULE_DIR_.$tab['module'].'/'.$tab['class_name'].'.png';
  1140. // Relative link will always work, whatever the base uri set in the admin
  1141. $img = '../modules/'.$tab['module'].'/'.$tab['class_name'].'.png';
  1142. }
  1143. // retrocompatibility
  1144. if (!file_exists($path_img))
  1145. $img = str_replace('png', 'gif', $img);
  1146. // tab[class_name] does not contains the "Controller" suffix
  1147. $tabs[$index]['current'] = ($tab['class_name'].'Controller' == get_class($this)) || ($current_id == $tab['id_tab']);
  1148. $tabs[$index]['img'] = $img;
  1149. $tabs[$index]['href'] = $this->context->link->getAdminLink($tab['class_name']);
  1150. $sub_tabs = Tab::getTabs($this->context->language->id, $tab['id_tab']);
  1151. foreach ($sub_tabs as $index2 => $sub_tab)
  1152. {
  1153. // class_name is the name of the class controller
  1154. if (Tab::checkTabRights($sub_tab['id_tab']) === true && (bool)$sub_tab['active'])
  1155. {
  1156. $sub_tabs[$index2]['href'] = $this->context->link->getAdminLink($sub_tab['class_name']);
  1157. $sub_tabs[$index2]['current'] = ($sub_tab['class_name'].'Controller' == get_class($this));
  1158. }
  1159. else
  1160. unset($sub_tabs[$index2]);
  1161. }
  1162. $tabs[$index]['sub_tabs'] = $sub_tabs;
  1163. // If there are no subtabs, we don't want to display the parent tab in menu
  1164. if (empty($sub_tabs))
  1165. unset($tabs[$index]);
  1166. }
  1167. if (Validate::isLoadedObject($this->context->employee))
  1168. {
  1169. $accesses = Profile::getProfileAccesses($this->context->employee->id_profile, 'class_name');
  1170. /* Hooks are volontary out the initialize array (need those variables already assigned) */
  1171. $bo_color = empty($this->context->employee->bo_color) ? '#FFFFFF' : $this->context->employee->bo_color;
  1172. $this->context->smarty->assign(array(
  1173. 'autorefresh_notifications' => Configuration::get('PS_ADMIN_REFRESH_NOTIFICATION'),
  1174. 'help_box' => Configuration::get('PS_HELPBOX'),
  1175. 'round_mode' => Configuration::get('PS_PRICE_ROUND_MODE'),
  1176. 'brightness' => Tools::getBrightness($bo_color) < 128 ? 'white' : '#383838',
  1177. 'bo_width' => (int)$this->context->employee->bo_width,
  1178. 'bo_color' => isset($this->context->employee->bo_color) ? Tools::htmlentitiesUTF8($this->context->employee->bo_color) : null,
  1179. 'show_new_orders' => Configuration::get('PS_SHOW_NEW_ORDERS') && $accesses['AdminOrders']['view'],
  1180. 'show_new_customers' => Configuration::get('PS_SHOW_NEW_CUSTOMERS') && $accesses['AdminCustomers']['view'],
  1181. 'show_new_messages' => Configuration::get('PS_SHOW_NEW_MESSAGES') && $accesses['AdminCustomerThreads']['view'],
  1182. 'first_name' => Tools::substr($this->context->employee->firstname, 0, 1),
  1183. 'last_name' => htmlentities($this->context->employee->lastname, ENT_COMPAT, 'UTF-8'),
  1184. 'employee' => $this->context->employee,
  1185. 'search_type' => Tools::getValue('bo_search_type'),
  1186. 'bo_query' => Tools::safeOutput(Tools::stripslashes(Tools::getValue('bo_query'))),
  1187. 'quick_access' => $quick_access,
  1188. 'multi_shop' => Shop::isFeatureActive(),
  1189. 'shop_list' => Helper::renderShopList(),
  1190. 'shop' => $this->context->shop,
  1191. 'shop_group' => new ShopGroup((int)Shop::getContextShopGroupID()),
  1192. 'current_parent_id' => (int)Tab::getCurrentParentId(),
  1193. 'tabs' => $tabs,
  1194. 'is_multishop' => $is_multishop,
  1195. 'multishop_context' => $this->multishop_context,
  1196. ));
  1197. }
  1198. $this->context->smarty->assign(array(
  1199. 'img_dir' => _PS_IMG_,
  1200. 'iso' => $this->context->language->iso_code,
  1201. 'class_name' => $this->className,
  1202. 'iso_user' => $this->context->language->iso_code,
  1203. 'country_iso_code' => $this->context->country->iso_code,
  1204. 'version' => _PS_VERSION_,
  1205. 'lang_iso' => $this->context->language->iso_code,
  1206. 'link' => $this->context->link,
  1207. 'shop_name' => Configuration::get('PS_SHOP_NAME'),
  1208. 'base_url' => $this->context->shop->getBaseURL(),
  1209. 'tab' => $tab, // Deprecated, this tab is declared in the foreach, so it's the last tab in the foreach
  1210. 'current_parent_id' => (int)Tab::getCurrentParentId(),
  1211. 'tabs' => $tabs,
  1212. 'install_dir_exists' => file_exists(_PS_ADMIN_DIR_.'/../install'),
  1213. 'pic_dir' => _THEME_PROD_PIC_DIR_,
  1214. 'controller_name' => htmlentities(Tools::getValue('controller')),
  1215. 'currentIndex' => self::$currentIndex
  1216. ));
  1217. }
  1218. /**
  1219. * Declare an action to use for each row in the list
  1220. */
  1221. public function addRowAction($action)
  1222. {
  1223. $action = strtolower($action);
  1224. $this->actions[] = $action;
  1225. }
  1226. /**
  1227. * Add an action to use for each row in the list
  1228. */
  1229. public function addRowActionSkipList($action, $list)
  1230. {
  1231. $action = strtolower($action);
  1232. $list = (array)$list;
  1233. if (array_key_exists($action, $this->list_skip_actions))
  1234. $this->list_skip_actions[$action] = array_merge($this->list_skip_actions[$action], $list);
  1235. else
  1236. $this->list_skip_actions[$action] = $list;
  1237. }
  1238. /**
  1239. * Assign smarty variables for all default views, list and form, then call other init functions
  1240. */
  1241. public function initContent()
  1242. {
  1243. if (!$this->viewAccess())
  1244. {
  1245. $this->errors[] = Tools::displayError('You do not have permission to view this.');
  1246. return;
  1247. }
  1248. $this->getLanguages();
  1249. // toolbar (save, cancel, new, ..)
  1250. $this->initToolbar();
  1251. $this->initTabModuleList();
  1252. if ($this->display == 'edit' || $this->display == 'add')
  1253. {
  1254. if (!$this->loadObject(true))
  1255. return;
  1256. $this->content .= $this->renderForm();
  1257. }
  1258. elseif ($this->display == 'view')
  1259. {
  1260. // Some controllers use the view action without an object
  1261. if ($this->className)
  1262. $this->loadObject(true);
  1263. $this->content .= $this->renderView();
  1264. }
  1265. elseif (!$this->ajax)
  1266. {
  1267. $this->content .= $this->renderModulesList();
  1268. $this->content .= $this->renderList();
  1269. $this->content .= $this->renderOptions();
  1270. // if we have to display the required fields form
  1271. if ($this->required_database)
  1272. $this->content .= $this->displayRequiredFields();
  1273. }
  1274. $this->context->smarty->assign(array(
  1275. 'content' => $this->content,
  1276. 'url_post' => self::$currentIndex.'&token='.$this->token,
  1277. ));
  1278. }
  1279. /**
  1280. * init tab modules list and add button in toolbar
  1281. */
  1282. protected function initTabModuleList()
  1283. {
  1284. if (!$this->isFresh(Module::CACHE_FILE_TAB_MODULES_LIST, 604800))
  1285. $this->refresh(Module::CACHE_FILE_TAB_MODULES_LIST

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