-
Notifications
You must be signed in to change notification settings - Fork 0
/
Dispatcher.php
1238 lines (1102 loc) · 44.6 KB
/
Dispatcher.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)
*/
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
/**
* @since 1.5.0
*/
class DispatcherCore
{
/**
* List of available front controllers types.
*/
const FC_FRONT = 1;
const FC_ADMIN = 2;
const FC_MODULE = 3;
const REWRITE_PATTERN = '[_a-zA-Z0-9\x{0600}-\x{06FF}\pL\pS-]*?';
/**
* @var Dispatcher
*/
public static $instance = null;
/**
* @var SymfonyRequest
*/
private $request;
/**
* @var array List of default routes
*/
public $default_routes = [
'category_rule' => [
'controller' => 'category',
'rule' => '{id}-{rewrite}',
'keywords' => [
'id' => ['regexp' => '[0-9]+', 'param' => 'id_category'],
'rewrite' => ['regexp' => self::REWRITE_PATTERN],
'meta_keywords' => ['regexp' => '[_a-zA-Z0-9-\pL]*'],
'meta_title' => ['regexp' => '[_a-zA-Z0-9-\pL]*'],
],
],
'supplier_rule' => [
'controller' => 'supplier',
'rule' => 'supplier/{id}-{rewrite}',
'keywords' => [
'id' => ['regexp' => '[0-9]+', 'param' => 'id_supplier'],
'rewrite' => ['regexp' => self::REWRITE_PATTERN],
'meta_keywords' => ['regexp' => '[_a-zA-Z0-9-\pL]*'],
'meta_title' => ['regexp' => '[_a-zA-Z0-9-\pL]*'],
],
],
'manufacturer_rule' => [
'controller' => 'manufacturer',
'rule' => 'brand/{id}-{rewrite}',
'keywords' => [
'id' => ['regexp' => '[0-9]+', 'param' => 'id_manufacturer'],
'rewrite' => ['regexp' => self::REWRITE_PATTERN],
'meta_keywords' => ['regexp' => '[_a-zA-Z0-9-\pL]*'],
'meta_title' => ['regexp' => '[_a-zA-Z0-9-\pL]*'],
],
],
'cms_rule' => [
'controller' => 'cms',
'rule' => 'content/{id}-{rewrite}',
'keywords' => [
'id' => ['regexp' => '[0-9]+', 'param' => 'id_cms'],
'rewrite' => ['regexp' => self::REWRITE_PATTERN],
'meta_keywords' => ['regexp' => '[_a-zA-Z0-9-\pL]*'],
'meta_title' => ['regexp' => '[_a-zA-Z0-9-\pL]*'],
],
],
'cms_category_rule' => [
'controller' => 'cms',
'rule' => 'content/category/{id}-{rewrite}',
'keywords' => [
'id' => ['regexp' => '[0-9]+', 'param' => 'id_cms_category'],
'rewrite' => ['regexp' => self::REWRITE_PATTERN],
'meta_keywords' => ['regexp' => '[_a-zA-Z0-9-\pL]*'],
'meta_title' => ['regexp' => '[_a-zA-Z0-9-\pL]*'],
],
],
'module' => [
'controller' => null,
'rule' => 'module/{module}{/:controller}',
'keywords' => [
'module' => ['regexp' => '[_a-zA-Z0-9_-]+', 'param' => 'module'],
'controller' => ['regexp' => '[_a-zA-Z0-9_-]+', 'param' => 'controller'],
],
'params' => [
'fc' => 'module',
],
],
'product_rule' => [
'controller' => 'product',
'rule' => '{category:/}{id}{-:id_product_attribute}-{rewrite}{-:ean13}.html',
'keywords' => [
'id' => ['regexp' => '[0-9]+', 'param' => 'id_product'],
'id_product_attribute' => ['regexp' => '[0-9]+', 'param' => 'id_product_attribute'],
'rewrite' => ['regexp' => self::REWRITE_PATTERN, 'param' => 'rewrite'],
'ean13' => ['regexp' => '[0-9\pL]*'],
'category' => ['regexp' => '[_a-zA-Z0-9-\pL]*'],
'categories' => ['regexp' => '[/_a-zA-Z0-9-\pL]*'],
'reference' => ['regexp' => '[_a-zA-Z0-9-\pL]*'],
'meta_keywords' => ['regexp' => '[_a-zA-Z0-9-\pL]*'],
'meta_title' => ['regexp' => '[_a-zA-Z0-9-\pL]*'],
'manufacturer' => ['regexp' => '[_a-zA-Z0-9-\pL]*'],
'supplier' => ['regexp' => '[_a-zA-Z0-9-\pL]*'],
'price' => ['regexp' => '[0-9\.,]*'],
'tags' => ['regexp' => '[a-zA-Z0-9-\pL]*'],
],
],
/* Must be after the product and category rules in order to avoid conflict */
'layered_rule' => [
'controller' => 'category',
'rule' => '{id}-{rewrite}{/:selected_filters}',
'keywords' => [
'id' => ['regexp' => '[0-9]+', 'param' => 'id_category'],
/* Selected filters is used by the module blocklayered */
'selected_filters' => ['regexp' => '.*', 'param' => 'selected_filters'],
'rewrite' => ['regexp' => self::REWRITE_PATTERN],
'meta_keywords' => ['regexp' => '[_a-zA-Z0-9-\pL]*'],
'meta_title' => ['regexp' => '[_a-zA-Z0-9-\pL]*'],
],
],
];
/**
* @var bool If true, use routes to build URL (mod rewrite must be activated)
*/
protected $use_routes = false;
protected $multilang_activated = false;
/**
* @var array List of loaded routes
*/
protected $routes = [];
/**
* @var string Current controller name
*/
protected $controller;
/**
* @var string Current request uri
*/
protected $request_uri;
/**
* @var array Store empty route (a route with an empty rule)
*/
protected $empty_route;
/**
* @var string Set default controller, which will be used if http parameter 'controller' is empty
*/
protected $default_controller;
protected $use_default_controller = false;
/**
* @var string Controller to use if found controller doesn't exist
*/
protected $controller_not_found = 'pagenotfound';
/**
* @var string Front controller to use
*/
protected $front_controller = self::FC_FRONT;
/**
* Get current instance of dispatcher (singleton).
*
* @return Dispatcher
*
* @throws PrestaShopException
*/
public static function getInstance(SymfonyRequest $request = null)
{
if (!self::$instance) {
if (null === $request) {
$request = SymfonyRequest::createFromGlobals();
}
self::$instance = new Dispatcher($request);
}
return self::$instance;
}
/**
* Needs to be instantiated from getInstance() method.
*
* @param SymfonyRequest|null $request
*
* @throws PrestaShopException
*/
protected function __construct(SymfonyRequest $request = null)
{
$this->setRequest($request);
$this->use_routes = (bool) Configuration::get('PS_REWRITING_SETTINGS');
// Select right front controller
if (defined('_PS_ADMIN_DIR_')) {
$this->front_controller = self::FC_ADMIN;
$this->controller_not_found = 'adminnotfound';
} elseif (Tools::getValue('fc') == 'module') {
$this->front_controller = self::FC_MODULE;
$this->controller_not_found = 'pagenotfound';
} else {
$this->front_controller = self::FC_FRONT;
$this->controller_not_found = 'pagenotfound';
}
$this->setRequestUri();
// Switch language if needed (only on front)
if (in_array($this->front_controller, [self::FC_FRONT, self::FC_MODULE])) {
Tools::switchLanguage();
}
if (Language::isMultiLanguageActivated()) {
$this->multilang_activated = true;
}
$this->loadRoutes();
}
/**
* Either sets a given request or a new one.
*
* @param SymfonyRequest|null $request
*/
private function setRequest(SymfonyRequest $request = null)
{
if (null === $request) {
$request = SymfonyRequest::createFromGlobals();
}
$this->request = $request;
}
/**
* Returns the request property.
*
* @return SymfonyRequest
*/
private function getRequest()
{
return $this->request;
}
/**
* Sets and returns the default controller.
*
* @param int $frontControllerType The front controller type
* @param Employee|null $employee The current employee
*
* @return string
*/
private function getDefaultController($frontControllerType, Employee $employee = null)
{
switch ($frontControllerType) {
case self::FC_ADMIN:
// Default
$defaultController = 'AdminDashboard';
// If there is an employee with a default tab set
if (null !== $employee) {
$tabClassName = $employee->getDefaultTabClassName();
if (null !== $tabClassName) {
$tabProfileAccess = Profile::getProfileAccess($employee->id_profile, Tab::getIdFromClassName($tabClassName));
if (is_array($tabProfileAccess) && isset($tabProfileAccess['view']) && $tabProfileAccess['view'] === '1') {
$defaultController = $tabClassName;
}
}
}
break;
case self::FC_MODULE:
$defaultController = 'default';
break;
default:
$defaultController = 'index';
}
$this->setDefaultController($defaultController);
return $defaultController;
}
/**
* Sets the default controller.
*
* @param string $defaultController
*/
private function setDefaultController($defaultController)
{
$this->default_controller = $defaultController;
}
/**
* Sets use_default_controller to true, sets and returns the default controller.
*
* @return string
*/
public function useDefaultController()
{
$this->use_default_controller = true;
// If it was already set just return it
if (null !== $this->default_controller) {
return $this->default_controller;
}
$employee = Context::getContext()->employee;
return $this->getDefaultController($this->front_controller, $employee);
}
/**
* Find the controller and instantiate it.
*/
public function dispatch()
{
$controller_class = '';
// Get current controller
$this->getController();
if (!$this->controller) {
$this->controller = $this->useDefaultController();
}
// Execute hook dispatcher before
Hook::exec('actionDispatcherBefore', ['controller_type' => $this->front_controller]);
// Dispatch with right front controller
switch ($this->front_controller) {
// Dispatch front office controller
case self::FC_FRONT:
$controllers = Dispatcher::getControllers([
_PS_FRONT_CONTROLLER_DIR_,
_PS_OVERRIDE_DIR_ . 'controllers/front/',
]);
$controllers['index'] = 'IndexController';
if (isset($controllers['auth'])) {
$controllers['authentication'] = $controllers['auth'];
}
if (isset($controllers['contact'])) {
$controllers['contactform'] = $controllers['contact'];
}
if (!isset($controllers[strtolower($this->controller)])) {
$this->controller = $this->controller_not_found;
}
$controller_class = $controllers[strtolower($this->controller)];
$params_hook_action_dispatcher = [
'controller_type' => self::FC_FRONT,
'controller_class' => $controller_class,
'is_module' => 0,
];
break;
// Dispatch module controller for front office
case self::FC_MODULE:
$module_name = Validate::isModuleName(Tools::getValue('module')) ? Tools::getValue('module') : '';
$module = Module::getInstanceByName($module_name);
$controller_class = 'PageNotFoundController';
if (Validate::isLoadedObject($module) && $module->active) {
$controllers = Dispatcher::getControllers(_PS_MODULE_DIR_ . "$module_name/controllers/front/");
if (isset($controllers[strtolower($this->controller)])) {
include_once _PS_MODULE_DIR_ . "$module_name/controllers/front/{$this->controller}.php";
if (file_exists(
_PS_OVERRIDE_DIR_ . "modules/$module_name/controllers/front/{$this->controller}.php"
)) {
include_once _PS_OVERRIDE_DIR_ . "modules/$module_name/controllers/front/{$this->controller}.php";
$controller_class = $module_name . $this->controller . 'ModuleFrontControllerOverride';
} else {
$controller_class = $module_name . $this->controller . 'ModuleFrontController';
}
}
}
$params_hook_action_dispatcher = [
'controller_type' => self::FC_FRONT,
'controller_class' => $controller_class,
'is_module' => 1,
];
break;
// Dispatch back office controller + module back office controller
case self::FC_ADMIN:
if ($this->use_default_controller
&& !Tools::getValue('token')
&& Validate::isLoadedObject(Context::getContext()->employee)
&& Context::getContext()->employee->isLoggedBack()
) {
Tools::redirectAdmin(
"index.php?controller={$this->controller}&token=" . Tools::getAdminTokenLite($this->controller)
);
}
$tab = Tab::getInstanceFromClassName($this->controller, Configuration::get('PS_LANG_DEFAULT'));
$retrocompatibility_admin_tab = null;
if ($tab->module) {
if (file_exists(_PS_MODULE_DIR_ . "{$tab->module}/{$tab->class_name}.php")) {
$retrocompatibility_admin_tab = _PS_MODULE_DIR_ . "{$tab->module}/{$tab->class_name}.php";
} else {
$controllers = Dispatcher::getControllers(_PS_MODULE_DIR_ . $tab->module . '/controllers/admin/');
if (!isset($controllers[strtolower($this->controller)])) {
$this->controller = $this->controller_not_found;
$controller_class = 'AdminNotFoundController';
} else {
$controller_name = $controllers[strtolower($this->controller)];
// Controllers in modules can be named AdminXXX.php or AdminXXXController.php
include_once _PS_MODULE_DIR_ . "{$tab->module}/controllers/admin/$controller_name.php";
if (file_exists(
_PS_OVERRIDE_DIR_ . "modules/{$tab->module}/controllers/admin/$controller_name.php"
)) {
include_once _PS_OVERRIDE_DIR_ . "modules/{$tab->module}/controllers/admin/$controller_name.php";
$controller_class = $controller_name . (
strpos($controller_name, 'Controller') ? 'Override' : 'ControllerOverride'
);
} else {
$controller_class = $controller_name . (
strpos($controller_name, 'Controller') ? '' : 'Controller'
);
}
}
}
$params_hook_action_dispatcher = [
'controller_type' => self::FC_ADMIN,
'controller_class' => $controller_class,
'is_module' => 1,
];
} else {
$controllers = Dispatcher::getControllers(
[
_PS_ADMIN_DIR_ . '/tabs/',
_PS_ADMIN_CONTROLLER_DIR_,
_PS_OVERRIDE_DIR_ . 'controllers/admin/',
]
);
if (!isset($controllers[strtolower($this->controller)])) {
// If this is a parent tab, load the first child
if (Validate::isLoadedObject($tab)
&& $tab->id_parent == 0
&& ($tabs = Tab::getTabs(Context::getContext()->language->id, $tab->id))
&& isset($tabs[0])
) {
Tools::redirectAdmin(Context::getContext()->link->getAdminLink($tabs[0]['class_name']));
}
$this->controller = $this->controller_not_found;
}
$controller_class = $controllers[strtolower($this->controller)];
$params_hook_action_dispatcher = [
'controller_type' => self::FC_ADMIN,
'controller_class' => $controller_class,
'is_module' => 0,
];
if (file_exists(_PS_ADMIN_DIR_ . '/tabs/' . $controller_class . '.php')) {
$retrocompatibility_admin_tab = _PS_ADMIN_DIR_ . '/tabs/' . $controller_class . '.php';
}
}
// @retrocompatibility with admin/tabs/ old system
if ($retrocompatibility_admin_tab) {
include_once $retrocompatibility_admin_tab;
include_once _PS_ADMIN_DIR_ . '/functions.php';
runAdminTab($this->controller, !empty($_REQUEST['ajaxMode']));
return;
}
break;
default:
throw new PrestaShopException('Bad front controller chosen');
}
// Instantiate controller
try {
// Loading controller
$controller = Controller::getController($controller_class);
// Execute hook dispatcher
if (isset($params_hook_action_dispatcher)) {
Hook::exec('actionDispatcher', $params_hook_action_dispatcher);
}
// Running controller
$controller->run();
// Execute hook dispatcher after
if (isset($params_hook_action_dispatcher)) {
Hook::exec('actionDispatcherAfter', $params_hook_action_dispatcher);
}
} catch (PrestaShopException $e) {
$e->displayMessage();
}
}
/**
* Sets request uri and if necessary $_GET['isolang'].
*/
protected function setRequestUri()
{
$shop = Context::getContext()->shop;
if (!Validate::isLoadedObject($shop)) {
$shop = null;
}
$this->request_uri = $this->buildRequestUri(
$this->getRequest()->getRequestUri(),
Language::isMultiLanguageActivated(),
$shop
);
}
/**
* Builds request URI and if necessary sets $_GET['isolang'].
*
* @param string $requestUri To retrieve the request URI from it
* @param bool $isMultiLanguageActivated
* @param Shop $shop
*
* @return string
*/
private function buildRequestUri($requestUri, $isMultiLanguageActivated, Shop $shop = null)
{
// Decode raw request URI
$requestUri = rawurldecode($requestUri);
// Remove the shop base URI part from the request URI
if (null !== $shop) {
$requestUri = preg_replace(
'#^' . preg_quote($shop->getBaseURI(), '#') . '#i',
'/',
$requestUri
);
}
// If there are several languages, set $_GET['isolang'] and remove the language part from the request URI
if (
$this->use_routes &&
$isMultiLanguageActivated &&
preg_match('#^/([a-z]{2})(?:/.*)?$#', $requestUri, $matches)
) {
$_GET['isolang'] = $matches[1];
$requestUri = substr($requestUri, 3);
}
return $requestUri;
}
/**
* Load default routes group by languages.
*
* @param int $id_shop
*/
protected function loadRoutes($id_shop = null)
{
$context = Context::getContext();
if (isset($context->shop) && $id_shop === null) {
$id_shop = (int) $context->shop->id;
}
// Load custom routes from modules
$modules_routes = Hook::exec('moduleRoutes', ['id_shop' => $id_shop], null, true, false);
if (is_array($modules_routes) && count($modules_routes)) {
foreach ($modules_routes as $module_route) {
if (is_array($module_route) && count($module_route)) {
foreach ($module_route as $route => $route_details) {
if (array_key_exists('controller', $route_details)
&& array_key_exists('rule', $route_details)
&& array_key_exists('keywords', $route_details)
&& array_key_exists('params', $route_details)
) {
if (!isset($this->default_routes[$route])) {
$this->default_routes[$route] = [];
}
$this->default_routes[$route] = array_merge($this->default_routes[$route], $route_details);
}
}
}
}
}
$language_ids = Language::getIDs();
if (isset($context->language) && !in_array($context->language->id, $language_ids)) {
$language_ids[] = (int) $context->language->id;
}
// Set default routes
foreach ($this->default_routes as $id => $route) {
$route = $this->computeRoute(
$route['rule'],
$route['controller'],
$route['keywords'],
isset($route['params']) ? $route['params'] : []
);
foreach ($language_ids as $id_lang) {
// the default routes are the same, whatever the language
$this->routes[$id_shop][$id_lang][$id] = $route;
}
}
// Load the custom routes prior the defaults to avoid infinite loops
if ($this->use_routes) {
// Load routes from meta table
$sql = 'SELECT m.page, ml.url_rewrite, ml.id_lang
FROM `' . _DB_PREFIX_ . 'meta` m
LEFT JOIN `' . _DB_PREFIX_ . 'meta_lang` ml ON (m.id_meta = ml.id_meta' . Shop::addSqlRestrictionOnLang('ml', (int) $id_shop) . ')
ORDER BY LENGTH(ml.url_rewrite) DESC';
if ($results = Db::getInstance()->executeS($sql)) {
foreach ($results as $row) {
if ($row['url_rewrite']) {
$this->addRoute(
$row['page'],
$row['url_rewrite'],
$row['page'],
$row['id_lang'],
[],
[],
$id_shop
);
}
}
}
// Set default empty route if no empty route (that's weird I know)
if (!$this->empty_route) {
$this->empty_route = [
'routeID' => 'index',
'rule' => '',
'controller' => 'index',
];
}
// Load custom routes
foreach ($this->default_routes as $route_id => $route_data) {
if ($custom_route = Configuration::get('PS_ROUTE_' . $route_id, null, null, $id_shop)) {
if (isset($context->language) && !in_array($context->language->id, $language_ids)) {
$language_ids[] = (int) $context->language->id;
}
$route = $this->computeRoute(
$custom_route,
$route_data['controller'],
$route_data['keywords'],
isset($route_data['params']) ? $route_data['params'] : []
);
foreach ($language_ids as $id_lang) {
// those routes are the same, whatever the language
$this->routes[$id_shop][$id_lang][$route_id] = $route;
}
}
}
}
}
/**
* Create the route array, by computing the final regex & keywords.
*
* @param string $rule Url rule
* @param string $controller Controller to call if request uri match the rule
* @param array $keywords keywords associated with the route
* @param array $params optional params of the route
*
* @return array
*/
public function computeRoute($rule, $controller, array $keywords = [], array $params = [])
{
$regexp = preg_quote($rule, '#');
if ($keywords) {
$transform_keywords = [];
preg_match_all(
'#\\\{(([^{}]*)\\\:)?(' .
implode('|', array_keys($keywords)) . ')(\\\:([^{}]*))?\\\}#',
$regexp,
$m
);
for ($i = 0, $total = count($m[0]); $i < $total; ++$i) {
$prepend = $m[2][$i];
$keyword = $m[3][$i];
$append = $m[5][$i];
$transform_keywords[$keyword] = [
'required' => isset($keywords[$keyword]['param']),
'prepend' => stripslashes($prepend),
'append' => stripslashes($append),
];
$prepend_regexp = $append_regexp = '';
if ($prepend || $append) {
$prepend_regexp = '(' . $prepend;
$append_regexp = $append . ')?';
}
if (isset($keywords[$keyword]['param'])) {
$regexp = str_replace(
$m[0][$i],
$prepend_regexp .
'(?P<' . $keywords[$keyword]['param'] . '>' . $keywords[$keyword]['regexp'] . ')' .
$append_regexp,
$regexp
);
} else {
$regexp = str_replace(
$m[0][$i],
$prepend_regexp .
'(' . $keywords[$keyword]['regexp'] . ')' .
$append_regexp,
$regexp
);
}
}
$keywords = $transform_keywords;
}
$regexp = '#^/' . $regexp . '$#u';
return [
'rule' => $rule,
'regexp' => $regexp,
'controller' => $controller,
'keywords' => $keywords,
'params' => $params,
];
}
/**
* @param string $route_id Name of the route (need to be uniq,a second route with same name will override the first)
* @param string $rule Url rule
* @param string $controller Controller to call if request uri match the rule
* @param int $id_lang
* @param array $keywords
* @param array $params
* @param int $id_shop
*/
public function addRoute(
$route_id,
$rule,
$controller,
$id_lang = null,
array $keywords = [],
array $params = [],
$id_shop = null
) {
$context = Context::getContext();
if (isset($context->language) && $id_lang === null) {
$id_lang = (int) $context->language->id;
}
if (isset($context->shop) && $id_shop === null) {
$id_shop = (int) $context->shop->id;
}
$route = $this->computeRoute($rule, $controller, $keywords, $params);
if (!isset($this->routes[$id_shop])) {
$this->routes[$id_shop] = [];
}
if (!isset($this->routes[$id_shop][$id_lang])) {
$this->routes[$id_shop][$id_lang] = [];
}
$this->routes[$id_shop][$id_lang][$route_id] = $route;
}
/**
* Check if a route exists.
*
* @param string $route_id
* @param int $id_lang
* @param int $id_shop
*
* @return bool
*/
public function hasRoute($route_id, $id_lang = null, $id_shop = null)
{
if (isset(Context::getContext()->language) && $id_lang === null) {
$id_lang = (int) Context::getContext()->language->id;
}
if (isset(Context::getContext()->shop) && $id_shop === null) {
$id_shop = (int) Context::getContext()->shop->id;
}
return isset($this->routes[$id_shop][$id_lang][$route_id]);
}
/**
* Check if a keyword is written in a route rule.
*
* @param string $route_id
* @param int $id_lang
* @param string $keyword
* @param int $id_shop
*
* @return bool
*/
public function hasKeyword($route_id, $id_lang, $keyword, $id_shop = null)
{
if ($id_shop === null) {
$id_shop = (int) Context::getContext()->shop->id;
}
if (!isset($this->routes[$id_shop])) {
$this->loadRoutes($id_shop);
}
if (!isset($this->routes[$id_shop]) || !isset($this->routes[$id_shop][$id_lang])
|| !isset($this->routes[$id_shop][$id_lang][$route_id])) {
return false;
}
return preg_match('#\{([^{}]*:)?' . preg_quote($keyword, '#') .
'(:[^{}]*)?\}#', $this->routes[$id_shop][$id_lang][$route_id]['rule']);
}
/**
* Check if a route rule contain all required keywords of default route definition.
*
* @param string $route_id
* @param string $rule Rule to verify
* @param array $errors List of missing keywords
*
* @return bool
*/
public function validateRoute($route_id, $rule, &$errors = [])
{
$errors = [];
if (!isset($this->default_routes[$route_id])) {
return false;
}
foreach ($this->default_routes[$route_id]['keywords'] as $keyword => $data) {
if (isset($data['param']) && !preg_match('#\{([^{}]*:)?' . $keyword . '(:[^{}]*)?\}#', $rule)) {
$errors[] = $keyword;
}
}
return (count($errors)) ? false : true;
}
/**
* Create an url from.
*
* @param string $route_id Name the route
* @param int $id_lang
* @param array $params
* @param bool $force_routes
* @param string $anchor Optional anchor to add at the end of this url
* @param null $id_shop
*
* @return string
*
* @throws PrestaShopException
*/
public function createUrl(
$route_id,
$id_lang = null,
array $params = [],
$force_routes = false,
$anchor = '',
$id_shop = null
) {
if ($id_lang === null) {
$id_lang = (int) Context::getContext()->language->id;
}
if ($id_shop === null) {
$id_shop = (int) Context::getContext()->shop->id;
}
if (!isset($this->routes[$id_shop])) {
$this->loadRoutes($id_shop);
}
if (!isset($this->routes[$id_shop][$id_lang][$route_id])) {
$query = http_build_query($params, '', '&');
$index_link = $this->use_routes ? '' : 'index.php';
return ($route_id == 'index') ? $index_link . (($query) ? '?' . $query : '') :
((trim($route_id) == '') ? '' : 'index.php?controller=' . $route_id) . (($query) ? '&' . $query : '') . $anchor;
}
$route = $this->routes[$id_shop][$id_lang][$route_id];
// Check required fields
$query_params = isset($route['params']) ? $route['params'] : [];
foreach ($route['keywords'] as $key => $data) {
if (!$data['required']) {
continue;
}
if (!array_key_exists($key, $params)) {
throw new PrestaShopException('Dispatcher::createUrl() miss required parameter "' . $key . '" for route "' . $route_id . '"');
}
if (isset($this->default_routes[$route_id])) {
$query_params[$this->default_routes[$route_id]['keywords'][$key]['param']] = $params[$key];
}
}
// Build an url which match a route
if ($this->use_routes || $force_routes) {
$url = $route['rule'];
$add_param = [];
foreach ($params as $key => $value) {
if (!isset($route['keywords'][$key])) {
if (!isset($this->default_routes[$route_id]['keywords'][$key])) {
$add_param[$key] = $value;
}
} else {
if ($params[$key]) {
$parameter = $params[$key];
if (is_array($parameter)) {
if (array_key_exists($id_lang, $parameter)) {
$parameter = $parameter[$id_lang];
} else {
// made the choice to return the first element of the array
$parameter = reset($parameter);
}
}
$replace = $route['keywords'][$key]['prepend'] . $parameter . $route['keywords'][$key]['append'];
} else {
$replace = '';
}
$url = preg_replace('#\{([^{}]*:)?' . $key . '(:[^{}]*)?\}#', $replace, $url);
}
}
$url = preg_replace('#\{([^{}]*:)?[a-z0-9_]+?(:[^{}]*)?\}#', '', $url);
if (count($add_param)) {
$url .= '?' . http_build_query($add_param, '', '&');
}
} else {
// Build a classic url index.php?controller=foo&...
$add_params = [];
foreach ($params as $key => $value) {
if (!isset($route['keywords'][$key]) && !isset($this->default_routes[$route_id]['keywords'][$key])) {
$add_params[$key] = $value;
}
}
if (!empty($route['controller'])) {
$query_params['controller'] = $route['controller'];
}
$query = http_build_query(array_merge($add_params, $query_params), '', '&');
if ($this->multilang_activated) {
$query .= (!empty($query) ? '&' : '') . 'id_lang=' . (int) $id_lang;
}
$url = 'index.php?' . $query;
}
return $url . $anchor;
}
/**
* Retrieve the controller from url or request uri if routes are activated.
*
* @param int $id_shop
*
* @return string
*/
public function getController($id_shop = null)
{
if (defined('_PS_ADMIN_DIR_')) {
$_GET['controllerUri'] = Tools::getValue('controller');
}
if ($this->controller) {
$_GET['controller'] = $this->controller;
return $this->controller;
}