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

/controllers/admin/AdminImportController.php

https://github.com/netplayer/PrestaShop
PHP | 3415 lines | 2935 code | 298 blank | 182 comment | 730 complexity | e89c6481b6852a6dce33350b71f75a3c MD5 | raw file
Possible License(s): CC-BY-SA-3.0, 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-2014 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-2014 PrestaShop SA
  23. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  24. * International Registered Trademark & Property of PrestaShop SA
  25. */
  26. @ini_set('max_execution_time', 0);
  27. /** No max line limit since the lines can be more than 4096. Performance impact is not significant. */
  28. define('MAX_LINE_SIZE', 0);
  29. /** Used for validatefields diying without user friendly error or not */
  30. define('UNFRIENDLY_ERROR', false);
  31. /** this value set the number of columns visible on each page */
  32. define('MAX_COLUMNS', 6);
  33. /** correct Mac error on eof */
  34. @ini_set('auto_detect_line_endings', '1');
  35. class AdminImportControllerCore extends AdminController
  36. {
  37. public static $column_mask;
  38. public $entities = array();
  39. public $available_fields = array();
  40. public $required_fields = array();
  41. public $cache_image_deleted = array();
  42. public static $default_values = array();
  43. public static $validators = array(
  44. 'active' => array('AdminImportController', 'getBoolean'),
  45. 'tax_rate' => array('AdminImportController', 'getPrice'),
  46. /** Tax excluded */
  47. 'price_tex' => array('AdminImportController', 'getPrice'),
  48. /** Tax included */
  49. 'price_tin' => array('AdminImportController', 'getPrice'),
  50. 'reduction_price' => array('AdminImportController', 'getPrice'),
  51. 'reduction_percent' => array('AdminImportController', 'getPrice'),
  52. 'wholesale_price' => array('AdminImportController', 'getPrice'),
  53. 'ecotax' => array('AdminImportController', 'getPrice'),
  54. 'name' => array('AdminImportController', 'createMultiLangField'),
  55. 'description' => array('AdminImportController', 'createMultiLangField'),
  56. 'description_short' => array('AdminImportController', 'createMultiLangField'),
  57. 'meta_title' => array('AdminImportController', 'createMultiLangField'),
  58. 'meta_keywords' => array('AdminImportController', 'createMultiLangField'),
  59. 'meta_description' => array('AdminImportController', 'createMultiLangField'),
  60. 'link_rewrite' => array('AdminImportController', 'createMultiLangField'),
  61. 'available_now' => array('AdminImportController', 'createMultiLangField'),
  62. 'available_later' => array('AdminImportController', 'createMultiLangField'),
  63. 'category' => array('AdminImportController', 'split'),
  64. 'online_only' => array('AdminImportController', 'getBoolean')
  65. );
  66. public $separator;
  67. public $multiple_value_separator;
  68. public function __construct()
  69. {
  70. $this->bootstrap = true;
  71. $this->entities = array(
  72. $this->l('Categories'),
  73. $this->l('Products'),
  74. $this->l('Combinations'),
  75. $this->l('Customers'),
  76. $this->l('Addresses'),
  77. $this->l('Manufacturers'),
  78. $this->l('Suppliers'),
  79. $this->l('Alias'),
  80. );
  81. // @since 1.5.0
  82. if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT'))
  83. {
  84. $this->entities = array_merge(
  85. $this->entities,
  86. array(
  87. $this->l('Supply Orders'),
  88. $this->l('Supply Order Details'),
  89. )
  90. );
  91. }
  92. $this->entities = array_flip($this->entities);
  93. switch ((int)Tools::getValue('entity'))
  94. {
  95. case $this->entities[$this->l('Combinations')]:
  96. $this->required_fields = array(
  97. 'id_product',
  98. 'group',
  99. 'attribute'
  100. );
  101. $this->available_fields = array(
  102. 'no' => array('label' => $this->l('Ignore this column')),
  103. 'id_product' => array('label' => $this->l('Product ID').'*'),
  104. 'group' => array(
  105. 'label' => $this->l('Attribute (Name:Type:Position)').'*'
  106. ),
  107. 'attribute' => array(
  108. 'label' => $this->l('Value (Value:Position)').'*'
  109. ),
  110. 'supplier_reference' => array('label' => $this->l('Supplier reference')),
  111. 'reference' => array('label' => $this->l('Reference')),
  112. 'ean13' => array('label' => $this->l('EAN13')),
  113. 'upc' => array('label' => $this->l('UPC')),
  114. 'wholesale_price' => array('label' => $this->l('Wholesale price')),
  115. 'price' => array('label' => $this->l('Impact on price')),
  116. 'ecotax' => array('label' => $this->l('Ecotax')),
  117. 'quantity' => array('label' => $this->l('Quantity')),
  118. 'minimal_quantity' => array('label' => $this->l('Minimal quantity')),
  119. 'weight' => array('label' => $this->l('Impact on weight')),
  120. 'default_on' => array('label' => $this->l('Default (0 = No, 1 = Yes)')),
  121. 'image_position' => array(
  122. 'label' => $this->l('Image position')
  123. ),
  124. 'image_url' => array('label' => $this->l('Image URL')),
  125. 'delete_existing_images' => array(
  126. 'label' => $this->l('Delete existing images (0 = No, 1 = Yes).')
  127. ),
  128. 'shop' => array(
  129. 'label' => $this->l('ID / Name of shop'),
  130. 'help' => $this->l('Ignore this field if you don\'t use the Multistore tool. If you leave this field empty, the default shop will be used.'),
  131. ),
  132. 'advanced_stock_management' => array(
  133. 'label' => $this->l('Advanced Stock Management'),
  134. 'help' => $this->l('Enable Advanced Stock Management on product (0 = No, 1 = Yes)')
  135. ),
  136. 'depends_on_stock' => array(
  137. 'label' => $this->l('Depends on stock'),
  138. 'help' => $this->l('0 = Use quantity set in product, 1 = Use quantity from warehouse.')
  139. ),
  140. 'warehouse' => array(
  141. 'label' => $this->l('Warehouse'),
  142. 'help' => $this->l('ID of the warehouse to set as storage.')
  143. ),
  144. );
  145. self::$default_values = array(
  146. 'reference' => '',
  147. 'supplier_reference' => '',
  148. 'ean13' => '',
  149. 'upc' => '',
  150. 'wholesale_price' => 0,
  151. 'price' => 0,
  152. 'ecotax' => 0,
  153. 'quantity' => 0,
  154. 'minimal_quantity' => 1,
  155. 'weight' => 0,
  156. 'default_on' => 0,
  157. 'advanced_stock_management' => 0,
  158. 'depends_on_stock' => 0,
  159. );
  160. break;
  161. case $this->entities[$this->l('Categories')]:
  162. $this->available_fields = array(
  163. 'no' => array('label' => $this->l('Ignore this column')),
  164. 'id' => array('label' => $this->l('ID')),
  165. 'active' => array('label' => $this->l('Active (0/1)')),
  166. 'name' => array('label' => $this->l('Name')),
  167. 'parent' => array('label' => $this->l('Parent category')),
  168. 'is_root_category' => array(
  169. 'label' => $this->l('Root category (0/1)'),
  170. 'help' => $this->l('A category root is where a category tree can begin. This is used with multistore.')
  171. ),
  172. 'description' => array('label' => $this->l('Description')),
  173. 'meta_title' => array('label' => $this->l('Meta title')),
  174. 'meta_keywords' => array('label' => $this->l('Meta keywords')),
  175. 'meta_description' => array('label' => $this->l('Meta description')),
  176. 'link_rewrite' => array('label' => $this->l('URL rewritten')),
  177. 'image' => array('label' => $this->l('Image URL')),
  178. 'shop' => array(
  179. 'label' => $this->l('ID / Name of shop'),
  180. 'help' => $this->l('Ignore this field if you don\'t use the Multistore tool. If you leave this field empty, the default shop will be used.'),
  181. ),
  182. );
  183. self::$default_values = array(
  184. 'active' => '1',
  185. 'parent' => Configuration::get('PS_HOME_CATEGORY'),
  186. 'link_rewrite' => ''
  187. );
  188. break;
  189. case $this->entities[$this->l('Products')]:
  190. self::$validators['image'] = array(
  191. 'AdminImportController',
  192. 'split'
  193. );
  194. $this->available_fields = array(
  195. 'no' => array('label' => $this->l('Ignore this column')),
  196. 'id' => array('label' => $this->l('ID')),
  197. 'active' => array('label' => $this->l('Active (0/1)')),
  198. 'name' => array('label' => $this->l('Name')),
  199. 'category' => array('label' => $this->l('Categories (x,y,z...)')),
  200. 'price_tex' => array('label' => $this->l('Price tax excluded')),
  201. 'price_tin' => array('label' => $this->l('Price tax included')),
  202. 'id_tax_rules_group' => array('label' => $this->l('Tax rules ID')),
  203. 'wholesale_price' => array('label' => $this->l('Wholesale price')),
  204. 'on_sale' => array('label' => $this->l('On sale (0/1)')),
  205. 'reduction_price' => array('label' => $this->l('Discount amount')),
  206. 'reduction_percent' => array('label' => $this->l('Discount percent')),
  207. 'reduction_from' => array('label' => $this->l('Discount from (yyyy-mm-dd)')),
  208. 'reduction_to' => array('label' => $this->l('Discount to (yyyy-mm-dd)')),
  209. 'reference' => array('label' => $this->l('Reference #')),
  210. 'supplier_reference' => array('label' => $this->l('Supplier reference #')),
  211. 'supplier' => array('label' => $this->l('Supplier')),
  212. 'manufacturer' => array('label' => $this->l('Manufacturer')),
  213. 'ean13' => array('label' => $this->l('EAN13')),
  214. 'upc' => array('label' => $this->l('UPC')),
  215. 'ecotax' => array('label' => $this->l('Ecotax')),
  216. 'width' => array('label' => $this->l('Width')),
  217. 'height' => array('label' => $this->l('Height')),
  218. 'depth' => array('label' => $this->l('Depth')),
  219. 'weight' => array('label' => $this->l('Weight')),
  220. 'quantity' => array('label' => $this->l('Quantity')),
  221. 'minimal_quantity' => array('label' => $this->l('Minimal quantity')),
  222. 'visibility' => array('label' => $this->l('Visibility')),
  223. 'additional_shipping_cost' => array('label' => $this->l('Additional shipping cost')),
  224. 'unity' => array('label' => $this->l('Unit for the unit price')),
  225. 'unit_price' => array('label' => $this->l('Unit price')),
  226. 'description_short' => array('label' => $this->l('Short description')),
  227. 'description' => array('label' => $this->l('Description')),
  228. 'tags' => array('label' => $this->l('Tags (x,y,z...)')),
  229. 'meta_title' => array('label' => $this->l('Meta title')),
  230. 'meta_keywords' => array('label' => $this->l('Meta keywords')),
  231. 'meta_description' => array('label' => $this->l('Meta description')),
  232. 'link_rewrite' => array('label' => $this->l('URL rewritten')),
  233. 'available_now' => array('label' => $this->l('Text when in stock')),
  234. 'available_later' => array('label' => $this->l('Text when backorder allowed')),
  235. 'available_for_order' => array('label' => $this->l('Available for order (0 = No, 1 = Yes)')),
  236. 'available_date' => array('label' => $this->l('Product available date')),
  237. 'date_add' => array('label' => $this->l('Product creation date')),
  238. 'show_price' => array('label' => $this->l('Show price (0 = No, 1 = Yes)')),
  239. 'image' => array('label' => $this->l('Image URLs (x,y,z...)')),
  240. 'delete_existing_images' => array(
  241. 'label' => $this->l('Delete existing images (0 = No, 1 = Yes)')
  242. ),
  243. 'features' => array('label' => $this->l('Feature (Name:Value:Position:Customized)')),
  244. 'online_only' => array('label' => $this->l('Available online only (0 = No, 1 = Yes)')),
  245. 'condition' => array('label' => $this->l('Condition')),
  246. 'customizable' => array('label' => $this->l('Customizable (0 = No, 1 = Yes)')),
  247. 'uploadable_files' => array('label' => $this->l('Uploadable files (0 = No, 1 = Yes)')),
  248. 'text_fields' => array('label' => $this->l('Text fields (0 = No, 1 = Yes)')),
  249. 'out_of_stock' => array('label' => $this->l('Action when out of stock')),
  250. 'shop' => array(
  251. 'label' => $this->l('ID / Name of shop'),
  252. 'help' => $this->l('Ignore this field if you don\'t use the Multistore tool. If you leave this field empty, the default shop will be used.'),
  253. ),
  254. 'advanced_stock_management' => array(
  255. 'label' => $this->l('Advanced Stock Management'),
  256. 'help' => $this->l('Enable Advanced Stock Management on product (0 = No, 1 = Yes).')
  257. ),
  258. 'depends_on_stock' => array(
  259. 'label' => $this->l('Depends on stock'),
  260. 'help' => $this->l('0 = Use quantity set in product, 1 = Use quantity from warehouse.')
  261. ),
  262. 'warehouse' => array(
  263. 'label' => $this->l('Warehouse'),
  264. 'help' => $this->l('ID of the warehouse to set as storage.')
  265. ),
  266. );
  267. self::$default_values = array(
  268. 'id_category' => array((int)Configuration::get('PS_HOME_CATEGORY')),
  269. 'id_category_default' => (int)Configuration::get('PS_HOME_CATEGORY'),
  270. 'active' => '1',
  271. 'width' => 0.000000,
  272. 'height' => 0.000000,
  273. 'depth' => 0.000000,
  274. 'weight' => 0.000000,
  275. 'visibility' => 'both',
  276. 'additional_shipping_cost' => 0.00,
  277. 'unit_price' => 0,
  278. 'quantity' => 0,
  279. 'minimal_quantity' => 1,
  280. 'price' => 0,
  281. 'id_tax_rules_group' => 0,
  282. 'description_short' => array((int)Configuration::get('PS_LANG_DEFAULT') => ''),
  283. 'link_rewrite' => array((int)Configuration::get('PS_LANG_DEFAULT') => ''),
  284. 'online_only' => 0,
  285. 'condition' => 'new',
  286. 'available_date' => date('Y-m-d'),
  287. 'date_add' => date('Y-m-d H:i:s'),
  288. 'customizable' => 0,
  289. 'uploadable_files' => 0,
  290. 'text_fields' => 0,
  291. 'out_of_stock' => '2',
  292. 'advanced_stock_management' => 0,
  293. 'depends_on_stock' => 0,
  294. );
  295. break;
  296. case $this->entities[$this->l('Customers')]:
  297. //Overwrite required_fields AS only email is required whereas other entities
  298. $this->required_fields = array('email', 'passwd', 'lastname', 'firstname');
  299. $this->available_fields = array(
  300. 'no' => array('label' => $this->l('Ignore this column')),
  301. 'id' => array('label' => $this->l('ID')),
  302. 'active' => array('label' => $this->l('Active (0/1)')),
  303. 'id_gender' => array('label' => $this->l('Titles ID (Mr = 1, Ms = 2, else 0)')),
  304. 'email' => array('label' => $this->l('Email *')),
  305. 'passwd' => array('label' => $this->l('Password *')),
  306. 'birthday' => array('label' => $this->l('Birthday (yyyy-mm-dd)')),
  307. 'lastname' => array('label' => $this->l('Last Name *')),
  308. 'firstname' => array('label' => $this->l('First Name *')),
  309. 'newsletter' => array('label' => $this->l('Newsletter (0/1)')),
  310. 'optin' => array('label' => $this->l('Opt-in (0/1)')),
  311. 'group' => array('label' => $this->l('Groups (x,y,z...)')),
  312. 'id_default_group' => array('label' => $this->l('Default group ID')),
  313. 'id_shop' => array(
  314. 'label' => $this->l('ID / Name of shop'),
  315. 'help' => $this->l('Ignore this field if you don\'t use the Multistore tool. If you leave this field empty, the default shop will be used.'),
  316. ),
  317. );
  318. self::$default_values = array(
  319. 'active' => '1',
  320. 'id_shop' => Configuration::get('PS_SHOP_DEFAULT'),
  321. );
  322. break;
  323. case $this->entities[$this->l('Addresses')]:
  324. //Overwrite required_fields
  325. $this->required_fields = array(
  326. 'alias',
  327. 'lastname',
  328. 'firstname',
  329. 'address1',
  330. 'postcode',
  331. 'country',
  332. 'customer_email',
  333. 'city'
  334. );
  335. $this->available_fields = array(
  336. 'no' => array('label' => $this->l('Ignore this column')),
  337. 'id' => array('label' => $this->l('ID')),
  338. 'alias' => array('label' => $this->l('Alias *')),
  339. 'active' => array('label' => $this->l('Active (0/1)')),
  340. 'customer_email' => array('label' => $this->l('Customer email *')),
  341. 'id_customer' => array('label' => $this->l('Customer ID')),
  342. 'manufacturer' => array('label' => $this->l('Manufacturer')),
  343. 'supplier' => array('label' => $this->l('Supplier')),
  344. 'company' => array('label' => $this->l('Company')),
  345. 'lastname' => array('label' => $this->l('Last Name *')),
  346. 'firstname' => array('label' => $this->l('First Name *')),
  347. 'address1' => array('label' => $this->l('Address 1 *')),
  348. 'address2' => array('label' => $this->l('Address 2')),
  349. 'postcode' => array('label' => $this->l('Zip/postal code *')),
  350. 'city' => array('label' => $this->l('City *')),
  351. 'country' => array('label' => $this->l('Country *')),
  352. 'state' => array('label' => $this->l('State')),
  353. 'other' => array('label' => $this->l('Other')),
  354. 'phone' => array('label' => $this->l('Phone')),
  355. 'phone_mobile' => array('label' => $this->l('Mobile Phone')),
  356. 'vat_number' => array('label' => $this->l('VAT number')),
  357. );
  358. self::$default_values = array(
  359. 'alias' => 'Alias',
  360. 'postcode' => 'X'
  361. );
  362. break;
  363. case $this->entities[$this->l('Manufacturers')]:
  364. case $this->entities[$this->l('Suppliers')]:
  365. //Overwrite validators AS name is not MultiLangField
  366. self::$validators = array(
  367. 'description' => array('AdminImportController', 'createMultiLangField'),
  368. 'short_description' => array('AdminImportController', 'createMultiLangField'),
  369. 'meta_title' => array('AdminImportController', 'createMultiLangField'),
  370. 'meta_keywords' => array('AdminImportController', 'createMultiLangField'),
  371. 'meta_description' => array('AdminImportController', 'createMultiLangField'),
  372. );
  373. $this->available_fields = array(
  374. 'no' => array('label' => $this->l('Ignore this column')),
  375. 'id' => array('label' => $this->l('ID')),
  376. 'active' => array('label' => $this->l('Active (0/1)')),
  377. 'name' => array('label' => $this->l('Name')),
  378. 'description' => array('label' => $this->l('Description')),
  379. 'short_description' => array('label' => $this->l('Short description')),
  380. 'meta_title' => array('label' => $this->l('Meta title')),
  381. 'meta_keywords' => array('label' => $this->l('Meta keywords')),
  382. 'meta_description' => array('label' => $this->l('Meta description')),
  383. 'image' => array('label' => $this->l('Image URL')),
  384. 'shop' => array(
  385. 'label' => $this->l('ID / Name of group shop'),
  386. 'help' => $this->l('Ignore this field if you don\'t use the Multistore tool. If you leave this field empty, the default shop will be used.'),
  387. ),
  388. );
  389. self::$default_values = array(
  390. 'shop' => Shop::getGroupFromShop(Configuration::get('PS_SHOP_DEFAULT')),
  391. );
  392. break;
  393. case $this->entities[$this->l('Alias')]:
  394. //Overwrite required_fields
  395. $this->required_fields = array(
  396. 'alias',
  397. 'search',
  398. );
  399. $this->available_fields = array(
  400. 'no' => array('label' => $this->l('Ignore this column')),
  401. 'id' => array('label' => $this->l('ID')),
  402. 'alias' => array('label' => $this->l('Alias *')),
  403. 'search' => array('label' => $this->l('Search *')),
  404. 'active' => array('label' => $this->l('Active')),
  405. );
  406. self::$default_values = array(
  407. 'active' => '1',
  408. );
  409. break;
  410. }
  411. // @since 1.5.0
  412. if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT'))
  413. switch ((int)Tools::getValue('entity'))
  414. {
  415. case $this->entities[$this->l('Supply Orders')]:
  416. // required fields
  417. $this->required_fields = array(
  418. 'id_supplier',
  419. 'id_warehouse',
  420. 'reference',
  421. 'date_delivery_expected',
  422. );
  423. // available fields
  424. $this->available_fields = array(
  425. 'no' => array('label' => $this->l('Ignore this column')),
  426. 'id' => array('label' => $this->l('ID')),
  427. 'id_supplier' => array('label' => $this->l('Supplier ID *')),
  428. 'id_lang' => array('label' => $this->l('Lang ID')),
  429. 'id_warehouse' => array('label' => $this->l('Warehouse ID *')),
  430. 'id_currency' => array('label' => $this->l('Currency ID *')),
  431. 'reference' => array('label' => $this->l('Supply Order Reference *')),
  432. 'date_delivery_expected' => array('label' => $this->l('Delivery Date (Y-M-D)*')),
  433. 'discount_rate' => array('label' => $this->l('Discount Rate')),
  434. 'is_template' => array('label' => $this->l('Template')),
  435. );
  436. // default values
  437. self::$default_values = array(
  438. 'id_lang' => (int)Configuration::get('PS_LANG_DEFAULT'),
  439. 'id_currency' => Currency::getDefaultCurrency()->id,
  440. 'discount_rate' => '0',
  441. 'is_template' => '0',
  442. );
  443. break;
  444. case $this->entities[$this->l('Supply Order Details')]:
  445. // required fields
  446. $this->required_fields = array(
  447. 'supply_order_reference',
  448. 'id_product',
  449. 'unit_price_te',
  450. 'quantity_expected',
  451. );
  452. // available fields
  453. $this->available_fields = array(
  454. 'no' => array('label' => $this->l('Ignore this column')),
  455. 'supply_order_reference' => array('label' => $this->l('Supply Order Reference *')),
  456. 'id_product' => array('label' => $this->l('Product ID *')),
  457. 'id_product_attribute' => array('label' => $this->l('Product Attribute ID')),
  458. 'unit_price_te' => array('label' => $this->l('Unit Price (tax excl.)*')),
  459. 'quantity_expected' => array('label' => $this->l('Quantity Expected *')),
  460. 'discount_rate' => array('label' => $this->l('Discount Rate')),
  461. 'tax_rate' => array('label' => $this->l('Tax Rate')),
  462. );
  463. // default values
  464. self::$default_values = array(
  465. 'discount_rate' => '0',
  466. 'tax_rate' => '0',
  467. );
  468. break;
  469. }
  470. $this->separator = ($separator = Tools::substr(strval(trim(Tools::getValue('separator'))), 0, 1)) ? $separator : ';';
  471. $this->multiple_value_separator = ($separator = Tools::substr(strval(trim(Tools::getValue('multiple_value_separator'))), 0, 1)) ? $separator : ',';
  472. parent::__construct();
  473. }
  474. public function setMedia()
  475. {
  476. $bo_theme = ((Validate::isLoadedObject($this->context->employee)
  477. && $this->context->employee->bo_theme) ? $this->context->employee->bo_theme : 'default');
  478. if (!file_exists(_PS_BO_ALL_THEMES_DIR_.$bo_theme.DIRECTORY_SEPARATOR
  479. .'template'))
  480. $bo_theme = 'default';
  481. // We need to set parent media first, so that jQuery is loaded before the dependant plugins
  482. parent::setMedia();
  483. $this->addJs(__PS_BASE_URI__.$this->admin_webpath.'/themes/'.$bo_theme.'/js/jquery.iframe-transport.js');
  484. $this->addJs(__PS_BASE_URI__.$this->admin_webpath.'/themes/'.$bo_theme.'/js/jquery.fileupload.js');
  485. $this->addJs(__PS_BASE_URI__.$this->admin_webpath.'/themes/'.$bo_theme.'/js/jquery.fileupload-process.js');
  486. $this->addJs(__PS_BASE_URI__.$this->admin_webpath.'/themes/'.$bo_theme.'/js/jquery.fileupload-validate.js');
  487. $this->addJs(__PS_BASE_URI__.'js/vendor/spin.js');
  488. $this->addJs(__PS_BASE_URI__.'js/vendor/ladda.js');
  489. }
  490. public function renderForm()
  491. {
  492. if (!is_dir(AdminImportController::getPath()))
  493. return !($this->errors[] = Tools::displayError('The import directory does not exist.'));
  494. if (!is_writable(AdminImportController::getPath()))
  495. $this->displayWarning($this->l('The import directory must be writable (CHMOD 755 / 777).'));
  496. if (isset($this->warnings) && count($this->warnings))
  497. {
  498. $warnings = array();
  499. foreach ($this->warnings as $warning)
  500. $warnings[] = $warning;
  501. }
  502. $files_to_import = scandir(AdminImportController::getPath());
  503. uasort($files_to_import, array('AdminImportController', 'usortFiles'));
  504. foreach ($files_to_import as $k => &$filename)
  505. //exclude . .. .svn and index.php and all hidden files
  506. if (preg_match('/^\..*|index\.php/i', $filename))
  507. unset($files_to_import[$k]);
  508. unset($filename);
  509. $this->fields_form = array('');
  510. $this->toolbar_scroll = false;
  511. $this->toolbar_btn = array();
  512. // adds fancybox
  513. $this->addJqueryPlugin(array('fancybox'));
  514. $entity_selected = 0;
  515. if (isset($this->entities[$this->l(Tools::ucfirst(Tools::getValue('import_type')))]))
  516. {
  517. $entity_selected = $this->entities[$this->l(Tools::ucfirst(Tools::getValue('import_type')))];
  518. $this->context->cookie->entity_selected = (int)$entity_selected;
  519. }
  520. elseif (isset($this->context->cookie->entity_selected))
  521. $entity_selected = (int)$this->context->cookie->entity_selected;
  522. $csv_selected = '';
  523. if (isset($this->context->cookie->csv_selected) && @filemtime(AdminImportController::getPath(
  524. urldecode($this->context->cookie->csv_selected))))
  525. $csv_selected = urldecode($this->context->cookie->csv_selected);
  526. else
  527. $this->context->cookie->csv_selected = $csv_selected;
  528. $id_lang_selected = '';
  529. if (isset($this->context->cookie->iso_lang_selected) && $this->context->cookie->iso_lang_selected)
  530. $id_lang_selected = (int)Language::getIdByIso(urldecode($this->context->cookie->iso_lang_selected));
  531. $separator_selected = $this->separator;
  532. if (isset($this->context->cookie->separator_selected) && $this->context->cookie->separator_selected)
  533. $separator_selected = urldecode($this->context->cookie->separator_selected);
  534. $multiple_value_separator_selected = $this->multiple_value_separator;
  535. if (isset($this->context->cookie->multiple_value_separator_selected) && $this->context->cookie->multiple_value_separator_selected)
  536. $multiple_value_separator_selected = urldecode($this->context->cookie->multiple_value_separator_selected);
  537. //get post max size
  538. $post_max_size = ini_get('post_max_size');
  539. $bytes = trim($post_max_size);
  540. $last = strtolower($post_max_size[strlen($post_max_size) - 1]);
  541. switch ($last)
  542. {
  543. case 'g': $bytes *= 1024;
  544. case 'm': $bytes *= 1024;
  545. case 'k': $bytes *= 1024;
  546. }
  547. if (!isset($bytes) || $bytes == '')
  548. $bytes = 20971520; // 20Mb
  549. $this->tpl_form_vars = array(
  550. 'post_max_size' => (int)$bytes,
  551. 'module_confirmation' => Tools::isSubmit('import') && (isset($this->warnings) && !count($this->warnings)),
  552. 'path_import' => AdminImportController::getPath(),
  553. 'entities' => $this->entities,
  554. 'entity_selected' => $entity_selected,
  555. 'csv_selected' => $csv_selected,
  556. 'separator_selected' => $separator_selected,
  557. 'multiple_value_separator_selected' => $multiple_value_separator_selected,
  558. 'files_to_import' => $files_to_import,
  559. 'languages' => Language::getLanguages(false),
  560. 'id_language' => ($id_lang_selected) ? $id_lang_selected : $this->context->language->id,
  561. 'available_fields' => $this->getAvailableFields(),
  562. 'truncateAuthorized' => (Shop::isFeatureActive() && $this->context->employee->isSuperAdmin()) || !Shop::isFeatureActive(),
  563. 'PS_ADVANCED_STOCK_MANAGEMENT' => Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT'),
  564. );
  565. return parent::renderForm();
  566. }
  567. public function ajaxProcessuploadCsv()
  568. {
  569. $filename_prefix = date('YmdHis').'-';
  570. if (isset($_FILES['file']) && !empty($_FILES['file']['error']))
  571. {
  572. switch ($_FILES['file']['error'])
  573. {
  574. case UPLOAD_ERR_INI_SIZE:
  575. $_FILES['file']['error'] = Tools::displayError('The uploaded file exceeds the upload_max_filesize directive in php.ini. If your server configuration allows it, you may add a directive in your .htaccess.');
  576. break;
  577. case UPLOAD_ERR_FORM_SIZE:
  578. $_FILES['file']['error'] = Tools::displayError('The uploaded file exceeds the post_max_size directive in php.ini.
  579. If your server configuration allows it, you may add a directive in your .htaccess, for example:')
  580. .'<br/><a href="'.$this->context->link->getAdminLink('AdminMeta').'" >
  581. <code>php_value post_max_size 20M</code> '.
  582. Tools::displayError('(click to open "Generators" page)').'</a>';
  583. break;
  584. break;
  585. case UPLOAD_ERR_PARTIAL:
  586. $_FILES['file']['error'] = Tools::displayError('The uploaded file was only partially uploaded.');
  587. break;
  588. break;
  589. case UPLOAD_ERR_NO_FILE:
  590. $_FILES['file']['error'] = Tools::displayError('No file was uploaded.');
  591. break;
  592. break;
  593. }
  594. }
  595. elseif (!preg_match('/.*\.csv$/i', $_FILES['file']['name']))
  596. $_FILES['file']['error'] = Tools::displayError('The extension of your file should be .csv.');
  597. elseif (!@filemtime($_FILES['file']['tmp_name']) ||
  598. !@move_uploaded_file($_FILES['file']['tmp_name'], AdminImportController::getPath().$filename_prefix.str_replace("\0", '', $_FILES['file']['name'])))
  599. $_FILES['file']['error'] = $this->l('An error occurred while uploading / copying the file.');
  600. else
  601. {
  602. @chmod(AdminImportController::getPath().$filename_prefix.$_FILES['file']['name'], 0664);
  603. $_FILES['file']['filename'] = $filename_prefix.str_replace('\0', '', $_FILES['file']['name']);
  604. }
  605. die(Tools::jsonEncode($_FILES));
  606. }
  607. public function renderView()
  608. {
  609. $this->addJS(_PS_JS_DIR_.'adminImport.js');
  610. $handle = $this->openCsvFile();
  611. $nb_column = $this->getNbrColumn($handle, $this->separator);
  612. $nb_table = ceil($nb_column / MAX_COLUMNS);
  613. $res = array();
  614. foreach ($this->required_fields as $elem)
  615. $res[] = '\''.$elem.'\'';
  616. $data = array();
  617. for ($i = 0; $i < $nb_table; $i++)
  618. $data[$i] = $this->generateContentTable($i, $nb_column, $handle, $this->separator);
  619. $this->context->cookie->entity_selected = (int)Tools::getValue('entity');
  620. $this->context->cookie->iso_lang_selected = urlencode(Tools::getValue('iso_lang'));
  621. $this->context->cookie->separator_selected = urlencode($this->separator);
  622. $this->context->cookie->multiple_value_separator_selected = urlencode($this->multiple_value_separator);
  623. $this->context->cookie->csv_selected = urlencode(Tools::getValue('csv'));
  624. $this->tpl_view_vars = array(
  625. 'import_matchs' => Db::getInstance()->executeS('SELECT * FROM '._DB_PREFIX_.'import_match'),
  626. 'fields_value' => array(
  627. 'csv' => Tools::getValue('csv'),
  628. 'convert' => Tools::getValue('convert'),
  629. 'entity' => (int)Tools::getValue('entity'),
  630. 'iso_lang' => Tools::getValue('iso_lang'),
  631. 'truncate' => Tools::getValue('truncate'),
  632. 'forceIDs' => Tools::getValue('forceIDs'),
  633. 'regenerate' => Tools::getValue('regenerate'),
  634. 'match_ref' => Tools::getValue('match_ref'),
  635. 'separator' => $this->separator,
  636. 'multiple_value_separator' => $this->multiple_value_separator
  637. ),
  638. 'nb_table' => $nb_table,
  639. 'nb_column' => $nb_column,
  640. 'res' => implode(',', $res),
  641. 'max_columns' => MAX_COLUMNS,
  642. 'no_pre_select' => array('price_tin', 'feature'),
  643. 'available_fields' => $this->available_fields,
  644. 'data' => $data
  645. );
  646. return parent::renderView();
  647. }
  648. public function initToolbar()
  649. {
  650. switch ($this->display)
  651. {
  652. case 'import':
  653. // Default cancel button - like old back link
  654. $back = Tools::safeOutput(Tools::getValue('back', ''));
  655. if (empty($back))
  656. $back = self::$currentIndex.'&token='.$this->token;
  657. $this->toolbar_btn['cancel'] = array(
  658. 'href' => $back,
  659. 'desc' => $this->l('Cancel')
  660. );
  661. // Default save button - action dynamically handled in javascript
  662. $this->toolbar_btn['save-import'] = array(
  663. 'href' => '#',
  664. 'desc' => $this->l('Import .CSV data')
  665. );
  666. break;
  667. }
  668. }
  669. protected function generateContentTable($current_table, $nb_column, $handle, $glue)
  670. {
  671. $html = '<table id="table'.$current_table.'" style="display: none;" class="table table-bordered"><thead><tr>';
  672. // Header
  673. for ($i = 0; $i < $nb_column; $i++)
  674. if (MAX_COLUMNS * (int)$current_table <= $i && (int)$i < MAX_COLUMNS * ((int)$current_table + 1))
  675. $html .= '<th>
  676. <select id="type_value['.$i.']"
  677. name="type_value['.$i.']"
  678. class="type_value">
  679. '.$this->getTypeValuesOptions($i).'
  680. </select>
  681. </th>';
  682. $html .= '</tr></thead><tbody>';
  683. AdminImportController::setLocale();
  684. for ($current_line = 0; $current_line < 10 && $line = fgetcsv($handle, MAX_LINE_SIZE, $glue); $current_line++)
  685. {
  686. /* UTF-8 conversion */
  687. if (Tools::getValue('convert'))
  688. $line = $this->utf8EncodeArray($line);
  689. $html .= '<tr id="table_'.$current_table.'_line_'.$current_line.'">';
  690. foreach ($line as $nb_c => $column)
  691. if ((MAX_COLUMNS * (int)$current_table <= $nb_c) && ((int)$nb_c < MAX_COLUMNS * ((int)$current_table + 1)))
  692. $html .= '<td>'.htmlentities(Tools::substr($column, 0, 200), ENT_QUOTES, 'UTF-8').'</td>';
  693. $html .= '</tr>';
  694. }
  695. $html .= '</tbody></table>';
  696. AdminImportController::rewindBomAware($handle);
  697. return $html;
  698. }
  699. public function init()
  700. {
  701. parent::init();
  702. if (Tools::isSubmit('submitImportFile'))
  703. $this->display = 'import';
  704. }
  705. public function initContent()
  706. {
  707. $this->initTabModuleList();
  708. // toolbar (save, cancel, new, ..)
  709. $this->initToolbar();
  710. $this->initPageHeaderToolbar();
  711. if ($this->display == 'import')
  712. {
  713. if (Tools::getValue('csv'))
  714. $this->content .= $this->renderView();
  715. else
  716. {
  717. $this->errors[] = $this->l('You must upload a file in order to proceed to the next step');
  718. $this->content .= $this->renderForm();
  719. }
  720. }
  721. else
  722. $this->content .= $this->renderForm();
  723. $this->context->smarty->assign(array(
  724. 'content' => $this->content,
  725. 'url_post' => self::$currentIndex.'&token='.$this->token,
  726. 'show_page_header_toolbar' => $this->show_page_header_toolbar,
  727. 'page_header_toolbar_title' => $this->page_header_toolbar_title,
  728. 'page_header_toolbar_btn' => $this->page_header_toolbar_btn
  729. ));
  730. }
  731. protected static function rewindBomAware($handle)
  732. {
  733. // A rewind wrapper that skips BOM signature wrongly
  734. if (!is_resource($handle))
  735. return false;
  736. rewind($handle);
  737. if (($bom = fread($handle, 3)) != "\xEF\xBB\xBF")
  738. rewind($handle);
  739. }
  740. protected static function getBoolean($field)
  741. {
  742. return (boolean)$field;
  743. }
  744. protected static function getPrice($field)
  745. {
  746. $field = ((float)str_replace(',', '.', $field));
  747. $field = ((float)str_replace('%', '', $field));
  748. return $field;
  749. }
  750. protected static function split($field)
  751. {
  752. if (empty($field))
  753. return array();
  754. $separator = Tools::getValue('multiple_value_separator');
  755. if (is_null($separator) || trim($separator) == '')
  756. $separator = ',';
  757. do $uniqid_path = _PS_UPLOAD_DIR_.uniqid(); while (file_exists($uniqid_path));
  758. file_put_contents($uniqid_path, $field);
  759. $tab = '';
  760. if (!empty($uniqid_path))
  761. {
  762. $fd = fopen($uniqid_path, 'r');
  763. $tab = fgetcsv($fd, MAX_LINE_SIZE, $separator);
  764. fclose($fd);
  765. if (file_exists($uniqid_path))
  766. @unlink($uniqid_path);
  767. }
  768. if (empty($tab) || (!is_array($tab)))
  769. return array();
  770. return $tab;
  771. }
  772. protected static function createMultiLangField($field)
  773. {
  774. $languages = Language::getLanguages(false);
  775. $res = array();
  776. foreach ($languages as $lang)
  777. $res[$lang['id_lang']] = $field;
  778. return $res;
  779. }
  780. protected function getTypeValuesOptions($nb_c)
  781. {
  782. $i = 0;
  783. $no_pre_select = array('price_tin', 'feature');
  784. $options = '';
  785. foreach ($this->available_fields as $k => $field)
  786. {
  787. $options .= '<option value="'.$k.'"';
  788. if ($k === 'price_tin')
  789. ++$nb_c;
  790. if ($i === ($nb_c + 1) && (!in_array($k, $no_pre_select)))
  791. $options .= ' selected="selected"';
  792. $options .= '>'.$field['label'].'</option>';
  793. ++$i;
  794. }
  795. return $options;
  796. }
  797. /*
  798. * Return fields to be display AS piece of advise
  799. *
  800. * @param $in_array boolean
  801. * @return string or return array
  802. */
  803. public function getAvailableFields($in_array = false)
  804. {
  805. $i = 0;
  806. $fields = array();
  807. $keys = array_keys($this->available_fields);
  808. array_shift($keys);
  809. foreach ($this->available_fields as $k => $field)
  810. {
  811. if ($k === 'no')
  812. continue;
  813. if ($k === 'price_tin')
  814. $fields[$i - 1] = '<div>'.$this->available_fields[$keys[$i - 1]]['label'].' '.$this->l('or').' '.$field['label'].'</div>';
  815. else
  816. {
  817. if (isset($field['help']))
  818. $html = '&nbsp;<a href="#" class="help-tooltip" data-toggle="tooltip" title="'.$field['help'].'"><i class="icon-info-sign"></i></a>';
  819. else
  820. $html = '';
  821. $fields[] = '<div>'.$field['label'].$html.'</div>';
  822. }
  823. ++$i;
  824. }
  825. if ($in_array)
  826. return $fields;
  827. else
  828. return implode("\n\r", $fields);
  829. }
  830. protected function receiveTab()
  831. {
  832. $type_value = Tools::getValue('type_value') ? Tools::getValue('type_value') : array();
  833. foreach ($type_value as $nb => $type)
  834. if ($type != 'no')
  835. self::$column_mask[$type] = $nb;
  836. }
  837. public static function getMaskedRow($row)
  838. {
  839. $res = array();
  840. if (is_array(self::$column_mask))
  841. foreach (self::$column_mask as $type => $nb)
  842. $res[$type] = isset($row[$nb]) ? $row[$nb] : null;
  843. return $res;
  844. }
  845. protected static function setDefaultValues(&$info)
  846. {
  847. foreach (self::$default_values as $k => $v)
  848. if (!isset($info[$k]) || $info[$k] == '')
  849. $info[$k] = $v;
  850. }
  851. protected static function setEntityDefaultValues(&$entity)
  852. {
  853. $members = get_object_vars($entity);
  854. foreach (self::$default_values as $k => $v)
  855. if ((array_key_exists($k, $members) && $entity->$k === null) || !array_key_exists($k, $members))
  856. $entity->$k = $v;
  857. }
  858. protected static function fillInfo($infos, $key, &$entity)
  859. {
  860. $infos = trim($infos);
  861. if (isset(self::$validators[$key][1]) && self::$validators[$key][1] == 'createMultiLangField' && Tools::getValue('iso_lang'))
  862. {
  863. $id_lang = Language::getIdByIso(Tools::getValue('iso_lang'));
  864. $tmp = call_user_func(self::$validators[$key], $infos);
  865. foreach ($tmp as $id_lang_tmp => $value)
  866. if (empty($entity->{$key}[$id_lang_tmp]) || $id_lang_tmp == $id_lang)
  867. $entity->{$key}[$id_lang_tmp] = $value;
  868. }
  869. else
  870. if (!empty($infos) || $infos == '0') // ($infos == '0') => if you want to disable a product by using "0" in active because empty('0') return true
  871. $entity->{$key} = isset(self::$validators[$key]) ? call_user_func(self::$validators[$key], $infos) : $infos;
  872. return true;
  873. }
  874. /**
  875. * @param $array
  876. * @param $funcname
  877. * @param mixed $user_data
  878. * @return bool
  879. */
  880. public static function arrayWalk(&$array, $funcname, &$user_data = false)
  881. {
  882. if (!is_callable($funcname)) return false;
  883. foreach ($array as $k => $row)
  884. if (!call_user_func_array($funcname, array($row, $k, $user_data)))
  885. return false;
  886. return true;
  887. }
  888. /**
  889. * copyImg copy an image located in $url and save it in a path
  890. * according to $entity->$id_entity .
  891. * $id_image is used if we need to add a watermark
  892. *
  893. * @param int $id_entity id of product or category (set in entity)
  894. * @param int $id_image (default null) id of the image if watermark enabled.
  895. * @param string $url path or url to use
  896. * @param string entity 'products' or 'categories'
  897. * @return boolean
  898. */
  899. protected static function copyImg($id_entity, $id_image = null, $url, $entity = 'products', $regenerate = true)
  900. {
  901. $tmpfile = tempnam(_PS_TMP_IMG_DIR_, 'ps_import');
  902. $watermark_types = explode(',', Configuration::get('WATERMARK_TYPES'));
  903. switch ($entity)
  904. {
  905. default:
  906. case 'products':
  907. $image_obj = new Image($id_image);
  908. $path = $image_obj->getPathForCreation();
  909. break;
  910. case 'categories':
  911. $path = _PS_CAT_IMG_DIR_.(int)$id_entity;
  912. break;
  913. case 'manufacturers':
  914. $path = _PS_MANU_IMG_DIR_.(int)$id_entity;
  915. break;
  916. case 'suppliers':
  917. $path = _PS_SUPP_IMG_DIR_.(int)$id_entity;
  918. break;
  919. }
  920. $url = str_replace(' ', '%20', trim($url));
  921. // Evaluate the memory required to resize the image: if it's too much, you can't resize it.
  922. if (!ImageManager::checkImageMemoryLimit($url))
  923. return false;
  924. // 'file_exists' doesn't work on distant file, and getimagesize makes the import slower.
  925. // Just hide the warning, the processing will be the same.
  926. if (Tools::copy($url, $tmpfile))
  927. {
  928. ImageManager::resize($tmpfile, $path.'.jpg');
  929. $images_types = ImageType::getImagesTypes($entity);
  930. if ($regenerate)
  931. foreach ($images_types as $image_type)
  932. {
  933. ImageManager::resize($tmpfile, $path.'-'.stripslashes($image_type['name']).'.jpg', $image_type['width'], $image_type['height']);
  934. if (in_array($image_type['id_image_type'], $watermark_types))
  935. Hook::exec('actionWatermark', array('id_image' => $id_image, 'id_product' => $id_entity));
  936. }
  937. }
  938. else
  939. {
  940. unlink($tmpfile);
  941. return false;
  942. }
  943. unlink($tmpfile);
  944. return true;
  945. }
  946. public function categoryImport()
  947. {
  948. $cat_moved = array();
  949. $this->receiveTab();
  950. $handle = $this->openCsvFile();
  951. $default_language_id = (int)Configuration::get('PS_LANG_DEFAULT');
  952. $id_lang = Language::getIdByIso(Tools::getValue('iso_lang'));
  953. if (!Validate::isUnsignedId($id_lang))
  954. $id_lang = $default_language_id;
  955. AdminImportController::setLocale();
  956. for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, $this->separator); $current_line++)
  957. {
  958. if (Tools::getValue('convert'))
  959. $line = $this->utf8EncodeArray($line);
  960. $info = AdminImportController::getMaskedRow($line);
  961. $tab_categ = array(Configuration::get('PS_HOME_CATEGORY'), Configuration::get('PS_ROOT_CATEGORY'));
  962. if (isset($info['id']) && in_array((int)$info['id'], $tab_categ))
  963. {
  964. $this->errors[] = Tools::displayError('The category ID cannot be the same as the Root category ID or the Home category ID.');
  965. continue;
  966. }
  967. AdminImportController::setDefaultValues($info);
  968. if (Tools::getValue('forceIDs') && isset($info['id']) && (int)$info['id'])
  969. $category = new Category((int)$info['id']);
  970. else
  971. {
  972. if (isset($info['id']) && (int)$info['id'] && Category::existsInDatabase((int)$info['id'], 'category'))
  973. $category = new Category((int)$info['id']);
  974. else
  975. $category = new Category();
  976. }
  977. AdminImportController::arrayWalk($info, array('AdminImportController', 'fillInfo'), $category);
  978. if (isset($category->parent) && is_numeric($category->parent))
  979. {
  980. if (isset($cat_moved[$category->parent]))
  981. $category->parent = $cat_moved[$category->parent];
  982. $category->id_parent = $category->parent;
  983. }
  984. elseif (isset($category->parent) && is_string($category->parent))
  985. {
  986. $category_parent = Category::searchByName($id_lang, $category->parent, true);
  987. if ($category_parent['id_category'])
  988. {
  989. $category->id_parent = (int)$category_parent['id_category'];
  990. $category->level_depth = (int)$category_parent['level_depth'] + 1;
  991. }
  992. else
  993. {
  994. $category_to_create = new Category();
  995. $category_to_create->name = AdminImportController::createMultiLangField($category->parent);
  996. $category_to_create->active = 1;
  997. $category_link_rewrite = Tools::link_rewrite($category_to_create->name[$id_lang]);
  998. $category_to_create->link_rewrite = AdminImportController::createMultiLangField($category_link_rewrite);
  999. $category_to_create->id_parent = Configuration::get('PS_HOME_CATEGORY'); // Default parent is home for unknown category to create
  1000. if (($field_error = $category_to_create->validateFields(UNFRIENDLY_ERROR, true)) === true &&
  1001. ($lang_field_error = $category_to_create->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $category_to_create->add())
  1002. $category->id_parent = $category_to_create->id;
  1003. else
  1004. {
  1005. $this->errors[] = sprintf(
  1006. Tools::displayError('%1$s (ID: %2$s) cannot be saved'),
  1007. $category_to_create->name[$id_lang],
  1008. (isset($category_to_create->id) && !empty($category_to_create->id))? $category_to_create->id : 'null'
  1009. );
  1010. $this->errors[] = ($field_error !== true ? $field_error : '').(isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '').
  1011. Db::getInstance()->getMsgError();
  1012. }
  1013. }
  1014. }
  1015. if (isset($category->link_rewrite) && !empty($category->link_rewrite[$default_language_id]))
  1016. $valid_link = Validate::isLinkRewrite($category->link_rewrite[$default_language_id]);
  1017. else
  1018. $valid_link = false;
  1019. if (!Shop::isFeatureActive())
  1020. $category->id_shop_default = 1;
  1021. else
  1022. $category->id_shop_default = (int)Context::getContext()->shop->id;
  1023. $bak = $category->link_rewrite[$default_language_id];
  1024. if ((isset($category->link_rewrite) && empty($category->link_rewrite[$default_language_id])) || !$valid_link)
  1025. {
  1026. $category->link_rewrite = Tools::link_rewrite($category->name[$default_language_id]);
  1027. if ($category->link_rewrite == '')
  1028. {
  1029. $category->link_rewrite = 'friendly-url-autogeneration-failed';
  1030. $this->warnings[] = sprintf(Tools::displayError('URL rewriting failed to auto-generate a friendly URL for: %s'), $category->name[$default_language_id]);
  1031. }
  1032. $category->link_rewrite = AdminImportController::createMultiLangField($category->link_rewrite);
  1033. }
  1034. if (!$valid_link)
  1035. $this->warnings[] = sprintf(
  1036. Tools::displayError('Rewrite link for %1$s (ID: %2$s) was re-written as %3$s.'),
  1037. $bak,
  1038. (isset($info['id']) && !empty($info['id']))? $info['id'] : 'null',
  1039. $category->link_rewrite[$default_language_id]
  1040. );
  1041. $res = false;
  1042. if (($field_error = $category->validateFields(UNFRIENDLY_ERROR, true)) === true &&
  1043. ($lang_field_error = $category->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && empty($this->errors))
  1044. {
  1045. $category_already_created = Category::searchByNameAndParentCategoryId(
  1046. $id_lang,
  1047. $category->name[$id_lang],
  1048. $category->id_parent
  1049. );
  1050. // If category already in base, get id category back
  1051. if ($category_already_created['id_category'])
  1052. {
  1053. $cat_moved[$category->id] = (int)$category_already_created['id_category'];
  1054. $category->id = (int)$category_already_created['id_category'];
  1055. }
  1056. if ($category->id && $category->id == $category->id_parent)
  1057. {
  1058. $this->errors[] = Tools::displayError('A category cannot be its own parent');
  1059. continue;
  1060. }
  1061. /* No automatic nTree regeneration for import */
  1062. $category->doNotRegenerateNTree = true;
  1063. // If id category AND id category already in base, trying to update
  1064. $categories_home_root = array(Configuration::get('PS_ROOT_CATEGORY'), Configuration::get('PS_HOME_CATEGORY'));
  1065. if ($category->id && $category->categoryExists($category->id) && !in_array($category->id, $categories_home_root))
  1066. $res = $category->update();
  1067. if ($category->id == Configuration::get('PS_ROOT_CATEGORY'))
  1068. $this->errors[] = Tools::displayError('The root category cannot be modified.');
  1069. // If no id_category or update failed
  1070. $category->force_id = (bool)Tools::getValue('forceIDs');
  1071. if (!$res)
  1072. $res = $category->add();
  1073. }
  1074. //copying images of categories
  1075. if (isset($category->image) && !empty($category->image))
  1076. if (!(AdminImportController::copyImg($category->id, null, $category->image, 'categories', !Tools::getValue('regenerate'))))
  1077. $this->warnings[] = $category->image.' '.Tools::displayError('cannot be copied.');
  1078. // If both failed, mysql error
  1079. if (!$res)
  1080. {
  1081. $this->errors[] = sprintf(
  1082. Tools::displayError('%1$s (ID: %2$s) cannot be saved'),
  1083. (isset($info['name']) && !empty($info['name']))? Tools::safeOutput($info['name']) : 'No Name',
  1084. (isset($info['id']) && !empty($info['id']))? Tools::safeOutput($info['id']) : 'No ID'
  1085. );
  1086. $error_tmp = ($field_error !== true ? $field_error : '').(isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '').Db::getInstance()->getMsgError();
  1087. if ($error_tmp != '')
  1088. $this->errors[] = $error_tmp;
  1089. }
  1090. else
  1091. {
  1092. // Associate category to shop
  1093. if (Shop::isFeatureActive())
  1094. {
  1095. Db::getInstance()->execute('
  1096. DELETE FROM '._DB_PREFIX_.'category_shop
  1097. WHERE id_category = '.(int)$category->id
  1098. );
  1099. if (!Shop::isFeatureActive())
  1100. $info['shop'] = 1;
  1101. elseif (!isset($info['shop']) || empty($info['shop']))
  1102. $info['shop'] = implode($this->multiple_value_separator, Shop::getContextListShopID());
  1103. // Get shops for each attributes
  1104. $info['shop'] = explode($this->multiple_value_separator, $info['shop']);
  1105. foreach ($info['shop'] as $shop)
  1106. if (!empty($shop) && !is_numeric($shop))
  1107. $category->addShop(Shop::getIdByName($shop));
  1108. elseif (!empty($shop))
  1109. $category->addShop($shop);
  1110. }
  1111. }
  1112. }
  1113. /* Import has finished, we can regenerate the categories nested tree */
  1114. Category::regenerateEntireNtree();
  1115. $this->closeCsvFile($handle);
  1116. }
  1117. public function productImport()
  1118. {
  1119. $this->receiveTab();
  1120. $handle = $this->openCsvFile();
  1121. $default_language_id = (int)Configuration::get('PS_LANG_DEFAULT');
  1122. $id_lang = Language::getIdByIso(Tools::getValue('iso_lang'));
  1123. if (!Validate::isUnsignedId($id_lang))
  1124. $id_lang = $default_language_id;
  1125. AdminImportController::setLocale();
  1126. $shop_ids = Shop::getCompleteListOfShopsID();
  1127. for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, $this->separator); $current_line++)
  1128. {
  1129. if (Tools::getValue('convert'))
  1130. $line = $this->utf8EncodeArray($line);
  1131. $info = AdminImportController::getMaskedRow($line);
  1132. if (Tools::getValue('forceIDs') && isset($info['id']) && (int)$info['id'])
  1133. $product = new Product((int)$info['id']);
  1134. elseif (Tools::getValue('match_ref') && array_key_exists('reference', $info))
  1135. {
  1136. $datas = Db::getInstance()->getRow('
  1137. SELECT p.`id_product`
  1138. FROM `'._DB_PREFIX_.'product` p
  1139. '.Shop::addSqlAssociation('product', 'p').'
  1140. WHERE p.`reference` = "'.pSQL($info['reference']).'"
  1141. ');
  1142. if (isset($datas['id_product']) && $datas['id_product'])
  1143. $product = new Product((int)$datas['id_product']);
  1144. else
  1145. $product = new Product();
  1146. }
  1147. elseif (array_key_exists('id', $info) && (int)$info['id'] && Product::existsInDatabase((int)$info['id'], 'product'))
  1148. $product = new Product((int)$info['id']);
  1149. else
  1150. $product = new Product();
  1151. if (isset($product->id) && $product->id && Product::existsInDatabase((int)$product->id, 'product'))
  1152. {
  1153. $product->loadStockData();
  1154. $category_data = Product::getProductCategories((int)$product->id);
  1155. foreach ($category_data as $tmp)
  1156. $product->category[] = $tmp;
  1157. }
  1158. AdminImportController::setEntityDefaultValues($product);
  1159. AdminImportController::arrayWalk($info, array('AdminImportController', 'fillInfo'), $product);
  1160. if (!Shop::isFeatureActive())
  1161. $product->shop = 1;
  1162. elseif (!isset($product->shop) || empty($product->shop))
  1163. $product->shop = implode($this->multiple_value_separator, Shop::getContextListShopID());
  1164. if (!Shop::isFeatureActive())
  1165. $product->id_shop_default = 1;
  1166. else
  1167. $product->id_shop_default = (int)Context::getContext()->shop->id;
  1168. // link product to shops
  1169. $product->id_shop_list = array();
  1170. foreach (explode($this->multiple_value_separator, $product->shop) as $shop)
  1171. if (!empty($shop) && !is_numeric($shop))
  1172. $product->id_shop_list[] =

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