forked from PrestaShop/PrestaShop
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxmlLoader.php
More file actions
1320 lines (1146 loc) · 45.8 KB
/
xmlLoader.php
File metadata and controls
1320 lines (1146 loc) · 45.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* 2007-2015 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2015 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class InstallXmlLoader
{
/**
* @var InstallLanguages
*/
protected $language;
/**
* @var array List of languages stored as array(id_lang => iso)
*/
protected $languages = array();
/**
* @var array Store in cache all loaded XML files
*/
protected $cache_xml_entity = array();
/**
* @var array List of errors
*/
protected $errors = array();
protected $data_path;
protected $lang_path;
protected $img_path;
public $path_type;
protected $ids = array();
protected $primaries = array();
protected $delayed_inserts = array();
public function __construct()
{
$this->language = InstallLanguages::getInstance();
$this->setDefaultPath();
}
/**
* Set list of installed languages
*
* @param array $languages array(id_lang => iso)
*/
public function setLanguages(array $languages)
{
$this->languages = $languages;
}
public function setDefaultPath()
{
$this->path_type = 'common';
$this->data_path = _PS_INSTALL_DATA_PATH_.'xml/';
$this->lang_path = _PS_INSTALL_LANGS_PATH_;
$this->img_path = _PS_INSTALL_DATA_PATH_.'img/';
}
public function setFixturesPath($path = null)
{
if ($path === null) {
$path = _PS_INSTALL_FIXTURES_PATH_.'fashion/';
}
$this->path_type = 'fixture';
$this->data_path = $path.'data/';
$this->lang_path = $path.'langs/';
$this->img_path = $path.'img/';
}
/**
* Get list of errors
*
* @return array
*/
public function getErrors()
{
return $this->errors;
}
/**
* Add an error
*
* @param string $error
*/
public function setError($error)
{
$this->errors[] = $error;
}
/**
* Store an ID related to an entity and its identifier (E.g. we want to save that product with ID "ipod_nano" has the ID 1)
*
* @param string $entity
* @param string $identifier
* @param int $id
*/
public function storeId($entity, $identifier, $id)
{
$this->ids[$entity.':'.$identifier] = $id;
}
/**
* Retrieve an ID related to an entity and its identifier
*
* @param string $entity
* @param string $identifier
*/
public function retrieveId($entity, $identifier)
{
return isset($this->ids[$entity.':'.$identifier]) ? $this->ids[$entity.':'.$identifier] : 0;
}
public function getIds()
{
return $this->ids;
}
public function setIds($ids)
{
$this->ids = $ids;
}
public function getSortedEntities()
{
// Browse all XML files from data/xml directory
$entities = array();
$dependencies = array();
$fd = opendir($this->data_path);
while ($file = readdir($fd)) {
if (preg_match('#^(.+)\.xml$#', $file, $m)) {
$entity = $m[1];
$xml = $this->loadEntity($entity);
// Store entities dependencies (with field type="relation")
if ($xml->fields) {
foreach ($xml->fields->field as $field) {
if ($field['relation'] && $field['relation'] != $entity) {
if (!isset($dependencies[(string)$field['relation']])) {
$dependencies[(string)$field['relation']] = array();
}
$dependencies[(string)$field['relation']][] = $entity;
}
}
}
$entities[] = $entity;
}
}
closedir($fd);
// Sort entities to populate database in good order (E.g. zones before countries)
do {
$current = (isset($sort_entities)) ? $sort_entities : array();
$sort_entities = array();
foreach ($entities as $key => $entity) {
if (isset($dependencies[$entity])) {
$min = count($entities) - 1;
foreach ($dependencies[$entity] as $item) {
if (($key = array_search($item, $sort_entities)) !== false) {
$min = min($min, $key);
}
}
if ($min == 0) {
array_unshift($sort_entities, $entity);
} else {
array_splice($sort_entities, $min, 0, array($entity));
}
} else {
$sort_entities[] = $entity;
}
}
$entities = $sort_entities;
} while ($current != $sort_entities);
return $sort_entities;
}
/**
* Read all XML files from data folder and populate tables
*/
public function populateFromXmlFiles()
{
$entities = $this->getSortedEntities();
// Populate entities
foreach ($entities as $entity) {
$this->populateEntity($entity);
}
}
/**
* Populate an entity
*
* @param string $entity
*/
public function populateEntity($entity)
{
if (method_exists($this, 'populateEntity'.Tools::toCamelCase($entity))) {
$this->{'populateEntity'.Tools::toCamelCase($entity)}();
return;
}
if (substr($entity, 0, 1) == '.' || substr($entity, 0, 1) == '_') {
return;
}
$xml = $this->loadEntity($entity);
// Read list of fields
if (!is_object($xml) || !$xml->fields) {
throw new PrestashopInstallerException('List of fields not found for entity '.$entity);
}
if ($this->isMultilang($entity)) {
$multilang_columns = $this->getColumns($entity, true);
$xml_langs = array();
$default_lang = null;
foreach ($this->languages as $id_lang => $iso) {
if ($iso == $this->language->getLanguageIso()) {
$default_lang = $id_lang;
}
try {
$xml_langs[$id_lang] = $this->loadEntity($entity, $iso);
} catch (PrestashopInstallerException $e) {
$xml_langs[$id_lang] = null;
}
}
}
// Load all row for current entity and prepare data to be populated
foreach ($xml->entities->$entity as $node) {
$data = array();
$identifier = (string)$node['id'];
// Read attributes
foreach ($node->attributes() as $k => $v) {
if ($k != 'id') {
$data[$k] = (string)$v;
}
}
// Read cdatas
foreach ($node->children() as $child) {
$data[$child->getName()] = (string)$child;
}
// Load multilang data
$data_lang = array();
if ($this->isMultilang($entity)) {
$xpath_query = $entity.'[@id="'.$identifier.'"]';
foreach ($xml_langs as $id_lang => $xml_lang) {
if (!$xml_lang) {
continue;
}
if (($node_lang = $xml_lang->xpath($xpath_query)) || ($node_lang = $xml_langs[$default_lang]->xpath($xpath_query))) {
$node_lang = $node_lang[0];
foreach ($multilang_columns as $column => $is_text) {
$value = '';
if ($node_lang[$column]) {
$value = (string)$node_lang[$column];
}
if ($node_lang->$column) {
$value = (string)$node_lang->$column;
}
$data_lang[$column][$id_lang] = $value;
}
}
}
}
$data = $this->rewriteRelationedData($entity, $data);
if (method_exists($this, 'createEntity'.Tools::toCamelCase($entity))) {
// Create entity with custom method in current class
$method = 'createEntity'.Tools::toCamelCase($entity);
$this->$method($identifier, $data, $data_lang);
} else {
$this->createEntity($entity, $identifier, (string)$xml->fields['class'], $data, $data_lang);
}
if ($xml->fields['image']) {
if (method_exists($this, 'copyImages'.Tools::toCamelCase($entity))) {
$this->{'copyImages'.Tools::toCamelCase($entity)}($identifier, $data);
} else {
$this->copyImages($entity, $identifier, (string)$xml->fields['image'], $data);
}
}
}
$this->flushDelayedInserts();
unset($this->cache_xml_entity[$this->path_type][$entity]);
}
protected function getFallBackToDefaultLanguage($iso)
{
return file_exists($this->lang_path.$iso.'/data/') ? $iso : 'en';
}
/**
* Special case for "tag" entity
*/
public function populateEntityTag()
{
foreach ($this->languages as $id_lang => $iso) {
if (!file_exists($this->lang_path.$this->getFallBackToDefaultLanguage($iso).'/data/tag.xml')) {
continue;
}
$xml = $this->loadEntity('tag', $this->getFallBackToDefaultLanguage($iso));
$tags = array();
foreach ($xml->tag as $tag_node) {
$products = trim((string)$tag_node['products']);
if (!$products) {
continue;
}
foreach (explode(',', $products) as $product) {
$product = trim($product);
$product_id = $this->retrieveId('product', $product);
if (!isset($tags[$product_id])) {
$tags[$product_id] = array();
}
$tags[$product_id][] = trim((string)$tag_node['name']);
}
}
foreach ($tags as $id_product => $tag_list) {
Tag::addTags($id_lang, $id_product, $tag_list);
}
}
}
/**
* Load an entity XML file
*
* @param string $entity
* @return SimpleXMLElement
*/
protected function loadEntity($entity, $iso = null)
{
if (!isset($this->cache_xml_entity[$this->path_type][$entity][$iso])) {
if (substr($entity, 0, 1) == '.' || substr($entity, 0, 1) == '_') {
return;
}
$path = $this->data_path.$entity.'.xml';
if ($iso) {
$path = $this->lang_path.$this->getFallBackToDefaultLanguage($iso).'/data/'.$entity.'.xml';
}
if (!file_exists($path)) {
throw new PrestashopInstallerException('XML data file '.$entity.'.xml not found');
}
$this->cache_xml_entity[$this->path_type][$entity][$iso] = @simplexml_load_file($path, 'InstallSimplexmlElement');
if (!$this->cache_xml_entity[$this->path_type][$entity][$iso]) {
throw new PrestashopInstallerException('XML data file '.$entity.'.xml invalid');
}
}
return $this->cache_xml_entity[$this->path_type][$entity][$iso];
}
/**
* Check fields related to an other entity, and replace their values by the ID created by the other entity
*
* @param string $entity
* @param array $data
*/
protected function rewriteRelationedData($entity, array $data)
{
$xml = $this->loadEntity($entity);
foreach ($xml->fields->field as $field) {
if ($field['relation']) {
$id = $this->retrieveId((string)$field['relation'], $data[(string)$field['name']]);
if (!$id && $data[(string)$field['name']] && is_numeric($data[(string)$field['name']])) {
$id = $data[(string)$field['name']];
}
$data[(string)$field['name']] = $id;
}
}
return $data;
}
public function flushDelayedInserts()
{
foreach ($this->delayed_inserts as $entity => $queries) {
$type = Db::INSERT_IGNORE;
if ($entity == 'access') {
$type = Db::REPLACE;
}
if (!Db::getInstance()->insert($entity, $queries, false, true, $type)) {
$this->setError($this->language->l('An SQL error occurred for entity <i>%1$s</i>: <i>%2$s</i>', $entity, Db::getInstance()->getMsgError()));
}
unset($this->delayed_inserts[$entity]);
}
}
/**
* Create a simple entity with all its data and lang data
* If a methode createEntity$entity exists, use it. Else if $classname is given, use it. Else do a simple insert in database.
*
* @param string $entity
* @param string $identifier
* @param string $classname
* @param array $data
* @param array $data_lang
*/
public function createEntity($entity, $identifier, $classname, array $data, array $data_lang = array())
{
$xml = $this->loadEntity($entity);
if ($classname) {
// Create entity with ObjectModel class
$object = new $classname();
$object->hydrate($data);
if ($data_lang) {
$object->hydrate($data_lang);
}
$object->add(true, (isset($xml->fields['null'])) ? true : false);
$entity_id = $object->id;
unset($object);
} else {
// Generate primary key manually
$primary = '';
$entity_id = 0;
if (!$xml->fields['primary']) {
$primary = 'id_'.$entity;
} elseif (strpos((string)$xml->fields['primary'], ',') === false) {
$primary = (string)$xml->fields['primary'];
}
unset($xml);
if ($primary) {
$entity_id = $this->generatePrimary($entity, $primary);
$data[$primary] = $entity_id;
}
// Store INSERT queries in order to optimize install with grouped inserts
$this->delayed_inserts[$entity][] = array_map('pSQL', $data);
if ($data_lang) {
$real_data_lang = array();
foreach ($data_lang as $field => $list) {
foreach ($list as $id_lang => $value) {
$real_data_lang[$id_lang][$field] = $value;
}
}
foreach ($real_data_lang as $id_lang => $insert_data_lang) {
$insert_data_lang['id_'.$entity] = $entity_id;
$insert_data_lang['id_lang'] = $id_lang;
$this->delayed_inserts[$entity.'_lang'][] = array_map('pSQL', $insert_data_lang);
}
// Store INSERT queries for _shop associations
$entity_asso = Shop::getAssoTable($entity);
if ($entity_asso !== false && $entity_asso['type'] == 'shop') {
$this->delayed_inserts[$entity.'_shop'][] = array(
'id_shop' => 1,
'id_'.$entity => $entity_id,
);
}
}
}
$this->storeId($entity, $identifier, $entity_id);
}
public function createEntityConfiguration($identifier, array $data, array $data_lang)
{
if (Db::getInstance()->getValue('SELECT id_configuration FROM '._DB_PREFIX_.'configuration WHERE name = \''.pSQL($data['name']).'\'')) {
return;
}
$entity = 'configuration';
$entity_id = $this->generatePrimary($entity, 'id_configuration');
$data['id_configuration'] = $entity_id;
// Store INSERT queries in order to optimize install with grouped inserts
$this->delayed_inserts[$entity][] = array_map('pSQL', $data);
if ($data_lang) {
$real_data_lang = array();
foreach ($data_lang as $field => $list) {
foreach ($list as $id_lang => $value) {
$real_data_lang[$id_lang][$field] = $value;
}
}
foreach ($real_data_lang as $id_lang => $insert_data_lang) {
$insert_data_lang['id_'.$entity] = $entity_id;
$insert_data_lang['id_lang'] = $id_lang;
$this->delayed_inserts[$entity.'_lang'][] = array_map('pSQL', $insert_data_lang);
}
}
$this->storeId($entity, $identifier, $entity_id);
}
public function createEntityStockAvailable($identifier, array $data, array $data_lang)
{
$stock_available = new StockAvailable();
$stock_available->updateQuantity($data['id_product'], $data['id_product_attribute'], $data['quantity'], $data['id_shop']);
}
public function createEntityTab($identifier, array $data, array $data_lang)
{
static $position = array();
$entity = 'tab';
$xml = $this->loadEntity($entity);
if (!isset($position[$data['id_parent']])) {
$position[$data['id_parent']] = 0;
}
$data['position'] = $position[$data['id_parent']]++;
// Generate primary key manually
$primary = '';
$entity_id = 0;
if (!$xml->fields['primary']) {
$primary = 'id_'.$entity;
} elseif (strpos((string)$xml->fields['primary'], ',') === false) {
$primary = (string)$xml->fields['primary'];
}
if ($primary) {
$entity_id = $this->generatePrimary($entity, $primary);
$data[$primary] = $entity_id;
}
// Store INSERT queries in order to optimize install with grouped inserts
$this->delayed_inserts[$entity][] = array_map('pSQL', $data);
if ($data_lang) {
$real_data_lang = array();
foreach ($data_lang as $field => $list) {
foreach ($list as $id_lang => $value) {
$real_data_lang[$id_lang][$field] = $value;
}
}
foreach ($real_data_lang as $id_lang => $insert_data_lang) {
$insert_data_lang['id_'.$entity] = $entity_id;
$insert_data_lang['id_lang'] = $id_lang;
$this->delayed_inserts[$entity.'_lang'][] = array_map('pSQL', $insert_data_lang);
}
}
$this->storeId($entity, $identifier, $entity_id);
}
public function generatePrimary($entity, $primary)
{
if (!isset($this->primaries[$entity])) {
$this->primaries[$entity] = (int)Db::getInstance()->getValue('SELECT '.$primary.' FROM '._DB_PREFIX_.$entity.' ORDER BY '.$primary.' DESC');
}
return ++$this->primaries[$entity];
}
public function copyImages($entity, $identifier, $path, array $data, $extension = 'jpg')
{
// Get list of image types
$reference = array(
'product' => 'products',
'category' => 'categories',
'manufacturer' => 'manufacturers',
'supplier' => 'suppliers',
'scene' => 'scenes',
'store' => 'stores',
);
$types = array();
if (isset($reference[$entity])) {
$types = ImageType::getImagesTypes($reference[$entity]);
}
// For each path copy images
$path = array_map('trim', explode(',', $path));
foreach ($path as $p) {
$from_path = $this->img_path.$p.'/';
$dst_path = _PS_IMG_DIR_.$p.'/';
$entity_id = $this->retrieveId($entity, $identifier);
if (!@copy($from_path.$identifier.'.'.$extension, $dst_path.$entity_id.'.'.$extension)) {
$this->setError($this->language->l('Cannot create image "%1$s" for entity "%2$s"', $identifier, $entity));
return;
}
foreach ($types as $type) {
$origin_file = $from_path.$identifier.'-'.$type['name'].'.'.$extension;
$target_file = $dst_path.$entity_id.'-'.$type['name'].'.'.$extension;
// Test if dest folder is writable
if (!is_writable(dirname($target_file))) {
$this->setError($this->language->l('Cannot create image "%1$s" (bad permissions on folder "%2$s")', $identifier.'-'.$type['name'], dirname($target_file)));
}
// If a file named folder/entity-type.extension exists just copy it, this is an optimisation in order to prevent to much resize
elseif (file_exists($origin_file)) {
if (!@copy($origin_file, $target_file)) {
$this->setError($this->language->l('Cannot create image "%s"', $identifier.'-'.$type['name']));
}
@chmod($target_file, 0644);
}
// Resize the image if no cache was prepared in fixtures
elseif (!ImageManager::resize($from_path.$identifier.'.'.$extension, $target_file, $type['width'], $type['height'])) {
$this->setError($this->language->l('Cannot create image "%1$s" for entity "%2$s"', $identifier.'-'.$type['name'], $entity));
}
}
}
Image::moveToNewFileSystem();
}
public function copyImagesScene($identifier, array $data)
{
$this->copyImages('scene', $identifier, 'scenes', $data);
$from_path = $this->img_path.'scenes/thumbs/';
$dst_path = _PS_IMG_DIR_.'scenes/thumbs/';
$entity_id = $this->retrieveId('scene', $identifier);
if (!@copy($from_path.$identifier.'-m_scene_default.jpg', $dst_path.$entity_id.'-m_scene_default.jpg')) {
$this->setError($this->language->l('Cannot create image "%1$s" for entity "%2$s"', $identifier, 'scene'));
return;
}
}
public function copyImagesOrderState($identifier, array $data)
{
$this->copyImages('order_state', $identifier, 'os', $data, 'gif');
}
public function copyImagesTab($identifier, array $data)
{
$from_path = $this->img_path.'t/';
$dst_path = _PS_IMG_DIR_.'t/';
if (file_exists($from_path.$data['class_name'].'.gif') && !file_exists($dst_path.$data['class_name'].'.gif')) {
//test if file exist in install dir and if do not exist in dest folder.
if (!@copy($from_path.$data['class_name'].'.gif', $dst_path.$data['class_name'].'.gif')) {
$this->setError($this->language->l('Cannot create image "%1$s" for entity "%2$s"', $identifier, 'tab'));
return;
}
}
}
public function copyImagesImage($identifier)
{
$path = $this->img_path.'p/';
$image = new Image($this->retrieveId('image', $identifier));
$dst_path = $image->getPathForCreation();
if (!@copy($path.$identifier.'.jpg', $dst_path.'.'.$image->image_format)) {
$this->setError($this->language->l('Cannot create image "%1$s" for entity "%2$s"', $identifier, 'product'));
return;
}
@chmod($dst_path.'.'.$image->image_format, 0644);
$types = ImageType::getImagesTypes('products');
foreach ($types as $type) {
$origin_file = $path.$identifier.'-'.$type['name'].'.jpg';
$target_file = $dst_path.'-'.$type['name'].'.'.$image->image_format;
// Test if dest folder is writable
if (!is_writable(dirname($target_file))) {
$this->setError($this->language->l('Cannot create image "%1$s" (bad permissions on folder "%2$s")', $identifier.'-'.$type['name'], dirname($target_file)));
}
// If a file named folder/entity-type.jpg exists just copy it, this is an optimisation in order to prevent to much resize
elseif (file_exists($origin_file)) {
if (!@copy($origin_file, $target_file)) {
$this->setError($this->language->l('Cannot create image "%1$s" for entity "%2$s"', $identifier.'-'.$type['name'], 'product'));
}
@chmod($target_file, 0644);
}
// Resize the image if no cache was prepared in fixtures
elseif (!ImageManager::resize($path.$identifier.'.jpg', $target_file, $type['width'], $type['height'])) {
$this->setError($this->language->l('Cannot create image "%1$s" for entity "%2$s"', $identifier.'-'.$type['name'], 'product'));
}
}
}
public function getTables()
{
static $tables = null;
if (is_null($tables)) {
$tables = array();
foreach (Db::getInstance()->executeS('SHOW TABLES') as $row) {
$table = current($row);
if (preg_match('#^'._DB_PREFIX_.'(.+?)(_lang)?$#i', $table, $m)) {
$tables[$m[1]] = (isset($m[2]) && $m[2]) ? true : false;
}
}
}
return $tables;
}
public function hasElements($table)
{
return (bool)Db::getInstance()->getValue('SELECT COUNT(*) FROM '._DB_PREFIX_.$table);
}
public function getColumns($table, $multilang = false, array $exclude = array())
{
static $columns = array();
if ($multilang) {
return ($this->isMultilang($table)) ? $this->getColumns($table.'_lang', false, array('id_'.$table)) : array();
}
if (!isset($columns[$table])) {
$columns[$table] = array();
$sql = 'SHOW COLUMNS FROM `'._DB_PREFIX_.bqSQL($table).'`';
foreach (Db::getInstance()->executeS($sql) as $row) {
$columns[$table][$row['Field']] = $this->checkIfTypeIsText($row['Type']);
}
}
$exclude = array_merge(array('id_'.$table, 'date_add', 'date_upd', 'deleted', 'id_lang'), $exclude);
$list = array();
foreach ($columns[$table] as $k => $v) {
if (!in_array($k, $exclude)) {
$list[$k] = $v;
}
}
return $list;
}
public function getClasses($path = null)
{
static $cache = null;
if (!is_null($cache)) {
return $cache;
}
$dir = $path;
if (is_null($dir)) {
$dir = _PS_CLASS_DIR_;
}
$classes = array();
foreach (scandir($dir) as $file) {
if ($file[0] != '.' && $file != 'index.php') {
if (is_dir($dir.$file)) {
$classes = array_merge($classes, $this->getClasses($dir.$file.'/'));
} elseif (preg_match('#^(.+)\.php$#', $file, $m)) {
$classes[] = $m[1];
}
}
}
sort($classes);
if (is_null($path)) {
$cache = $classes;
}
return $classes;
}
public function checkIfTypeIsText($type)
{
if (preg_match('#^(longtext|text|tinytext)#i', $type)) {
return true;
}
if (preg_match('#^varchar\(([0-9]+)\)$#i', $type, $m)) {
return intval($m[1]) >= 64 ? true : false;
}
return false;
}
public function isMultilang($entity)
{
$tables = $this->getTables();
return isset($tables[$entity]) && $tables[$entity];
}
public function entityExists($entity)
{
return file_exists($this->data_path.$entity.'.xml');
}
public function getEntitiesList()
{
$entities = array();
foreach (scandir($this->data_path) as $file) {
if ($file[0] != '.' && preg_match('#^(.+)\.xml$#', $file, $m)) {
$entities[] = $m[1];
}
}
return $entities;
}
public function getEntityInfo($entity)
{
$info = array(
'config' => array(
'id' => '',
'primary' => '',
'class' => '',
'sql' => '',
'ordersql' => '',
'image' => '',
'null' => '',
),
'fields' => array(),
);
if (!$this->entityExists($entity)) {
return $info;
}
$xml = @simplexml_load_file($this->data_path.$entity.'.xml', 'InstallSimplexmlElement');
if (!$xml) {
return $info;
}
if ($xml->fields['id']) {
$info['config']['id'] = (string)$xml->fields['id'];
}
if ($xml->fields['primary']) {
$info['config']['primary'] = (string)$xml->fields['primary'];
}
if ($xml->fields['class']) {
$info['config']['class'] = (string)$xml->fields['class'];
}
if ($xml->fields['sql']) {
$info['config']['sql'] = (string)$xml->fields['sql'];
}
if ($xml->fields['ordersql']) {
$info['config']['ordersql'] = (string)$xml->fields['ordersql'];
}
if ($xml->fields['null']) {
$info['config']['null'] = (string)$xml->fields['null'];
}
if ($xml->fields['image']) {
$info['config']['image'] = (string)$xml->fields['image'];
}
foreach ($xml->fields->field as $field) {
$column = (string)$field['name'];
$info['fields'][$column] = array();
if (isset($field['relation'])) {
$info['fields'][$column]['relation'] = (string)$field['relation'];
}
}
return $info;
}
public function getDependencies()
{
$entities = array();
foreach ($this->getEntitiesList() as $entity) {
$entities[$entity] = $this->getEntityInfo($entity);
}
$dependencies = array();
foreach ($entities as $entity => $info) {
foreach ($info['fields'] as $field => $info_field) {
if (isset($info_field['relation']) && $info_field['relation'] != $entity) {
if (!isset($dependencies[$info_field['relation']])) {
$dependencies[$info_field['relation']] = array();
}
$dependencies[$info_field['relation']][] = $entity;
}
}
}
return $dependencies;
}
public function generateEntitySchema($entity, array $fields, array $config)
{
if ($this->entityExists($entity)) {
$xml = $this->loadEntity($entity);
} else {
$xml = new InstallSimplexmlElement('<entity_'.$entity.' />');
}
unset($xml->fields);
// Fill <fields> attributes (config)
$xml_fields = $xml->addChild('fields');
foreach ($config as $k => $v) {
if ($v) {
$xml_fields[$k] = $v;
}
}
// Create list of fields
foreach ($fields as $column => $info) {
$field = $xml_fields->addChild('field');
$field['name'] = $column;
if (isset($info['relation'])) {
$field['relation'] = $info['relation'];
}
}
// Recreate entities nodes, in order to have the <entities> node after the <fields> node
$store_entities = clone $xml->entities;
unset($xml->entities);
$xml->addChild('entities', $store_entities);
$xml->asXML($this->data_path.$entity.'.xml');
}
/**
* ONLY FOR DEVELOPMENT PURPOSE
*/
public function generateAllEntityFiles()
{
$entities = array();
foreach ($this->getEntitiesList() as $entity) {
$entities[$entity] = $this->getEntityInfo($entity);
}
$this->generateEntityFiles($entities);
}
/**
* ONLY FOR DEVELOPMENT PURPOSE
*/
public function generateEntityFiles($entities)
{
$dependencies = $this->getDependencies();
// Sort entities to populate database in good order (E.g. zones before countries)
do {
$current = (isset($sort_entities)) ? $sort_entities : array();
$sort_entities = array();
foreach ($entities as $entity) {
if (isset($dependencies[$entity])) {
$min = count($entities) - 1;
foreach ($dependencies[$entity] as $item) {
if (($key = array_search($item, $sort_entities)) !== false) {
$min = min($min, $key);
}
}
if ($min == 0) {
array_unshift($sort_entities, $entity);
} else {
array_splice($sort_entities, $min, 0, array($entity));
}
} else {
$sort_entities[] = $entity;
}
}
$entities = $sort_entities;
} while ($current != $sort_entities);
foreach ($sort_entities as $entity) {
$this->generateEntityContent($entity);
}
}
public function generateEntityContent($entity)
{
$xml = $this->loadEntity($entity);
if (method_exists($this, 'getEntityContents'.Tools::toCamelCase($entity))) {
$content = $this->{'getEntityContents'.Tools::toCamelCase($entity)}($entity);
} else {
$content = $this->getEntityContents($entity);
}
unset($xml->entities);
$entities = $xml->addChild('entities');
$this->createXmlEntityNodes($entity, $content['nodes'], $entities);
$xml->asXML($this->data_path.$entity.'.xml');
// Generate multilang XML files