-
Notifications
You must be signed in to change notification settings - Fork 0
/
Category.php
2455 lines (2197 loc) · 86.3 KB
/
Category.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
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* 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.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* 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 https://devdocs.prestashop.com/ for more information.
*
* @author PrestaShop SA and Contributors <[email protected]>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
*/
/**
* Class CategoryCore.
*/
class CategoryCore extends ObjectModel
{
public $id;
/** @var int category ID */
public $id_category;
/** @var mixed string or array of Name */
public $name;
/** @var bool Status for display */
public $active = 1;
/** @var int category position */
public $position;
/** @var mixed string or array of Description */
public $description;
/** @var int Parent category ID */
public $id_parent;
/** @var int default Category id */
public $id_category_default;
/** @var int Parents number */
public $level_depth;
/** @var int Nested tree model "left" value */
public $nleft;
/** @var int Nested tree model "right" value */
public $nright;
/** @var mixed string or array of string used in rewrited URL */
public $link_rewrite;
/** @var mixed string or array of Meta title */
public $meta_title;
/** @var mixed string or array of Meta keywords */
public $meta_keywords;
/** @var mixed string or array of Meta description */
public $meta_description;
/** @var string Object creation date */
public $date_add;
/** @var string Object last modification date */
public $date_upd;
/** @var bool is Category Root */
public $is_root_category;
/** @var int */
public $id_shop_default;
public $groupBox;
/** @var bool */
public $doNotRegenerateNTree = false;
protected static $_links = [];
/**
* @see ObjectModel::$definition
*/
public static $definition = [
'table' => 'category',
'primary' => 'id_category',
'multilang' => true,
'multilang_shop' => true,
'fields' => [
'nleft' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'],
'nright' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'],
'level_depth' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'],
'active' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool', 'required' => true],
'id_parent' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'],
'id_shop_default' => ['type' => self::TYPE_INT, 'validate' => 'isUnsignedId'],
'is_root_category' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
'position' => ['type' => self::TYPE_INT],
'date_add' => ['type' => self::TYPE_DATE, 'validate' => 'isDate'],
'date_upd' => ['type' => self::TYPE_DATE, 'validate' => 'isDate'],
/* Lang fields */
'name' => ['type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isCatalogName', 'required' => true, 'size' => 128],
'link_rewrite' => [
'type' => self::TYPE_STRING,
'lang' => true,
'validate' => 'isLinkRewrite',
'required' => true,
'size' => 128,
'ws_modifier' => [
'http_method' => WebserviceRequest::HTTP_POST,
'modifier' => 'modifierWsLinkRewrite',
],
],
'description' => ['type' => self::TYPE_HTML, 'lang' => true, 'validate' => 'isCleanHtml'],
'meta_title' => ['type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'size' => 255],
'meta_description' => ['type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'size' => 512],
'meta_keywords' => ['type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'size' => 255],
],
];
/** @var string id_image is the category ID when an image exists and 'default' otherwise */
public $id_image = 'default';
protected $webserviceParameters = [
'objectsNodeName' => 'categories',
'hidden_fields' => ['nleft', 'nright', 'groupBox'],
'fields' => [
'id_parent' => ['xlink_resource' => 'categories'],
'level_depth' => ['setter' => false],
'nb_products_recursive' => ['getter' => 'getWsNbProductsRecursive', 'setter' => false],
],
'associations' => [
'categories' => ['getter' => 'getChildrenWs', 'resource' => 'category'],
'products' => ['getter' => 'getProductsWs', 'resource' => 'product'],
],
];
/**
* CategoryCore constructor.
*
* @param int|null $idCategory
* @param int|null $idLang
* @param int|null $idShop
*/
public function __construct($idCategory = null, $idLang = null, $idShop = null)
{
parent::__construct($idCategory, $idLang, $idShop);
$this->image_dir = _PS_CAT_IMG_DIR_;
$this->id_image = ($this->id && file_exists($this->image_dir . (int) $this->id . '.jpg')) ? (int) $this->id : false;
if (defined('PS_INSTALLATION_IN_PROGRESS')) {
$this->doNotRegenerateNTree = true;
}
}
/**
* Get the clean description without HTML tags and slashes.
*
* @param string $description Category description with HTML
*
* @return string Category description without HTML
*/
public static function getDescriptionClean($description)
{
return Tools::getDescriptionClean($description);
}
/**
* Adds current Category as a new Object to the database.
*
* @param bool $autoDate Automatically set `date_upd` and `date_add` columns
* @param bool $nullValues Whether we want to use NULL values instead of empty quotes values
*
* @return bool Indicates whether the Category has been successfully added
*
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function add($autoDate = true, $nullValues = false)
{
if (!isset($this->level_depth)) {
$this->level_depth = $this->calcLevelDepth();
}
if ($this->is_root_category && ($idRootCategory = (int) Configuration::get('PS_ROOT_CATEGORY'))) {
$this->id_parent = $idRootCategory;
}
$ret = parent::add($autoDate, $nullValues);
if (Tools::isSubmit('checkBoxShopAsso_category')) {
foreach (Tools::getValue('checkBoxShopAsso_category') as $idShop => $value) {
$position = (int) Category::getLastPosition((int) $this->id_parent, $idShop);
$this->addPosition($position, $idShop);
}
} else {
foreach (Shop::getShops(true) as $shop) {
$position = (int) Category::getLastPosition((int) $this->id_parent, $shop['id_shop']);
$this->addPosition($position, $shop['id_shop']);
}
}
if (!$this->doNotRegenerateNTree) {
Category::regenerateEntireNtree();
}
// if access group is not set, initialize it with 3 default groups
$this->updateGroup(($this->groupBox !== null) ? $this->groupBox : []);
Hook::exec('actionCategoryAdd', ['category' => $this]);
return $ret;
}
/**
* Updates the current object in the database.
*
* @param bool $nullValues Whether we want to use NULL values instead of empty quotes values
*
* @return bool Indicates whether the CartRule has been successfully updated
*
* @throws PrestaShopDatabaseException
* @throws PrestaShopException
*/
public function update($nullValues = false)
{
if ($this->id_parent == $this->id) {
throw new PrestaShopException('a category cannot be its own parent');
}
if ($this->is_root_category && $this->id_parent != (int) Configuration::get('PS_ROOT_CATEGORY')) {
$this->is_root_category = 0;
}
// Update group selection
$this->updateGroup($this->groupBox);
if ($this->level_depth != $this->calcLevelDepth()) {
$this->level_depth = $this->calcLevelDepth();
$changed = true;
}
// If the parent category was changed, we don't want to have 2 categories with the same position
if (!isset($changed)) {
$changed = $this->getDuplicatePosition();
}
if ($changed) {
if (Tools::isSubmit('checkBoxShopAsso_category')) {
foreach (Tools::getValue('checkBoxShopAsso_category') as $idAssoObject => $idShop) {
$this->addPosition($this->position, (int) $idShop);
}
} else {
foreach (Shop::getShops(true) as $shop) {
$this->addPosition($this->position, $shop['id_shop']);
}
}
}
$ret = parent::update($nullValues);
if ($changed && !$this->doNotRegenerateNTree) {
$this->cleanPositions((int) $this->id_parent);
Category::regenerateEntireNtree();
$this->recalculateLevelDepth($this->id);
}
Hook::exec('actionCategoryUpdate', ['category' => $this]);
return $ret;
}
/**
* Toggles the `active` flag.
*
* @return bool Indicates whether the status was successfully toggled
*/
public function toggleStatus()
{
$result = parent::toggleStatus();
Hook::exec('actionCategoryUpdate', ['category' => $this]);
return $result;
}
/**
* Recursive scan of subcategories.
*
* @param int $maxDepth Maximum depth of the tree (i.e. 2 => 3 levels depth)
* @param int $currentDepth specify the current depth in the tree (don't use it, only for recursive calls!)
* @param int $idLang Specify the id of the language used
* @param array $excludedIdsArray Specify a list of IDs to exclude of results
* @param string $format
*
* @return array Subcategories lite tree
*/
public function recurseLiteCategTree($maxDepth = 3, $currentDepth = 0, $idLang = null, $excludedIdsArray = null, $format = 'default')
{
$idLang = null === $idLang ? Context::getContext()->language->id : (int) $idLang;
$children = [];
$subcats = $this->getSubCategories($idLang, true);
if (($maxDepth == 0 || $currentDepth < $maxDepth) && $subcats && count($subcats)) {
foreach ($subcats as $subcat) {
if (!$subcat['id_category']) {
break;
} elseif (!is_array($excludedIdsArray) || !in_array($subcat['id_category'], $excludedIdsArray)) {
$categ = new Category($subcat['id_category'], $idLang);
$children[] = $categ->recurseLiteCategTree($maxDepth, $currentDepth + 1, $idLang, $excludedIdsArray, $format);
}
}
}
if (is_array($this->description)) {
foreach ($this->description as $lang => $description) {
$this->description[$lang] = Category::getDescriptionClean($description);
}
} else {
$this->description = Category::getDescriptionClean($this->description);
}
if ($format === 'sitemap') {
return [
'id' => 'category-page-' . (int) $this->id,
'label' => $this->name,
'url' => Context::getContext()->link->getCategoryLink($this->id, $this->link_rewrite),
'children' => $children,
];
}
return [
'id' => (int) $this->id,
'link' => Context::getContext()->link->getCategoryLink($this->id, $this->link_rewrite),
'name' => $this->name,
'desc' => $this->description,
'children' => $children,
];
}
/**
* Recursively add specified category childs to $to_delete array.
*
* @param array &$toDelete Array reference where categories ID will be saved
* @param int $idCategory Parent category ID
*/
protected function recursiveDelete(&$toDelete, $idCategory)
{
if (!is_array($toDelete) || !$idCategory) {
die(Tools::displayError());
}
$sql = new DbQuery();
$sql->select('`id_category`');
$sql->from('category');
$sql->where('`id_parent` = ' . (int) $idCategory);
$result = Db::getInstance()->executeS($sql);
foreach ($result as $row) {
$toDelete[] = (int) $row['id_category'];
$this->recursiveDelete($toDelete, (int) $row['id_category']);
}
}
/**
* Delete this object
* Skips the deletion procedure of Category and directly calls
* the delete() method of ObjectModel instead.
*
* @return bool Indicates whether this Category was successfully deleted
*/
public function deleteLite()
{
return parent::delete();
}
/**
* Deletes current CartRule from the database.
*
* @return bool `true` if successfully deleted
*
* @throws PrestaShopException
*/
public function delete()
{
if ((int) $this->id === 0 || (int) $this->id === (int) Configuration::get('PS_ROOT_CATEGORY')) {
return false;
}
$this->clearCache();
$deletedChildren = $allCat = $this->getAllChildren();
$allCat[] = $this;
foreach ($allCat as $cat) {
/* @var Category $cat */
$cat->deleteLite();
if (!$cat->hasMultishopEntries()) {
$cat->deleteImage();
$cat->cleanGroups();
$cat->cleanAssoProducts();
// Delete associated restrictions on cart rules
CartRule::cleanProductRuleIntegrity('categories', [$cat->id]);
Category::cleanPositions($cat->id_parent);
/* Delete Categories in GroupReduction */
if (GroupReduction::getGroupsReductionByCategoryId((int) $cat->id)) {
GroupReduction::deleteCategory($cat->id);
}
}
}
/* Rebuild the nested tree */
if (!$this->hasMultishopEntries() && !$this->doNotRegenerateNTree) {
Category::regenerateEntireNtree();
}
Hook::exec('actionCategoryDelete', ['category' => $this, 'deleted_children' => $deletedChildren]);
return true;
}
/**
* Delete selected categories from database.
*
* @param array $idCategories Category IDs to delete
*
* @return bool Deletion result
*/
public function deleteSelection($idCategories)
{
$return = 1;
foreach ($idCategories as $idCategory) {
$category = new Category($idCategory);
if ($category->isRootCategoryForAShop()) {
return false;
} else {
$return &= $category->delete();
}
}
return $return;
}
/**
* Get the depth level for the category.
*
* @return int Depth level
*
* @throws PrestaShopException
*/
public function calcLevelDepth()
{
/* Root category */
if (!$this->id_parent) {
return 0;
}
$parentCategory = new Category((int) $this->id_parent);
if (!Validate::isLoadedObject($parentCategory)) {
if (is_array($this->name)) {
$name = $this->name[Context::getContext()->language->id];
} else {
$name = $this->name;
}
throw new PrestaShopException('Parent category ' . $this->id_parent . ' does not exist. Current category: ' . $name);
}
return (int) $parentCategory->level_depth + 1;
}
/**
* Re-calculate the values of all branches of the nested tree.
*/
public static function regenerateEntireNtree()
{
$id = Context::getContext()->shop->id;
$idShop = $id ? $id : Configuration::get('PS_SHOP_DEFAULT');
$sql = new DbQuery();
$sql->select('c.`id_category`, c.`id_parent`');
$sql->from('category', 'c');
$sql->leftJoin('category_shop', 'cs', 'c.`id_category` = cs.`id_category` AND cs.`id_shop` = ' . (int) $idShop);
$sql->orderBy('c.`id_parent`, cs.`position` ASC');
$categories = Db::getInstance()->executeS($sql);
$categoriesArray = [];
foreach ($categories as $category) {
$categoriesArray[$category['id_parent']]['subcategories'][] = $category['id_category'];
}
$n = 1;
if (isset($categoriesArray[0]) && $categoriesArray[0]['subcategories']) {
$queries = Category::computeNTreeInfos($categoriesArray, $categoriesArray[0]['subcategories'][0], $n);
// update by batch of 5000 categories
$chunks = array_chunk($queries, 5000);
foreach ($chunks as $chunk) {
$sqlChunk = array_map(function ($value) { return '(' . rtrim(implode(',', $value)) . ')'; }, $chunk);
Db::getInstance()->execute('INSERT INTO `' . _DB_PREFIX_ . 'category` (id_category, nleft, nright)
VALUES ' . rtrim(implode(',', $sqlChunk), ',') . '
ON DUPLICATE KEY UPDATE nleft=VALUES(nleft), nright=VALUES(nright)');
}
}
}
/**
* @param $categories
* @param $idCategory
* @param $n
*
* @deprecated 1.7.0
*/
protected static function _subTree(&$categories, $idCategory, &$n)
{
self::subTree($categories, $idCategory, $n);
}
/**
* @param array $categories
* @param int $idCategory
* @param int $n
*
* @return array ntree infos
*/
protected static function computeNTreeInfos(&$categories, $idCategory, &$n)
{
$queries = [];
$left = $n++;
if (isset($categories[(int) $idCategory]['subcategories'])) {
foreach ($categories[(int) $idCategory]['subcategories'] as $idSubcategory) {
$queries = array_merge($queries, Category::computeNTreeInfos($categories, (int) $idSubcategory, $n));
}
}
$right = (int) $n++;
$queries[] = [$idCategory, $left, $right];
return $queries;
}
/**
* @param $categories
* @param $idCategory
* @param $n
*
* @return bool Indicates whether the sub tree of categories has been successfully updated
*
* @deprecated 1.7.6.0 use computeNTreeInfos + sql query instead
*/
protected static function subTree(&$categories, $idCategory, &$n)
{
$left = $n++;
if (isset($categories[(int) $idCategory]['subcategories'])) {
foreach ($categories[(int) $idCategory]['subcategories'] as $idSubcategory) {
Category::subTree($categories, (int) $idSubcategory, $n);
}
}
$right = (int) $n++;
return Db::getInstance()->update(
'category',
[
'nleft' => (int) $left,
'nright' => (int) $right,
],
'`id_category` = ' . (int) $idCategory,
1
);
}
/**
* Updates `level_depth` for all children of the given `id_category`.
*
* @param int $idParentCategory Parent Category ID
*
* @throws PrestaShopException
*/
public function recalculateLevelDepth($idParentCategory)
{
if (!is_numeric($idParentCategory)) {
throw new PrestaShopException('id category is not numeric');
}
/* Gets all children */
$sql = new DbQuery();
$sql->select('c.`id_category`, c.`id_parent`, c.`level_depth`');
$sql->from('category', 'c');
$sql->where('c.`id_parent` = ' . (int) $idParentCategory);
$categories = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
/* Gets level_depth */
$sql = new DbQuery();
$sql->select('c.`level_depth`');
$sql->from('category', 'c');
$sql->where('c.`id_category` = ' . (int) $idParentCategory);
$level = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql);
/* Updates level_depth for all children */
foreach ($categories as $subCategory) {
Db::getInstance()->update(
'category',
[
'level_depth' => (int) ($level['level_depth'] + 1),
],
'`id_category` = ' . (int) $subCategory['id_category']
);
/* Recursive call */
$this->recalculateLevelDepth($subCategory['id_category']);
}
}
/**
* Return available categories.
*
* @param bool|int $idLang Language ID
* @param bool $active Only return active categories
* @param bool $order Order the results
* @param string $sqlFilter Additional SQL clause(s) to filter results
* @param string $orderBy Change the default order by
* @param string $limit Set the limit
* Both the offset and limit can be given
*
* @return array Categories
*/
public static function getCategories($idLang = false, $active = true, $order = true, $sqlFilter = '', $orderBy = '', $limit = '')
{
if (!Validate::isBool($active)) {
die(Tools::displayError());
}
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(
'
SELECT *
FROM `' . _DB_PREFIX_ . 'category` c
' . Shop::addSqlAssociation('category', 'c') . '
LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON c.`id_category` = cl.`id_category`' . Shop::addSqlRestrictionOnLang('cl') . '
WHERE 1 ' . $sqlFilter . ' ' . ($idLang ? 'AND `id_lang` = ' . (int) $idLang : '') . '
' . ($active ? 'AND `active` = 1' : '') . '
' . (!$idLang ? 'GROUP BY c.id_category' : '') . '
' . ($orderBy != '' ? $orderBy : 'ORDER BY c.`level_depth` ASC, category_shop.`position` ASC') . '
' . ($limit != '' ? $limit : '')
);
if (!$order) {
return $result;
}
$categories = [];
foreach ($result as $row) {
$categories[$row['id_parent']][$row['id_category']]['infos'] = $row;
}
return $categories;
}
/**
* @param int $idRootCategory ID of root Category
* @param int|bool $idLang Language ID
* `false` if language filter should not be applied
* @param bool $active Only return active categories
* @param array|null $groups
* @param bool $useShopRestriction Restrict to current Shop
* @param string $sqlFilter Additional SQL clause(s) to filter results
* @param string $orderBy Change the default order by
* @param string $limit Set the limit
* Both the offset and limit can be given
*
* @return array|false|mysqli_result|PDOStatement|resource|null Array with `id_category` and `name`
*/
public static function getAllCategoriesName(
$idRootCategory = null,
$idLang = false,
$active = true,
$groups = null,
$useShopRestriction = true,
$sqlFilter = '',
$orderBy = '',
$limit = ''
) {
if (isset($idRootCategory) && !Validate::isInt($idRootCategory)) {
die(Tools::displayError());
}
if (!Validate::isBool($active)) {
die(Tools::displayError());
}
if (isset($groups) && Group::isFeatureActive() && !is_array($groups)) {
$groups = (array) $groups;
}
$cacheId = 'Category::getAllCategoriesName_' . md5(
(int) $idRootCategory .
(int) $idLang .
(int) $active .
(int) $useShopRestriction .
(isset($groups) && Group::isFeatureActive() ? implode('', $groups) : '') .
(isset($sqlFilter) ? $sqlFilter : '') .
(isset($orderBy) ? $orderBy : '') .
(isset($limit) ? $limit : '')
);
if (!Cache::isStored($cacheId)) {
$result = Db::getInstance()->executeS(
'
SELECT c.`id_category`, cl.`name`
FROM `' . _DB_PREFIX_ . 'category` c
' . ($useShopRestriction ? Shop::addSqlAssociation('category', 'c') : '') . '
LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON c.`id_category` = cl.`id_category`' . Shop::addSqlRestrictionOnLang('cl') . '
' . (isset($groups) && Group::isFeatureActive() ? 'LEFT JOIN `' . _DB_PREFIX_ . 'category_group` cg ON c.`id_category` = cg.`id_category`' : '') . '
' . (isset($idRootCategory) ? 'RIGHT JOIN `' . _DB_PREFIX_ . 'category` c2 ON c2.`id_category` = ' . (int) $idRootCategory . ' AND c.`nleft` >= c2.`nleft` AND c.`nright` <= c2.`nright`' : '') . '
WHERE 1 ' . $sqlFilter . ' ' . ($idLang ? 'AND `id_lang` = ' . (int) $idLang : '') . '
' . ($active ? ' AND c.`active` = 1' : '') . '
' . (isset($groups) && Group::isFeatureActive() ? ' AND cg.`id_group` IN (' . implode(',', array_map('intval', $groups)) . ')' : '') . '
' . (!$idLang || (isset($groups) && Group::isFeatureActive()) ? ' GROUP BY c.`id_category`' : '') . '
' . ($orderBy != '' ? $orderBy : ' ORDER BY c.`level_depth` ASC') . '
' . ($orderBy == '' && $useShopRestriction ? ', category_shop.`position` ASC' : '') . '
' . ($limit != '' ? $limit : '')
);
Cache::store($cacheId, $result);
} else {
$result = Cache::retrieve($cacheId);
}
return $result;
}
/**
* Get nested categories.
*
* @param int|null $idRootCategory Root Category ID
* @param int|bool $idLang Language ID
* `false` if language filter should not be used
* @param bool $active Whether the category must be active
* @param null $groups
* @param bool $useShopRestriction Restrict to current Shop
* @param string $sqlFilter Additional SQL clause(s) to filter results
* @param string $orderBy Change the default order by
* @param string $limit Set the limit
* Both the offset and limit can be given
*
* @return array|null
*/
public static function getNestedCategories(
$idRootCategory = null,
$idLang = false,
$active = true,
$groups = null,
$useShopRestriction = true,
$sqlFilter = '',
$orderBy = '',
$limit = ''
) {
if (isset($idRootCategory) && !Validate::isInt($idRootCategory)) {
die(Tools::displayError());
}
if (!Validate::isBool($active)) {
die(Tools::displayError());
}
if (isset($groups) && Group::isFeatureActive() && !is_array($groups)) {
$groups = (array) $groups;
}
$cacheId = 'Category::getNestedCategories_' . md5(
(int) $idRootCategory .
(int) $idLang .
(int) $active .
(int) $useShopRestriction .
(isset($groups) && Group::isFeatureActive() ? implode('', $groups) : '') .
(isset($sqlFilter) ? $sqlFilter : '') .
(isset($orderBy) ? $orderBy : '') .
(isset($limit) ? $limit : '')
);
if (!Cache::isStored($cacheId)) {
$result = Db::getInstance()->executeS(
'
SELECT c.*, cl.*
FROM `' . _DB_PREFIX_ . 'category` c
' . ($useShopRestriction ? Shop::addSqlAssociation('category', 'c') : '') . '
LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON c.`id_category` = cl.`id_category`' . Shop::addSqlRestrictionOnLang('cl') . '
' . (isset($groups) && Group::isFeatureActive() ? 'LEFT JOIN `' . _DB_PREFIX_ . 'category_group` cg ON c.`id_category` = cg.`id_category`' : '') . '
' . (isset($idRootCategory) ? 'RIGHT JOIN `' . _DB_PREFIX_ . 'category` c2 ON c2.`id_category` = ' . (int) $idRootCategory . ' AND c.`nleft` >= c2.`nleft` AND c.`nright` <= c2.`nright`' : '') . '
WHERE 1 ' . $sqlFilter . ' ' . ($idLang ? 'AND `id_lang` = ' . (int) $idLang : '') . '
' . ($active ? ' AND c.`active` = 1' : '') . '
' . (isset($groups) && Group::isFeatureActive() ? ' AND cg.`id_group` IN (' . implode(',', array_map('intval', $groups)) . ')' : '') . '
' . (!$idLang || (isset($groups) && Group::isFeatureActive()) ? ' GROUP BY c.`id_category`' : '') . '
' . ($orderBy != '' ? $orderBy : ' ORDER BY c.`level_depth` ASC') . '
' . ($orderBy == '' && $useShopRestriction ? ', category_shop.`position` ASC' : '') . '
' . ($limit != '' ? $limit : '')
);
$categories = [];
$buff = [];
if (!isset($idRootCategory)) {
$idRootCategory = Category::getRootCategory()->id;
}
foreach ($result as $row) {
$current = &$buff[$row['id_category']];
$current = $row;
if ($row['id_category'] == $idRootCategory) {
$categories[$row['id_category']] = &$current;
} else {
$buff[$row['id_parent']]['children'][$row['id_category']] = &$current;
}
}
Cache::store($cacheId, $categories);
} else {
$categories = Cache::retrieve($cacheId);
}
return $categories;
}
/**
* Get a simple list of categories with id_category and name for each Category.
*
* @param int $idLang Language ID
*
* @return array|false|mysqli_result|PDOStatement|resource|null
*/
public static function getSimpleCategories($idLang)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
SELECT c.`id_category`, cl.`name`
FROM `' . _DB_PREFIX_ . 'category` c
LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON (c.`id_category` = cl.`id_category`' . Shop::addSqlRestrictionOnLang('cl') . ')
' . Shop::addSqlAssociation('category', 'c') . '
WHERE cl.`id_lang` = ' . (int) $idLang . '
AND c.`id_category` != ' . Configuration::get('PS_ROOT_CATEGORY') . '
GROUP BY c.id_category
ORDER BY c.`id_category`, category_shop.`position`', true, false);
}
/**
* Get a simple list of categories with id_category, name and id_parent infos
* It also takes into account the root category of the current shop.
*
* @param int $idLang Language ID
*
* @return array|false|mysqli_result|PDOStatement|resource|null
*/
public static function getSimpleCategoriesWithParentInfos($idLang)
{
$context = Context::getContext();
if (count(Category::getCategoriesWithoutParent()) > 1
&& \Configuration::get('PS_MULTISHOP_FEATURE_ACTIVE')
&& count(Shop::getShops(true, null, true)) !== 1) {
$idCategoryRoot = (int) \Configuration::get('PS_ROOT_CATEGORY');
} elseif (!$context->shop->id) {
$idCategoryRoot = (new Shop(\Configuration::get('PS_SHOP_DEFAULT')))->id_category;
} else {
$idCategoryRoot = $context->shop->id_category;
}
$rootTreeInfo = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow(
'SELECT c.`nleft`, c.`nright` FROM `' . _DB_PREFIX_ . 'category` c ' .
'WHERE c.`id_category` = ' . (int) $idCategoryRoot
);
return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
SELECT c.`id_category`, cl.`name`, c.id_parent
FROM `' . _DB_PREFIX_ . 'category` c
LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl
ON (c.`id_category` = cl.`id_category`' . Shop::addSqlRestrictionOnLang('cl') . ')
' . Shop::addSqlAssociation('category', 'c') . '
WHERE cl.`id_lang` = ' . (int) $idLang . '
AND c.`nleft` >= ' . (int) $rootTreeInfo['nleft'] . '
AND c.`nright` <= ' . (int) $rootTreeInfo['nright'] . '
GROUP BY c.id_category
ORDER BY c.`id_category`, category_shop.`position`');
}
/**
* Get Shop ID.
*
* @return int
*
* @deprecated 1.7.0
*/
public function getShopID()
{
return $this->id_shop;
}
/**
* Return current category childs.
*
* @param int $idLang Language ID
* @param bool $active return only active categories
*
* @return array Categories
*/
public function getSubCategories($idLang, $active = true)
{
$sqlGroupsWhere = '';
$sqlGroupsJoin = '';
if (Group::isFeatureActive()) {
$sqlGroupsJoin = 'LEFT JOIN `' . _DB_PREFIX_ . 'category_group` cg ON (cg.`id_category` = c.`id_category`)';
$groups = FrontController::getCurrentCustomerGroups();
$sqlGroupsWhere = 'AND cg.`id_group` ' . (count($groups) ? 'IN (' . implode(',', $groups) . ')' : '=' . (int) Configuration::get('PS_UNIDENTIFIED_GROUP'));
}
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
SELECT c.*, cl.`id_lang`, cl.`name`, cl.`description`, cl.`link_rewrite`, cl.`meta_title`, cl.`meta_keywords`, cl.`meta_description`
FROM `' . _DB_PREFIX_ . 'category` c
' . Shop::addSqlAssociation('category', 'c') . '
LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON (c.`id_category` = cl.`id_category` AND `id_lang` = ' . (int) $idLang . ' ' . Shop::addSqlRestrictionOnLang('cl') . ')
' . $sqlGroupsJoin . '
WHERE `id_parent` = ' . (int) $this->id . '
' . ($active ? 'AND `active` = 1' : '') . '
' . $sqlGroupsWhere . '
GROUP BY c.`id_category`
ORDER BY `level_depth` ASC, category_shop.`position` ASC');
foreach ($result as &$row) {
$row['id_image'] = Tools::file_exists_cache($this->image_dir . $row['id_category'] . '.jpg') ? (int) $row['id_category'] : Language::getIsoById($idLang) . '-default';
$row['legend'] = 'no picture';
}
return $result;
}
/**
* Returns category products.
*
* @param int $idLang Language ID
* @param int $pageNumber Page number
* @param int $productPerPage Number of products per page
* @param string|null $orderBy ORDER BY column
* @param string|null $orderWay Order way
* @param bool $getTotal If set to true, returns the total number of results only
* @param bool $active If set to true, finds only active products
* @param bool $random If true, sets a random filter for returned products
* @param int $randomNumberProducts Number of products to return if random is activated
* @param bool $checkAccess If set to `true`, check if the current customer
* can see the products from this category
* @param Context|null $context Instance of Context
*
* @return array|int|false Products, number of products or false (no access)
*
* @throws PrestaShopDatabaseException
*/
public function getProducts(
$idLang,
$pageNumber,
$productPerPage,
$orderBy = null,
$orderWay = null,
$getTotal = false,
$active = true,
$random = false,
$randomNumberProducts = 1,
$checkAccess = true,
Context $context = null
) {
if (!$context) {
$context = Context::getContext();
}
if ($checkAccess && !$this->checkAccess($context->customer->id)) {
return false;
}
$front = in_array($context->controller->controller_type, ['front', 'modulefront']);
$idSupplier = (int) Tools::getValue('id_supplier');
/* Return only the number of products */
if ($getTotal) {
$sql = 'SELECT COUNT(cp.`id_product`) AS total
FROM `' . _DB_PREFIX_ . 'product` p
' . Shop::addSqlAssociation('product', 'p') . '
LEFT JOIN `' . _DB_PREFIX_ . 'category_product` cp ON p.`id_product` = cp.`id_product`
WHERE cp.`id_category` = ' . (int) $this->id .
($front ? ' AND product_shop.`visibility` IN ("both", "catalog")' : '') .
($active ? ' AND product_shop.`active` = 1' : '') .
($idSupplier ? ' AND p.id_supplier = ' . (int) $idSupplier : '');
return (int) Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql);
}
if ($pageNumber < 1) {
$pageNumber = 1;
}
/** Tools::strtolower is a fix for all modules which are now using lowercase values for 'orderBy' parameter */
$orderBy = Validate::isOrderBy($orderBy) ? Tools::strtolower($orderBy) : 'position';
$orderWay = Validate::isOrderWay($orderWay) ? Tools::strtoupper($orderWay) : 'ASC';
$orderByPrefix = false;
if ($orderBy === 'id_product' || $orderBy === 'date_add' || $orderBy === 'date_upd') {
$orderByPrefix = 'p';
} elseif ($orderBy === 'name') {