forked from PrestaShop/PrestaShop-webservice-lib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PSWebServiceLibrary.php
520 lines (480 loc) · 18.4 KB
/
PSWebServiceLibrary.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
<?php
/*
* 2007-2022 PrestaShop SA and Contributors
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to https://www.prestashop.com for more information.
*
* @author PrestaShop SA <[email protected]>
* @copyright 2007-2022 PrestaShop SA
* @license https://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
* PrestaShop Webservice Library
* @package PrestaShopWebservice
*/
/**
* @package PrestaShopWebservice
*/
class PrestaShopWebservice
{
/** @var string Shop URL */
protected $url;
/** @var string Authentication key */
protected $key;
/** @var boolean is debug activated */
protected $debug;
/** @var string PS version */
protected $version;
/** @var string Minimal version of PrestaShop to use with this library */
const psCompatibleVersionsMin = '1.4.0.0';
/** @var string Maximal version of PrestaShop to use with this library */
const psCompatibleVersionsMax = '8.1.1';
/**
* PrestaShopWebservice constructor. Throw an exception when CURL is not installed/activated
* <code>
* <?php
* require_once('./PrestaShopWebservice.php');
* try
* {
* $ws = new PrestaShopWebservice('https://mystore.com/', 'ZQ88PRJX5VWQHCWE4EE7SQ7HPNX00RAJ', false);
* // Now we have a webservice object to play with
* }
* catch (PrestaShopWebserviceException $ex)
* {
* echo 'Error : '.$ex->getMessage();
* }
* ?>
* </code>
*
* @param string $url Root URL for the shop
* @param string $key Authentication key
* @param mixed $debug Debug mode Activated (true) or deactivated (false)
*
* @throws PrestaShopWebserviceException if curl is not loaded
*/
function __construct($url, $key, $debug = true)
{
if (!extension_loaded('curl')) {
throw new PrestaShopWebserviceException(
'Please activate the PHP extension \'curl\' to allow use of PrestaShop webservice library'
);
}
$this->url = $url;
$this->key = $key;
$this->debug = $debug;
$this->version = 'unknown';
}
/**
* Take the status code and throw an exception if the server didn't return 200 or 201 code
* <p>Unique parameter must take : <br><br>
* 'status_code' => Status code of an HTTP return<br>
* 'response' => CURL response
* </p>
*
* @param array $request Response elements of CURL request
*
* @throws PrestaShopWebserviceException if HTTP status code is not 200 or 201
*/
protected function checkStatusCode($request)
{
switch ($request['status_code']) {
case 200:
case 201:
break;
case 204:
$error_message = 'No content';
break;
case 400:
$error_message = 'Bad Request';
break;
case 401:
$error_message = 'Unauthorized';
break;
case 404:
$error_message = 'Not Found';
break;
case 405:
$error_message = 'Method Not Allowed';
break;
case 500:
$error_message = 'Internal Server Error';
break;
default:
throw new PrestaShopWebserviceException(
'This call to PrestaShop Web Services returned an unexpected HTTP status of:' . $request['status_code']
);
}
if (!empty($error_message)) {
$response = $this->parseXML($request['response']);
$errors = $response->children()->children();
if ($errors && count($errors) > 0) {
foreach ($errors as $error) {
$error_message.= ' - (Code ' . $error->code . '): ' . $error->message;
}
}
$error_label = 'This call to PrestaShop Web Services failed and returned an HTTP status of %d. That means: %s.';
throw new PrestaShopWebserviceException(sprintf($error_label, $request['status_code'], $error_message));
}
}
/**
* Provides default parameters for the curl connection(s)
* @return array Default parameters for curl connection(s)
*/
protected function getCurlDefaultParams()
{
$defaultParams = array(
CURLOPT_HEADER => true,
CURLOPT_RETURNTRANSFER => true,
CURLINFO_HEADER_OUT => true,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => $this->key . ':',
CURLOPT_HTTPHEADER => array('Expect:'),
//CURLOPT_SSL_VERIFYPEER => false, // reminder, in dev environment sometimes self-signed certificates are used
//CURLOPT_CAINFO => "PATH2CAINFO", // ssl certificate chain checking
//CURLOPT_CAPATH => "PATH2CAPATH",
);
return $defaultParams;
}
/**
* Handles a CURL request to PrestaShop Webservice. Can throw exception.
*
* @param string $url Resource name
* @param mixed $curl_params CURL parameters (sent to curl_set_opt)
*
* @return array status_code, response, header
*
* @throws PrestaShopWebserviceException
*/
protected function executeRequest($url, $curl_params = array())
{
$defaultParams = $this->getCurlDefaultParams();
$session = curl_init($url);
$curl_options = array();
foreach ($defaultParams as $defkey => $defval) {
if (isset($curl_params[$defkey])) {
$curl_options[$defkey] = $curl_params[$defkey];
} else {
$curl_options[$defkey] = $defaultParams[$defkey];
}
}
foreach ($curl_params as $defkey => $defval) {
if (!isset($curl_options[$defkey])) {
$curl_options[$defkey] = $curl_params[$defkey];
}
}
curl_setopt_array($session, $curl_options);
$response = curl_exec($session);
$index = strpos($response, "\r\n\r\n");
if ($index === false && $curl_params[CURLOPT_CUSTOMREQUEST] != 'HEAD') {
throw new PrestaShopWebserviceException('Bad HTTP response ' . $response . curl_error($session));
}
$header = substr($response, 0, $index);
$body = substr($response, $index + 4);
$headerArrayTmp = explode("\n", $header);
$headerArray = array();
foreach ($headerArrayTmp as &$headerItem) {
$tmp = explode(':', $headerItem);
$tmp = array_map('trim', $tmp);
if (count($tmp) == 2) {
$headerArray[$tmp[0]] = $tmp[1];
}
}
if (array_key_exists('PSWS-Version', $headerArray)) {
$this->version = $headerArray['PSWS-Version'];
if (
version_compare(PrestaShopWebservice::psCompatibleVersionsMin, $headerArray['PSWS-Version']) == 1 ||
version_compare(PrestaShopWebservice::psCompatibleVersionsMax, $headerArray['PSWS-Version']) == -1
) {
throw new PrestaShopWebserviceException(
'This library is not compatible with this version of PrestaShop. Please upgrade/downgrade this library'
);
}
}
if ($this->debug) {
$this->printDebug('HTTP REQUEST HEADER', curl_getinfo($session, CURLINFO_HEADER_OUT));
$this->printDebug('HTTP RESPONSE HEADER', $header);
}
$status_code = curl_getinfo($session, CURLINFO_HTTP_CODE);
if ($status_code === 0) {
throw new PrestaShopWebserviceException('CURL Error: ' . curl_error($session));
}
curl_close($session);
if ($this->debug) {
if ($curl_params[CURLOPT_CUSTOMREQUEST] == 'PUT' || $curl_params[CURLOPT_CUSTOMREQUEST] == 'POST') {
$this->printDebug('XML SENT', urldecode($curl_params[CURLOPT_POSTFIELDS]));
}
if ($curl_params[CURLOPT_CUSTOMREQUEST] != 'DELETE' && $curl_params[CURLOPT_CUSTOMREQUEST] != 'HEAD') {
$this->printDebug('RETURN HTTP BODY', $body);
}
}
return array('status_code' => $status_code, 'response' => $body, 'header' => $header);
}
public function printDebug($title, $content)
{
if (php_sapi_name() == 'cli') {
echo $title . PHP_EOL . $content;
} else {
echo '<div style="display:table;background:#CCC;font-size:8pt;padding:7px"><h6 style="font-size:9pt;margin:0">'
. $title
. '</h6><pre>'
. htmlentities($content)
. '</pre></div>';
}
}
public function getVersion()
{
return $this->version;
}
/**
* Load XML from string. Can throw exception
*
* @param string $response String from a CURL response
*
* @return SimpleXMLElement status_code, response
* @throws PrestaShopWebserviceException
*/
protected function parseXML($response)
{
if ($response != '') {
libxml_clear_errors();
libxml_use_internal_errors(true);
$xml = simplexml_load_string(trim($response), 'SimpleXMLElement', LIBXML_NOCDATA);
if (libxml_get_errors()) {
$msg = var_export(libxml_get_errors(), true);
libxml_clear_errors();
throw new PrestaShopWebserviceException('HTTP XML response is not parsable: ' . $msg);
}
return $xml;
} else {
throw new PrestaShopWebserviceException('HTTP response is empty');
}
}
/**
* Add (POST) a resource
* <p>Unique parameter must take : <br><br>
* 'resource' => Resource name<br>
* 'postXml' => Full XML string to add resource<br><br>
* Examples are given in the tutorial</p>
*
* @param array $options
*
* @return SimpleXMLElement status_code, response
* @throws PrestaShopWebserviceException
*/
public function add($options)
{
$xml = '';
if (isset($options['resource'], $options['postXml']) || isset($options['url'], $options['postXml'])) {
$url = (isset($options['resource']) ? $this->url . '/api/' . $options['resource'] : $options['url']);
$xml = $options['postXml'];
if (isset($options['id_shop'])) {
$url .= '&id_shop=' . $options['id_shop'];
}
if (isset($options['id_group_shop'])) {
$url .= '&id_group_shop=' . $options['id_group_shop'];
}
} else {
throw new PrestaShopWebserviceException('Bad parameters given');
}
$request = $this->executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => $xml));
$this->checkStatusCode($request);
return $this->parseXML($request['response']);
}
/**
* Retrieve (GET) a resource
* <p>Unique parameter must take : <br><br>
* 'url' => Full URL for a GET request of Webservice (ex: https://mystore.com/api/customers/1/)<br>
* OR<br>
* 'resource' => Resource name,<br>
* 'id' => ID of a resource you want to get<br><br>
* </p>
* <code>
* <?php
* require_once('./PrestaShopWebservice.php');
* try
* {
* $ws = new PrestaShopWebservice('https://mystore.com/', 'ZQ88PRJX5VWQHCWE4EE7SQ7HPNX00RAJ', false);
* $xml = $ws->get(array('resource' => 'orders', 'id' => 1));
* // Here in $xml, a SimpleXMLElement object you can parse
* foreach ($xml->children()->children() as $attName => $attValue)
* echo $attName.' = '.$attValue.'<br />';
* }
* catch (PrestaShopWebserviceException $ex)
* {
* echo 'Error : '.$ex->getMessage();
* }
* ?>
* </code>
*
* @param array $options Array representing resource to get.
*
* @return SimpleXMLElement status_code, response
* @throws PrestaShopWebserviceException
*/
public function get($options)
{
if (isset($options['url'])) {
$url = $options['url'];
} elseif (isset($options['resource'])) {
$url = $this->url . '/api/' . $options['resource'];
$url_params = array();
if (isset($options['id'])) {
$url .= '/' . $options['id'];
}
$params = array('filter', 'display', 'sort', 'limit', 'id_shop', 'id_group_shop', 'schema', 'language', 'date', 'price');
foreach ($params as $p) {
foreach ($options as $k => $o) {
if (strpos($k, $p) !== false) {
$url_params[$k] = $options[$k];
}
}
}
if (count($url_params) > 0) {
$url .= '?' . http_build_query($url_params);
}
} else {
throw new PrestaShopWebserviceException('Bad parameters given');
}
$request = $this->executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'GET'));
$this->checkStatusCode($request);// check the response validity
return $this->parseXML($request['response']);
}
/**
* Head method (HEAD) a resource
*
* @param array $options Array representing resource for head request.
*
* @return SimpleXMLElement status_code, response
* @throws PrestaShopWebserviceException
*/
public function head($options)
{
if (isset($options['url'])) {
$url = $options['url'];
} elseif (isset($options['resource'])) {
$url = $this->url . '/api/' . $options['resource'];
$url_params = array();
if (isset($options['id'])) {
$url .= '/' . $options['id'];
}
$params = array('filter', 'display', 'sort', 'limit');
foreach ($params as $p) {
foreach ($options as $k => $o) {
if (strpos($k, $p) !== false) {
$url_params[$k] = $options[$k];
}
}
}
if (count($url_params) > 0) {
$url .= '?' . http_build_query($url_params);
}
} else {
throw new PrestaShopWebserviceException('Bad parameters given');
}
$request = $this->executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'HEAD', CURLOPT_NOBODY => true));
$this->checkStatusCode($request);// check the response validity
return $request['header'];
}
/**
* Edit (PUT) a resource
* <p>Unique parameter must take : <br><br>
* 'resource' => Resource name ,<br>
* 'id' => ID of a resource you want to edit,<br>
* 'putXml' => Modified XML string of a resource<br><br>
* Examples are given in the tutorial</p>
*
* @param array $options Array representing resource to edit.
*
* @return SimpleXMLElement
* @throws PrestaShopWebserviceException
*/
public function edit($options)
{
$xml = '';
if (isset($options['url'])) {
$url = $options['url'];
} elseif ((isset($options['resource'], $options['id']) || isset($options['url'])) && $options['putXml']) {
$url = (isset($options['url']) ? $options['url'] :
$this->url . '/api/' . $options['resource'] . '/' . $options['id']);
$xml = $options['putXml'];
if (isset($options['id_shop'])) {
$url .= '&id_shop=' . $options['id_shop'];
}
if (isset($options['id_group_shop'])) {
$url .= '&id_group_shop=' . $options['id_group_shop'];
}
} else {
throw new PrestaShopWebserviceException('Bad parameters given');
}
$request = $this->executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'PUT', CURLOPT_POSTFIELDS => $xml));
$this->checkStatusCode($request);// check the response validity
return $this->parseXML($request['response']);
}
/**
* Delete (DELETE) a resource.
* Unique parameter must take : <br><br>
* 'resource' => Resource name<br>
* 'id' => ID or array which contains IDs of a resource(s) you want to delete<br><br>
* <code>
* <?php
* require_once('./PrestaShopWebservice.php');
* try
* {
* $ws = new PrestaShopWebservice('https://mystore.com/', 'ZQ88PRJX5VWQHCWE4EE7SQ7HPNX00RAJ', false);
* $xml = $ws->delete(array('resource' => 'orders', 'id' => 1));
* // Following code will not be executed if an exception is thrown.
* echo 'Successfully deleted.';
* }
* catch (PrestaShopWebserviceException $ex)
* {
* echo 'Error : '.$ex->getMessage();
* }
* ?>
* </code>
*
* @param array $options Array representing resource to delete.
*
* @return bool
* @throws PrestaShopWebserviceException
*/
public function delete($options)
{
if (isset($options['url'])) {
$url = $options['url'];
} elseif (isset($options['resource']) && isset($options['id'])) {
$url = (is_array($options['id']))
? $this->url . '/api/' . $options['resource'] . '/?id=[' . implode(',', $options['id']) . ']'
: $this->url . '/api/' . $options['resource'] . '/' . $options['id'];
} else {
throw new PrestaShopWebserviceException('Bad parameters given');
}
if (isset($options['id_shop'])) {
$url .= '&id_shop=' . $options['id_shop'];
}
if (isset($options['id_group_shop'])) {
$url .= '&id_group_shop=' . $options['id_group_shop'];
}
$request = $this->executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'DELETE'));
$this->checkStatusCode($request);// check the response validity
return true;
}
}
/**
* @package PrestaShopWebservice
*/
class PrestaShopWebserviceException extends Exception
{
}