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

/classes/ObjectModel.php

http://marocmall.googlecode.com/
PHP | 717 lines | 502 code | 83 blank | 132 comment | 112 complexity | 7ff758dc81e79241849120831b2669fc MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php
  2. /*
  3. * 2007-2011 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-2011 PrestaShop SA
  23. * @version Release: $Revision: 7046 $
  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. abstract class ObjectModelCore
  28. {
  29. /** @var integer Object id */
  30. public $id;
  31. /** @var integer lang id */
  32. protected $id_lang = NULL;
  33. /** @var string SQL Table name */
  34. protected $table = NULL;
  35. /** @var string SQL Table identifier */
  36. protected $identifier = NULL;
  37. /** @var array Required fields for admin panel forms */
  38. protected $fieldsRequired = array();
  39. /** @var fieldsRequiredDatabase */
  40. protected static $fieldsRequiredDatabase = NULL;
  41. /** @var array Maximum fields size for admin panel forms */
  42. protected $fieldsSize = array();
  43. /** @var array Fields validity functions for admin panel forms */
  44. protected $fieldsValidate = array();
  45. /** @var array Multilingual required fields for admin panel forms */
  46. protected $fieldsRequiredLang = array();
  47. /** @var array Multilingual maximum fields size for admin panel forms */
  48. protected $fieldsSizeLang = array();
  49. /** @var array Multilingual fields validity functions for admin panel forms */
  50. protected $fieldsValidateLang = array();
  51. /** @var array tables */
  52. protected $tables = array();
  53. /** @var array tables */
  54. protected $webserviceParameters = array();
  55. protected static $_cache = array();
  56. /** @var string path to image directory. Used for image deletion. */
  57. protected $image_dir = NULL;
  58. /** @var string file type of image files. Used for image deletion. */
  59. protected $image_format = 'jpg';
  60. /**
  61. * Returns object validation rules (fields validity)
  62. *
  63. * @param string $className Child class name for static use (optional)
  64. * @return array Validation rules (fields validity)
  65. */
  66. static public function getValidationRules($className = __CLASS__)
  67. {
  68. $object = new $className();
  69. return array(
  70. 'required' => $object->fieldsRequired,
  71. 'size' => $object->fieldsSize,
  72. 'validate' => $object->fieldsValidate,
  73. 'requiredLang' => $object->fieldsRequiredLang,
  74. 'sizeLang' => $object->fieldsSizeLang,
  75. 'validateLang' => $object->fieldsValidateLang);
  76. }
  77. /**
  78. * Prepare fields for ObjectModel class (add, update)
  79. * All fields are verified (pSQL, intval...)
  80. *
  81. * @return array All object fields
  82. */
  83. public function getFields() { return array(); }
  84. /**
  85. * Build object
  86. *
  87. * @param integer $id Existing object id in order to load object (optional)
  88. * @param integer $id_lang Required if object is multilingual (optional)
  89. */
  90. public function __construct($id = NULL, $id_lang = NULL)
  91. {
  92. if ($id_lang != NULL && Validate::isLoadedObject(new Language($id_lang)))
  93. $this->id_lang = $id_lang;
  94. elseif ($id_lang != NULL)
  95. die(Tools::displayError());
  96. /* Connect to database and check SQL table/identifier */
  97. if (!Validate::isTableOrIdentifier($this->identifier) OR !Validate::isTableOrIdentifier($this->table))
  98. die(Tools::displayError());
  99. $this->identifier = pSQL($this->identifier);
  100. /* Load object from database if object id is present */
  101. if ($id)
  102. {
  103. if (!isset(self::$_cache[$this->table][(int)($id)][(int)($id_lang)]))
  104. self::$_cache[$this->table][(int)($id)][(int)($id_lang)] = Db::getInstance()->getRow('
  105. SELECT *
  106. FROM `'._DB_PREFIX_.$this->table.'` a '.
  107. ($id_lang ? ('LEFT JOIN `'.pSQL(_DB_PREFIX_.$this->table).'_lang` b ON (a.`'.$this->identifier.'` = b.`'.$this->identifier).'` AND `id_lang` = '.(int)($id_lang).')' : '')
  108. .' WHERE a.`'.$this->identifier.'` = '.(int)($id));
  109. $result = self::$_cache[$this->table][(int)($id)][(int)($id_lang)];
  110. if ($result)
  111. {
  112. $this->id = (int)($id);
  113. foreach ($result AS $key => $value)
  114. if (key_exists($key, $this))
  115. $this->{$key} = stripslashes($value);
  116. /* Join multilingual tables */
  117. if (!$id_lang AND method_exists($this, 'getTranslationsFieldsChild'))
  118. {
  119. $result = Db::getInstance()->ExecuteS('
  120. SELECT *
  121. FROM `'.pSQL(_DB_PREFIX_.$this->table).'_lang`
  122. WHERE `'.$this->identifier.'` = '.(int)$id);
  123. if ($result)
  124. foreach ($result AS $row)
  125. foreach ($row AS $key => $value)
  126. if (key_exists($key, $this) AND $key != $this->identifier)
  127. {
  128. if (!is_array($this->{$key}))
  129. $this->{$key} = array();
  130. $this->{$key}[(int)$row['id_lang']] = stripslashes($value);
  131. }
  132. }
  133. }
  134. }
  135. if (!is_array(self::$fieldsRequiredDatabase))
  136. {
  137. $fields = $this->getfieldsRequiredDatabase(true);
  138. if ($fields)
  139. foreach ($fields AS $row)
  140. self::$fieldsRequiredDatabase[$row['object_name']][(int)$row['id_required_field']] = pSQL($row['field_name']);
  141. else
  142. self::$fieldsRequiredDatabase = array();
  143. }
  144. }
  145. /**
  146. * Save current object to database (add or update)
  147. *
  148. * return boolean Insertion result
  149. */
  150. public function save($nullValues = false, $autodate = true)
  151. {
  152. return (int)($this->id) > 0 ? $this->update($nullValues) : $this->add($autodate, $nullValues);
  153. }
  154. /**
  155. * Add current object to database
  156. *
  157. * return boolean Insertion result
  158. */
  159. public function add($autodate = true, $nullValues = false)
  160. {
  161. if (!Validate::isTableOrIdentifier($this->table))
  162. die(Tools::displayError());
  163. /* Automatically fill dates */
  164. if ($autodate AND key_exists('date_add', $this))
  165. $this->date_add = date('Y-m-d H:i:s');
  166. if ($autodate AND key_exists('date_upd', $this))
  167. $this->date_upd = date('Y-m-d H:i:s');
  168. /* Database insertion */
  169. if ($nullValues)
  170. $result = Db::getInstance()->autoExecuteWithNullValues(_DB_PREFIX_.$this->table, $this->getFields(), 'INSERT');
  171. else
  172. $result = Db::getInstance()->autoExecute(_DB_PREFIX_.$this->table, $this->getFields(), 'INSERT');
  173. if (!$result)
  174. return false;
  175. /* Get object id in database */
  176. $this->id = Db::getInstance()->Insert_ID();
  177. /* Database insertion for multilingual fields related to the object */
  178. if (method_exists($this, 'getTranslationsFieldsChild'))
  179. {
  180. $fields = $this->getTranslationsFieldsChild();
  181. if ($fields AND is_array($fields))
  182. foreach ($fields AS $field)
  183. {
  184. foreach ($field AS $key => $value)
  185. if (!Validate::isTableOrIdentifier($key))
  186. die(Tools::displayError());
  187. $field[$this->identifier] = (int)$this->id;
  188. $result = Db::getInstance()->AutoExecute(_DB_PREFIX_.$this->table.'_lang', $field, 'INSERT') && $result;
  189. }
  190. }
  191. return $result;
  192. }
  193. /**
  194. * Update current object to database
  195. *
  196. * return boolean Update result
  197. */
  198. public function update($nullValues = false)
  199. {
  200. if (!Validate::isTableOrIdentifier($this->identifier) OR !Validate::isTableOrIdentifier($this->table))
  201. die(Tools::displayError());
  202. $this->clearCache();
  203. /* Automatically fill dates */
  204. if (key_exists('date_upd', $this))
  205. $this->date_upd = date('Y-m-d H:i:s');
  206. /* Database update */
  207. if ($nullValues)
  208. $result = Db::getInstance()->autoExecuteWithNullValues(_DB_PREFIX_.$this->table, $this->getFields(), 'UPDATE', '`'.pSQL($this->identifier).'` = '.(int)($this->id));
  209. else
  210. $result = Db::getInstance()->autoExecute(_DB_PREFIX_.$this->table, $this->getFields(), 'UPDATE', '`'.pSQL($this->identifier).'` = '.(int)($this->id));
  211. if (!$result)
  212. return false;
  213. // Database update for multilingual fields related to the object
  214. if (method_exists($this, 'getTranslationsFieldsChild'))
  215. {
  216. $fields = $this->getTranslationsFieldsChild();
  217. if (is_array($fields))
  218. foreach ($fields as $field)
  219. {
  220. foreach ($field as $key => $value)
  221. if (!Validate::isTableOrIdentifier($key))
  222. die(Tools::displayError());
  223. // used to insert missing lang entries
  224. $where_lang = '`'.pSQL($this->identifier).'` = '.(int)($this->id).' AND `id_lang` = '.(int)($field['id_lang']);
  225. $lang_found = Db::getInstance()->getValue('SELECT COUNT(*) FROM `'.pSQL(_DB_PREFIX_.$this->table).'_lang` WHERE '. $where_lang);
  226. if (!$lang_found)
  227. $result &= Db::getInstance()->AutoExecute(_DB_PREFIX_.$this->table.'_lang', $field, 'INSERT');
  228. else
  229. $result &= Db::getInstance()->AutoExecute(_DB_PREFIX_.$this->table.'_lang', $field, 'UPDATE', $where_lang);
  230. }
  231. }
  232. return $result;
  233. }
  234. /**
  235. * Delete current object from database
  236. *
  237. * return boolean Deletion result
  238. */
  239. public function delete()
  240. {
  241. if (!Validate::isTableOrIdentifier($this->identifier) OR !Validate::isTableOrIdentifier($this->table))
  242. die(Tools::displayError());
  243. $this->clearCache();
  244. /* Database deletion */
  245. $result = Db::getInstance()->Execute('DELETE FROM `'.pSQL(_DB_PREFIX_.$this->table).'` WHERE `'.pSQL($this->identifier).'` = '.(int)($this->id));
  246. if (!$result)
  247. return false;
  248. /* Database deletion for multilingual fields related to the object */
  249. if (method_exists($this, 'getTranslationsFieldsChild'))
  250. Db::getInstance()->Execute('DELETE FROM `'.pSQL(_DB_PREFIX_.$this->table).'_lang` WHERE `'.pSQL($this->identifier).'` = '.(int)($this->id));
  251. return $result;
  252. }
  253. /**
  254. * Delete several objects from database
  255. *
  256. * return boolean Deletion result
  257. */
  258. public function deleteSelection($selection)
  259. {
  260. if (!is_array($selection) OR !Validate::isTableOrIdentifier($this->identifier) OR !Validate::isTableOrIdentifier($this->table))
  261. die(Tools::displayError());
  262. $result = true;
  263. foreach ($selection AS $id)
  264. {
  265. $this->id = (int)($id);
  266. $result = $result AND $this->delete();
  267. }
  268. return $result;
  269. }
  270. /**
  271. * Toggle object status in database
  272. *
  273. * return boolean Update result
  274. */
  275. public function toggleStatus()
  276. {
  277. if (!Validate::isTableOrIdentifier($this->identifier) OR !Validate::isTableOrIdentifier($this->table))
  278. die(Tools::displayError());
  279. /* Object must have a variable called 'active' */
  280. elseif (!key_exists('active', $this))
  281. die(Tools::displayError());
  282. /* Update active status on object */
  283. $this->active = (int)(!$this->active);
  284. /* Change status to active/inactive */
  285. return Db::getInstance()->Execute('
  286. UPDATE `'.pSQL(_DB_PREFIX_.$this->table).'`
  287. SET `active` = !`active`
  288. WHERE `'.pSQL($this->identifier).'` = '.(int)($this->id));
  289. }
  290. /**
  291. * Prepare multilingual fields for database insertion
  292. *
  293. * @param array $fieldsArray Multilingual fields to prepare
  294. * return array Prepared fields for database insertion
  295. */
  296. protected function getTranslationsFields($fieldsArray)
  297. {
  298. /* WARNING : Product do not use this function, so do not forget to report any modification if necessary */
  299. if (!Validate::isTableOrIdentifier($this->identifier))
  300. die(Tools::displayError());
  301. $fields = array();
  302. if($this->id_lang == NULL)
  303. foreach (Language::getLanguages() as $language)
  304. $this->makeTranslationFields($fields, $fieldsArray, $language['id_lang']);
  305. else
  306. $this->makeTranslationFields($fields, $fieldsArray, $this->id_lang);
  307. return $fields;
  308. }
  309. protected function makeTranslationFields(&$fields, &$fieldsArray, $id_language)
  310. {
  311. $fields[$id_language]['id_lang'] = $id_language;
  312. $fields[$id_language][$this->identifier] = (int)($this->id);
  313. foreach ($fieldsArray as $field)
  314. {
  315. /* Check fields validity */
  316. if (!Validate::isTableOrIdentifier($field))
  317. die(Tools::displayError());
  318. /* Copy the field, or the default language field if it's both required and empty */
  319. if ((!$this->id_lang AND isset($this->{$field}[$id_language]) AND !empty($this->{$field}[$id_language]))
  320. OR ($this->id_lang AND isset($this->$field) AND !empty($this->$field)))
  321. $fields[$id_language][$field] = $this->id_lang ? pSQL($this->$field) : pSQL($this->{$field}[$id_language]);
  322. elseif (in_array($field, $this->fieldsRequiredLang))
  323. $fields[$id_language][$field] = $this->id_lang ? pSQL($this->$field) : pSQL($this->{$field}[Configuration::get('PS_LANG_DEFAULT')]);
  324. else
  325. $fields[$id_language][$field] = '';
  326. }
  327. }
  328. /**
  329. * Check for fields validity before database interaction
  330. */
  331. public function validateFields($die = true, $errorReturn = false)
  332. {
  333. $fieldsRequired = array_merge($this->fieldsRequired, (isset(self::$fieldsRequiredDatabase[get_class($this)]) ? self::$fieldsRequiredDatabase[get_class($this)] : array()));
  334. foreach ($fieldsRequired as $field)
  335. if (Tools::isEmpty($this->{$field}) AND (!is_numeric($this->{$field})))
  336. {
  337. if ($die) die (Tools::displayError().' ('.get_class($this).' -> '.$field.' is empty)');
  338. return $errorReturn ? get_class($this).' -> '.$field.' is empty' : false;
  339. }
  340. foreach ($this->fieldsSize as $field => $size)
  341. if (isset($this->{$field}) AND Tools::strlen($this->{$field}) > $size)
  342. {
  343. if ($die) die (Tools::displayError().' ('.get_class($this).' -> '.$field.' Length '.$size.')');
  344. return $errorReturn ? get_class($this).' -> '.$field.' Length '.$size : false;
  345. }
  346. $validate = new Validate();
  347. foreach ($this->fieldsValidate as $field => $method)
  348. if (!method_exists($validate, $method))
  349. die (Tools::displayError('Validation function not found.').' '.$method);
  350. elseif (!empty($this->{$field}) AND !call_user_func(array('Validate', $method), $this->{$field}))
  351. {
  352. if ($die) die (Tools::displayError().' ('.get_class($this).' -> '.$field.' = '.$this->{$field}.')');
  353. return $errorReturn ? get_class($this).' -> '.$field.' = '.$this->{$field} : false;
  354. }
  355. return true;
  356. }
  357. /**
  358. * Check for multilingual fields validity before database interaction
  359. */
  360. public function validateFieldsLang($die = true, $errorReturn = false)
  361. {
  362. $defaultLanguage = (int)(Configuration::get('PS_LANG_DEFAULT'));
  363. foreach ($this->fieldsRequiredLang as $fieldArray)
  364. {
  365. if (!is_array($this->{$fieldArray}))
  366. continue ;
  367. if (!$this->{$fieldArray} OR !sizeof($this->{$fieldArray}) OR ($this->{$fieldArray}[$defaultLanguage] !== '0' AND empty($this->{$fieldArray}[$defaultLanguage])))
  368. {
  369. if ($die) die (Tools::displayError().' ('.get_class($this).'->'.$fieldArray.' '.Tools::displayError('is empty for default language.').')');
  370. return $errorReturn ? get_class($this).'->'.$fieldArray.' '.Tools::displayError('is empty for default language.') : false;
  371. }
  372. }
  373. foreach ($this->fieldsSizeLang as $fieldArray => $size)
  374. {
  375. if (!is_array($this->{$fieldArray}))
  376. continue ;
  377. foreach ($this->{$fieldArray} as $k => $value)
  378. if (Tools::strlen($value) > $size)
  379. {
  380. if ($die) die (Tools::displayError().' ('.get_class($this).'->'.$fieldArray.' '.Tools::displayError('Length').' '.$size.' '.Tools::displayError('for language').')');
  381. return $errorReturn ? get_class($this).'->'.$fieldArray.' '.Tools::displayError('Length').' '.$size.' '.Tools::displayError('for language') : false;
  382. }
  383. }
  384. $validate = new Validate();
  385. foreach ($this->fieldsValidateLang as $fieldArray => $method)
  386. {
  387. if (!is_array($this->{$fieldArray}))
  388. continue ;
  389. foreach ($this->{$fieldArray} as $k => $value)
  390. if (!method_exists($validate, $method))
  391. die (Tools::displayError('Validation function not found.').' '.$method);
  392. elseif (!empty($value) AND !call_user_func(array('Validate', $method), $value))
  393. {
  394. if ($die) die (Tools::displayError('The following field is invalid according to the validate method ').'<b>'.$method.'</b>:<br/> ('.get_class($this).'->'.$fieldArray.' = '.$value.' '.Tools::displayError('for language').' '.$k.')');
  395. return $errorReturn ? Tools::displayError('The following field is invalid according to the validate method ').'<b>'.$method.'</b>:<br/> ('. get_class($this).'->'.$fieldArray.' = '.$value.' '.Tools::displayError('for language').' '.$k : false;
  396. }
  397. }
  398. return true;
  399. }
  400. static public function displayFieldName($field, $className = __CLASS__, $htmlentities = true)
  401. {
  402. global $_FIELDS, $cookie;
  403. $iso = strtolower(Language::getIsoById($cookie->id_lang ? (int)$cookie->id_lang : Configuration::get('PS_LANG_DEFAULT')));
  404. @include(_PS_TRANSLATIONS_DIR_.$iso.'/fields.php');
  405. $key = $className.'_'.md5($field);
  406. return ((is_array($_FIELDS) AND array_key_exists($key, $_FIELDS)) ? ($htmlentities ? htmlentities($_FIELDS[$key], ENT_QUOTES, 'utf-8') : $_FIELDS[$key]) : $field);
  407. }
  408. /**
  409. * TODO: refactor rename all calls to this to validateController
  410. */
  411. public function validateControler($htmlentities = true)
  412. {
  413. return $this->validateController($htmlentities);
  414. }
  415. public function validateController($htmlentities = true)
  416. {
  417. $errors = array();
  418. /* Checking for required fields */
  419. $fieldsRequired = array_merge($this->fieldsRequired, (isset(self::$fieldsRequiredDatabase[get_class($this)]) ? self::$fieldsRequiredDatabase[get_class($this)] : array()));
  420. foreach ($fieldsRequired AS $field)
  421. if (($value = Tools::getValue($field, $this->{$field})) == false AND (string)$value != '0')
  422. if (!$this->id OR $field != 'passwd')
  423. $errors[] = '<b>'.self::displayFieldName($field, get_class($this), $htmlentities).'</b> '.Tools::displayError('is required.');
  424. /* Checking for maximum fields sizes */
  425. foreach ($this->fieldsSize AS $field => $maxLength)
  426. if (($value = Tools::getValue($field, $this->{$field})) AND Tools::strlen($value) > $maxLength)
  427. $errors[] = '<b>'.self::displayFieldName($field, get_class($this), $htmlentities).'</b> '.Tools::displayError('is too long.').' ('.Tools::displayError('Maximum length:').' '.$maxLength.')';
  428. /* Checking for fields validity */
  429. foreach ($this->fieldsValidate AS $field => $function)
  430. {
  431. // Hack for postcode required for country which does not have postcodes
  432. if ($value = Tools::getValue($field, $this->{$field}) OR ($field == 'postcode' AND $value == '0'))
  433. {
  434. if (!Validate::$function($value))
  435. $errors[] = '<b>'.self::displayFieldName($field, get_class($this), $htmlentities).'</b> '.Tools::displayError('is invalid.');
  436. else
  437. {
  438. if ($field == 'passwd')
  439. {
  440. if ($value = Tools::getValue($field))
  441. $this->{$field} = Tools::encrypt($value);
  442. }
  443. else
  444. $this->{$field} = $value;
  445. }
  446. }
  447. }
  448. return $errors;
  449. }
  450. public function getWebserviceParameters($wsParamsAttributeName = NULL)
  451. {
  452. $defaultResourceParameters = array(
  453. 'objectSqlId' => $this->identifier,
  454. 'retrieveData' => array(
  455. 'className' => get_class($this),
  456. 'retrieveMethod' => 'getWebserviceObjectList',
  457. 'params' => array(),
  458. 'table' => $this->table,
  459. ),
  460. 'fields' => array(
  461. 'id' => array('sqlId' => $this->identifier, 'i18n' => false),
  462. ),
  463. );
  464. if (is_null($wsParamsAttributeName))
  465. $wsParamsAttributeName = 'webserviceParameters';
  466. if (!isset($this->{$wsParamsAttributeName}['objectNodeName']))
  467. $defaultResourceParameters['objectNodeName'] = $this->table;
  468. if (!isset($this->{$wsParamsAttributeName}['objectsNodeName']))
  469. $defaultResourceParameters['objectsNodeName'] = $this->table.'s';
  470. if (isset($this->{$wsParamsAttributeName}['associations']))
  471. foreach ($this->{$wsParamsAttributeName}['associations'] as $assocName => &$association)
  472. {
  473. if (!array_key_exists('setter', $association) || (isset($association['setter']) && !$association['setter']))
  474. $association['setter'] = Tools::toCamelCase('set_ws_'.$assocName);
  475. if (!array_key_exists('getter', $association))
  476. $association['getter'] = Tools::toCamelCase('get_ws_'.$assocName);
  477. }
  478. if (isset($this->{$wsParamsAttributeName}['retrieveData']) && isset($this->{$wsParamsAttributeName}['retrieveData']['retrieveMethod']))
  479. unset($defaultResourceParameters['retrieveData']['retrieveMethod']);
  480. $resourceParameters = array_merge_recursive($defaultResourceParameters, $this->{$wsParamsAttributeName});
  481. if (isset($this->fieldsSize))
  482. foreach ($this->fieldsSize as $fieldName => $maxSize)
  483. {
  484. if (!isset($resourceParameters['fields'][$fieldName]))
  485. $resourceParameters['fields'][$fieldName] = array('required' => false);
  486. $resourceParameters['fields'][$fieldName] = array_merge(
  487. $resourceParameters['fields'][$fieldName],
  488. $resourceParameters['fields'][$fieldName] = array('sqlId' => $fieldName, 'maxSize' => $maxSize, 'i18n' => false)
  489. );
  490. }
  491. if (isset($this->fieldsValidate))
  492. foreach ($this->fieldsValidate as $fieldName => $validateMethod)
  493. {
  494. if (!isset($resourceParameters['fields'][$fieldName]))
  495. $resourceParameters['fields'][$fieldName] = array('required' => false);
  496. $resourceParameters['fields'][$fieldName] = array_merge(
  497. $resourceParameters['fields'][$fieldName],
  498. $resourceParameters['fields'][$fieldName] = array(
  499. 'sqlId' => $fieldName,
  500. 'validateMethod' => (
  501. array_key_exists('validateMethod', $resourceParameters['fields'][$fieldName]) ?
  502. array_merge($resourceParameters['fields'][$fieldName]['validateMethod'], array($validateMethod)) :
  503. array($validateMethod)
  504. ),
  505. 'i18n' => false
  506. )
  507. );
  508. }
  509. if (isset($this->fieldsRequired))
  510. {
  511. $fieldsRequired = array_merge($this->fieldsRequired, (isset(self::$fieldsRequiredDatabase[get_class($this)]) ? self::$fieldsRequiredDatabase[get_class($this)] : array()));
  512. foreach ($fieldsRequired as $fieldRequired)
  513. {
  514. if (!isset($resourceParameters['fields'][$fieldRequired]))
  515. $resourceParameters['fields'][$fieldRequired] = array();
  516. $resourceParameters['fields'][$fieldRequired] = array_merge(
  517. $resourceParameters['fields'][$fieldRequired],
  518. $resourceParameters['fields'][$fieldRequired] = array('sqlId' => $fieldRequired, 'required' => true, 'i18n' => false)
  519. );
  520. }
  521. }
  522. if (isset($this->fieldsSizeLang))
  523. foreach ($this->fieldsSizeLang as $fieldName => $maxSize)
  524. {
  525. if (!isset($resourceParameters['fields'][$fieldName]))
  526. $resourceParameters['fields'][$fieldName] = array('required' => false);
  527. $resourceParameters['fields'][$fieldName] = array_merge(
  528. $resourceParameters['fields'][$fieldName],
  529. $resourceParameters['fields'][$fieldName] = array('sqlId' => $fieldName, 'maxSize' => $maxSize, 'i18n' => true)
  530. );
  531. }
  532. if (isset($this->fieldsValidateLang))
  533. foreach ($this->fieldsValidateLang as $fieldName => $validateMethod)
  534. {
  535. if (!isset($resourceParameters['fields'][$fieldName]))
  536. $resourceParameters['fields'][$fieldName] = array('required' => false);
  537. $resourceParameters['fields'][$fieldName] = array_merge(
  538. $resourceParameters['fields'][$fieldName],
  539. $resourceParameters['fields'][$fieldName] = array(
  540. 'sqlId' => $fieldName,
  541. 'validateMethod' => (
  542. array_key_exists('validateMethod', $resourceParameters['fields'][$fieldName]) ?
  543. array_merge($resourceParameters['fields'][$fieldName]['validateMethod'], array($validateMethod)) :
  544. array($validateMethod)
  545. ),
  546. 'i18n' => true
  547. )
  548. );
  549. }
  550. if (isset($this->fieldsRequiredLang))
  551. foreach ($this->fieldsRequiredLang as $field)
  552. {
  553. if (!isset($resourceParameters['fields'][$field]))
  554. $resourceParameters['fields'][$field] = array();
  555. $resourceParameters['fields'][$field] = array_merge(
  556. $resourceParameters['fields'][$field],
  557. $resourceParameters['fields'][$field] = array('sqlId' => $field, 'required' => true, 'i18n' => true)
  558. );
  559. }
  560. if (isset($this->date_add))
  561. $resourceParameters['fields']['date_add']['setter'] = false;
  562. if (isset($this->date_upd))
  563. $resourceParameters['fields']['date_upd']['setter'] = false;
  564. foreach ($resourceParameters['fields'] as $key => &$resourceParametersField)
  565. if (!isset($resourceParametersField['sqlId']))
  566. $resourceParametersField['sqlId'] = $key;
  567. return $resourceParameters;
  568. }
  569. public function getWebserviceObjectList($sql_join, $sql_filter, $sql_sort, $sql_limit)
  570. {
  571. $query = '
  572. SELECT DISTINCT main.`'.$this->identifier.'` FROM `'._DB_PREFIX_.$this->table.'` AS main
  573. '.$sql_join.'
  574. WHERE 1 '.$sql_filter.'
  575. '.($sql_sort != '' ? $sql_sort : '').'
  576. '.($sql_limit != '' ? $sql_limit : '').'
  577. ';
  578. return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($query);
  579. }
  580. public function getFieldsRequiredDatabase($all = false)
  581. {
  582. return Db::getInstance()->ExecuteS('
  583. SELECT id_required_field, object_name, field_name
  584. FROM '._DB_PREFIX_.'required_field
  585. '.(!$all ? 'WHERE object_name = \''.pSQL(get_class($this)).'\'' : ''));
  586. }
  587. public function addFieldsRequiredDatabase($fields)
  588. {
  589. if (!is_array($fields))
  590. return false;
  591. if (!Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'required_field WHERE object_name = \''.pSQL(get_class($this)).'\''))
  592. return false;
  593. foreach ($fields AS $field)
  594. if (!Db::getInstance()->AutoExecute(_DB_PREFIX_.'required_field', array('object_name' => pSQL(get_class($this)), 'field_name' => pSQL($field)), 'INSERT'))
  595. return false;
  596. return true;
  597. }
  598. public function clearCache($all = false)
  599. {
  600. if ($all AND isset(self::$_cache[$this->table]))
  601. unset(self::$_cache[$this->table]);
  602. elseif ($this->id AND isset(self::$_cache[$this->table][(int)$this->id]))
  603. unset(self::$_cache[$this->table][(int)$this->id]);
  604. }
  605. /**
  606. * Delete images associated with the object
  607. *
  608. * @return bool success
  609. */
  610. public function deleteImage()
  611. {
  612. if (!$this->id)
  613. return false;
  614. /* Deleting object images and thumbnails (cache) */
  615. if ($this->image_dir)
  616. {
  617. if (file_exists($this->image_dir.$this->id.'.'.$this->image_format)
  618. && !unlink($this->image_dir.$this->id.'.'.$this->image_format))
  619. return false;
  620. }
  621. if (file_exists(_PS_TMP_IMG_DIR_.$this->table.'_'.$this->id.'.'.$this->image_format)
  622. && !unlink(_PS_TMP_IMG_DIR_.$this->table.'_'.$this->id.'.'.$this->image_format))
  623. return false;
  624. if (file_exists(_PS_TMP_IMG_DIR_.$this->table.'_mini_'.$this->id.'.'.$this->image_format)
  625. && !unlink(_PS_TMP_IMG_DIR_.$this->table.'_mini_'.$this->id.'.'.$this->image_format))
  626. return false;
  627. $types = ImageType::getImagesTypes();
  628. foreach ($types AS $image_type)
  629. if (file_exists($this->image_dir.$this->id.'-'.stripslashes($image_type['name']).'.'.$this->image_format)
  630. && !unlink($this->image_dir.$this->id.'-'.stripslashes($image_type['name']).'.'.$this->image_format))
  631. return false;
  632. return true;
  633. }
  634. }