PageRenderTime 66ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/classes/AdminTab.php

https://bitbucket.org/marcenuc/prestashop
PHP | 2435 lines | 1743 code | 268 blank | 424 comment | 519 complexity | 4a05da5969aba5b19e189c5b5171b5e2 MD5 | raw file
Possible License(s): LGPL-2.1, LGPL-3.0

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

  1. <?php
  2. /*
  3. * 2007-2012 PrestaShop
  4. *
  5. * NOTICE OF LICENSE
  6. *
  7. * This source file is subject to the Open Software License (OSL 3.0)
  8. * that is bundled with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://opensource.org/licenses/osl-3.0.php
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@prestashop.com so we can send you a copy immediately.
  14. *
  15. * DISCLAIMER
  16. *
  17. * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
  18. * versions in the future. If you wish to customize PrestaShop for your
  19. * needs please refer to http://www.prestashop.com for more information.
  20. *
  21. * @author PrestaShop SA <contact@prestashop.com>
  22. * @copyright 2007-2012 PrestaShop SA
  23. * @version Release: $Revision: 7499 $
  24. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  25. * International Registered Trademark & Property of PrestaShop SA
  26. */
  27. /**
  28. * @deprecated 1.5.0
  29. */
  30. abstract class AdminTabCore
  31. {
  32. /** @var integer Tab id */
  33. public $id = -1;
  34. /** @var string Associated table name */
  35. public $table;
  36. /** @var string Object identifier inside the associated table */
  37. protected $identifier = false;
  38. /** @var string Tab name */
  39. public $className;
  40. /** @var string Security token */
  41. public $token;
  42. /** @var boolean Automatically join language table if true */
  43. public $lang = false;
  44. /** @var boolean Tab Automatically displays edit/delete icons if true */
  45. public $edit = false;
  46. /** @var boolean Tab Automatically displays view icon if true */
  47. public $view = false;
  48. /** @var boolean Tab Automatically displays delete icon if true */
  49. public $delete = false;
  50. /** @var boolean Table records are not deleted but marked as deleted */
  51. public $deleted = false;
  52. /** @var boolean Tab Automatically displays duplicate icon if true */
  53. public $duplicate = false;
  54. /** @var boolean Content line is clickable if true */
  55. public $noLink = false;
  56. /** @var boolean select other required fields */
  57. public $requiredDatabase = false;
  58. /** @var boolean Tab Automatically displays '$color' as background color on listing if true */
  59. public $colorOnBackground = false;
  60. /** @var string Add fields into data query to display list */
  61. protected $_select;
  62. /** @var string Join tables into data query to display list */
  63. protected $_join;
  64. /** @var string Add conditions into data query to display list */
  65. protected $_where;
  66. /** @var string Group rows into data query to display list */
  67. protected $_group;
  68. /** @var string Having rows into data query to display list */
  69. protected $_having;
  70. /** @var array Name and directory where class image are located */
  71. public $fieldImageSettings = array();
  72. /** @var string Image type */
  73. public $imageType = 'jpg';
  74. /** @var array Fields to display in list */
  75. public $fieldsDisplay = array();
  76. public $optionTitle = null;
  77. /** @var string shop */
  78. public $shopLinkType;
  79. /** @var bool */
  80. public $shopShareDatas = false;
  81. /** @var array Cache for query results */
  82. protected $_list = array();
  83. /** @var integer Number of results in list */
  84. protected $_listTotal = 0;
  85. /** @var array WHERE clause determined by filter fields */
  86. protected $_filter;
  87. /** @var array Temporary SQL table WHERE clause determinated by filter fields */
  88. protected $_tmpTableFilter = '';
  89. /** @var array Number of results in list per page (used in select field) */
  90. protected $_pagination = array(20, 50, 100, 300);
  91. /** @var string ORDER BY clause determined by field/arrows in list header */
  92. protected $_orderBy;
  93. /** @var string Default ORDER BY clause when $_orderBy is not defined */
  94. protected $_defaultOrderBy = false;
  95. /** @var string Order way (ASC, DESC) determined by arrows in list header */
  96. protected $_orderWay;
  97. /** @var integer Max image size for upload
  98. * As of 1.5 it is recommended to not set a limit to max image size
  99. **/
  100. protected $maxImageSize;
  101. /** @var array Errors displayed after post processing */
  102. public $_errors = array();
  103. /** @var array Confirmations displayed after post processing */
  104. protected $_conf;
  105. /** @var object Object corresponding to the tab */
  106. protected $_object = false;
  107. /** @var array tabAccess */
  108. public $tabAccess;
  109. /** @var string specificConfirmDelete */
  110. public $specificConfirmDelete = NULL;
  111. public static $currentIndex;
  112. public $smarty;
  113. protected $identifiersDnd = array('id_product' => 'id_product', 'id_category' => 'id_category_to_move','id_cms_category' => 'id_cms_category_to_move', 'id_cms' => 'id_cms', 'id_attribute' => 'id_attribute', 'id_attribute_group' => 'id_attribute_group', 'id_feature' => 'id_feature', 'id_carrier' => 'id_carrier');
  114. /** @var bool Redirect or not ater a creation */
  115. protected $_redirect = true;
  116. /** @var bool If false, don't add form tags in options forms */
  117. protected $formOptions = true;
  118. public $_fieldsOptions = array();
  119. /**
  120. * @since 1.5.0
  121. * @var array
  122. */
  123. public $optionsList = array();
  124. /**
  125. * @since 1.5.0
  126. * @var Context
  127. */
  128. public $context;
  129. protected $_languages = NULL;
  130. protected $_defaultFormLanguage = NULL;
  131. protected $_includeObj = array();
  132. protected $_includeVars = false;
  133. protected $_includeContainer = true;
  134. public $ajax = false;
  135. /**
  136. * if true, ajax-tab will not wait 1 sec
  137. * @var boolean
  138. */
  139. public $ignore_sleep = false;
  140. public static $tabParenting = array(
  141. 'AdminCms' => 'AdminCmsContent',
  142. 'AdminCmsCategories' => 'AdminCmsContent',
  143. 'AdminOrdersStates' => 'AdminStatuses',
  144. 'AdminAttributeGenerator' => 'AdminProducts',
  145. 'AdminAttributes' => 'AdminAttributesGroups',
  146. 'AdminFeaturesValues' => 'AdminFeatures',
  147. 'AdminReturnStates' => 'AdminStatuses',
  148. 'AdminStatsTab' => 'AdminStats'
  149. );
  150. public function __construct()
  151. {
  152. $this->context = Context::getContext();
  153. $this->id = Tab::getIdFromClassName(get_class($this));
  154. $this->_conf = array(
  155. 1 => $this->l('Deletion successful'), 2 => $this->l('Selection successfully deleted'),
  156. 3 => $this->l('Creation successful'), 4 => $this->l('Update successful'),
  157. 5 => $this->l('Status update successful'), 6 => $this->l('Settings update successful'),
  158. 7 => $this->l('Image successfully deleted'), 8 => $this->l('Module downloaded successfully'),
  159. 9 => $this->l('Thumbnails successfully regenerated'), 10 => $this->l('Message sent to the customer'),
  160. 11 => $this->l('Comment added'), 12 => $this->l('Module installed successfully'),
  161. 13 => $this->l('Module uninstalled successfully'), 14 => $this->l('Language successfully copied'),
  162. 15 => $this->l('Translations successfully added'), 16 => $this->l('Module transplanted successfully to hook'),
  163. 17 => $this->l('Module removed successfully from hook'), 18 => $this->l('Upload successful'),
  164. 19 => $this->l('Duplication completed successfully'), 20 => $this->l('Translation added successfully but the language has not been created'),
  165. 21 => $this->l('Module reset successfully'), 22 => $this->l('Module deleted successfully'),
  166. 23 => $this->l('Localization pack imported successfully'), 24 => $this->l('Refund Successful'),
  167. 25 => $this->l('Images successfully moved'),
  168. );
  169. if (!$this->identifier) $this->identifier = 'id_'.$this->table;
  170. if (!$this->_defaultOrderBy) $this->_defaultOrderBy = $this->identifier;
  171. $className = get_class($this);
  172. // if ($className == 'AdminCategories' OR $className == 'AdminProducts')
  173. // $className = 'AdminCatalog';
  174. $this->token = Tools::getAdminToken($className.(int)$this->id.(int)$this->context->employee->id);
  175. if (!Shop::isFeatureActive())
  176. $this->shopLinkType = '';
  177. }
  178. /**
  179. * use translations files to replace english expression.
  180. *
  181. * @param mixed $string term or expression in english
  182. * @param string $class
  183. * @param boolan $addslashes if set to true, the return value will pass through addslashes(). Otherwise, stripslashes().
  184. * @param boolean $htmlentities if set to true(default), the return value will pass through htmlentities($string, ENT_QUOTES, 'utf-8')
  185. * @return string the translation if available, or the english default text.
  186. */
  187. protected function l($string, $class = 'AdminTab', $addslashes = FALSE, $htmlentities = TRUE)
  188. {
  189. // if the class is extended by a module, use modules/[module_name]/xx.php lang file
  190. $currentClass = get_class($this);
  191. if(Module::getModuleNameFromClass($currentClass))
  192. {
  193. $string = str_replace('\'', '\\\'', $string);
  194. return Translate::getModuleTranslation(Module::$classInModule[$currentClass], $string, $currentClass);
  195. }
  196. global $_LANGADM;
  197. if ($class == __CLASS__)
  198. $class = 'AdminTab';
  199. $key = md5(str_replace('\'', '\\\'', $string));
  200. $str = (key_exists(get_class($this).$key, $_LANGADM)) ? $_LANGADM[get_class($this).$key] : ((key_exists($class.$key, $_LANGADM)) ? $_LANGADM[$class.$key] : $string);
  201. $str = $htmlentities ? htmlentities($str, ENT_QUOTES, 'utf-8') : $str;
  202. return str_replace('"', '&quot;', ($addslashes ? addslashes($str) : stripslashes($str)));
  203. }
  204. /**
  205. * ajaxDisplay is the default ajax return sytem
  206. *
  207. * @return void
  208. */
  209. public function displayAjax()
  210. {
  211. }
  212. /**
  213. * Manage page display (form, list...)
  214. */
  215. public function display()
  216. {
  217. // Include other tab in current tab
  218. if ($this->includeSubTab('display', array('submitAdd2', 'add', 'update', 'view'))){}
  219. // Include current tab
  220. elseif ((Tools::getValue('submitAdd'.$this->table) && count($this->_errors)) || isset($_GET['add'.$this->table]))
  221. {
  222. if ($this->tabAccess['add'] === '1')
  223. {
  224. $this->displayForm();
  225. if ($this->tabAccess['view'])
  226. echo '<br /><br /><a href="'.((Tools::getValue('back')) ? Tools::getValue('back') : self::$currentIndex.'&token='.$this->token).'"><img src="../img/admin/arrow2.gif" /> '.((Tools::getValue('back')) ? $this->l('Back') : $this->l('Back to list')).'</a><br />';
  227. }
  228. else
  229. echo $this->l('You do not have permission to add here');
  230. }
  231. elseif (isset($_GET['update'.$this->table]))
  232. {
  233. if ($this->tabAccess['edit'] === '1' || ($this->table == 'employee' && $this->context->employee->id == Tools::getValue('id_employee')))
  234. {
  235. $this->displayForm();
  236. if ($this->tabAccess['view'])
  237. echo '<br /><br /><a href="'.((Tools::getValue('back')) ? Tools::getValue('back') : self::$currentIndex.'&token='.$this->token).'"><img src="../img/admin/arrow2.gif" /> '.((Tools::getValue('back')) ? $this->l('Back') : $this->l('Back to list')).'</a><br />';
  238. }
  239. else
  240. echo $this->l('You do not have permission to edit here');
  241. }
  242. elseif (isset($_GET['view'.$this->table]))
  243. $this->{'view'.$this->table}();
  244. else
  245. {
  246. $this->getList($this->context->language->id);
  247. $this->displayList();
  248. echo '<br />';
  249. $this->displayOptionsList();
  250. $this->displayRequiredFields();
  251. $this->includeSubTab('display');
  252. }
  253. }
  254. public function displayRequiredFields()
  255. {
  256. if (!$this->tabAccess['add'] || !$this->tabAccess['delete'] === '1' || !$this->requiredDatabase)
  257. return;
  258. $rules = call_user_func_array(array($this->className, 'getValidationRules'), array($this->className));
  259. $required_class_fields = array($this->identifier);
  260. foreach ($rules['required'] as $required)
  261. $required_class_fields[] = $required;
  262. echo '<br />
  263. <p><a href="#" onclick="if ($(\'.requiredFieldsParameters:visible\').length == 0) $(\'.requiredFieldsParameters\').slideDown(\'slow\'); else $(\'.requiredFieldsParameters\').slideUp(\'slow\'); return false;"><img src="../img/admin/duplicate.gif" alt="" /> '.$this->l('Set required fields for this section').'</a></p>
  264. <fieldset style="display:none" class="width1 requiredFieldsParameters">
  265. <legend>'.$this->l('Required Fields').'</legend>
  266. <form name="updateFields" action="'.self::$currentIndex.'&submitFields'.$this->table.'=1&token='.$this->token.'" method="post">
  267. <p><b>'.$this->l('Select the fields you would like to be required for this section.').'<br />
  268. <table cellspacing="0" cellpadding="0" class="table width1 clear">
  269. <tr>
  270. <th><input type="checkbox" onclick="checkDelBoxes(this.form, \'fieldsBox[]\', this.checked)" class="noborder" name="checkme"></th>
  271. <th>'.$this->l('Field Name').'</th>
  272. </tr>';
  273. $object = new $this->className();
  274. $res = $object->getFieldsRequiredDatabase();
  275. $required_fields = array();
  276. foreach ($res as $row)
  277. $required_fields[(int)$row['id_required_field']] = $row['field_name'];
  278. $table_fields = Db::getInstance()->executeS('SHOW COLUMNS FROM '.pSQL(_DB_PREFIX_.$this->table));
  279. $irow = 0;
  280. foreach ($table_fields as $field)
  281. {
  282. if (in_array($field['Field'], $required_class_fields))
  283. continue;
  284. echo '<tr class="'.($irow++ % 2 ? 'alt_row' : '').'">
  285. <td class="noborder"><input type="checkbox" name="fieldsBox[]" value="'.$field['Field'].'" '.(in_array($field['Field'], $required_fields) ? 'checked="checked"' : '').' /></td>
  286. <td>'.$field['Field'].'</td>
  287. </tr>';
  288. }
  289. echo '</table><br />
  290. <center><input style="margin-left:15px;" class="button" type="submit" value="'.$this->l(' Save ').'" name="submitFields" /></center>
  291. </fieldset>';
  292. }
  293. public function includeSubTab($methodname, $actions = array())
  294. {
  295. if (!isset($this->_includeTab) || !is_array($this->_includeTab))
  296. return false;
  297. $key = 0;
  298. $inc = false;
  299. foreach ($this->_includeTab as $subtab => $extraVars)
  300. {
  301. /* New tab loading */
  302. $classname = 'Admin'.$subtab;
  303. if (($module = Db::getInstance()->getValue('SELECT `module` FROM `'._DB_PREFIX_.'tab` WHERE `class_name` = \''.pSQL($classname).'\'')) && file_exists(_PS_MODULE_DIR_.'/'.$module.'/'.$classname.'.php'))
  304. include_once(_PS_MODULE_DIR_.'/'.$module.'/'.$classname.'.php');
  305. elseif (file_exists(_PS_ADMIN_DIR_.'/tabs/'.$classname.'.php'))
  306. include_once('tabs/'.$classname.'.php');
  307. if (!isset($this->_includeObj[$key]))
  308. $this->_includeObj[$key] = new $classname;
  309. $adminTab = $this->_includeObj[$key];
  310. $adminTab->token = $this->token;
  311. /* Extra variables addition */
  312. if (!empty($extraVars) && is_array($extraVars))
  313. foreach ($extraVars as $varKey => $varValue)
  314. $adminTab->$varKey = $varValue;
  315. /* Actions management */
  316. foreach ($actions as $action)
  317. {
  318. switch ($action)
  319. {
  320. case 'submitAdd1':
  321. if (Tools::getValue('submitAdd'.$adminTab->table))
  322. $ok_inc = true;
  323. break;
  324. case 'submitAdd2':
  325. if (Tools::getValue('submitAdd'.$adminTab->table) && count($adminTab->_errors))
  326. $ok_inc = true;
  327. break;
  328. case 'submitDel':
  329. if (Tools::getValue('submitDel'.$adminTab->table))
  330. $ok_inc = true;
  331. break;
  332. case 'submitFilter':
  333. if (Tools::isSubmit('submitFilter'.$adminTab->table))
  334. $ok_inc = true;
  335. case 'submitReset':
  336. if (Tools::isSubmit('submitReset'.$adminTab->table))
  337. $ok_inc = true;
  338. default:
  339. if (isset($_GET[$action.$adminTab->table]))
  340. $ok_inc = true;
  341. }
  342. }
  343. $inc = false;
  344. if ((isset($ok_inc) && $ok_inc) || !count($actions))
  345. {
  346. if (!$adminTab->viewAccess())
  347. {
  348. echo Tools::displayError('Access denied.');
  349. return false;
  350. }
  351. if (!count($actions))
  352. if (($methodname == 'displayErrors' && count($adminTab->_errors)) || $methodname != 'displayErrors')
  353. echo (isset($this->_includeTabTitle[$key]) ? '<h2>'.$this->_includeTabTitle[$key].'</h2>' : '');
  354. if ($adminTab->_includeVars)
  355. foreach ($adminTab->_includeVars as $var => $value)
  356. $adminTab->$var = $this->$value;
  357. $adminTab->$methodname();
  358. $inc = true;
  359. }
  360. $key++;
  361. }
  362. return $inc;
  363. }
  364. /**
  365. * Manage page display (form, list...)
  366. *
  367. * @param string $className Allow to validate a different class than the current one
  368. */
  369. public function validateRules($className = false)
  370. {
  371. if (!$className)
  372. $className = $this->className;
  373. /* Class specific validation rules */
  374. $rules = call_user_func(array($className, 'getValidationRules'), $className);
  375. if ((count($rules['requiredLang']) || count($rules['sizeLang']) || count($rules['validateLang'])))
  376. {
  377. /* Language() instance determined by default language */
  378. $defaultLanguage = new Language((int)(Configuration::get('PS_LANG_DEFAULT')));
  379. /* All availables languages */
  380. $languages = Language::getLanguages(false);
  381. }
  382. /* Checking for required fields */
  383. foreach ($rules['required'] as $field)
  384. if (($value = Tools::getValue($field)) == false && (string)$value != '0')
  385. if (!Tools::getValue($this->identifier) || ($field != 'passwd' && $field != 'no-picture'))
  386. $this->_errors[] = sprintf(Tools::displayError('The field %s is required.'), call_user_func(array($className, 'displayFieldName'), $field, $className));
  387. /* Checking for multilingual required fields */
  388. foreach ($rules['requiredLang'] as $fieldLang)
  389. if (($empty = Tools::getValue($fieldLang.'_'.$defaultLanguage->id)) === false || $empty !== '0' && empty($empty))
  390. $this->_errors[] = sprintf(Tools::displayError('The field %1$s is required at least in %2$s.'), call_user_func(array($className, 'displayFieldName'), $fieldLang, $className), $defaultLanguage->name);
  391. /* Checking for maximum fields sizes */
  392. foreach ($rules['size'] as $field => $maxLength)
  393. if (Tools::getValue($field) !== false && Tools::strlen(Tools::getValue($field)) > $maxLength)
  394. $this->_errors[] = sprintf(Tools::displayError('field %1$s is too long. (%2$d chars max)'), call_user_func(array($className, 'displayFieldName'), $field, $className), $maxLength);
  395. /* Checking for maximum multilingual fields size */
  396. foreach ($rules['sizeLang'] as $fieldLang => $maxLength)
  397. foreach ($languages as $language)
  398. if (Tools::getValue($fieldLang.'_'.$language['id_lang']) !== false && Tools::strlen(Tools::getValue($fieldLang.'_'.$language['id_lang'])) > $maxLength)
  399. $this->_errors[] = sprintf(Tools::displayError('field %1$s is too long. (%2$d chars max, html chars including)'), call_user_func(array($className, 'displayFieldName'), $fieldLang, $className), $maxLength);
  400. /* Overload this method for custom checking */
  401. $this->_childValidation();
  402. /* Checking for fields validity */
  403. foreach ($rules['validate'] AS $field => $function)
  404. if (($value = Tools::getValue($field)) !== false AND !empty($value) AND ($field != 'passwd'))
  405. if (!Validate::$function($value))
  406. $this->_errors[] = sprintf(Tools::displayError('The field %1$s (%2$s) is invalid.'), call_user_func(array($className, 'displayFieldName'), $field, $className));
  407. /* Checking for passwd_old validity */
  408. if (($value = Tools::getValue('passwd')) != false)
  409. {
  410. if ($className == 'Employee' && !Validate::isPasswdAdmin($value))
  411. $this->_errors[] = sprintf(Tools::displayError('The field %1$s (%2$s) is invalid.'), call_user_func(array($className, 'displayFieldName'), 'passwd', $className));
  412. elseif ($className == 'Customer' && !Validate::isPasswd($value))
  413. $this->_errors[] = sprintf(Tools::displayError('The field %1$s (%2$s) is invalid.'), call_user_func(array($className, 'displayFieldName'), 'passwd', $className));
  414. }
  415. /* Checking for multilingual fields validity */
  416. foreach ($rules['validateLang'] as $fieldLang => $function)
  417. foreach ($languages as $language)
  418. if (($value = Tools::getValue($fieldLang.'_'.$language['id_lang'])) !== false && !empty($value))
  419. if (!Validate::$function($value))
  420. $this->_errors[] = sprintf(Tools::displayError('The field %1$s (%2$s) is invalid.'), call_user_func(array($className, 'displayFieldName'), $fieldLang, $className), $language['name']);
  421. }
  422. /**
  423. * Overload this method for custom checking
  424. */
  425. protected function _childValidation() { }
  426. /**
  427. * Overload this method for custom checking
  428. *
  429. * @param integer $id Object id used for deleting images
  430. * @deprecated As of 1.5 use ObjectModel->deleteImage instead.
  431. */
  432. public function deleteImage($id)
  433. {
  434. Tools::displayAsDeprecated();
  435. $dir = null;
  436. /* Deleting object images and thumbnails (cache) */
  437. if (key_exists('dir', $this->fieldImageSettings))
  438. {
  439. $dir = $this->fieldImageSettings['dir'].'/';
  440. if (file_exists(_PS_IMG_DIR_.$dir.$id.'.'.$this->imageType) && !unlink(_PS_IMG_DIR_.$dir.$id.'.'.$this->imageType))
  441. return false;
  442. }
  443. if (file_exists(_PS_TMP_IMG_DIR_.$this->table.'_'.$id.'.'.$this->imageType) && !unlink(_PS_TMP_IMG_DIR_.$this->table.'_'.$id.'.'.$this->imageType))
  444. return false;
  445. if (file_exists(_PS_TMP_IMG_DIR_.$this->table.'_mini_'.$id.'.'.$this->imageType) && !unlink(_PS_TMP_IMG_DIR_.$this->table.'_mini_'.$id.'.'.$this->imageType))
  446. return false;
  447. $types = ImageType::getImagesTypes();
  448. foreach ($types as $imageType)
  449. if (file_exists(_PS_IMG_DIR_.$dir.$id.'-'.stripslashes($imageType['name']).'.'.$this->imageType) && !unlink(_PS_IMG_DIR_.$dir.$id.'-'.stripslashes($imageType['name']).'.'.$this->imageType))
  450. return false;
  451. return true;
  452. }
  453. /**
  454. * ajaxPreProcess is a method called in ajax-tab.php before displayConf().
  455. *
  456. * @return void
  457. */
  458. public function ajaxPreProcess()
  459. {
  460. }
  461. /**
  462. * ajaxProcess is the default handle method for request with ajax-tab.php
  463. *
  464. * @return void
  465. */
  466. public function ajaxProcess()
  467. {
  468. }
  469. /**
  470. * Manage page processing
  471. */
  472. public function postProcess()
  473. {
  474. if (!isset($this->table))
  475. return false;
  476. // set token
  477. $token = Tools::getValue('token') ? Tools::getValue('token') : $this->token;
  478. // Sub included tab postProcessing
  479. $this->includeSubTab('postProcess', array('status', 'submitAdd1', 'submitDel', 'delete', 'submitFilter', 'submitReset'));
  480. /* Delete object image */
  481. if (isset($_GET['deleteImage']))
  482. {
  483. if (Validate::isLoadedObject($object = $this->loadObject()))
  484. if (($object->deleteImage()))
  485. Tools::redirectAdmin(self::$currentIndex.'&add'.$this->table.'&'.$this->identifier.'='.Tools::getValue($this->identifier).'&conf=7&token='.$token);
  486. $this->_errors[] = Tools::displayError('An error occurred during image deletion (cannot load object).');
  487. }
  488. /* Delete object */
  489. elseif (isset($_GET['delete'.$this->table]))
  490. {
  491. if ($this->tabAccess['delete'] === '1')
  492. {
  493. if (Validate::isLoadedObject($object = $this->loadObject()) && isset($this->fieldImageSettings))
  494. {
  495. // check if request at least one object with noZeroObject
  496. if (isset($object->noZeroObject) && count(call_user_func(array($this->className, $object->noZeroObject))) <= 1)
  497. $this->_errors[] = Tools::displayError('You need at least one object.').' <b>'.$this->table.'</b><br />'.Tools::displayError('You cannot delete all of the items.');
  498. else
  499. {
  500. if ($this->deleted)
  501. {
  502. $object->deleteImage();
  503. $object->deleted = 1;
  504. if(method_exists($object, 'cleanPositions'))
  505. $object->cleanPositions();
  506. if ($object->update())
  507. Tools::redirectAdmin(self::$currentIndex.'&conf=1&token='.$token);
  508. }
  509. elseif ($object->delete())
  510. {
  511. if(method_exists($object, 'cleanPositions'))
  512. $object->cleanPositions();
  513. Tools::redirectAdmin(self::$currentIndex.'&conf=1&token='.$token);
  514. }
  515. $this->_errors[] = Tools::displayError('An error occurred during deletion.');
  516. }
  517. }
  518. else
  519. $this->_errors[] = Tools::displayError('An error occurred while deleting object.').' <b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)');
  520. }
  521. else
  522. $this->_errors[] = Tools::displayError('You do not have permission to delete here.');
  523. }
  524. /* Change object statuts (active, inactive) */
  525. elseif ((isset($_GET['status'.$this->table]) || isset($_GET['status'])) && Tools::getValue($this->identifier))
  526. {
  527. if ($this->tabAccess['edit'] === '1')
  528. {
  529. if (Validate::isLoadedObject($object = $this->loadObject()))
  530. {
  531. if ($object->toggleStatus())
  532. Tools::redirectAdmin(self::$currentIndex.'&conf=5'.((($id_category = (int)(Tools::getValue('id_category'))) && Tools::getValue('id_product')) ? '&id_category='.$id_category : '').'&token='.$token);
  533. else
  534. $this->_errors[] = Tools::displayError('An error occurred while updating status.');
  535. }
  536. else
  537. $this->_errors[] = Tools::displayError('An error occurred while updating status for object.').' <b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)');
  538. }
  539. else
  540. $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
  541. }
  542. /* Move an object */
  543. elseif (isset($_GET['position']))
  544. {
  545. if ($this->tabAccess['edit'] !== '1')
  546. $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
  547. elseif (!Validate::isLoadedObject($object = $this->loadObject()))
  548. $this->_errors[] = Tools::displayError('An error occurred while updating status for object.').' <b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)');
  549. elseif (!$object->updatePosition((int)(Tools::getValue('way')), (int)(Tools::getValue('position'))))
  550. $this->_errors[] = Tools::displayError('Failed to update the position.');
  551. else
  552. Tools::redirectAdmin(self::$currentIndex.'&'.$this->table.'Orderby=position&'.$this->table.'Orderway=asc&conf=5'.(($id_identifier = (int)(Tools::getValue($this->identifier))) ? ('&'.$this->identifier.'='.$id_identifier) : '').'&token='.$token);
  553. }
  554. /* Delete multiple objects */
  555. elseif (Tools::getValue('submitDel'.$this->table))
  556. {
  557. if ($this->tabAccess['delete'] === '1')
  558. {
  559. if (isset($_POST[$this->table.'Box']))
  560. {
  561. $object = new $this->className();
  562. if (isset($object->noZeroObject) &&
  563. // Check if all object will be deleted
  564. (count(call_user_func(array($this->className, $object->noZeroObject))) <= 1 || count($_POST[$this->table.'Box']) == count(call_user_func(array($this->className, $object->noZeroObject)))))
  565. $this->_errors[] = Tools::displayError('You need at least one object.').' <b>'.$this->table.'</b><br />'.Tools::displayError('You cannot delete all of the items.');
  566. else
  567. {
  568. $result = true;
  569. if ($this->deleted)
  570. {
  571. foreach(Tools::getValue($this->table.'Box') as $id)
  572. {
  573. $toDelete = new $this->className($id);
  574. $toDelete->deleted = 1;
  575. $result = $result && $toDelete->update();
  576. }
  577. }
  578. else
  579. $result = $object->deleteSelection(Tools::getValue($this->table.'Box'));
  580. if ($result)
  581. Tools::redirectAdmin(self::$currentIndex.'&conf=2&token='.$token);
  582. $this->_errors[] = Tools::displayError('An error occurred while deleting selection.');
  583. }
  584. // clean carriers positions
  585. Carrier::cleanPositions();
  586. }
  587. else
  588. $this->_errors[] = Tools::displayError('You must select at least one element to delete.');
  589. }
  590. else
  591. $this->_errors[] = Tools::displayError('You do not have permission to delete here.');
  592. }
  593. /* Create or update an object */
  594. elseif (Tools::getValue('submitAdd'.$this->table))
  595. {
  596. /* Checking fields validity */
  597. $this->validateRules();
  598. if (!count($this->_errors))
  599. {
  600. $id = (int)(Tools::getValue($this->identifier));
  601. /* Object update */
  602. if (isset($id) && !empty($id))
  603. {
  604. if ($this->tabAccess['edit'] === '1' || ($this->table == 'employee' && $this->context->employee->id == Tools::getValue('id_employee') && Tools::isSubmit('updateemployee')))
  605. {
  606. $object = new $this->className($id);
  607. if (Validate::isLoadedObject($object))
  608. {
  609. /* Specific to objects which must not be deleted */
  610. if ($this->deleted && $this->beforeDelete($object))
  611. {
  612. // Create new one with old objet values
  613. $objectNew = new $this->className($object->id);
  614. $objectNew->id = NULL;
  615. $objectNew->date_add = '';
  616. $objectNew->date_upd = '';
  617. // Update old object to deleted
  618. $object->deleted = 1;
  619. $object->update();
  620. // Update new object with post values
  621. $this->copyFromPost($objectNew, $this->table);
  622. $result = $objectNew->add();
  623. if (Validate::isLoadedObject($objectNew))
  624. $this->afterDelete($objectNew, $object->id);
  625. }
  626. else
  627. {
  628. $this->copyFromPost($object, $this->table);
  629. $result = $object->update();
  630. $this->afterUpdate($object);
  631. }
  632. if ($object->id)
  633. $this->updateAssoShop($object->id);
  634. if (!$result)
  635. $this->_errors[] = Tools::displayError('An error occurred while updating object.').' <b>'.$this->table.'</b> ('.Db::getInstance()->getMsgError().')';
  636. elseif ($this->postImage($object->id) && !count($this->_errors))
  637. {
  638. if ($this->table == 'group')
  639. $this->updateRestrictions($object->id);
  640. $parent_id = (int)(Tools::getValue('id_parent', 1));
  641. // Specific back redirect
  642. if ($back = Tools::getValue('back'))
  643. Tools::redirectAdmin(urldecode($back).'&conf=4');
  644. // Specific scene feature
  645. if (Tools::getValue('stay_here') == 'on' || Tools::getValue('stay_here') == 'true' || Tools::getValue('stay_here') == '1')
  646. Tools::redirectAdmin(self::$currentIndex.'&'.$this->identifier.'='.$object->id.'&conf=4&updatescene&token='.$token);
  647. // Save and stay on same form
  648. if (Tools::isSubmit('submitAdd'.$this->table.'AndStay'))
  649. Tools::redirectAdmin(self::$currentIndex.'&'.$this->identifier.'='.$object->id.'&conf=4&update'.$this->table.'&token='.$token);
  650. // Save and back to parent
  651. if (Tools::isSubmit('submitAdd'.$this->table.'AndBackToParent'))
  652. Tools::redirectAdmin(self::$currentIndex.'&'.$this->identifier.'='.$parent_id.'&conf=4&token='.$token);
  653. // Default behavior (save and back)
  654. Tools::redirectAdmin(self::$currentIndex.($parent_id ? '&'.$this->identifier.'='.$object->id : '').'&conf=4&token='.$token);
  655. }
  656. }
  657. else
  658. $this->_errors[] = Tools::displayError('An error occurred while updating object.').' <b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)');
  659. }
  660. else
  661. $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
  662. }
  663. /* Object creation */
  664. else
  665. {
  666. if ($this->tabAccess['add'] === '1')
  667. {
  668. $object = new $this->className();
  669. $this->copyFromPost($object, $this->table);
  670. if (!$object->add())
  671. $this->_errors[] = Tools::displayError('An error occurred while creating object.').' <b>'.$this->table.' ('.Db::getInstance()->getMsgError().')</b>';
  672. elseif (($_POST[$this->identifier] = $object->id /* voluntary */) && $this->postImage($object->id) && !count($this->_errors) && $this->_redirect)
  673. {
  674. $parent_id = (int)(Tools::getValue('id_parent', 1));
  675. $this->afterAdd($object);
  676. $this->updateAssoShop($object->id);
  677. if ($this->table == 'group')
  678. {
  679. $this->updateRestrictions($object->id);
  680. // assign group access to every categories
  681. $categories = Category::getCategories($this->context->language->id, true);
  682. $rowList = array();$a=0;
  683. foreach ($categories as $category)
  684. foreach ($category as $categ_id => $categ)
  685. if ($categ_id != 1)
  686. $rowList[] = array('id_category' => $categ_id, 'id_group' => $object->id);
  687. Db::getInstance()->insert('category_group', $rowList);
  688. }
  689. // Save and stay on same form
  690. if (Tools::isSubmit('submitAdd'.$this->table.'AndStay'))
  691. Tools::redirectAdmin(self::$currentIndex.'&'.$this->identifier.'='.$object->id.'&conf=3&update'.$this->table.'&token='.$token);
  692. // Save and back to parent
  693. if (Tools::isSubmit('submitAdd'.$this->table.'AndBackToParent'))
  694. Tools::redirectAdmin(self::$currentIndex.'&'.$this->identifier.'='.$parent_id.'&conf=3&token='.$token);
  695. // Default behavior (save and back)
  696. Tools::redirectAdmin(self::$currentIndex.($parent_id ? '&'.$this->identifier.'='.$object->id : '').'&conf=3&token='.$token);
  697. }
  698. }
  699. else
  700. $this->_errors[] = Tools::displayError('You do not have permission to add here.');
  701. }
  702. }
  703. $this->_errors = array_unique($this->_errors);
  704. }
  705. /* Cancel all filters for this tab */
  706. elseif (isset($_POST['submitReset'.$this->table]))
  707. {
  708. $filters = $this->context->cookie->getFamily($this->table.'Filter_');
  709. foreach ($filters as $cookieKey => $filter)
  710. if (strncmp($cookieKey, $this->table.'Filter_', 7 + Tools::strlen($this->table)) == 0)
  711. {
  712. $key = substr($cookieKey, 7 + Tools::strlen($this->table));
  713. /* Table alias could be specified using a ! eg. alias!field */
  714. $tmpTab = explode('!', $key);
  715. $key = (count($tmpTab) > 1 ? $tmpTab[1] : $tmpTab[0]);
  716. if (array_key_exists($key, $this->fieldsDisplay))
  717. unset($this->context->cookie->$cookieKey);
  718. }
  719. if (isset($this->context->cookie->{'submitFilter'.$this->table}))
  720. unset($this->context->cookie->{'submitFilter'.$this->table});
  721. if (isset($this->context->cookie->{$this->table.'Orderby'}))
  722. unset($this->context->cookie->{$this->table.'Orderby'});
  723. if (isset($this->context->cookie->{$this->table.'Orderway'}))
  724. unset($this->context->cookie->{$this->table.'Orderway'});
  725. unset($_POST);
  726. }
  727. /* Submit options list */
  728. elseif (Tools::getValue('submitOptions'.$this->table))
  729. {
  730. $this->updateOptions($token);
  731. }
  732. /* Manage list filtering */
  733. elseif (Tools::isSubmit('submitFilter'.$this->table) || $this->context->cookie->{'submitFilter'.$this->table} !== false)
  734. {
  735. $_POST = array_merge($this->context->cookie->getFamily($this->table.'Filter_'), (isset($_POST) ? $_POST : array()));
  736. foreach ($_POST as $key => $value)
  737. {
  738. /* Extracting filters from $_POST on key filter_ */
  739. if ($value != NULL && !strncmp($key, $this->table.'Filter_', 7 + Tools::strlen($this->table)))
  740. {
  741. $key = Tools::substr($key, 7 + Tools::strlen($this->table));
  742. /* Table alias could be specified using a ! eg. alias!field */
  743. $tmpTab = explode('!', $key);
  744. $filter = count($tmpTab) > 1 ? $tmpTab[1] : $tmpTab[0];
  745. if ($field = $this->filterToField($key, $filter))
  746. {
  747. $type = (array_key_exists('filter_type', $field) ? $field['filter_type'] : (array_key_exists('type', $field) ? $field['type'] : false));
  748. if (($type == 'date' || $type == 'datetime') && is_string($value))
  749. $value = Tools::unSerialize($value);
  750. $key = isset($tmpTab[1]) ? $tmpTab[0].'.`'.bqSQL($tmpTab[1]).'`' : '`'.bqSQL($tmpTab[0]).'`';
  751. if (array_key_exists('tmpTableFilter', $field))
  752. $sqlFilter = & $this->_tmpTableFilter;
  753. elseif (array_key_exists('havingFilter', $field))
  754. $sqlFilter = & $this->_filterHaving;
  755. else
  756. $sqlFilter = & $this->_filter;
  757. /* Only for date filtering (from, to) */
  758. if (is_array($value))
  759. {
  760. if (isset($value[0]) && !empty($value[0]))
  761. {
  762. if (!Validate::isDate($value[0]))
  763. $this->_errors[] = Tools::displayError('\'From:\' date format is invalid (YYYY-MM-DD)');
  764. else
  765. $sqlFilter .= ' AND '.$key.' >= \''.pSQL(Tools::dateFrom($value[0])).'\'';
  766. }
  767. if (isset($value[1]) && !empty($value[1]))
  768. {
  769. if (!Validate::isDate($value[1]))
  770. $this->_errors[] = Tools::displayError('\'To:\' date format is invalid (YYYY-MM-DD)');
  771. else
  772. $sqlFilter .= ' AND '.$key.' <= \''.pSQL(Tools::dateTo($value[1])).'\'';
  773. }
  774. }
  775. else
  776. {
  777. $sqlFilter .= ' AND ';
  778. if ($type == 'int' || $type == 'bool')
  779. $sqlFilter .= (($key == $this->identifier || $key == '`'.$this->identifier.'`' || $key == '`active`') ? 'a.' : '').pSQL($key).' = '.(int)($value).' ';
  780. elseif ($type == 'decimal')
  781. $sqlFilter .= (($key == $this->identifier || $key == '`'.$this->identifier.'`') ? 'a.' : '').pSQL($key).' = '.(float)($value).' ';
  782. elseif ($type == 'select')
  783. $sqlFilter .= (($key == $this->identifier || $key == '`'.$this->identifier.'`') ? 'a.' : '').pSQL($key).' = \''.pSQL($value).'\' ';
  784. else
  785. $sqlFilter .= (($key == $this->identifier || $key == '`'.$this->identifier.'`') ? 'a.' : '').pSQL($key).' LIKE \'%'.pSQL($value).'%\' ';
  786. }
  787. }
  788. }
  789. }
  790. }
  791. elseif(Tools::isSubmit('submitFields') && $this->requiredDatabase && $this->tabAccess['add'] === '1' && $this->tabAccess['delete'] === '1')
  792. {
  793. if (!is_array($fields = Tools::getValue('fieldsBox')))
  794. $fields = array();
  795. $object = new $this->className();
  796. if (!$object->addFieldsRequiredDatabase($fields))
  797. $this->_errors[] = Tools::displayError('Error in updating required fields');
  798. else
  799. Tools::redirectAdmin(self::$currentIndex.'&conf=4&token='.$token);
  800. }
  801. }
  802. protected function updateAssoShop($id_object = false)
  803. {
  804. if (!Shop::isFeatureActive())
  805. return ;
  806. if (!$assos = AdminTab::getAssoShop($this->table, $id_object))
  807. return;
  808. Db::getInstance()->execute('DELETE FROM '._DB_PREFIX_.$this->table.'_'.$assos[1].($id_object ? ' WHERE `'.$this->identifier.'`='.(int)$id_object : ''));
  809. foreach ($assos[0] as $asso)
  810. Db::getInstance()->execute('INSERT INTO '._DB_PREFIX_.$this->table.'_'.$assos[1].' (`'.pSQL($this->identifier).'`, id_'.$assos[1].')
  811. VALUES('.(int)$asso['id_object'].', '.(int)$asso['id_'.$assos[1]].')');
  812. }
  813. protected static function getAssoShop($table, $id_object = false)
  814. {
  815. if (Shop::isTableAssociated($table))
  816. $type = 'shop';
  817. else
  818. return;
  819. $assos = array();
  820. foreach ($_POST as $k => $row)
  821. {
  822. if (!preg_match('/^checkBox'.Tools::toCamelCase($type, true).'Asso_'.$table.'_([0-9]+)?_([0-9]+)$/Ui', $k, $res))
  823. continue;
  824. $id_asso_object = (!empty($res[1]) ? $res[1] : $id_object);
  825. $assos[] = array('id_object' => (int)$id_asso_object, 'id_'.$type => (int)$res[2]);
  826. }
  827. return array($assos, $type);
  828. }
  829. /**
  830. * Update options and preferences
  831. *
  832. * @param string $token
  833. */
  834. protected function updateOptions($token)
  835. {
  836. if ($this->tabAccess['edit'] === '1')
  837. {
  838. $this->beforeUpdateOptions();
  839. $languages = Language::getLanguages(false);
  840. foreach ($this->optionsList as $category => $categoryData)
  841. {
  842. $fields = $categoryData['fields'];
  843. /* Check required fields */
  844. foreach ($fields as $field => $values)
  845. if (isset($values['required']) && $values['required'] && !empty($_POST['multishopOverrideOption'][$field]))
  846. if (isset($values['type']) && $values['type'] == 'textLang')
  847. {
  848. foreach ($languages as $language)
  849. if (($value = Tools::getValue($field.'_'.$language['id_lang'])) == false && (string)$value != '0')
  850. $this->_errors[] = sprintf(Tools::displayError('field %s is required.'), $values['title']);
  851. }
  852. elseif (($value = Tools::getValue($field)) == false && (string)$value != '0')
  853. $this->_errors[] = sprintf(Tools::displayError('field %s is required.'), $values['title']);
  854. /* Check fields validity */
  855. foreach ($fields as $field => $values)
  856. if (isset($values['type']) && $values['type'] == 'textLang')
  857. {
  858. foreach ($languages as $language)
  859. if (Tools::getValue($field.'_'.$language['id_lang']) && isset($values['validation']))
  860. if (!Validate::$values['validation'](Tools::getValue($field.'_'.$language['id_lang'])))
  861. $this->_errors[] = sprintf(Tools::displayError('field %s is invalid.'), $values['title']);
  862. }
  863. elseif (Tools::getValue($field) && isset($values['validation']))
  864. if (!Validate::$values['validation'](Tools::getValue($field)))
  865. $this->_errors[] = sprintf(Tools::displayError('field %s is invalid.'), $values['title']);
  866. /* Default value if null */
  867. foreach ($fields as $field => $values)
  868. if (!Tools::getValue($field) && isset($values['default']))
  869. $_POST[$field] = $values['default'];
  870. if (!count($this->_errors))
  871. {
  872. foreach ($fields as $key => $options)
  873. {
  874. if (isset($options['visibility']) && $options['visibility'] > Shop::getContext())
  875. continue;
  876. if (Shop::isFeatureActive() && empty($_POST['multishopOverrideOption'][$key]))
  877. {
  878. Configuration::deleteFromContext($key);
  879. continue;
  880. }
  881. // check if a method updateOptionFieldName is available
  882. $method_name = 'updateOption'.Tools::toCamelCase($key, true);
  883. if (method_exists($this, $method_name))
  884. $this->$method_name(Tools::getValue($key));
  885. else if (isset($options['type']) && in_array($options['type'], array('textLang', 'textareaLang')))
  886. {
  887. $list = array();
  888. foreach ($languages as $language)
  889. {
  890. $val = (isset($options['cast']) ? $options['cast'](Tools::getValue($key.'_'.$language['id_lang'])) : Tools::getValue($key.'_'.$language['id_lang']));
  891. if ($this->validateField($val, $options))
  892. {
  893. if (Validate::isCleanHtml($val))
  894. $list[$language['id_lang']] = $val;
  895. else
  896. $this->_errors[] = Tools::displayError('Can not add configuration '.$key.' for lang '.Language::getIsoById((int)$language['id_lang']));
  897. }
  898. }
  899. Configuration::updateValue($key, $list);
  900. }
  901. else
  902. {
  903. $val = (isset($options['cast']) ? $options['cast'](Tools::getValue($key)) : Tools::getValue($key));
  904. if ($this->validateField($val, $options))
  905. {
  906. if (Validate::isCleanHtml($val))
  907. Configuration::updateValue($key, $val);
  908. else
  909. $this->_errors[] = Tools::displayError('Can not add configuration '.$key);
  910. }
  911. }
  912. }
  913. }
  914. }
  915. if (count($this->_errors) <= 0)
  916. Tools::redirectAdmin(self::$currentIndex.'&conf=6&token='.$token);
  917. }
  918. else
  919. $this->_errors[] = Tools::displayError('You do not have permission to edit here.');
  920. }
  921. /**
  922. * Can be overriden
  923. */
  924. public function beforeUpdateOptions()
  925. {
  926. }
  927. protected function validateField($value, $field)
  928. {
  929. if (isset($field['validation']))
  930. {
  931. if ((!isset($field['empty']) || !$field['empty'] || (isset($field['empty']) && $field['empty'] && $value)) && method_exists('Validate', $field['validation']))
  932. {
  933. if (!Validate::$field['validation']($value))
  934. {
  935. $this->_errors[] = Tools::displayError($field['title'].' : Incorrect value');
  936. return false;
  937. }
  938. }
  939. }
  940. return true;
  941. }
  942. protected function uploadImage($id, $name, $dir, $ext = false, $width = NULL, $height = NULL)
  943. {
  944. if (isset($_FILES[$name]['tmp_name']) && !empty($_FILES[$name]['tmp_name']))
  945. {
  946. // Delete old image
  947. if (Validate::isLoadedObject($object = $this->loadObject()))
  948. $object->deleteImage();
  949. else
  950. return false;
  951. // Check image validity
  952. $max_size = isset($this->maxImageSize) ? $this->maxImageSize : 0;
  953. if ($error = ImageManager::validateUpload($_FILES[$name], Tools::getMaxUploadSize($max_size)))
  954. $this->_errors[] = $error;
  955. elseif (!($tmpName = tempnam(_PS_TMP_IMG_DIR_, 'PS')) || !move_uploaded_file($_FILES[$name]['tmp_name'], $tmpName))
  956. return false;
  957. else
  958. {
  959. $_FILES[$name]['tmp_name'] = $tmpName;
  960. // Copy new image
  961. if (!ImageManager::resize($tmpName, _PS_IMG_DIR_.$dir.$id.'.'.$this->imageType, (int)$width, (int)$height, ($ext ? $ext : $this->imageType)))
  962. $this->_errors[] = Tools::displayError('An error occurred while uploading image.');
  963. if (count($this->_errors))
  964. return false;
  965. if ($this->afterImageUpload())
  966. {
  967. unlink($tmpName);
  968. return true;
  969. }
  970. return false;
  971. }
  972. }
  973. return true;
  974. }
  975. /**
  976. * Overload this method for custom checking
  977. *
  978. * @param integer $id Object id used for deleting images
  979. * @return boolean
  980. */
  981. protected function postImage($id)
  982. {
  983. if (isset($this->fieldImageSettings['name']) && isset($this->fieldImageSettings['dir']))
  984. return $this->uploadImage($id, $this->fieldImageSettings['name'], $this->fieldImageSettings['dir'].'/');
  985. elseif (!empty($this->fieldImageSettings))
  986. foreach ($this->fieldImageSettings as $image)
  987. if (isset($image['name']) && isset($image['dir']))
  988. $this->uploadImage($id, $image['name'], $image['dir'].'/');
  989. return !count($this->_errors) ? true : false;
  990. }
  991. /**
  992. * Copy datas from $_POST to object
  993. *
  994. * @param object &$object Object
  995. * @param string $table Object table
  996. */
  997. protected function copyFromPost(&$object, $table)
  998. {
  999. /* Classical fields */
  1000. foreach ($_POST as $key => $value)
  1001. if (key_exists($key, $object) && $key != 'id_'.$table)
  1002. {
  1003. /* Do not take care of password field if empty */
  1004. if ($key == 'passwd' && Tools::getValue('id_'.$table) && empty($value))
  1005. continue;
  1006. /* Automatically encrypt password in MD5 */
  1007. if ($key == 'passwd' && !empty($value))
  1008. $value = Tools::encrypt($value);
  1009. $object->{$key} = $value;
  1010. }
  1011. /* Multilingual fields */
  1012. $rules = call_user_func(array(get_class($object), 'getValidationRules'), get_class($object));
  1013. if (count($rules['validateLang']))
  1014. {
  1015. $languages = Language::getLanguages(false);
  1016. foreach ($languages as $language)
  1017. foreach (array_keys($rules['validateLang']) as $field)
  1018. if (isset($_POST[$field.'_'.(int)($language['id_lang'])]))
  1019. $object->{$field}[(int)($language['id_lang'])] = $_POST[$field.'_'.(int)($language['id_lang'])];
  1020. }
  1021. }
  1022. /**
  1023. * Display errors
  1024. */
  1025. public function displayErrors()
  1026. {
  1027. if ($nbErrors = count($this->_errors) && $this->_includeContainer)
  1028. {
  1029. echo '<script type="text/javascript">
  1030. $(document).ready(function() {
  1031. $(\'#hideError\').unbind(\'click\').click(function(){
  1032. $(\'.error\').hide(\'slow\', function (){
  1033. $(\'.error\').remove();
  1034. });
  1035. return false;
  1036. });
  1037. });
  1038. </script>
  1039. <div class="error"><span style="float:right"><a id="hideError" href=""><img alt="X" src="../img/admin/close.png" /></a></span><img src="../img/admin/error2.png" />';
  1040. if (count($this->_errors) == 1)
  1041. echo $this->_errors[0];
  1042. else
  1043. {
  1044. echo sprintf($this->l('%d errors'), $nbErrors).'<br /><ol>';
  1045. foreach ($this->_errors as $error)
  1046. echo '<li>'.$error.'</li>';
  1047. echo '</ol>';
  1048. }
  1049. echo '</div>';
  1050. }
  1051. $this->includeSubTab('displayErrors');
  1052. }
  1053. /**
  1054. * Display a warning message
  1055. *
  1056. * @param string $warn Warning message to display
  1057. */
  1058. public function displayWarning($warn)
  1059. {
  1060. $str_output = '';
  1061. if (!empty($warn))
  1062. {
  1063. $str_output .= '<script type="text/javascript">
  1064. $(document).ready(function() {
  1065. $(\'#linkSeeMore\').unbind(\'click\').click(function(){
  1066. $(\'#seeMore\').show(\'slow\');
  1067. $(this).hide();
  1068. $(\'#linkHide\').show();
  1069. return false;
  1070. });
  1071. $(\'#linkHide\').unbind(\'click\').click(function(){
  1072. $(\'#seeMore\').hide(\'slow\');
  1073. $(this).hide();
  1074. $(\'#linkSeeMore\').show();
  1075. return false;
  1076. });
  1077. $(\'#hideWarn\').unbind(\'click\').click(function(){
  1078. $(\'.warn\').hide(\'slow\', function (){
  1079. $(\'.warn\').remove();
  1080. });
  1081. return false;
  1082. });
  1083. });
  1084. </script>
  1085. <div class="warn">';
  1086. if (!is_array($warn))
  1087. $str_output .= '<img src="../img/admin/warn2.png" />'.$warn;
  1088. else
  1089. { $str_output .= '<span style="float:right"><a id="hideWarn" href=""><img alt="X" src="../img/admin/close.png" /></a></span><img src="../img/admin/warn2.png" />'.
  1090. (count($warn) > 1 ? $this->l('There are') : $this->l('There is')).' '.count($warn).' '.(count($warn) > 1 ? $this->l('warnings') : $this->l('warning'))
  1091. .'<span style="margin-left:20px;" id="labelSeeMore">
  1092. <a id="linkSeeMore" href="#" style="text-decoration:underline">'.$this->l('Click here to see more').'</a>
  1093. <a id="linkHide" href="#" style="text-decoration:underline;display:none">'.$this->l('Hide warning').'</a></span><ul style="display:none;" id="seeMore">';
  1094. foreach($warn as $val)
  1095. $str_output .= '<li>'.$val.'</li>';
  1096. $str_output .= '</ul>';
  1097. }
  1098. $str_output .= '</div>';
  1099. }
  1100. echo $str_output;
  1101. }
  1102. /**
  1103. * Display confirmations
  1104. */
  1105. public function displayConf()
  1106. {
  1107. if ($conf = Tools::getValue('conf'))
  1108. echo '
  1109. <div class="conf">
  1110. '.$this->_conf[(int)($conf)].'
  1111. </div>';
  1112. }
  1113. /**
  1114. * Get the current objects' list form the database
  1115. *
  1116. * @param integer $id_lang Language used for display
  1117. * @param string $orderBy ORDER BY clause
  1118. * @param string $_orderWay Order way (ASC, DESC)
  1119. * @param integer $start Offset in LIMIT clause
  1120. * @param integer $limit Row count in LIMIT clause
  1121. */
  1122. public function getList($id_lang, $orderBy = NULL, $orderWay = NULL, $start = 0, $limit = NULL, $id_lang_shop = false)
  1123. {
  1124. /* Manage default params values */
  1125. if (empty($limit))
  1126. $limit = ((!isset($this->context->cookie->{$this->table.'_pagination'})) ? $this->_pagination[1] : $limit = $this->context->cookie->{$this->table.'_pagination'});
  1127. if (!Validate::isTableOrIdentifier($this->table))
  1128. $this->_errors[] = Tools::displayError('Table name is invalid:').' "'.$this->table.'"';
  1129. if (empty($orderBy))
  1130. $orderBy = $this->context->cookie->__get($this->table.'Orderby') ? $this->context->cookie->__get($this->table.'Orderby') : $this->_defaultOrderBy;
  1131. if (empty($orderWay))
  1132. $orderWay = $this->context->cookie->__get($this->table.'Orderway') ? $this->context->cookie->__get($this->table.'Orderway') : 'ASC';
  1133. $limit = (int)(Tools::getValue('pagination', $limit));
  1134. $this->context->cookie->{$this->table.'_pagination'} = $limit;
  1135. /* Check params validity */
  1136. if (!Validate::isOrderBy($orderBy) || !Validate::isOrderWay($orderWay)
  1137. OR !is_numeric($start) || !is_numeric($limit)
  1138. OR !Validate::isUnsignedId($id_lang))
  1139. die(Tools::displayError('get list params is not valid'));
  1140. /* Determine offset from current page */
  1141. if ((isset($_POST['submitFilter'.$this->table]) OR
  1142. isset($_POST['submitFilter'.$this->table.'_x']) OR
  1143. isset($_POST['submitFilter'.$this->table.'_y'])) AND
  1144. !empty($_POST['submitFilter'.$this->table]) AND
  1145. is_numeric($_POST['submitFilter'.$this->table]))
  1146. $start = (int)($_POST['submitFilter'.$this->table] - 1) * $limit;
  1147. /* Cache */
  1148. $this->_lang = (int)($id_lang);
  1149. $this->_orderBy = $orderBy;
  1150. $this->_orderWay = Tools::strtoupper($orderWay);
  1151. /* SQL table : orders, but class name is Order */
  1152. $sqlTable = $this->table == 'order' ? 'orders' : $this->table

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