forked from Qloapps/QloApps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathObjectModel.php
2023 lines (1777 loc) · 71.4 KB
/
ObjectModel.php
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-2017 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 [email protected] 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 <[email protected]>
* @copyright 2007-2017 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
abstract class ObjectModelCore implements Core_Foundation_Database_EntityInterface
{
/**
* List of field types
*/
const TYPE_INT = 1;
const TYPE_BOOL = 2;
const TYPE_STRING = 3;
const TYPE_FLOAT = 4;
const TYPE_DATE = 5;
const TYPE_HTML = 6;
const TYPE_NOTHING = 7;
const TYPE_SQL = 8;
/**
* List of data to format
*/
const FORMAT_COMMON = 1;
const FORMAT_LANG = 2;
const FORMAT_SHOP = 3;
/**
* List of association types
*/
const HAS_ONE = 1;
const HAS_MANY = 2;
/** @var int Object ID */
public $id;
/** @var int Language ID */
protected $id_lang = null;
/** @var int Shop ID */
protected $id_shop = null;
/** @var array List of shop IDs */
public $id_shop_list = array();
/** @var bool */
protected $get_shop_from_context = true;
/** @var array|null Holds required fields for each ObjectModel class */
protected static $fieldsRequiredDatabase = null;
/**
* @deprecated 1.5.0.1 Define property using $definition['table'] property instead.
* @var string
*/
protected $table;
/**
* @deprecated 1.5.0.1 Define property using $definition['table'] property instead.
* @var string
*/
protected $identifier;
/**
* @deprecated 1.5.0.1 Define property using $definition['table'] property instead.
* @var array
*/
protected $fieldsRequired = array();
/**
* @deprecated 1.5.0.1 Define property using $definition['table'] property instead.
* @var array
*/
protected $fieldsSize = array();
/**
* @deprecated 1.5.0.1 Define property using $definition['table'] property instead.
* @var array
*/
protected $fieldsValidate = array();
/**
* @deprecated 1.5.0.1 Define property using $definition['table'] property instead.
* @var array
*/
protected $fieldsRequiredLang = array();
/**
* @deprecated 1.5.0.1 Define property using $definition['table'] property instead.
* @var array
*/
protected $fieldsSizeLang = array();
/**
* @deprecated 1.5.0.1 Define property using $definition['table'] property instead.
* @var array
*/
protected $fieldsValidateLang = array();
/**
* @deprecated 1.5.0.1
* @var array
*/
protected $tables = array();
/** @var array Tables */
protected $webserviceParameters = array();
/** @var string Path to image directory. Used for image deletion. */
protected $image_dir = null;
/** @var string image name used for image deletion. */ //by webkul
protected $image_name = null;
/** @var String file type of image files. */
protected $image_format = 'jpg';
/**
* @var array Contains object definition
* @since 1.5.0.1
*/
public static $definition = array();
/**
* Holds compiled definitions of each ObjectModel class.
* Values are assigned during object initialization.
*
* @var array
*/
protected static $loaded_classes = array();
/** @var array Contains current object definition. */
protected $def;
/** @var array|null List of specific fields to update (all fields if null). */
protected $update_fields = null;
/** @var Db An instance of the db in order to avoid calling Db::getInstance() thousands of times. */
protected static $db = false;
/** @var bool Enables to define an ID before adding object. */
public $force_id = false;
/**
* @var bool If true, objects are cached in memory.
*/
protected static $cache_objects = true;
public static function getRepositoryClassName()
{
return null;
}
/**
* Returns object validation rules (fields validity)
*
* @param string $class Child class name for static use (optional)
*
* @return array Validation rules (fields validity)
*/
public static function getValidationRules($class = __CLASS__)
{
$object = new $class();
return array(
'required' => $object->fieldsRequired,
'size' => $object->fieldsSize,
'validate' => $object->fieldsValidate,
'requiredLang' => $object->fieldsRequiredLang,
'sizeLang' => $object->fieldsSizeLang,
'validateLang' => $object->fieldsValidateLang,
);
}
/**
* Builds the object
*
* @param int|null $id If specified, loads and existing object from DB (optional).
* @param int|null $id_lang Required if object is multilingual (optional).
* @param int|null $id_shop ID shop for objects with multishop tables.
*
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function __construct($id = null, $id_lang = null, $id_shop = null)
{
$class_name = get_class($this);
if (!isset(ObjectModel::$loaded_classes[$class_name])) {
$this->def = ObjectModel::getDefinition($class_name);
$this->setDefinitionRetrocompatibility();
if (!Validate::isTableOrIdentifier($this->def['primary']) || !Validate::isTableOrIdentifier($this->def['table'])) {
throw new PrestaShopException('Identifier or table format not valid for class '.$class_name);
}
ObjectModel::$loaded_classes[$class_name] = get_object_vars($this);
} else {
foreach (ObjectModel::$loaded_classes[$class_name] as $key => $value) {
$this->{$key} = $value;
}
}
if ($id_lang !== null) {
$this->id_lang = (Language::getLanguage($id_lang) !== false) ? $id_lang : Configuration::get('PS_LANG_DEFAULT');
}
if ($id_shop && $this->isMultishop()) {
$this->id_shop = (int)$id_shop;
$this->get_shop_from_context = false;
}
if ($this->isMultishop() && !$this->id_shop) {
$this->id_shop = Context::getContext()->shop->id;
}
if ($id) {
$entity_mapper = Adapter_ServiceLocator::get("Adapter_EntityMapper");
$entity_mapper->load($id, $id_lang, $this, $this->def, $this->id_shop, self::$cache_objects);
}
}
/**
* Prepare fields for ObjectModel class (add, update)
* All fields are verified (pSQL, intval, ...)
*
* @return array All object fields
* @throws PrestaShopException
*/
public function getFields()
{
$this->validateFields();
$fields = $this->formatFields(self::FORMAT_COMMON);
// For retro compatibility
if (Shop::isTableAssociated($this->def['table'])) {
$fields = array_merge($fields, $this->getFieldsShop());
}
// Ensure that we get something to insert
if (!$fields && isset($this->id) && Validate::isUnsignedId($this->id)) {
$fields[$this->def['primary']] = $this->id;
}
return $fields;
}
/**
* Prepare fields for multishop
* Fields are not validated here, we consider they are already validated in getFields() method,
* this is not the best solution but this is the only one possible for retro compatibility.
*
* @since 1.5.0.1
* @return array All object fields
*/
public function getFieldsShop()
{
$fields = $this->formatFields(self::FORMAT_SHOP);
if (!$fields && isset($this->id) && Validate::isUnsignedId($this->id)) {
$fields[$this->def['primary']] = $this->id;
}
return $fields;
}
/**
* Prepare multilang fields
*
* @since 1.5.0.1
*
* @return array
* @throws PrestaShopException
*/
public function getFieldsLang()
{
// Backward compatibility
if (method_exists($this, 'getTranslationsFieldsChild')) {
return $this->getTranslationsFieldsChild();
}
$this->validateFieldsLang();
$is_lang_multishop = $this->isLangMultishop();
$fields = array();
if ($this->id_lang === null) {
foreach (Language::getIDs(false) as $id_lang) {
$fields[$id_lang] = $this->formatFields(self::FORMAT_LANG, $id_lang);
$fields[$id_lang]['id_lang'] = $id_lang;
if ($this->id_shop && $is_lang_multishop) {
$fields[$id_lang]['id_shop'] = (int)$this->id_shop;
}
}
} else {
$fields = array($this->id_lang => $this->formatFields(self::FORMAT_LANG, $this->id_lang));
$fields[$this->id_lang]['id_lang'] = $this->id_lang;
if ($this->id_shop && $is_lang_multishop) {
$fields[$this->id_lang]['id_shop'] = (int)$this->id_shop;
}
}
return $fields;
}
/**
* Formats values of each fields.
*
* @since 1.5.0.1
* @param int $type FORMAT_COMMON or FORMAT_LANG or FORMAT_SHOP
* @param int $id_lang If this parameter is given, only take lang fields
*
* @return array
*/
protected function formatFields($type, $id_lang = null)
{
$fields = array();
// Set primary key in fields
if (isset($this->id)) {
$fields[$this->def['primary']] = $this->id;
}
foreach ($this->def['fields'] as $field => $data) {
// Only get fields we need for the type
// E.g. if only lang fields are filtered, ignore fields without lang => true
if (($type == self::FORMAT_LANG && empty($data['lang']))
|| ($type == self::FORMAT_SHOP && empty($data['shop']))
|| ($type == self::FORMAT_COMMON && ((!empty($data['shop']) && $data['shop'] != 'both') || !empty($data['lang'])))) {
continue;
}
if (is_array($this->update_fields)) {
if ((!empty($data['lang']) || (!empty($data['shop']) && $data['shop'] != 'both')) && (empty($this->update_fields[$field]) || ($type == self::FORMAT_LANG && empty($this->update_fields[$field][$id_lang])))) {
continue;
}
}
// Get field value, if value is multilang and field is empty, use value from default lang
$value = $this->$field;
if ($type == self::FORMAT_LANG && $id_lang && is_array($value)) {
if (!empty($value[$id_lang])) {
$value = $value[$id_lang];
} elseif (!empty($data['required'])) {
$value = $value[Configuration::get('PS_LANG_DEFAULT')];
} else {
$value = '';
}
}
$purify = (isset($data['validate']) && Tools::strtolower($data['validate']) == 'iscleanhtml') ? true : false;
// Format field value
$fields[$field] = ObjectModel::formatValue($value, $data['type'], false, $purify, !empty($data['allow_null']));
}
return $fields;
}
/**
* Formats a value
*
* @param mixed $value
* @param int $type
* @param bool $with_quotes
* @param bool $purify
* @param bool $allow_null
* @return mixed
*/
public static function formatValue($value, $type, $with_quotes = false, $purify = true, $allow_null = false)
{
if ($allow_null && $value === null) {
return array('type' => 'sql', 'value' => 'NULL');
}
switch ($type) {
case self::TYPE_INT:
return (int)$value;
case self::TYPE_BOOL:
return (int)$value;
case self::TYPE_FLOAT:
return (float)str_replace(',', '.', $value);
case self::TYPE_DATE:
if (!$value) {
return '0000-00-00';
}
if ($with_quotes) {
return '\''.pSQL($value).'\'';
}
return pSQL($value);
case self::TYPE_HTML:
if ($purify) {
$value = Tools::purifyHTML($value);
}
if ($with_quotes) {
return '\''.pSQL($value, true).'\'';
}
return pSQL($value, true);
case self::TYPE_SQL:
if ($with_quotes) {
return '\''.pSQL($value, true).'\'';
}
return pSQL($value, true);
case self::TYPE_NOTHING:
return $value;
case self::TYPE_STRING:
default :
if ($with_quotes) {
return '\''.pSQL($value).'\'';
}
return pSQL($value);
}
}
/**
* Saves current object to database (add or update)
*
* @param bool $null_values
* @param bool $auto_date
*
* @return bool Insertion result
* @throws PrestaShopException
*/
public function save($null_values = false, $auto_date = true)
{
return (int)$this->id > 0 ? $this->update($null_values) : $this->add($auto_date, $null_values);
}
/**
* Adds current object to the database
*
* @param bool $auto_date
* @param bool $null_values
*
* @return bool Insertion result
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function add($auto_date = true, $null_values = false)
{
if (isset($this->id) && !$this->force_id) {
unset($this->id);
}
// @hook actionObject*AddBefore
Hook::exec('actionObjectAddBefore', array('object' => $this));
Hook::exec('actionObject'.get_class($this).'AddBefore', array('object' => $this));
// Automatically fill dates
if ($auto_date && property_exists($this, 'date_add')) {
$this->date_add = date('Y-m-d H:i:s');
}
if ($auto_date && property_exists($this, 'date_upd')) {
$this->date_upd = date('Y-m-d H:i:s');
}
if (Shop::isTableAssociated($this->def['table'])) {
$id_shop_list = Shop::getContextListShopID();
if (count($this->id_shop_list) > 0) {
$id_shop_list = $this->id_shop_list;
}
}
// Database insertion
if (Shop::checkIdShopDefault($this->def['table'])) {
$this->id_shop_default = (in_array(Configuration::get('PS_SHOP_DEFAULT'), $id_shop_list) == true) ? Configuration::get('PS_SHOP_DEFAULT') : min($id_shop_list);
}
if (!$result = Db::getInstance()->insert($this->def['table'], $this->getFields(), $null_values)) {
return false;
}
// Get object id in database
$this->id = Db::getInstance()->Insert_ID();
// Database insertion for multishop fields related to the object
if (Shop::isTableAssociated($this->def['table'])) {
$fields = $this->getFieldsShop();
$fields[$this->def['primary']] = (int)$this->id;
foreach ($id_shop_list as $id_shop) {
$fields['id_shop'] = (int)$id_shop;
$result &= Db::getInstance()->insert($this->def['table'].'_shop', $fields, $null_values);
}
}
if (!$result) {
return false;
}
// Database insertion for multilingual fields related to the object
if (!empty($this->def['multilang'])) {
$fields = $this->getFieldsLang();
if ($fields && is_array($fields)) {
$shops = Shop::getCompleteListOfShopsID();
$asso = Shop::getAssoTable($this->def['table'].'_lang');
foreach ($fields as $field) {
foreach (array_keys($field) as $key) {
if (!Validate::isTableOrIdentifier($key)) {
throw new PrestaShopException('key '.$key.' is not table or identifier');
}
}
$field[$this->def['primary']] = (int)$this->id;
if ($asso !== false && $asso['type'] == 'fk_shop') {
foreach ($shops as $id_shop) {
$field['id_shop'] = (int)$id_shop;
$result &= Db::getInstance()->insert($this->def['table'].'_lang', $field);
}
} else {
$result &= Db::getInstance()->insert($this->def['table'].'_lang', $field);
}
}
}
}
// @hook actionObject*AddAfter
Hook::exec('actionObjectAddAfter', array('object' => $this));
Hook::exec('actionObject'.get_class($this).'AddAfter', array('object' => $this));
return $result;
}
/**
* Takes current object ID, gets its values from database,
* saves them in a new row and loads newly saved values as a new object.
*
* @return ObjectModel|false
* @throws PrestaShopDatabaseException
*/
public function duplicateObject()
{
$definition = ObjectModel::getDefinition($this);
$res = Db::getInstance()->getRow('
SELECT *
FROM `'._DB_PREFIX_.bqSQL($definition['table']).'`
WHERE `'.bqSQL($definition['primary']).'` = '.(int)$this->id
);
if (!$res) {
return false;
}
unset($res[$definition['primary']]);
foreach ($res as $field => &$value) {
if (isset($definition['fields'][$field])) {
$value = ObjectModel::formatValue($value, $definition['fields'][$field]['type'], false, true,
!empty($definition['fields'][$field]['allow_null']));
}
}
if (!Db::getInstance()->insert($definition['table'], $res)) {
return false;
}
$object_id = Db::getInstance()->Insert_ID();
if (isset($definition['multilang']) && $definition['multilang']) {
$result = Db::getInstance()->executeS('
SELECT *
FROM `'._DB_PREFIX_.bqSQL($definition['table']).'_lang`
WHERE `'.bqSQL($definition['primary']).'` = '.(int)$this->id);
if (!$result) {
return false;
}
foreach ($result as &$row) {
foreach ($row as $field => &$value) {
if (isset($definition['fields'][$field])) {
$value = ObjectModel::formatValue($value, $definition['fields'][$field]['type'], false, true,
!empty($definition['fields'][$field]['allow_null']));
}
}
}
// Keep $row2, you cannot use $row because there is an unexplicated conflict with the previous usage of this variable
foreach ($result as $row2) {
$row2[$definition['primary']] = (int)$object_id;
if (!Db::getInstance()->insert($definition['table'].'_lang', $row2)) {
return false;
}
}
}
/** @var ObjectModel $object_duplicated */
$object_duplicated = new $definition['classname']((int)$object_id);
$object_duplicated->duplicateShops((int)$this->id);
return $object_duplicated;
}
/**
* Updates the current object in the database
*
* @param bool $null_values
*
* @return bool
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function update($null_values = false)
{
// @hook actionObject*UpdateBefore
Hook::exec('actionObjectUpdateBefore', array('object' => $this));
Hook::exec('actionObject'.get_class($this).'UpdateBefore', array('object' => $this));
$this->clearCache();
// Automatically fill dates
if (property_exists($this, 'date_upd')) {
$this->date_upd = date('Y-m-d H:i:s');
if (isset($this->update_fields) && is_array($this->update_fields) && count($this->update_fields)) {
$this->update_fields['date_upd'] = true;
}
}
// Automatically fill dates
if (property_exists($this, 'date_add') && $this->date_add == null) {
$this->date_add = date('Y-m-d H:i:s');
if (isset($this->update_fields) && is_array($this->update_fields) && count($this->update_fields)) {
$this->update_fields['date_add'] = true;
}
}
$id_shop_list = Shop::getContextListShopID();
if (count($this->id_shop_list) > 0) {
$id_shop_list = $this->id_shop_list;
}
if (Shop::checkIdShopDefault($this->def['table']) && !$this->id_shop_default) {
$this->id_shop_default = (in_array(Configuration::get('PS_SHOP_DEFAULT'), $id_shop_list) == true) ? Configuration::get('PS_SHOP_DEFAULT') : min($id_shop_list);
}
// Database update
if (!$result = Db::getInstance()->update($this->def['table'], $this->getFields(), '`'.pSQL($this->def['primary']).'` = '.(int)$this->id, 0, $null_values)) {
return false;
}
// Database insertion for multishop fields related to the object
if (Shop::isTableAssociated($this->def['table'])) {
$fields = $this->getFieldsShop();
$fields[$this->def['primary']] = (int)$this->id;
if (is_array($this->update_fields)) {
$update_fields = $this->update_fields;
$this->update_fields = null;
$all_fields = $this->getFieldsShop();
$all_fields[$this->def['primary']] = (int)$this->id;
$this->update_fields = $update_fields;
} else {
$all_fields = $fields;
}
foreach ($id_shop_list as $id_shop) {
$fields['id_shop'] = (int)$id_shop;
$all_fields['id_shop'] = (int)$id_shop;
$where = $this->def['primary'].' = '.(int)$this->id.' AND id_shop = '.(int)$id_shop;
// A little explanation of what we do here : we want to create multishop entry when update is called, but
// only if we are in a shop context (if we are in all context, we just want to update entries that alread exists)
$shop_exists = Db::getInstance()->getValue('SELECT '.$this->def['primary'].' FROM '._DB_PREFIX_.$this->def['table'].'_shop WHERE '.$where);
if ($shop_exists) {
if (Shop::isFeatureActive() && Shop::getContext() != Shop::CONTEXT_SHOP) {
foreach ($fields as $key => $val) {
if (!array_key_exists($key, (array)$this->update_fields)) {
unset($fields[$key]);
}
}
}
$result &= Db::getInstance()->update($this->def['table'] . '_shop', $fields, $where, 0, $null_values);
} elseif (Shop::getContext() == Shop::CONTEXT_SHOP) {
$result &= Db::getInstance()->insert($this->def['table'] . '_shop', $all_fields, $null_values);
}
}
}
// Database update for multilingual fields related to the object
if (isset($this->def['multilang']) && $this->def['multilang']) {
$fields = $this->getFieldsLang();
if (is_array($fields)) {
foreach ($fields as $field) {
foreach (array_keys($field) as $key) {
if (!Validate::isTableOrIdentifier($key)) {
throw new PrestaShopException('key '.$key.' is not a valid table or identifier');
}
}
// If this table is linked to multishop system, update / insert for all shops from context
if ($this->isLangMultishop()) {
$id_shop_list = Shop::getContextListShopID();
if (count($this->id_shop_list) > 0) {
$id_shop_list = $this->id_shop_list;
}
foreach ($id_shop_list as $id_shop) {
$field['id_shop'] = (int)$id_shop;
$where = pSQL($this->def['primary']).' = '.(int)$this->id
.' AND id_lang = '.(int)$field['id_lang']
.' AND id_shop = '.(int)$id_shop;
if (Db::getInstance()->getValue('SELECT COUNT(*) FROM '.pSQL(_DB_PREFIX_.$this->def['table']).'_lang WHERE '.$where)) {
$result &= Db::getInstance()->update($this->def['table'].'_lang', $field, $where);
} else {
$result &= Db::getInstance()->insert($this->def['table'].'_lang', $field);
}
}
}
// If this table is not linked to multishop system ...
else {
$where = pSQL($this->def['primary']).' = '.(int)$this->id
.' AND id_lang = '.(int)$field['id_lang'];
if (Db::getInstance()->getValue('SELECT COUNT(*) FROM '.pSQL(_DB_PREFIX_.$this->def['table']).'_lang WHERE '.$where)) {
$result &= Db::getInstance()->update($this->def['table'].'_lang', $field, $where);
} else {
$result &= Db::getInstance()->insert($this->def['table'].'_lang', $field, $null_values);
}
}
}
}
}
// @hook actionObject*UpdateAfter
Hook::exec('actionObjectUpdateAfter', array('object' => $this));
Hook::exec('actionObject'.get_class($this).'UpdateAfter', array('object' => $this));
return $result;
}
/**
* Deletes current object from database
*
* @return bool True if delete was successful
* @throws PrestaShopException
*/
public function delete()
{
// @hook actionObject*DeleteBefore
Hook::exec('actionObjectDeleteBefore', array('object' => $this));
Hook::exec('actionObject'.get_class($this).'DeleteBefore', array('object' => $this));
$this->clearCache();
$result = true;
// Remove association to multishop table
if (Shop::isTableAssociated($this->def['table'])) {
$id_shop_list = Shop::getContextListShopID();
if (count($this->id_shop_list)) {
$id_shop_list = $this->id_shop_list;
}
$result &= Db::getInstance()->delete($this->def['table'].'_shop', '`'.$this->def['primary'].'`='.(int)$this->id.' AND id_shop IN ('.implode(', ', $id_shop_list).')');
}
// Database deletion
$has_multishop_entries = $this->hasMultishopEntries();
if ($result && !$has_multishop_entries) {
$result &= Db::getInstance()->delete($this->def['table'], '`'.bqSQL($this->def['primary']).'` = '.(int)$this->id);
}
if (!$result) {
return false;
}
// Database deletion for multilingual fields related to the object
if (!empty($this->def['multilang']) && !$has_multishop_entries) {
$result &= Db::getInstance()->delete($this->def['table'].'_lang', '`'.bqSQL($this->def['primary']).'` = '.(int)$this->id);
}
// @hook actionObject*DeleteAfter
Hook::exec('actionObjectDeleteAfter', array('object' => $this));
Hook::exec('actionObject'.get_class($this).'DeleteAfter', array('object' => $this));
return $result;
}
/**
* Deletes multiple objects from the database at once
*
* @param array $ids Array of objects IDs.
*
* @return bool
*/
public function deleteSelection($ids)
{
$result = true;
foreach ($ids as $id) {
$this->id = (int)$id;
$result = $result && $this->delete();
}
return $result;
}
/**
* Toggles object status in database
*
* @return bool Update result
* @throws PrestaShopException
*/
public function toggleStatus()
{
// Object must have a variable called 'active'
if (!property_exists($this, 'active')) {
throw new PrestaShopException('property "active" is missing in object '.get_class($this));
}
// Update only active field
$this->setFieldsToUpdate(array('active' => true));
// Update active status on object
$this->active = !(int)$this->active;
// Change status to active/inactive
return $this->update(false);
}
/**
* @deprecated 1.5.0.1 (use getFieldsLang())
* @param array $fields_array
*
* @return array
* @throws PrestaShopException
*/
protected function getTranslationsFields($fields_array)
{
$fields = array();
if ($this->id_lang == null) {
foreach (Language::getIDs(false) as $id_lang) {
$this->makeTranslationFields($fields, $fields_array, $id_lang);
}
} else {
$this->makeTranslationFields($fields, $fields_array, $this->id_lang);
}
return $fields;
}
/**
* @deprecated 1.5.0.1
* @param array $fields
* @param array $fields_array
* @param int $id_language
*
* @throws PrestaShopException
*/
protected function makeTranslationFields(&$fields, &$fields_array, $id_language)
{
$fields[$id_language]['id_lang'] = $id_language;
$fields[$id_language][$this->def['primary']] = (int)$this->id;
if ($this->id_shop && $this->isLangMultishop()) {
$fields[$id_language]['id_shop'] = (int)$this->id_shop;
}
foreach ($fields_array as $k => $field) {
$html = false;
$field_name = $field;
if (is_array($field)) {
$field_name = $k;
$html = (isset($field['html'])) ? $field['html'] : false;
}
/* Check fields validity */
if (!Validate::isTableOrIdentifier($field_name)) {
throw new PrestaShopException('identifier is not table or identifier : '.$field_name);
}
// Copy the field, or the default language field if it's both required and empty
if ((!$this->id_lang && isset($this->{$field_name}[$id_language]) && !empty($this->{$field_name}[$id_language]))
|| ($this->id_lang && isset($this->$field_name) && !empty($this->$field_name))) {
$fields[$id_language][$field_name] = $this->id_lang ? pSQL($this->$field_name, $html) : pSQL($this->{$field_name}[$id_language], $html);
} elseif (in_array($field_name, $this->fieldsRequiredLang)) {
$fields[$id_language][$field_name] = pSQL($this->id_lang ? $this->$field_name : $this->{$field_name}[Configuration::get('PS_LANG_DEFAULT')], $html);
} else {
$fields[$id_language][$field_name] = '';
}
}
}
/**
* Checks if object field values are valid before database interaction
*
* @param bool $die
* @param bool $error_return
*
* @return bool|string True, false or error message.
* @throws PrestaShopException
*/
public function validateFields($die = true, $error_return = false)
{
foreach ($this->def['fields'] as $field => $data) {
if (!empty($data['lang'])) {
continue;
}
if (is_array($this->update_fields) && empty($this->update_fields[$field]) && isset($this->def['fields'][$field]['shop']) && $this->def['fields'][$field]['shop']) {
continue;
}
$message = $this->validateField($field, $this->$field);
if ($message !== true) {
if ($die) {
throw new PrestaShopException($message);
}
return $error_return ? $message : false;
}
}
return true;
}
/**
* Checks if multilingual object field values are valid before database interaction.
*
* @param bool $die
* @param bool $error_return
*
* @return bool|string True, false or error message.
* @throws PrestaShopException
*/
public function validateFieldsLang($die = true, $error_return = false)
{
foreach ($this->def['fields'] as $field => $data) {
if (empty($data['lang'])) {
continue;
}
$values = $this->$field;
// If the object has not been loaded in multilanguage, then the value is the one for the current language of the object
if (!is_array($values)) {
$values = array($this->id_lang => $values);
}
// The value for the default must always be set, so we put an empty string if it does not exists
if (!isset($values[Configuration::get('PS_LANG_DEFAULT')])) {
$values[Configuration::get('PS_LANG_DEFAULT')] = '';
}
foreach ($values as $id_lang => $value) {
if (is_array($this->update_fields) && empty($this->update_fields[$field][$id_lang])) {
continue;
}
$message = $this->validateField($field, $value, $id_lang);
if ($message !== true) {
if ($die) {
throw new PrestaShopException($message);
}
return $error_return ? $message : false;
}
}
}
return true;
}
/**
* Validate a single field
*
* @since 1.5.0.1
* @param string $field Field name
* @param mixed $value Field value
* @param int|null $id_lang Language ID
* @param array $skip Array of fields to skip.
* @param bool $human_errors If true, uses more descriptive, translatable error strings.
*
* @return true|string True or error message string.
* @throws PrestaShopException
*/
public function validateField($field, $value, $id_lang = null, $skip = array(), $human_errors = false)
{
static $ps_lang_default = null;
static $ps_allow_html_iframe = null;
if ($ps_lang_default === null) {
$ps_lang_default = Configuration::get('PS_LANG_DEFAULT');
}
if ($ps_allow_html_iframe === null) {
$ps_allow_html_iframe = (int)Configuration::get('PS_ALLOW_HTML_IFRAME');
}