PageRenderTime 52ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

/modules/shopimporter/shopimporter.php

https://github.com/vappelgren/PrestaShop
PHP | 1505 lines | 1363 code | 72 blank | 70 comment | 229 complexity | a7b037d8bc6f5a895fd0e72b11edcd86 MD5 | raw file

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

  1. <?php
  2. /*
  3. * 2007-2012 PrestaShop
  4. *
  5. * NOTICE OF LICENSE
  6. *
  7. * This source file is subject to the Academic Free License (AFL 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/afl-3.0.php
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@prestashop.com so we can send you a copy immediately.
  14. *
  15. * DISCLAIMER
  16. *
  17. * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
  18. * versions in the future. If you wish to customize PrestaShop for your
  19. * needs please refer to http://www.prestashop.com for more information.
  20. *
  21. * @author PrestaShop SA <contact@prestashop.com>
  22. * @copyright 2007-2012 PrestaShop SA
  23. * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
  24. * International Registered Trademark & Property of PrestaShop SA
  25. */
  26. if (!defined('_PS_VERSION_'))
  27. exit;
  28. class shopimporter extends ImportModule
  29. {
  30. public $supportedImports = array();
  31. public function __construct()
  32. {
  33. $this->name = 'shopimporter';
  34. $this->tab = 'migration_tools';
  35. $this->version = '1.0';
  36. $this->author = 'PrestaShop';
  37. $this->need_instance = 0;
  38. $this->is_configurable = 1;
  39. parent::__construct ();
  40. $this->displayName = $this->l('Shop Importer');
  41. $this->description = $this->l('This module allows you to import your shop from another system into Prestashop.');
  42. $this->supportedImports = array(
  43. 'language' => array('methodName' => 'getLangagues',
  44. 'name' => $this->l('Language'),
  45. 'className' => 'Language',
  46. 'label' => $this->l('Import Languages'),
  47. 'table' => 'lang',
  48. 'identifier' => 'id_lang',
  49. 'alterTable' => array('id_lang' => 'int(10)'),
  50. 'info' => $this->l('New languages will automatically add translations.'),
  51. 'defaultId' => 'PS_LANG_DEFAULT'
  52. ),
  53. 'currency' => array('methodName' => 'getCurrencies',
  54. 'name' => $this->l('Currency'),
  55. 'className' => 'Currency',
  56. 'label' => $this->l('Import Currencies'),
  57. 'table' => 'currency',
  58. 'identifier' => 'id_currency',
  59. 'alterTable' => array('id_currency' => 'int(10)'),
  60. 'delete' => true,
  61. 'defaultId' => 'PS_CURRENCY_DEFAULT'
  62. ),
  63. /*
  64. 'tax' => array('methodName' => 'getTaxes',
  65. 'name' => $this->l('Taxes'),
  66. 'className' => 'Tax',
  67. 'label' => $this->l('Import Taxes'),
  68. 'table' => 'tax',
  69. 'identifier' => 'id_tax',
  70. 'alterTable' => array('id_tax' => 'int(10)'),
  71. 'delete' => true
  72. ),
  73. 'tax_rule' => array('methodName' => 'getTaxes rules',
  74. 'name' => $this->l('Taxes rules'),
  75. 'className' => 'TaxRule',
  76. 'label' => $this->l('Import Taxes Rules'),
  77. 'table' => 'tax_rules_group',
  78. 'identifier' => 'id_tax',
  79. 'alterTable' => array('id_tax_rules_group' => 'int(10)'),
  80. 'delete' => true
  81. ),
  82. */
  83. 'zone' => array('methodName' => 'getZones',
  84. 'name' => $this->l('Zone'),
  85. 'className' => 'Zone',
  86. 'label' => $this->l('Import Zones'),
  87. 'table' => 'zone',
  88. 'identifier' => 'id_zone',
  89. 'alterTable' => array('id_zone' => 'int(10)'),
  90. 'delete' => true
  91. ),
  92. 'country' => array('methodName' => 'getCountries',
  93. 'name' => $this->l('Country'),
  94. 'className' => 'Country',
  95. 'label' => $this->l('Import Countries'),
  96. 'table' => 'country',
  97. 'identifier' => 'id_country',
  98. 'foreign_key' => array('id_zone', 'id_currency'),
  99. 'alterTable' => array('id_country' => 'int(10)'),
  100. 'delete' => true,
  101. 'defaultId' => 'PS_COUNTRY_DEFAULT'
  102. ),
  103. 'state' => array('methodName' => 'getStates',
  104. 'name' => $this->l('State'),
  105. 'className' => 'State',
  106. 'label' => $this->l('Import States'),
  107. 'table' => 'state',
  108. 'identifier' => 'id_state',
  109. 'foreign_key' => array('id_zone', 'id_country'),
  110. 'alterTable' => array('id_state' => 'int(10)'),
  111. 'delete' => true
  112. ),
  113. 'group' => array('methodName' => 'getGroups',
  114. 'name' => $this->l('Group'),
  115. 'className' => 'Group',
  116. 'label' => $this->l('Import Groups'),
  117. 'table' => 'group',
  118. 'identifier' => 'id_group',
  119. 'alterTable' => array('id_group' => 'int(10)'),
  120. 'delete' => true,
  121. ),
  122. 'customer' => array('methodName' => 'getCustomers',
  123. 'name' => $this->l('Customer'),
  124. 'className' => 'Customer',
  125. 'label' => $this->l('Import Customers'),
  126. 'table' => 'customer',
  127. 'identifier' => 'id_customer',
  128. 'foreign_key' => array('id_group'),
  129. 'alterTable' => array('id_customer' => 'int(10)', 'passwd' => 'varchar(100)'),
  130. 'delete' => true,
  131. 'association' => array(
  132. array(
  133. 'table' => 'customer_group',
  134. 'fields' => array('id_customer', 'id_group'),
  135. 'matchTable' => array('customer', 'group'),
  136. )
  137. )
  138. ),
  139. 'address' => array('methodName' => 'getAddresses',
  140. 'name' => $this->l('Address'),
  141. 'className' => 'Address',
  142. 'label' => $this->l('Import Addresses'),
  143. 'table' => 'address',
  144. 'identifier' => 'id_address',
  145. 'foreign_key' => array('id_country', 'id_state', 'id_customer'),
  146. 'alterTable' => array('id_address' => 'int(10)'),
  147. 'delete' => true
  148. ),
  149. 'manufacturer' => array('methodName' => 'getManufacturers',
  150. 'name' => $this->l('Manufacturer'),
  151. 'className' => 'Manufacturer',
  152. 'label' => $this->l('Import Manufacturers'),
  153. 'table' => 'manufacturer',
  154. 'identifier' => 'id_manufacturer',
  155. 'delete' => true,
  156. 'alterTable' => array('id_manufacturer' => 'int(10)'),
  157. 'hasImage' => true
  158. ),
  159. 'supplier' => array('methodName' => 'getSuppliers',
  160. 'name' => $this->l('Supplier'),
  161. 'className' => 'Supplier',
  162. 'label' => $this->l('Import Suppliers'),
  163. 'table' => 'supplier',
  164. 'identifier' => 'id_supplier',
  165. 'delete' => true,
  166. 'alterTable' => array('id_supplier' => 'int(10)'),
  167. 'hasImage' => true
  168. ),
  169. 'category' => array('methodName' => 'getCategories',
  170. 'name' => $this->l('Category'),
  171. 'className' => 'Category',
  172. 'label' => $this->l('Import Categories'),
  173. 'table' => 'category',
  174. 'identifier' => 'id_category',
  175. 'alterTable' => array('id_category' => 'int(10)'),
  176. 'delete' => true,
  177. 'hasImage' => true,
  178. ),
  179. 'attributegroup' => array('methodName' => 'getAttributesGroups',
  180. 'name' => $this->l('AttributeGroup'),
  181. 'className' => 'AttributeGroup',
  182. 'label' => $this->l('Import Attributes Groups'),
  183. 'table' => 'attribute_group',
  184. 'identifier' => 'id_attribute_group',
  185. 'alterTable' => array('id_attribute_group' => 'int(10)'),
  186. 'delete' => true
  187. ),
  188. 'attribute' => array('methodName' => 'getAttributes',
  189. 'name' => $this->l('Attribute'),
  190. 'className' => 'Attribute',
  191. 'label' => $this->l('Import Attributes'),
  192. 'table' => 'attribute',
  193. 'identifier' => 'id_attribute',
  194. 'alterTable' => array('id_attribute' => 'int(10)'),
  195. 'foreign_key' => array('id_attribute_group'),
  196. 'delete' => true
  197. ),
  198. 'product' => array('methodName' => 'getProducts',
  199. 'name' => $this->l('Product'),
  200. 'className' => 'Product',
  201. 'label' => $this->l('Import Products'),
  202. 'table' => 'product',
  203. 'identifier' => 'id_product',
  204. 'alterTable' => array('id_product' => 'int(10)'),
  205. 'foreign_key' => array('id_category', 'id_manufacturer'),
  206. 'delete' => true,
  207. 'association' => array(
  208. array(
  209. 'table' => 'category_product',
  210. 'fields' => array('id_category', 'id_product'),
  211. 'matchTable' => array('category', 'product')
  212. )
  213. ),
  214. 'hasImage' => true
  215. ),
  216. 'combination' => array('methodName' => 'getProductsCombination',
  217. 'name' => $this->l('Combination'),
  218. 'className' => 'Combination',
  219. 'label' => $this->l('Import Products Combinations'),
  220. 'table' => 'product_attribute',
  221. 'identifier' => 'id_product_attribute',
  222. 'alterTable' => array('id_product_attribute' => 'int(10)', 'id_product' => 'int(10)'),
  223. 'foreign_key' => array('id_product'),
  224. 'delete' => false,
  225. 'association' => array(
  226. array(
  227. 'table' => 'product_attribute_combination',
  228. 'fields' => array('id_attribute', 'id_product_attribute'),
  229. 'matchTable' => array('attribute', 'product_attribute')
  230. )
  231. )
  232. ),
  233. 'orderstate' => array('methodName' => 'getOrdersStates',
  234. 'name' => $this->l('Orders States'),
  235. 'className' => 'OrderState',
  236. 'label' => $this->l('Import Orders States'),
  237. 'table' => 'order_state',
  238. 'identifier' => 'id_order_state',
  239. 'alterTable' => array('id_order_state' => 'int(10)')
  240. ),
  241. 'cart' => array('methodName' => 'getOrders',
  242. 'name' => $this->l('Order'),
  243. 'className' => 'Cart',
  244. 'label' => $this->l('Import Orders'),
  245. 'table' => 'cart',
  246. 'identifier' => 'id_cart',
  247. 'foreign_key' => array('id_address_delivery', 'id_address_invoice', 'id_customer'),
  248. 'alterTable' => array('id_cart' => 'int(10)')
  249. ),
  250. 'orderhistory' => array('methodName' => 'getOrdersHistory',
  251. 'name' => $this->l('Order history'),
  252. 'className' => 'Order history',
  253. 'label' => $this->l('Import Order History'),
  254. 'table' => 'order_history',
  255. 'identifier' => 'id_order_history',
  256. 'foreign_key' => array('id_order', 'id_order_state'),
  257. 'alterTable' => array('id_order_history' => 'int(10)'),
  258. 'hidden' => true
  259. ),
  260. 'order' => array('methodName' => 'getOrders',
  261. 'name' => $this->l('Order'),
  262. 'className' => 'Order',
  263. 'label' => $this->l('Import Order History'),
  264. 'table' => 'orders',
  265. 'identifier' => 'id_order',
  266. 'alterTable' => array('id_order' => 'int(10)'),
  267. 'hidden' => true
  268. )
  269. );
  270. }
  271. public function install()
  272. {
  273. return parent::install();
  274. }
  275. public function uninstall()
  276. {
  277. return parent::uninstall();
  278. }
  279. public function getContent()
  280. {
  281. $exportModules = parent::getImportModulesOnDisk();
  282. //get installed module only
  283. foreach($exportModules as $key => $module)
  284. if ($module->name == $this->name || !(bool)$module->id)
  285. unset($exportModules[$key]);
  286. $html = '<script type="text/javascript">var globalAjaxShopImporterToken = "'.sha1(_COOKIE_KEY_.'ajaxShopImporter').'";</script>
  287. <script type="text/javascript" src="../modules/shopimporter/shopimporter.js"></script>
  288. <script src="'._PS_JS_DIR_.'jquery/jquery.scrollTo-1.4.2-min.js"></script>
  289. <script type="text/javascript">
  290. var conf = new Array(); ';
  291. $i = 0;
  292. foreach($this->supportedImports as $import)
  293. {
  294. if(!array_key_exists('hidden', $import))
  295. $html .= 'conf['.$i.'] = new Array(\''.addslashes($import['methodName']).'\', \''.addslashes($import['label']).'\', \''.addslashes($import['className']).'\', \''.addslashes($import['name']).'\');';
  296. $i++;
  297. }
  298. $html .= ' var notExist = "'.$this->l('is not available in this module').'";
  299. var databaseOk = "'.$this->l('Connection to the database OK').'";
  300. var wsOk = "'.$this->l('Connection to the web service OK').'";
  301. var showErrors = "'.$this->l('Show errors').'";
  302. var testImport = "'.$this->l('Test import process').'";
  303. var runImport = "'.$this->l('Run Import').'";
  304. var importHasErrors = "'.$this->l('Errors occurred during import. For more details click on "Show errors".').'"
  305. var importFinish = "'.$this->l('Import is complete.').'"
  306. var truncateTable = "'.$this->l('Remove data').'"
  307. var oneThing = "'.$this->l('Please choose one thing to import').'"
  308. </script>
  309. <style>
  310. .margin-form{padding: 0px 0px 1em 120px;width:300px;}
  311. label{width: 170px;}
  312. .import{background-color: #CCCCCC;border: 1px solid gray;margin: 0px 0px 10px;padding: 10px 15px;line-height: 20px;}
  313. </style>
  314. <fieldset><legend><img src="'.$this->_path.'logo.gif" alt="" />'.$this->l('Import from another system').'</legend>
  315. <div class="warn" ><img src="../img/admin/warn2.png">
  316. '.$this->l('Before starting the import please backup your database. ').'
  317. <a href="index.php?tab=AdminBackup&token='.Tools::getAdminToken('AdminBackup'.(int)Tab::getIdFromClassName('AdminBackup').(int)$this->context->employee->id).'"">'.$this->l(' Click here to backup').'</a>
  318. </div>
  319. <br>
  320. <div style="float:right;width:450px" id="steps"></div>';
  321. if (sizeof($exportModules))
  322. {
  323. $html .= '
  324. <label>'.$this->l('Choose your import').' : </label>
  325. <div class="margin-form">
  326. <select name="import_module_name" id="import_module_name">
  327. <option value="0">---</option>';
  328. foreach($exportModules as $key => $module)
  329. (($module->name != $this->name AND $module->id) ? $html .= '<option value="'.$module->name.'">'.$module->displayName.'</option>' : '' );
  330. $html .= '</select><input type="submit" class="button" id="choose_module_name" value="'.$this->l('Choose').'">
  331. </div>';
  332. }
  333. else
  334. $html .= '<div class="warn" ><img src="../img/admin/warn2.png">'.$this->l('No import module installed').'</div>';
  335. $html .= '
  336. <div style="display:none;" class="error" id="connectionInformation"></div>
  337. <div id="config_connector"></div>
  338. <div class="margin-form">
  339. <input type="submit" name="displayOptions" id="displayOptions" class="button" value="'.$this->l('Next Step').'">
  340. </div>
  341. <hr>
  342. <div style="display:none" id="importOptions">
  343. <h2>'.$this->l('Import Options').'</h2>
  344. <div id="importOptionsYesNo">';
  345. foreach($this->supportedImports as $key => $import)
  346. {
  347. if(!array_key_exists('hidden', $import))
  348. $html .= '<label>'.$import['name'].' : </label>
  349. <div class="margin-form">
  350. <label class="t" for="'.$import['identifier'].'_on'.'"><img src="../img/admin/enabled.gif" alt="Yes" title="Yes"></label>
  351. <input type="radio" id="'.$import['identifier'].'_on'.'" name="'.$import['methodName'].'" class="'.$key.'" value="1" checked="checked">
  352. <label class="t" for="'.$import['identifier'].'_off'.'"><img src="../img/admin/disabled.gif" alt="No" title="No" style="margin-left: 10px;"></label>
  353. <input type="radio" id="'.$import['identifier'].'_off'.'" name="'.$import['methodName'].'" class="'.$key.'" value="0">
  354. '.(array_key_exists('delete', $import) ? '
  355. <label class="t"><img src="../img/admin/delete.gif" alt="Delete" title="Delete"></label>
  356. <input type="checkbox" class="truncateTable" id="'.$key.'" name="delete_'.$import['className'].'">' : '' ).
  357. (array_key_exists('hasImage', $import) ? '
  358. <label class="t"><img src="../img/admin/picture.gif" alt="Images" title="Images"></label>
  359. <input type="checkbox" class="importImages" id="'.$key.'" name="images_'.$import['className'].'">' : '' ).
  360. (array_key_exists('info', $import) ? '<p>'.$import['info'].'</p>' : '').'
  361. </div>';
  362. }
  363. $html .= '</div><hr>
  364. <h2>'.$this->l('Advanced Options').'</h2>
  365. <div class="warn" id="warnSkip" style="display:none"><img src="../img/admin/warn2.png">
  366. '.$this->l('This mode is dangerous').'
  367. </div>
  368. <label>'.$this->l('Import for every').' : </label>
  369. <div class="margin-form">
  370. <select name="nbr_import" id="nbr_import">
  371. <option value="10">10</option>
  372. <option value="50">50</option>
  373. <option value="100" selected="selected">100</option>
  374. <option value="200">200</option>
  375. </select>
  376. <p>'.$this->l('Select the number of occurrences for each query to import').'</p>
  377. </div>
  378. <label>'.$this->l('If errors occur').' : </label>
  379. <div class="margin-form">
  380. <label class="t"><img src="'.$this->_path.'img/stop.png"></label>
  381. <input type="radio" name="hasErrors" id="hasErrors" value="0" checked="checked">
  382. <label class="t">'.$this->l('Stop').'</label>
  383. <label class="t"><img src="'.$this->_path.'img/skip.png" style="margin-left: 10px;"></label>
  384. <input type="radio" name="hasErrors" id="hasErrors" value="1">
  385. <label class="t">'.$this->l('Skip').'</label>
  386. <label class="t"><img src="'.$this->_path.'img/force.gif" style="margin-left: 10px;"></label>
  387. <input type="radio" name="hasErrors" id="hasErrors" value="2">
  388. <label class="t">'.$this->l('Force').'</label>
  389. <p>'.$this->l('Stop: if there are errors with the data, import will not run.').'</p>
  390. <p>'.$this->l('Skip: if there are errors with the data, import will skip incorrect data.').'</p>
  391. <p>'.$this->l('Force: if there are errors with the data, import will replace incorrect data by generic data.').'</p>
  392. </div>
  393. <hr>
  394. <div style="display:none" id="specificOptions">
  395. <h2>'.$this->l('Specific Options').'</h2>
  396. <div style="display:none" class="error" id="specificOptionsErrors"></div>
  397. <div id="specificOptionsContent">
  398. </div>
  399. </div>
  400. <hr>
  401. <div class="margin-form">
  402. <input type="submit" class="button" name="checkAndSaveConfig" id="checkAndSaveConfig" value="'.$this->l('Next Step').'">
  403. </div>
  404. </div>
  405. </fieldset>';
  406. return $html;
  407. }
  408. public function genericImport($className, $fields, $save = false)
  409. {
  410. $return = '';
  411. $json = array();
  412. $errors = array();
  413. $json['hasError'] = false;
  414. $json['datas'] = array_values($fields);
  415. $languages = array();
  416. $defaultLanguage = '';
  417. $table = $this->supportedImports[strtolower($className)]['table'];
  418. $object = new $className();
  419. $rules = call_user_func(array($className, 'getValidationRules'), $className);
  420. if ((sizeof($rules['requiredLang']) || sizeof($rules['sizeLang']) || sizeof($rules['validateLang']) || Tools::isSubmit('syncLang') || Tools::isSubmit('syncCurrency')))
  421. {
  422. $moduleName = Tools::getValue('moduleName');
  423. if (Validate::isModuleName($moduleName) && Validate::file_exists('../../modules/'.$moduleName.'/'.$moduleName.'.php'))
  424. {
  425. require_once('../../modules/'.$moduleName.'/'.$moduleName.'.php');
  426. $importModule = new $moduleName();
  427. $importModule->server = Tools::getValue('server');
  428. $importModule->user = Tools::getValue('user');
  429. $importModule->passwd = Tools::getValue('password');
  430. $importModule->database = Tools::getValue('database');
  431. $importModule->prefix = Tools::getValue('prefix');
  432. $defaultLanguage = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
  433. $languages = $importModule->getLangagues(0);
  434. if (Tools::isSubmit('syncLang') || Tools::isSubmit('syncLangWS'))
  435. {
  436. $defaultIdLand = $importModule->getDefaultIdLang();
  437. $defaultLanguageImport = new Language(Language::getIdByIso($languages[$defaultIdLand]['iso_code']));
  438. if ($defaultLanguage->iso_code != $defaultLanguageImport->iso_code)
  439. $errors[] = $this->l('Default language doesn\'t match : ').'<br>'.Configuration::get('PS_SHOP_NAME').' : '.$defaultLanguage->name.' ≠
  440. '.$importModule->displayName.' : '.$defaultLanguageImport->name.'<br>'.$this->l('Please change default language in your configuration');
  441. }
  442. if (Tools::isSubmit('syncCurrency') || Tools::isSubmit('syncCurrencyWS'))
  443. {
  444. $defaultIdCurrency = $importModule->getDefaultIdCurrency();
  445. $currencies = $importModule->getCurrencies(0);
  446. if(!empty($currencies[$defaultIdCurrency]['iso_code']))
  447. $defaultCurrencyImport = new Currency((int)Currency::getIdByIsoCode($currencies[$defaultIdCurrency]['iso_code']));
  448. else
  449. $defaultCurrencyImport = new Currency((int)Currency::getIdByIsoCodeNum($currencies[$defaultIdCurrency]['iso_code_num']));
  450. $defaultCurrency = new Currency((int)Configuration::get('PS_CURRENCY_DEFAULT'));
  451. if ($defaultCurrency->iso_code != $defaultCurrencyImport->iso_code)
  452. $errors[] = $this->l('Default currency doesn\'t match : ').'<br>'.Configuration::get('PS_SHOP_NAME').' : '.$defaultCurrency->name.' ≠ '.$importModule->displayName.' : '.$defaultCurrencyImport->name.'<br>'.$this->l('Please change default currency in your configuration');
  453. }
  454. if (!empty($errors))
  455. die('{"hasError" : true, "error" : '.Tools::jsonEncode($errors).'}');
  456. }
  457. else
  458. die('{"hasError" : true, "error" : ["FATAL ERROR"], "datas" : []}');
  459. }
  460. foreach($fields as $key => $field)
  461. {
  462. $id = $this->supportedImports[strtolower($className)]['identifier'];
  463. //remove wrong fields (ex : id_toto in Customer)
  464. foreach($field as $name => $value)
  465. if (!array_key_exists($name, get_object_vars($object)) AND ($name != $id) AND ($name != 'association') AND ($name != 'images') AND (strtolower($className) != 'cart'))
  466. unset($field[$name]);
  467. $return = $this->validateRules($rules, $field, $className, $languages, $defaultLanguage);
  468. $fields[$key] = $field;
  469. if (!empty($return))
  470. {
  471. //skip mode
  472. if (Tools::getValue('hasErrors') == 1)
  473. unset($fields[$key]);
  474. $errors[] = $return;
  475. array_unshift($errors[sizeof($errors)-1], $field[$id]);
  476. }
  477. }
  478. if (sizeof($errors) > 0)
  479. {
  480. $json['hasError'] = true;
  481. $json['error'] = $errors;
  482. }
  483. if ($save || Tools::isSubmit('syncLang') || Tools::isSubmit('syncLangWS'))
  484. {
  485. //add language if not exist in prestashop
  486. if ($className == 'Language')
  487. {
  488. if (Tools::isSubmit('syncLang') || Tools::isSubmit('syncLangWS'))
  489. $add = true;
  490. else
  491. $add = false;
  492. $errors = $this->checkAndAddLang($fields, $add);
  493. }
  494. elseif ($className == 'Cart')
  495. {
  496. $this->saveOrders($fields);
  497. }
  498. else
  499. {
  500. $return = $this->saveObject($className, $fields);
  501. $this->cleanPositions($table);
  502. //insert association
  503. if (array_key_exists('association', $this->supportedImports[strtolower($className)]))
  504. $this->insertAssociation(strtolower($className), $fields);
  505. if (!empty($return))
  506. {
  507. $json['hasError'] = true;
  508. $json['error'] = $return;
  509. }
  510. }
  511. if ($className == 'Category' AND (sizeof($fields) != (int)Tools::getValue('nbr_import')))
  512. $this->updateCat();
  513. }
  514. if (sizeof($errors) > 0 AND is_array($errors))
  515. {
  516. $json['hasError'] = true;
  517. $json['error'] = $errors;
  518. }
  519. die(Tools::jsonEncode($json));
  520. }
  521. public function genericImportWS($className, $fields, $save = false)
  522. {
  523. $return = '';
  524. $json = array();
  525. $errors = array();
  526. $json['hasError'] = false;
  527. $json['datas'] = array_values($fields);
  528. $languages = array();
  529. $defaultLanguage = '';
  530. $table = $this->supportedImports[strtolower($className)]['table'];
  531. $object = new $className();
  532. $rules = call_user_func(array($className, 'getValidationRules'), $className);
  533. if ((sizeof($rules['requiredLang']) || sizeof($rules['sizeLang']) || sizeof($rules['validateLang']) || Tools::isSubmit('syncLangWS') || Tools::isSubmit('syncCurrency')))
  534. {
  535. $moduleName = Tools::getValue('moduleName');
  536. if (Validate::isModuleName($moduleName) && file_exists('../../modules/'.$moduleName.'/'.$moduleName.'.php'))
  537. {
  538. require_once('../../modules/'.$moduleName.'/'.$moduleName.'.php');
  539. $importModule = new $moduleName();
  540. $defaultLanguage = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
  541. $languages = $importModule->getLangagues();
  542. if (Tools::isSubmit('syncLangWS'))
  543. {
  544. $defaultIdLand = $importModule->getDefaultIdLang();
  545. $defaultLanguageImport = new Language(Language::getIdByIso($languages[$defaultIdLand]['iso_code']));
  546. if ($defaultLanguage->iso_code != $defaultLanguageImport->iso_code)
  547. $errors[] = $this->l('Default language doesn\'t match : ').'<br>'.Configuration::get('PS_SHOP_NAME').' : '.$defaultLanguage->name.' ≠
  548. '.$importModule->displayName.' : '.$defaultLanguageImport->name.'<br>'.$this->l('Please change default language in your configuration');
  549. }
  550. if (Tools::isSubmit('syncCurrency'))
  551. {
  552. $defaultIdCurrency = $importModule->getDefaultIdCurrency();
  553. $currencies = $importModule->getCurrencies();
  554. if (!empty($currencies[$defaultIdCurrency]['iso_code']))
  555. $defaultCurrencyImport = new Currency((int)Currency::getIdByIsoCode($currencies[$defaultIdCurrency]['iso_code']));
  556. else
  557. $defaultCurrencyImport = new Currency((int)Currency::getIdByIsoCodeNum($currencies[$defaultIdCurrency]['iso_code_num']));
  558. $defaultCurrency = new Currency((int)Configuration::get('PS_CURRENCY_DEFAULT'));
  559. if ($defaultCurrency->iso_code != $defaultCurrencyImport->iso_code)
  560. $errors[] = $this->l('Default currency doesn\'t match : ').'<br>'.Configuration::get('PS_SHOP_NAME').' : '.$defaultCurrency->name.' ≠ '.$importModule->displayName.' : '.$defaultCurrencyImport->name.'<br>'.$this->l('Please change default currency in your configuration');
  561. }
  562. if (!empty($errors))
  563. die('{"hasError" : true, "error" : '.Tools::jsonEncode($errors).'}');
  564. }
  565. else
  566. die('{"hasError" : true, "error" : ["FATAL ERROR"], "datas" : []}');
  567. }
  568. foreach($fields as $key => $field)
  569. {
  570. $id = $this->supportedImports[strtolower($className)]['identifier'];
  571. //remove wrong fields (ex : id_toto in Customer)
  572. foreach($field as $name => $value)
  573. if (!array_key_exists($name, get_object_vars($object)) AND ($name != $id) AND ($name != 'association') AND ($name != 'images') AND (strtolower($className) != 'cart'))
  574. unset($field[$name]);
  575. $return = $this->validateRules($rules, $field, $className, $languages, $defaultLanguage);
  576. $fields[$key] = $field;
  577. if (!empty($return))
  578. {
  579. //skip mode
  580. if (Tools::getValue('hasErrors') == 1)
  581. unset($fields[$key]);
  582. $errors[] = $return;
  583. array_unshift($errors[sizeof($errors)-1], $field[$id]);
  584. }
  585. }
  586. if (sizeof($errors) > 0)
  587. {
  588. $json['hasError'] = true;
  589. $json['error'] = $errors;
  590. }
  591. if ($save || Tools::isSubmit('syncLang') || Tools::isSubmit('syncLangWS'))
  592. {
  593. //add language if not exist in prestashop
  594. if ($className == 'Language')
  595. {
  596. if (Tools::isSubmit('syncLang') || Tools::isSubmit('syncLangWS'))
  597. $add = true;
  598. else
  599. $add = false;
  600. $errors = $this->checkAndAddLang($fields, $add);
  601. }
  602. elseif ($className == 'Cart')
  603. {
  604. $this->saveOrders($fields);
  605. }
  606. else
  607. {
  608. $return = $this->saveObject($className, $fields);
  609. $this->cleanPositions($table);
  610. //insert association
  611. if (array_key_exists('association', $this->supportedImports[strtolower($className)]))
  612. $this->insertAssociation(strtolower($className), $fields);
  613. if (!empty($return))
  614. {
  615. $json['hasError'] = true;
  616. $json['error'] = $return;
  617. }
  618. }
  619. if ($className == 'Category' AND (sizeof($fields) != (int)Tools::getValue('nbr_import')))
  620. $this->updateCat();
  621. }
  622. if (sizeof($errors) > 0 AND is_array($errors))
  623. {
  624. $json['hasError'] = true;
  625. $json['error'] = $errors;
  626. }
  627. die(Tools::jsonEncode($json));
  628. }
  629. private function saveObject($className, $items)
  630. {
  631. $return = array();
  632. $table = $this->supportedImports[strtolower($className)]['table'];
  633. //creating temporary fields for identifiers matching and password
  634. if (array_key_exists('alterTable', $this->supportedImports[strtolower($className)]))
  635. $this->alterTable(strtolower($className));
  636. $matchIdLang = $this->getMatchIdLang(1);
  637. foreach($items as $item)
  638. {
  639. $object = new $className;
  640. $id = $item[$this->supportedImports[strtolower($className)]['identifier']];
  641. if (array_key_exists('foreign_key', $this->supportedImports[strtolower($className)]))
  642. $this->replaceForeignKey($item, $table);
  643. foreach($item as $key => $val)
  644. {
  645. if ($key == 'passwd')
  646. {
  647. $password = $val;
  648. $val = '------';
  649. }
  650. if (is_array($val) AND $key != 'images')
  651. {
  652. $tmp = array();
  653. foreach($matchIdLang as $k => $v)
  654. {
  655. if (array_key_exists($k, $val))
  656. {
  657. $tmp[$v] = $val[$k];
  658. }
  659. }
  660. $object->$key = $tmp;
  661. }
  662. else
  663. $object->$key = $val;
  664. }
  665. if (!$object->save(false, false))
  666. $return[] = array($item[$this->supportedImports[strtolower($className)]['identifier']], $this->l('An error occurred when adding the object'));
  667. else
  668. {
  669. $this->saveMatchId(strtolower($className), (int)$object->id, (int)$id);
  670. if ($className == 'Customer')
  671. Db::getInstance()->execute('UPDATE '._DB_PREFIX_.'customer SET `passwd_'.bqSQL(Tools::getValue('moduleName')).'` = \''.pSQL($password).'\' WHERE id_customer = '.(int)$object->id);
  672. if (array_key_exists('hasImage', $this->supportedImports[strtolower($className)]) AND Tools::isSubmit('images_'.$className))
  673. $this->copyImg($item, $className);
  674. }
  675. }
  676. return $return;
  677. }
  678. private function saveOrders($items)
  679. {
  680. $this->saveObject('cart', $items);
  681. //import cart product
  682. $foreignKey = $this->getForeignKey('Cart', array('id_cart', 'id_product', 'id_product_attribute', 'id_customer','id_address_invoice', 'id_address_delivery'));
  683. foreach($items as &$item)
  684. {
  685. foreach($item['cart_products'] as $k => $cart_products)
  686. {
  687. foreach($cart_products as $key => $val)
  688. if (array_key_exists($key, $foreignKey))
  689. if (array_key_exists($val, $foreignKey[$key]))
  690. $item['cart_products'][$k][$key] = $foreignKey[$key][$val];
  691. else
  692. $item['cart_products'][$k][$key] = 0;
  693. Db::getInstance()->insert('cart_product', $item['cart_products'][$k]);
  694. }
  695. foreach($item['order_products'] as $k => $order_products)
  696. {
  697. foreach($order_products as $key => $val)
  698. if (array_key_exists($key, $foreignKey) || $key == 'product_id')
  699. //patch to correct a mistake naming column in the database
  700. if ($key == 'product_id')
  701. $item['order_products'][$k]['product_id'] = $foreignKey['id_product'][$val];
  702. elseif (array_key_exists($val, $foreignKey[$key]))
  703. $item['order_products'][$k][$key] = $foreignKey[$key][$val];
  704. else
  705. $item['order_products'][$k][$key] = 0;
  706. }
  707. }
  708. //cart to order
  709. $this->cartToOrder($items, $foreignKey);
  710. $foreignKey = array_merge($this->getForeignKey('Cart', array('id_order', 'id_order_state')), $foreignKey);
  711. foreach($items as &$item)
  712. {
  713. //insert product in order detail
  714. foreach($item['order_products'] as $k => $order_products)
  715. {
  716. foreach($order_products as $key => $val)
  717. if (array_key_exists($key, $foreignKey))
  718. if (array_key_exists($val, $foreignKey[$key]))
  719. $item['order_products'][$k][$key] = $foreignKey[$key][$val];
  720. else
  721. $item['order_products'][$k][$key] = 0;
  722. Db::getInstance()->insert('order_detail', $item['order_products'][$k]);
  723. }
  724. //save order history
  725. foreach($item['order_history'] as $k => $order_history)
  726. {
  727. foreach($order_history as $key => $val)
  728. if (array_key_exists($key, $foreignKey))
  729. if (array_key_exists($val, $foreignKey[$key]))
  730. $item['order_history'][$k][$key] = $foreignKey[$key][$val];
  731. else
  732. $item['order_history'][$k][$key] = 0;
  733. Db::getInstance()->insert('order_history', $item['order_history'][$k]);
  734. }
  735. }
  736. }
  737. private function insertAssociation($table, $items)
  738. {
  739. foreach($this->supportedImports[$table]['association'] AS $association)
  740. {
  741. $associatFields = '';
  742. $associatFieldsName = implode('`, `', $association['fields']);
  743. $tableAssociation = $association['table'];
  744. $matchTable = $association['matchTable'];
  745. if (!empty($items))
  746. {
  747. $match = array();
  748. foreach($matchTable as $mTable)
  749. {
  750. $tmp = $this->getForeignKey($mTable, array('id_'.$mTable));
  751. if (array_key_exists('id_'.$mTable, $tmp))
  752. $match['id_'.$mTable] = $tmp['id_'.$mTable];
  753. else
  754. $match['id_'.$mTable] = $this->getDefaultId($table);
  755. }
  756. foreach($items AS $item)
  757. foreach($item AS $key => $val)
  758. if ($key == 'association' AND !empty($key))
  759. foreach($val[$tableAssociation] AS $k => $v)
  760. {
  761. $associatFields .= ' ('.((array_key_exists($k, $match[$association['fields'][0]])) ? (int)$match[$association['fields'][0]][$k] : '1').', ';
  762. $associatFields .= (int)$match[$association['fields'][1]][$v].'), ';
  763. }
  764. if ($associatFields != '')
  765. Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.bqSQL($tableAssociation).'` (`'.$associatFieldsName.'`) VALUES '.rtrim($associatFields, ', '));
  766. }
  767. }
  768. }
  769. private function saveMatchId($className, $psId, $matchId)
  770. {
  771. $table = $this->supportedImports[$className]['table'];
  772. $moduleName = Tools::getValue('moduleName');
  773. $identifier = $this->supportedImports[$className]['identifier'];
  774. Db::getInstance()->execute('UPDATE `'._DB_PREFIX_.bqSQL($table).'` SET `'.bqSQL($identifier).'_'.bqSQL($moduleName).'` = '.(int)$matchId.' WHERE `'.bqSQL($identifier).'` = '.(int)$psId);
  775. }
  776. private function getMatchId($className)
  777. {
  778. $table = $this->supportedImports[$className]['table'];
  779. $moduleName = Tools::getValue('moduleName');
  780. $identifier = $this->supportedImports[$className]['identifier'];
  781. $returns = Db::getInstance()->executeS('SELECT `'.bqSQL($identifier).'_'.bqSQL($moduleName).'`, `'.bqSQL($identifier).'` FROM `'._DB_PREFIX_.bqSQL($table).'` WHERE `'.bqSQL($identifier).'_'.bqSQL($moduleName).'` != 0 ');
  782. $match = array();
  783. foreach($returns as $return)
  784. $match[$return[$identifier.'_'.$moduleName]] = $return[$identifier];
  785. return $match;
  786. }
  787. private function getDefaultId($table)
  788. {
  789. $defaultId = 1;
  790. if (array_key_exists('defaultId', $this->supportedImports[strtolower($table)]))
  791. $defaultId = Configuration::get($this->supportedImports[strtolower($table)]['defaultId']);
  792. return $defaultId;
  793. }
  794. private function copyImg($item, $className)
  795. {
  796. require_once('../../images.inc.php');
  797. $identifier = $this->supportedImports[strtolower($className)]['identifier'];
  798. $matchId = $this->getMatchId(strtolower($className));
  799. $matchIdLang = $this->getMatchIdLang();
  800. switch($className)
  801. {
  802. default:
  803. case 'Product':
  804. $path = _PS_PROD_IMG_DIR_;
  805. $type = 'products';
  806. break;
  807. case 'Category':
  808. $path = _PS_CAT_IMG_DIR_;
  809. $type = 'categories';
  810. break;
  811. case 'Manufacturer':
  812. $path = _PS_MANU_IMG_DIR_;
  813. $type = 'manufacturers';
  814. break;
  815. case 'Supplier':
  816. $path = _PS_SUPP_IMG_DIR_;
  817. $type = 'suppliers';
  818. break;
  819. }
  820. $cover = 1;
  821. if (array_key_exists($item[$identifier], $matchId))
  822. if(array_key_exists('images', $item) && !is_null($item['images']))
  823. foreach($item['images'] as $key => $image)
  824. {
  825. $tmpfile = tempnam(_PS_TMP_IMG_DIR_, 'import');
  826. if (@copy(str_replace(' ', '%20', $image), $tmpfile))
  827. {
  828. $imagesTypes = ImageType::getImagesTypes($type);
  829. ImageManager::resize($tmpfile, $path.(int)$matchId[$item[$identifier]].'.jpg');
  830. if ($className == 'Product')
  831. {
  832. $image = new Image();
  833. $image->id_product = (int)($matchId[$item[$identifier]]);
  834. $image->cover = $cover;
  835. $image->position = Image::getHighestPosition((int)$matchId[$item[$identifier]]) + 1;
  836. $legend = array();
  837. foreach($item['name'] as $key => $val)
  838. if (array_key_exists($key, $matchIdLang))
  839. $legend[$matchIdLang[$key]] = Tools::link_rewrite($val);
  840. else
  841. $legend[Configuration::get('PS_LANG_DEFAULT')] = Tools::link_rewrite($val);
  842. $image->legend = $legend;
  843. $image->add();
  844. ImageManager::resize($tmpfile, $path.(int)$matchId[$item[$identifier]].'-'.(int)$image->id.'.jpg');
  845. foreach ($imagesTypes AS $k => $imageType)
  846. ImageManager::resize($tmpfile, $path.(int)$matchId[$item[$identifier]].'-'.(int)$image->id.'-'.stripslashes($imageType['name']).'.jpg', $imageType['width'], $imageType['height']);
  847. }
  848. else
  849. foreach ($imagesTypes as $imageType)
  850. ImageManager::resize($tmpfile, $path.(int)$matchId[$item[$identifier]].'-'.stripslashes($imageType['name']).'.jpg', $imageType['width'], $imageType['height']);
  851. }
  852. else
  853. @unlink($tmpfile);
  854. @unlink($tmpfile);
  855. $cover = 0;
  856. }
  857. }
  858. private function replaceForeignKey(&$item, $table)
  859. {
  860. if ($table == 'product_attribute')
  861. $table2 = 'combination';
  862. else
  863. $table2 = $table;
  864. $foreingKey = $this->supportedImports[$table2]['foreign_key'];
  865. $foreingKeyValue = $this->getForeignKey($table, $foreingKey);
  866. foreach($foreingKey as $key)
  867. {
  868. if ($table == 'product' AND $key == 'id_category')
  869. $key2 = 'id_category_default';
  870. else if ($table == 'customer' AND $key == 'id_group')
  871. $key2 = 'id_default_group';
  872. else
  873. $key2 = $key;
  874. if (array_key_exists($key, $foreingKeyValue) && $item[$key2] != 0)
  875. $item[$key2] = (array_key_exists($item[$key2], $foreingKeyValue[$key]) ? $item[$key2] = $foreingKeyValue[$key][$item[$key2]] : $item[$key2] = 0);
  876. else
  877. $item[$key2] = $this->getDefaultId($table);
  878. }
  879. }
  880. private function alterTable($className)
  881. {
  882. $query ='';
  883. $queryTmp = '';
  884. $from = $this->supportedImports[$className]['table'];
  885. $result = array();
  886. $result = Db::getInstance()->getRow('SELECT * FROM `'._DB_PREFIX_.bqSQL($from).'`');
  887. if (!$result)
  888. $result = array();
  889. foreach ($this->supportedImports[$className]['alterTable'] AS $name => $type)
  890. {
  891. $moduleName = Tools::getValue('moduleName');
  892. Db::getInstance()->executeS("SHOW COLUMNS FROM `"._DB_PREFIX_.bqSQL($from)."` LIKE '".pSQL($name).'_'.pSQL($moduleName)."'");
  893. if (!Db::getInstance()->numRows() AND !array_key_exists($name.'_'.$moduleName, $result))
  894. $queryTmp .= ' ADD `'.$name.'_'.$moduleName.'` '.$type.' NOT NULL,';
  895. }
  896. if (!empty($queryTmp))
  897. {
  898. $query = 'ALTER TABLE `'._DB_PREFIX_.bqSQL($from).'` ';
  899. $query .= rtrim($queryTmp, ',');
  900. Db::getInstance()->execute($query);
  901. }
  902. }
  903. private function updateCat()
  904. {
  905. $moduleName = Tools::getValue('moduleName');
  906. Db::getInstance()->execute('UPDATE
  907. '._DB_PREFIX_.'category c
  908. INNER JOIN
  909. '._DB_PREFIX_.'category c2
  910. ON
  911. c.id_parent = c2.`id_category_'.bqSQL($moduleName).'`
  912. SET
  913. c.id_parent = c2.id_category
  914. WHERE c.`id_category_'.bqSQL($moduleName).'` != 0');
  915. $category = new Category();
  916. $cats = $category->getSimpleCategories((int)Configuration::get('PS_LANG_DEFAULT'));
  917. foreach($cats as $cat)
  918. {
  919. $cat = new Category((int)$cat['id_category']);
  920. $cat->level_depth = $cat->calcLevelDepth();
  921. $cat->update();
  922. }
  923. }
  924. private function getForeignKey($className, $foreign_key = null)
  925. {
  926. $moduleName = Tools::getValue('moduleName');
  927. if (is_null($foreign_key))
  928. $foreign_key = $this->supportedImports[$className]['foreign_key'];
  929. $match = array();
  930. foreach($foreign_key AS $key)
  931. {
  932. if (in_array($key , array('id_address_invoice', 'id_address_delivery')))
  933. $key2 = 'id_address';
  934. elseif (in_array($key , array('id_category_default')))
  935. $key2 = 'id_category';
  936. else
  937. $key2 = $key;
  938. foreach($this->supportedImports AS $table => $conf)
  939. if ($conf['identifier'] == $key2)
  940. $from = $this->supportedImports[$table]['table'];
  941. $return = Db::getInstance()->executeS('SELECT `'.bqSQL($key2).'_'.bqSQL($moduleName).'`, `'.bqSQL($key2).'` FROM `'._DB_PREFIX_.bqSQL($from).'` WHERE `'.bqSQL($key2).'_'.bqSQL($moduleName).'` != 0');
  942. if (!empty($return))
  943. foreach($return AS $name => $val)
  944. $match[$key][$val[$key2.'_'.$moduleName]] = $val[$key2];
  945. }
  946. return $match;
  947. }
  948. private function getForeignKeyLang($table)
  949. {
  950. $id = $this->supportedImports[$table]['identifier'];
  951. $moduleName = Tools::getValue('moduleName');
  952. $return = Db::getInstance()->executeS('SELECT `'.bqSQL($id).'_'.bqSQL($moduleName).'`, `'.bqSQL($id).'` FROM `'._DB_PREFIX_.bqSQL($table).'` WHERE `'.bqSQL($id).'_'.bqSQL($moduleName).'` != 0');
  953. $match = array();
  954. foreach($return AS $name => $val)
  955. $match[$val[$id.'_'.$moduleName]] = $val[$id];
  956. return $match;
  957. }
  958. private function getMatchIdLang($order = 1)
  959. {
  960. $moduleName = Tools::getValue('moduleName');
  961. $return = Db::getInstance()->executeS('SELECT `id_lang`, `id_lang_'.bqSQL($moduleName).'` FROM `'._DB_PREFIX_.'lang'.'` WHERE `id_lang_'.bqSQL($moduleName).'` != 0');
  962. $match = array();
  963. foreach($return AS $name => $val)
  964. if ((bool)$order)
  965. $match[$val['id_lang_'.$moduleName]] = $val['id_lang'];
  966. else
  967. $match[$val['id_lang']] = $val['id_lang_'.$moduleName];
  968. return $match;
  969. }
  970. private function validateRules($rules, &$fields, $className, $languages, $defaultLanguage)
  971. {
  972. $returnErrors = array();
  973. $hasErrors = Tools::getValue('hasErrors');
  974. /* Checking for required fields */
  975. foreach ($rules['required'] AS $field)
  976. if (($value = $fields[$field]) == false AND (string)$value != '0')
  977. if ($hasErrors == 2)
  978. {
  979. if (array_key_exists($field, $rules['size']))
  980. $size = $rules['size'][$field];
  981. else
  982. $size = 1;
  983. $fields[$field] = $this->generateData($size, $rules['validate'][$field]);
  984. }
  985. else
  986. $returnErrors[] = sprintf(
  987. $this->l('The field %s is required.'),
  988. call_user_func(array($className, 'displayFieldName'), $field, $className)
  989. );
  990. /* Checking for maximum fields sizes */
  991. foreach ($rules['size'] AS $field => $maxLength)
  992. if (array_key_exists($field, $fields) AND $field != 'passwd')
  993. if ($fields[$field] !== false AND Tools::strlen($fields[$field]) > $maxLength)
  994. if ($hasErrors == 2)
  995. $fields[$field] = substr($fields[$field], 0, $maxLength);
  996. else
  997. $returnErrors[] = sprintf(
  998. $this->l('The field %1$s is too long (%2$d chars max).'),
  999. call_user_func(array($className, 'displayFieldName'), $field, $className),
  1000. $maxLength
  1001. );
  1002. /* Checking for fields validity */
  1003. foreach ($rules['validate'] AS $field => $function)
  1004. if (array_key_exists($field, $fields))
  1005. if (($value = $fields[$field]) !== false AND ($field != 'passwd'))
  1006. if (!Validate::$function($value))
  1007. if ($hasErrors == 2)
  1008. {
  1009. if (array_key_exists($field, $rules['size']))
  1010. $size = $rules['size'][$field];
  1011. else
  1012. $size = 1;
  1013. $fields[$field] = $this->generateData($size, $rules['validate'][$field]);
  1014. }
  1015. else
  1016. $returnErrors[] = sprintf(
  1017. $this->l('The field %s is invalid.'),
  1018. call_user_func(array($className, 'displayFieldName'), $field, $className)
  1019. );
  1020. if ((sizeof($rules['requiredLang']) || sizeof($rules['sizeLang']) || sizeof($rules['validateLang'])))
  1021. {
  1022. $matchIdLang = $this->getMatchIdLang(0);
  1023. /* Checking for multilingual required fields */
  1024. foreach ($rules['requiredLang'] AS $fieldLang)
  1025. {
  1026. if (($empty = $fields[$fieldLang][$matchIdLang[$defaultLanguage->id]]) === false || empty($empty))
  1027. if ($hasErrors == 2)
  1028. {
  1029. if (array_key_exists($fieldLang, $rules['sizeLang']))
  1030. $size = $rules['sizeLang'][$fieldLang];
  1031. else
  1032. $size = 1;
  1033. $fields[$fieldLang][$matchIdLang[$defaultLanguage->id]] = $this->generateData($size, $rules['validateLang'][$fieldLang]);
  1034. }
  1035. else
  1036. $returnErrors[] = sprintf(
  1037. $this->l('This field %1$s is required at least in %2$s'),
  1038. call_user_func(array($className, 'displayFieldName'), $fieldLang, $className),
  1039. $defaultLanguage->name
  1040. );
  1041. }
  1042. /* Checking for maximum multilingual fields size */
  1043. foreach ($rules['sizeLang'] AS $fieldLang => $maxLength)
  1044. foreach ($languages AS $language)
  1045. if (isset($fields[$fieldLang][$language['id_lang']]) && $fields[$fieldLang] !== false AND Tools::strlen($fields[$fieldLang][$language['id_lang']]) > $maxLength)
  1046. if ($hasErrors == 2)
  1047. $fields[$fieldLang] = substr($fields[$fieldLang], 0, $maxLength);
  1048. else
  1049. $returnErrors[] = sprintf(
  1050. $this->l('This field %1$s (%2$s) is too long: %3$d chars max.'),
  1051. call_user_func(array($className, 'displayFieldName'), $fieldLang, $className),
  1052. $language['name'],
  1053. $maxLength
  1054. );
  1055. foreach ($rules['validateLang'] AS $fieldLang => $function)
  1056. {
  1057. foreach ($languages AS $language)
  1058. {
  1059. if (array_key_exists($fieldLang, $fields) AND array_key_exists($language['id_lang'], $fields[$fieldLang]) AND ($value = $fields[$fieldLang][$language['id_lang']]) !== false AND !empty($value))
  1060. {
  1061. if (!Validate::$function($value))
  1062. if ($hasErrors == 2)
  1063. {
  1064. if (array_key_exists($fieldLang, $rules['sizeLang']))
  1065. $size = $rules['sizeLang'][$fieldLang];
  1066. else
  1067. $size = 1;
  1068. $fields[$fieldLang][$language['id_lang']] = $this->generateData($size, $rules['validateLang'][$fieldLang]);
  1069. }
  1070. else
  1071. $returnErrors[] = sprintf(
  1072. $this->l('The field %1$s (%2$s) is invalid.'),
  1073. call_user_func(array($className, 'displayFieldName'), $fieldLang, $className),
  1074. $language['name']
  1075. );
  1076. }
  1077. }
  1078. }
  1079. }
  1080. return $returnErrors;
  1081. }
  1082. private function validateRulesWS($rules, &$fields, $className, $languages, $defaultLanguage)
  1083. {
  1084. $returnErrors = array();
  1085. $hasErrors = Tools::getValue('hasErrors');
  1086. /* Checking for required fields */
  1087. foreach ($rules['required'] AS $field)
  1088. if (($value = $fields[$field]) == false AND (string)$value != '0')
  1089. if ($hasErrors == 2)
  1090. {
  1091. if (array_key_exists($field, $rules['size']))
  1092. $size = $rules['size'][$field];
  1093. else
  1094. $size = 1;
  1095. $fields[$field] = $this->generateData($size, $rules['validate'][$field]);
  1096. }
  1097. else
  1098. $returnErrors[] = sprintf(
  1099. $this->l('The field %s is required.'),
  1100. call_user_func(array($className, 'displayFieldName'), $field, $className)
  1101. );
  1102. /* Checking for maximum fields sizes */
  1103. foreach ($rules['size'] AS $field => $maxLength)
  1104. if (array_key_exists($field, $fields) AND $field != 'passwd')
  1105. if ($fields[$field] !== false AND Tools::strlen($fields[$field]) > $maxLength)
  1106. if ($hasErrors == 2)
  1107. $fields[$field] = substr($fields[$field], 0, $maxLength);
  1108. else
  1109. $returnErrors[] = sprintf(
  1110. $this->l('The field %1$s is too long (%2$d chars max).'),
  1111. call_user_func(array($className, 'displayFieldName'), $field, $className),
  1112. $maxLength
  1113. );
  1114. /* Checking for fields validity */
  1115. foreach ($rules['validate'] AS $field => $function)
  1116. if (array_key_exists($field, $fields))
  1117. if (($value = $fields[$field]) !== false AND ($field != 'passwd'))
  1118. if (!Validate::$function($value))
  1119. if ($hasErrors == 2)
  1120. {
  1121. if (array_key_exists($field, $rules['size']))
  1122. $size = $rules['size'][$field];
  1123. else
  1124. $size = 1;
  1125. $fields[$field] = $this->generateData($size, $rules['validate'][$field]);
  1126. }
  1127. else
  1128. $returnErrors[] = sprintf(
  1129. $this->l('The field %s is invalid.'),
  1130. call_user_func(array($className, 'displayFieldName'), $field, $className)
  1131. );
  1132. return $returnErrors;
  1133. }
  1134. public function checkAndAddLang ($languages, $add = true)
  1135. {
  1136. $errors = '';
  1137. $moduleName = Tools::getValue('moduleName');
  1138. $this->alterTable('language');
  1139. foreach($languages as $language)
  1140. {
  1141. $iso = $language['iso_code'];
  1142. if (!Language::isInstalled($iso))
  1143. {
  1144. if ($add)
  1145. {
  1146. if (@fsockopen('www.prestashop.com', 80))
  1147. {
  1148. if ($lang_pack = Tools::jsonDecode(Tools::file_get_contents('http://www.prestashop.com/download/lang_packs/…

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