/
WebserviceRequest.php
1905 lines (1691 loc) · 80.1 KB
/
WebserviceRequest.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 license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to https://devdocs.prestashop.com/ for more information.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
*/
class WebserviceRequestCore
{
const HTTP_GET = 1;
const HTTP_POST = 2;
const HTTP_PUT = 4;
protected $_available_languages = null;
/**
* Errors triggered at execution.
*
* @var array
*/
public $errors = [];
/**
* Set if return should display content or not.
*
* @var bool
*/
protected $_outputEnabled = true;
/**
* Set if the management is specific or if it is classic (entity management)
*
* @var WebserviceSpecificManagementImages|WebserviceSpecificManagementSearch|WebserviceSpecificManagementAttachments|false
*/
protected $objectSpecificManagement = false;
/**
* Base PrestaShop webservice URL.
*
* @var string
*/
public $wsUrl;
/**
* PrestaShop Webservice Documentation URL.
*
* @var string
*/
protected $_docUrl = 'https://devdocs.prestashop.com/1.7/webservice';
/**
* Set if the authentication key was checked.
*
* @var bool
*/
protected $_authenticated = false;
/**
* HTTP Method to support.
*
* @var string
*/
public $method;
/**
* The segment of the URL.
*
* @var array
*/
public $urlSegment = [];
/**
* The segment list of the URL after the "api" segment.
*
* @var array
*/
public $urlFragments = [];
/**
* The time in microseconds of the start of the execution of the web service request.
*
* @var int
*/
protected $_startTime = 0;
/**
* The list of each resources manageable via web service.
*
* @var array
*/
public $resourceList;
/**
* The configuration parameters of the current resource.
*
* @var array
*/
public $resourceConfiguration;
/**
* The permissions for the current key.
*
* @var array
*/
public $keyPermissions;
/**
* The XML string to display if web service call succeed.
*
* @var string
*/
protected $specificOutput = '';
/**
* The list of objects to display.
*
* @var array
*/
public $objects;
/**
* The current object to support, it extends the PrestaShop ObjectModel.
*
* @var ObjectModel
*/
protected $_object;
/**
* The schema to display.
* If null, no schema have to be displayed and normal management has to be performed.
*
* @var string
*/
public $schemaToDisplay;
/**
* The fields to display. These fields will be displayed when retrieving objects.
*
* @var string
*/
public $fieldsToDisplay = 'minimum';
/**
* If we are in PUT or POST case, we use this attribute to store the xml string value during process.
*
* @var string
*/
protected $_inputXml;
/**
* Object instance for singleton.
*
* @var WebserviceRequest
*/
protected static $_instance;
/**
* Key used for authentication.
*
* @var string
*/
protected $_key;
/**
* This is used to have a deeper tree diagram.
*
* @var int
*/
public $depth = 0;
/**
* Name of the output format.
*
* @var string
*/
protected $outputFormat = 'xml';
/**
* The object to build the output.
*
* @var WebserviceOutputBuilder
*/
protected $objOutput;
/**
* Save the class name for override used in getInstance().
*
* @var string
*/
public static $ws_current_classname;
/**
* @var array the list of shop ids, can be empty
*/
public static $shopIDs = [];
public function getOutputEnabled()
{
return $this->_outputEnabled;
}
public function setOutputEnabled($bool)
{
if (Validate::isBool($bool)) {
$this->_outputEnabled = $bool;
}
return $this;
}
/**
* Get WebserviceRequest object instance (Singleton).
*
* @return object WebserviceRequest instance
*/
public static function getInstance()
{
if (!isset(self::$_instance)) {
self::$_instance = new WebserviceRequest::$ws_current_classname();
}
return self::$_instance;
}
protected function getOutputObject($type)
{
// set header param in header or as get param
$headers = self::getallheaders();
if (isset($headers['Io-Format'])) {
$type = $headers['Io-Format'];
} elseif (isset($headers['Output-Format'])) {
$type = $headers['Output-Format'];
} elseif (isset($_GET['output_format'])) {
$type = $_GET['output_format'];
} elseif (isset($_GET['io_format'])) {
$type = $_GET['io_format'];
}
$this->outputFormat = $type;
switch ($type) {
case 'JSON':
require_once __DIR__ . '/WebserviceOutputJSON.php';
$obj_render = new WebserviceOutputJSON();
break;
case 'XML':
default:
$obj_render = new WebserviceOutputXML();
break;
}
return $obj_render;
}
public static function getResources()
{
$resources = [
'addresses' => ['description' => 'The Customer, Brand and Customer addresses', 'class' => 'Address'],
'attachments' => ['description' => 'The product Attachments', 'class' => 'Attachment', 'specific_management' => true],
'carriers' => ['description' => 'The Carriers', 'class' => 'Carrier'],
'carts' => ['description' => 'Customer\'s carts', 'class' => 'Cart'],
'cart_rules' => ['description' => 'Cart rules management', 'class' => 'CartRule'],
'categories' => ['description' => 'The product categories', 'class' => 'Category'],
'combinations' => ['description' => 'The product combinations', 'class' => 'Combination'],
'configurations' => ['description' => 'Shop configuration', 'class' => 'Configuration'],
'contacts' => ['description' => 'Shop contacts', 'class' => 'Contact'],
'countries' => ['description' => 'The countries', 'class' => 'Country'],
'currencies' => ['description' => 'The currencies', 'class' => 'Currency'],
'customers' => ['description' => 'The e-shop\'s customers', 'class' => 'Customer'],
'customer_threads' => ['description' => 'Customer services threads', 'class' => 'CustomerThread'],
'customer_messages' => ['description' => 'Customer services messages', 'class' => 'CustomerMessage'],
'deliveries' => ['description' => 'Product delivery', 'class' => 'Delivery'],
'groups' => ['description' => 'The customer\'s groups', 'class' => 'Group'],
'guests' => ['description' => 'The guests', 'class' => 'Guest'],
'images' => ['description' => 'The images', 'specific_management' => true],
'image_types' => ['description' => 'The image types', 'class' => 'ImageType'],
'languages' => ['description' => 'Shop languages', 'class' => 'Language'],
'manufacturers' => ['description' => 'The product brands', 'class' => 'Manufacturer'],
'messages' => ['description' => 'The Messages', 'class' => 'Message'],
'order_carriers' => ['description' => 'The Order carriers', 'class' => 'OrderCarrier'],
'order_cart_rules' => ['description' => 'The Order cart rules', 'class' => 'OrderCartRule'],
'order_details' => ['description' => 'Details of an order', 'class' => 'OrderDetail'],
'order_histories' => ['description' => 'The Order histories', 'class' => 'OrderHistory'],
'order_invoices' => ['description' => 'The Order invoices', 'class' => 'OrderInvoice'],
'orders' => ['description' => 'The Customers orders', 'class' => 'Order'],
'order_payments' => ['description' => 'The Order payments', 'class' => 'OrderPayment'],
'order_states' => ['description' => 'The Order statuses', 'class' => 'OrderState'],
'order_slip' => ['description' => 'The Order slips', 'class' => 'OrderSlip'],
'price_ranges' => ['description' => 'Price ranges', 'class' => 'RangePrice'],
'product_features' => ['description' => 'The product features', 'class' => 'Feature'],
'product_feature_values' => ['description' => 'The product feature values', 'class' => 'FeatureValue'],
'product_options' => ['description' => 'The product options', 'class' => 'AttributeGroup'],
'product_option_values' => ['description' => 'The product options value', 'class' => 'Attribute'],
'products' => ['description' => 'The products', 'class' => 'Product'],
'states' => ['description' => 'The available states of countries', 'class' => 'State'],
'stores' => ['description' => 'The stores', 'class' => 'Store'],
'suppliers' => ['description' => 'The product suppliers', 'class' => 'Supplier'],
'tags' => ['description' => 'The Products tags', 'class' => 'Tag'],
'translated_configurations' => ['description' => 'Shop configuration', 'class' => 'TranslatedConfiguration'],
'weight_ranges' => ['description' => 'Weight ranges', 'class' => 'RangeWeight'],
'zones' => ['description' => 'The Countries zones', 'class' => 'Zone'],
'employees' => ['description' => 'The Employees', 'class' => 'Employee'],
'search' => ['description' => 'Search', 'specific_management' => true, 'forbidden_method' => ['PUT', 'POST', 'DELETE']],
'content_management_system' => ['description' => 'Content management system', 'class' => 'CMS'],
'shops' => ['description' => 'Shops from multi-shop feature', 'class' => 'Shop'],
'shop_groups' => ['description' => 'Shop groups from multi-shop feature', 'class' => 'ShopGroup'],
'taxes' => ['description' => 'The tax rate', 'class' => 'Tax'],
'stock_movements' => ['description' => 'Stock movements', 'class' => 'StockMvtWS', 'forbidden_method' => ['PUT', 'POST', 'DELETE']],
'stock_movement_reasons' => ['description' => 'Stock movement reason', 'class' => 'StockMvtReason'],
'warehouses' => ['description' => 'Warehouses', 'class' => 'Warehouse', 'forbidden_method' => ['DELETE']],
'stocks' => ['description' => 'Stocks', 'class' => 'Stock', 'forbidden_method' => ['PUT', 'POST', 'DELETE']],
'stock_availables' => ['description' => 'Available quantities', 'class' => 'StockAvailable', 'forbidden_method' => ['POST', 'DELETE']],
'warehouse_product_locations' => ['description' => 'Location of products in warehouses', 'class' => 'WarehouseProductLocation', 'forbidden_method' => ['PUT', 'POST', 'DELETE']],
'supply_orders' => ['description' => 'Supply Orders', 'class' => 'SupplyOrder', 'forbidden_method' => ['PUT', 'POST', 'DELETE']],
'supply_order_details' => ['description' => 'Supply Order Details', 'class' => 'SupplyOrderDetail', 'forbidden_method' => ['PUT', 'POST', 'DELETE']],
'supply_order_states' => ['description' => 'Supply Order Statuses', 'class' => 'SupplyOrderState', 'forbidden_method' => ['PUT', 'POST', 'DELETE']],
'supply_order_histories' => ['description' => 'Supply Order Histories', 'class' => 'SupplyOrderHistory', 'forbidden_method' => ['PUT', 'POST', 'DELETE']],
'supply_order_receipt_histories' => ['description' => 'Supply Order Receipt Histories', 'class' => 'SupplyOrderReceiptHistory', 'forbidden_method' => ['PUT', 'POST', 'DELETE']],
'product_suppliers' => ['description' => 'Product Suppliers', 'class' => 'ProductSupplier'],
'tax_rules' => ['description' => 'Tax rules entity', 'class' => 'TaxRule'],
'tax_rule_groups' => ['description' => 'Tax rule groups', 'class' => 'TaxRulesGroup'],
'specific_prices' => ['description' => 'Specific price management', 'class' => 'SpecificPrice'],
'specific_price_rules' => ['description' => 'Specific price management', 'class' => 'SpecificPriceRule'],
'shop_urls' => ['description' => 'Shop URLs from multi-shop feature', 'class' => 'ShopUrl'],
'product_customization_fields' => ['description' => 'Customization Field', 'class' => 'CustomizationField'],
'customizations' => ['description' => 'Customization values', 'class' => 'Customization'],
];
$extra_resources = Hook::exec('addWebserviceResources', ['resources' => $resources], null, true, false);
if (is_countable($extra_resources) && count($extra_resources)) {
foreach ($extra_resources as $new_resources) {
if (is_countable($new_resources) && count($new_resources)) {
$resources = array_merge($resources, $new_resources);
}
}
}
ksort($resources);
return $resources;
}
/**
* This method is used for calculate the price for products on the output details.
*
* @param $field
* @param $entity_object
* @param $ws_params
*
* @return array field parameters
*/
public function getPriceForProduct($field, $entity_object, $ws_params)
{
if (is_int($entity_object->id)) {
$arr_return = $this->specificPriceForProduct($entity_object, ['default_price' => '']);
$field['value'] = $arr_return['default_price']['value'];
}
return $field;
}
/**
* This method is used for calculate the price for products on a virtual fields.
*
* @param $entity_object
* @param array $parameters
*
* @return array
*/
public function specificPriceForProduct($entity_object, $parameters)
{
foreach (array_keys($parameters) as $name) {
$parameters[$name]['object_id'] = $entity_object->id;
}
$arr_return = $this->specificPriceCalculation($parameters);
return $arr_return;
}
public function specificPriceCalculation($parameters)
{
$arr_return = [];
foreach ($parameters as $name => $value) {
$id_shop = (int) Context::getContext()->shop->id;
$id_country = (int) (isset($value['country']) ? $value['country'] : (Configuration::get('PS_COUNTRY_DEFAULT')));
$id_state = (int) (isset($value['state']) ? $value['state'] : 0);
$id_currency = (int) (isset($value['currency']) ? $value['currency'] : Configuration::get('PS_CURRENCY_DEFAULT'));
$id_group = (int) (isset($value['group']) ? $value['group'] : (int) Configuration::get('PS_CUSTOMER_GROUP'));
$quantity = (int) (isset($value['quantity']) ? $value['quantity'] : 1);
$use_tax = (int) (isset($value['use_tax']) ? $value['use_tax'] : Configuration::get('PS_TAX'));
$decimals = (int) (isset($value['decimals']) ? $value['decimals'] : Configuration::get('PS_PRICE_ROUND_MODE'));
$id_product_attribute = (int) (isset($value['product_attribute']) ? $value['product_attribute'] : null);
$only_reduc = (int) (isset($value['only_reduction']) ? $value['only_reduction'] : false);
$use_reduc = (int) (isset($value['use_reduction']) ? $value['use_reduction'] : true);
$use_ecotax = (int) (isset($value['use_ecotax']) ? $value['use_ecotax'] : Configuration::get('PS_USE_ECOTAX'));
$specific_price_output = null;
$id_county = (int) (isset($value['county']) ? $value['county'] : 0);
$return_value = Product::priceCalculation(
$id_shop,
$value['object_id'],
$id_product_attribute,
$id_country,
$id_state,
$id_county,
$id_currency,
$id_group,
$quantity,
$use_tax,
$decimals,
$only_reduc,
$use_reduc,
$use_ecotax,
$specific_price_output,
null
);
$arr_return[$name] = ['sqlId' => strtolower($name), 'value' => sprintf('%f', $return_value)];
}
return $arr_return;
}
/**
* This method is used for calculate the price for products on a virtual fields.
*
* @param $entity_object
* @param array $parameters
*
* @return array
*/
public function specificPriceForCombination($entity_object, $parameters)
{
foreach (array_keys($parameters) as $name) {
$parameters[$name]['object_id'] = $entity_object->id_product;
$parameters[$name]['product_attribute'] = $entity_object->id;
}
$arr_return = $this->specificPriceCalculation($parameters);
return $arr_return;
}
/**
* Start Webservice request
* Check webservice activation
* Check authentication
* Check resource
* Check HTTP Method
* Execute the action
* Display the result.
*
* @param string $key
* @param string $method
* @param string $url
* @param string $params
* @param string $bad_class_name
* @param string $inputXml
*
* @return array Returns an array of results (headers, content, type of resource...)
*/
public function fetch($key, $method, $url, $params, $bad_class_name, $inputXml = null)
{
// Time logger
$this->_startTime = microtime(true);
$this->objects = [];
// Error handler
set_error_handler([$this, 'webserviceErrorHandler']);
ini_set('html_errors', 'off');
// Two global vars, for compatibility with the PS core
global $webservice_call, $display_errors;
$webservice_call = true;
$display_errors = strtolower(ini_get('display_errors')) != 'off';
// __PS_BASE_URI__ is from Shop::$current_base_uri
$this->wsUrl = Tools::getHttpHost(true) . __PS_BASE_URI__ . 'api/';
// set the output object which manage the content and header structure and information
$this->objOutput = new WebserviceOutputBuilder($this->wsUrl);
$this->_key = trim($key);
$this->outputFormat = isset($params['output_format']) ? $params['output_format'] : $this->outputFormat;
// Set the render object to build the output on the asked format (XML, JSON, CSV, ...)
$this->objOutput->setObjectRender($this->getOutputObject($this->outputFormat));
$this->params = $params;
// Check webservice activation and request authentication
if ($this->webserviceChecks()) {
if ($bad_class_name) {
$this->setError(500, 'Class "' . htmlspecialchars($bad_class_name) . '" not found. Please update the class_name field in the webservice_account table.', 126);
}
// parse request url
$this->method = $method;
$this->urlSegment = explode('/', $url);
$this->urlFragments = $params;
$this->_inputXml = $inputXml;
$this->depth = isset($this->urlFragments['depth']) ? (int) $this->urlFragments['depth'] : $this->depth;
try {
// Method below set a particular fonction to use on the price field for products entity
// @see WebserviceRequest::getPriceForProduct() method
// @see WebserviceOutputBuilder::setSpecificField() method
//$this->objOutput->setSpecificField($this, 'getPriceForProduct', 'price', 'products');
if (isset($this->urlFragments['price'])) {
$this->objOutput->setVirtualField($this, 'specificPriceForCombination', 'combinations', $this->urlFragments['price']);
$this->objOutput->setVirtualField($this, 'specificPriceForProduct', 'products', $this->urlFragments['price']);
}
} catch (Exception $e) {
$this->setError(500, $e->getMessage(), $e->getCode());
}
if (isset($this->urlFragments['language'])) {
$this->_available_languages = $this->filterLanguage();
} else {
$this->_available_languages = Language::getIDs();
}
if (empty($this->_available_languages)) {
$this->setError(400, 'language is not available', 81);
}
// Need to set available languages for the render object.
// Thus we can filter i18n field for the output
// @see WebserviceOutputXML::renderField() method for example
$this->objOutput->objectRender->setLanguages($this->_available_languages);
// check method and resource
if (empty($this->errors) && $this->checkResource() && $this->checkHTTPMethod()) {
// The resource list is necessary for build the output
$this->objOutput->setWsResources($this->resourceList);
// if the resource is a core entity...
if (!isset($this->resourceList[$this->urlSegment[0]]['specific_management']) || !$this->resourceList[$this->urlSegment[0]]['specific_management']) {
// load resource configuration
if ($this->urlSegment[0] != '') {
/** @var ObjectModel $object */
$object = new $this->resourceList[$this->urlSegment[0]]['class']();
if (isset($this->resourceList[$this->urlSegment[0]]['parameters_attribute'])) {
$this->resourceConfiguration = $object->getWebserviceParameters($this->resourceList[$this->urlSegment[0]]['parameters_attribute']);
} else {
$this->resourceConfiguration = $object->getWebserviceParameters();
}
}
$success = false;
// execute the action
switch ($this->method) {
case 'GET':
case 'HEAD':
if ($this->executeEntityGetAndHead()) {
$success = true;
}
break;
case 'POST':
if ($this->executeEntityPost()) {
$success = true;
}
break;
case 'PUT':
if ($this->executeEntityPut()) {
$success = true;
}
break;
case 'DELETE':
$this->executeEntityDelete();
break;
}
// Need to set an object for the WebserviceOutputBuilder object in any case
// because schema need to get webserviceParameters of this object
if (isset($object)) {
$this->objects['empty'] = $object;
}
} else {
// if the management is specific
$specificObjectName = 'WebserviceSpecificManagement' . ucfirst(Tools::toCamelCase($this->urlSegment[0]));
if (!class_exists($specificObjectName)) {
$this->setError(501, sprintf('The specific management class is not implemented for the "%s" entity.', $this->urlSegment[0]), 124);
} else {
$this->setObjectSpecificManagement(new $specificObjectName());
$this->objectSpecificManagement->setObjectOutput($this->objOutput)
->setWsObject($this);
try {
$this->objectSpecificManagement->manage();
} catch (WebserviceException $e) {
if ($e->getType() == WebserviceException::DID_YOU_MEAN) {
$this->setErrorDidYouMean($e->getStatus(), $e->getMessage(), $e->getWrongValue(), $e->getAvailableValues(), $e->getCode());
} elseif ($e->getType() == WebserviceException::SIMPLE) {
$this->setError($e->getStatus(), $e->getMessage(), $e->getCode());
}
}
}
}
}
}
$return = $this->returnOutput();
unset(
$webservice_call,
$display_errors
);
return $return;
}
protected function webserviceChecks()
{
return $this->isActivated() && $this->authenticate() && $this->groupShopExists($this->params) && $this->shopExists($this->params) && $this->shopHasRight($this->_key);
}
/**
* Set a webservice error.
*
* @param int $status
* @param string $label
* @param int $code
*/
public function setError($status, $label, $code)
{
global $display_errors;
if (!isset($display_errors)) {
$display_errors = strtolower(ini_get('display_errors')) != 'off';
}
if (isset($this->objOutput)) {
$this->objOutput->setStatus($status);
}
$this->errors[] = [$code, $label];
}
/**
* Set a webservice error and propose a new value near from the available values.
*
* @param int $num
* @param string $label
* @param array $value
* @param array $values
* @param int $code
*/
public function setErrorDidYouMean($num, $label, $value, $available_values, $code)
{
$this->setError($num, $label . '. Did you mean: "' . $this->getClosest($value, $available_values) . '"?' . (count($available_values) > 1 ? ' The full list is: "' . implode('", "', $available_values) . '"' : ''), $code);
}
/**
* Return the nearest value picked in the values list.
*
* @param string $input
* @param array $words
*
* @return string
*/
protected function getClosest($input, $words)
{
$shortest = -1;
foreach ($words as $word) {
$lev = levenshtein($input, $word);
if ($lev == 0) {
$closest = $word;
$shortest = 0;
break;
}
if ($lev <= $shortest || $shortest < 0) {
$closest = $word;
$shortest = $lev;
}
}
return $closest;
}
/**
* Used to replace the default PHP error handler, in order to display PHP errors in a XML format.
*
* @param string $errno contains the level of the error raised, as an integer
* @param array $errstr contains the error message, as a string
* @param array $errfile errfile, which contains the filename that the error was raised in, as a string
* @param array $errline errline, which contains the line number the error was raised at, as an integer
*
* @return bool Always return true to avoid the default PHP error handler
*/
public function webserviceErrorHandler($errno, $errstr, $errfile, $errline)
{
$display_errors = strtolower(ini_get('display_errors')) != 'off';
if (!(error_reporting() & $errno) || $display_errors) {
return;
}
$errortype = [
E_ERROR => 'Error',
E_WARNING => 'Warning',
E_PARSE => 'Parse',
E_NOTICE => 'Notice',
E_CORE_ERROR => 'Core Error',
E_CORE_WARNING => 'Core Warning',
E_COMPILE_ERROR => 'Compile Error',
E_COMPILE_WARNING => 'Compile Warning',
E_USER_ERROR => 'Error',
E_USER_WARNING => 'User warning',
E_USER_NOTICE => 'User notice',
E_STRICT => 'Runtime Notice',
E_RECOVERABLE_ERROR => 'Recoverable error',
];
$type = (isset($errortype[$errno]) ? $errortype[$errno] : 'Unknown error');
Tools::error_log('[PHP ' . $type . ' #' . $errno . '] ' . $errstr . ' (' . $errfile . ', line ' . $errline . ')');
switch ($errno) {
case E_ERROR:
WebserviceRequest::getInstance()->setError(500, '[PHP Error #' . $errno . '] ' . $errstr . ' (' . $errfile . ', line ' . $errline . ')', 2);
break;
case E_WARNING:
WebserviceRequest::getInstance()->setError(500, '[PHP Warning #' . $errno . '] ' . $errstr . ' (' . $errfile . ', line ' . $errline . ')', 3);
break;
case E_PARSE:
WebserviceRequest::getInstance()->setError(500, '[PHP Parse #' . $errno . '] ' . $errstr . ' (' . $errfile . ', line ' . $errline . ')', 4);
break;
case E_NOTICE:
WebserviceRequest::getInstance()->setError(500, '[PHP Notice #' . $errno . '] ' . $errstr . ' (' . $errfile . ', line ' . $errline . ')', 5);
break;
case E_CORE_ERROR:
WebserviceRequest::getInstance()->setError(500, '[PHP Core #' . $errno . '] ' . $errstr . ' (' . $errfile . ', line ' . $errline . ')', 6);
break;
case E_CORE_WARNING:
WebserviceRequest::getInstance()->setError(500, '[PHP Core warning #' . $errno . '] ' . $errstr . ' (' . $errfile . ', line ' . $errline . ')', 7);
break;
case E_COMPILE_ERROR:
WebserviceRequest::getInstance()->setError(500, '[PHP Compile #' . $errno . '] ' . $errstr . ' (' . $errfile . ', line ' . $errline . ')', 8);
break;
case E_COMPILE_WARNING:
WebserviceRequest::getInstance()->setError(500, '[PHP Compile warning #' . $errno . '] ' . $errstr . ' (' . $errfile . ', line ' . $errline . ')', 9);
break;
case E_USER_ERROR:
WebserviceRequest::getInstance()->setError(500, '[PHP Error #' . $errno . '] ' . $errstr . ' (' . $errfile . ', line ' . $errline . ')', 10);
break;
case E_USER_WARNING:
WebserviceRequest::getInstance()->setError(500, '[PHP User warning #' . $errno . '] ' . $errstr . ' (' . $errfile . ', line ' . $errline . ')', 11);
break;
case E_USER_NOTICE:
WebserviceRequest::getInstance()->setError(500, '[PHP User notice #' . $errno . '] ' . $errstr . ' (' . $errfile . ', line ' . $errline . ')', 12);
break;
case E_STRICT:
WebserviceRequest::getInstance()->setError(500, '[PHP Strict #' . $errno . '] ' . $errstr . ' (' . $errfile . ', line ' . $errline . ')', 13);
break;
case E_RECOVERABLE_ERROR:
WebserviceRequest::getInstance()->setError(500, '[PHP Recoverable error #' . $errno . '] ' . $errstr . ' (' . $errfile . ', line ' . $errline . ')', 14);
break;
default:
WebserviceRequest::getInstance()->setError(500, '[PHP Unknown error #' . $errno . '] ' . $errstr . ' (' . $errfile . ', line ' . $errline . ')', 15);
}
return true;
}
/**
* Check if there is one or more error.
*
* @return bool
*/
protected function hasErrors()
{
return (bool) $this->errors;
}
/**
* Check request authentication.
*
* @return bool
*/
protected function authenticate()
{
if (!$this->hasErrors()) {
if (null === $this->_key) {
$this->setError(401, 'Please enter the authentication key as the login. No password required', 16);
} else {
if (empty($this->_key)) {
$this->setError(401, 'Authentication key is empty', 17);
} elseif (strlen($this->_key) != '32') {
$this->setError(401, 'Invalid authentication key format', 18);
} else {
if (WebserviceKey::isKeyActive($this->_key)) {
$this->keyPermissions = WebserviceKey::getPermissionForAccount($this->_key);
} else {
$this->setError(401, 'Authentification key is not active', 20);
}
if (!$this->keyPermissions) {
$this->setError(401, 'No permission for this authentication key', 21);
}
}
}
if ($this->hasErrors()) {
header('WWW-Authenticate: Basic realm="Welcome to PrestaShop Webservice, please enter the authentication key as the login. No password required."');
$this->objOutput->setStatus(401);
return false;
} else {
// only now we can say the access is authenticated
$this->_authenticated = true;
return true;
}
}
}
/**
* Check webservice activation.
*
* @return bool
*/
protected function isActivated()
{
if (!Configuration::get('PS_WEBSERVICE')) {
$this->setError(503, 'The PrestaShop webservice is disabled. Please activate it in the PrestaShop Back Office', 22);
return false;
}
return true;
}
/**
* @param string $key
*
* @return bool
*/
protected function shopHasRight($key)
{
$sql = 'SELECT 1
FROM ' . _DB_PREFIX_ . 'webservice_account wsa LEFT JOIN ' . _DB_PREFIX_ . 'webservice_account_shop wsas ON (wsa.id_webservice_account = wsas.id_webservice_account)
WHERE wsa.key = \'' . pSQL($key) . '\'';
foreach (self::$shopIDs as $id_shop) {
$OR[] = ' wsas.id_shop = ' . (int) $id_shop . ' ';
}
$sql .= ' AND (' . implode('OR', $OR) . ') ';
if (!Db::getInstance()->getValue($sql)) {
$this->setError(403, 'No permission for this key on this shop', 132);
return false;
}
return true;
}
/**
* @param $params
*
* @return bool
*/
protected function shopExists($params)
{
if (is_countable(self::$shopIDs) && count(self::$shopIDs)) {
return true;
}
if (isset($params['id_shop'])) {
if ($params['id_shop'] != 'all' && is_numeric($params['id_shop'])) {
Shop::setContext(Shop::CONTEXT_SHOP, (int) $params['id_shop']);
self::$shopIDs[] = (int) $params['id_shop'];
return true;
} elseif ($params['id_shop'] == 'all') {
Shop::setContext(Shop::CONTEXT_ALL);
self::$shopIDs = Shop::getShops(true, null, true);
return true;
}
} else {
self::$shopIDs[] = Context::getContext()->shop->id;
return true;
}
$this->setError(404, 'This shop id does not exist', 999);
return false;
}
/**
* @param $params
*
* @return bool
*/
protected function groupShopExists($params)
{
$idShopGroup = null;
if (isset($params['id_shop_group']) && is_numeric($params['id_shop_group'])) {
$idShopGroup = (int) $params['id_shop_group'];
} elseif (isset($params['id_group_shop']) && is_numeric($params['id_group_shop'])) {
$idShopGroup = (int) $params['id_group_shop'];
}
if (null !== $idShopGroup) {
Shop::setContext(Shop::CONTEXT_GROUP, $idShopGroup);
self::$shopIDs = Shop::getShops(true, $idShopGroup, true);
if (!is_countable(self::$shopIDs) || count(self::$shopIDs) == 0) {
// @FIXME Set ErrorCode !
$this->setError(500, 'This shop group doesn\'t have shops', 999);
return false;
}
}
// id_shop_group isn't mandatory
return true;
}
/**
* Check HTTP method.
*
* @return bool
*/
protected function checkHTTPMethod()
{
if (!in_array($this->method, ['GET', 'POST', 'PUT', 'DELETE', 'HEAD'])) {
$this->setError(405, 'Method ' . $this->method . ' is not valid', 23);
} elseif (isset($this->urlSegment[0], $this->resourceList[$this->urlSegment[0]]['forbidden_method']) && in_array($this->method, $this->resourceList[$this->urlSegment[0]]['forbidden_method'])) {
$this->setError(405, 'Method ' . $this->method . ' is not allowed for the resource ' . $this->urlSegment[0], 101);
} elseif ($this->urlSegment[0] && !in_array($this->method, $this->keyPermissions[$this->urlSegment[0]])) {
$this->setError(405, 'Method ' . $this->method . ' is not allowed for the resource ' . $this->urlSegment[0] . ' with this authentication key', 25);
} else {
return true;
}
return false;
}
/**
* Check resource validity.
*
* @return bool
*/
protected function checkResource()
{
$this->resourceList = $this->getResources();
$resourceNames = array_keys($this->resourceList);
if ($this->urlSegment[0] == '') {
$this->resourceConfiguration['objectsNodeName'] = 'resources';
} elseif (in_array($this->urlSegment[0], $resourceNames)) {
if (!in_array($this->urlSegment[0], array_keys($this->keyPermissions))) {
$this->setError(401, 'Resource of type "' . $this->urlSegment[0] . '" is not allowed with this authentication key', 26);
return false;
}
} else {
$this->setErrorDidYouMean(400, 'Resource of type "' . $this->urlSegment[0] . '" does not exists', $this->urlSegment[0], $resourceNames, 27);
return false;
}
return true;
}
protected function setObjects()
{
$objects = [];
$arr_avoid_id = [];
$ids = [];
if (isset($this->urlFragments['id'])) {
preg_match('#^\[(.*)\]$#Ui', $this->urlFragments['id'], $matches);
if (count($matches) > 1) {
$ids = explode(',', $matches[1]);
}
} else {
$ids[] = (int) $this->urlSegment[1];
}
if (!empty($ids)) {
foreach ($ids as $id) {
$object = new $this->resourceConfiguration['retrieveData']['className']((int) $id);
if (!$object->id) {
$arr_avoid_id[] = $id;
} else {
$objects[] = $object;
}
}