PSWebServiceLibrary.class.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. <?php
  2. /*
  3. * 2007-2022 PrestaShop SA and Contributors
  4. *
  5. * NOTICE OF LICENSE
  6. *
  7. * This source file is subject to the Open Software License (OSL 3.0)
  8. * that is bundled with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * https://opensource.org/licenses/osl-3.0.php
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@prestashop.com so we can send you a copy immediately.
  14. *
  15. * DISCLAIMER
  16. *
  17. * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
  18. * versions in the future. If you wish to customize PrestaShop for your
  19. * needs please refer to https://www.prestashop.com for more information.
  20. *
  21. * @author PrestaShop SA <contact@prestashop.com>
  22. * @copyright 2007-2022 PrestaShop SA
  23. * @license https://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  24. * International Registered Trademark & Property of PrestaShop SA
  25. * PrestaShop Webservice Library
  26. * @package PrestaShopWebservice
  27. */
  28. /**
  29. * @package PrestaShopWebservice
  30. */
  31. class PrestaShopWebservice
  32. {
  33. /** @var string Shop URL */
  34. protected $url;
  35. /** @var string Authentication key */
  36. protected $key;
  37. /** @var boolean is debug activated */
  38. protected $debug;
  39. /** @var string PS version */
  40. protected $version;
  41. /** @var string Minimal version of PrestaShop to use with this library */
  42. const psCompatibleVersionsMin = '1.4.0.0';
  43. /** @var string Maximal version of PrestaShop to use with this library */
  44. const psCompatibleVersionsMax = '8.1.1';
  45. /**
  46. * PrestaShopWebservice constructor. Throw an exception when CURL is not installed/activated
  47. * <code>
  48. * <?php
  49. * require_once('./PrestaShopWebservice.php');
  50. * try
  51. * {
  52. * $ws = new PrestaShopWebservice('https://mystore.com/', 'ZQ88PRJX5VWQHCWE4EE7SQ7HPNX00RAJ', false);
  53. * // Now we have a webservice object to play with
  54. * }
  55. * catch (PrestaShopWebserviceException $ex)
  56. * {
  57. * echo 'Error : '.$ex->getMessage();
  58. * }
  59. * ?>
  60. * </code>
  61. *
  62. * @param string $url Root URL for the shop
  63. * @param string $key Authentication key
  64. * @param mixed $debug Debug mode Activated (true) or deactivated (false)
  65. *
  66. * @throws PrestaShopWebserviceException if curl is not loaded
  67. */
  68. function __construct($url, $key, $debug = true)
  69. {
  70. if (!extension_loaded('curl')) {
  71. throw new PrestaShopWebserviceException(
  72. 'Please activate the PHP extension \'curl\' to allow use of PrestaShop webservice library'
  73. );
  74. }
  75. $this->url = $url;
  76. $this->key = $key;
  77. $this->debug = $debug;
  78. $this->version = 'unknown';
  79. }
  80. /**
  81. * Take the status code and throw an exception if the server didn't return 200 or 201 code
  82. * <p>Unique parameter must take : <br><br>
  83. * 'status_code' => Status code of an HTTP return<br>
  84. * 'response' => CURL response
  85. * </p>
  86. *
  87. * @param array $request Response elements of CURL request
  88. *
  89. * @return void
  90. * @throws PrestaShopWebserviceException if HTTP status code is not 200 or 201
  91. */
  92. protected function checkStatusCode($request)
  93. {
  94. switch ($request['status_code']) {
  95. case 200:
  96. case 201:
  97. break;
  98. case 204:
  99. $error_message = 'No content';
  100. break;
  101. case 400:
  102. $error_message = 'Bad Request';
  103. break;
  104. case 401:
  105. $error_message = 'Unauthorized';
  106. break;
  107. case 404:
  108. $error_message = 'Not Found';
  109. break;
  110. case 405:
  111. $error_message = 'Method Not Allowed';
  112. break;
  113. case 500:
  114. $error_message = 'Internal Server Error';
  115. break;
  116. default:
  117. throw new PrestaShopWebserviceException(
  118. 'This call to PrestaShop Web Services returned an unexpected HTTP status of:' . $request['status_code']
  119. );
  120. }
  121. if (!empty($error_message)) {
  122. $response = $this->parseXML($request['response']);
  123. $errors = $response->children()->children();
  124. if ($errors && count($errors) > 0) {
  125. foreach ($errors as $error) {
  126. $error_message.= ' - (Code ' . $error->code . '): ' . $error->message;
  127. }
  128. }
  129. $error_label = 'This call to PrestaShop Web Services failed and returned an HTTP status of %d. That means: %s.';
  130. throw new PrestaShopWebserviceException(sprintf($error_label, $request['status_code'], $error_message));
  131. }
  132. }
  133. /**
  134. * Provides default parameters for the curl connection(s)
  135. * @return array Default parameters for curl connection(s)
  136. */
  137. protected function getCurlDefaultParams()
  138. {
  139. $defaultParams = array(
  140. CURLOPT_HEADER => true,
  141. CURLOPT_RETURNTRANSFER => true,
  142. CURLINFO_HEADER_OUT => true,
  143. CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
  144. CURLOPT_USERPWD => $this->key . ':',
  145. CURLOPT_HTTPHEADER => array('Expect:'),
  146. //CURLOPT_SSL_VERIFYPEER => false, // reminder, in dev environment sometimes self-signed certificates are used
  147. //CURLOPT_CAINFO => "PATH2CAINFO", // ssl certificate chain checking
  148. //CURLOPT_CAPATH => "PATH2CAPATH",
  149. );
  150. return $defaultParams;
  151. }
  152. /**
  153. * Handles a CURL request to PrestaShop Webservice. Can throw exception.
  154. *
  155. * @param string $url Resource name
  156. * @param mixed $curl_params CURL parameters (sent to curl_set_opt)
  157. *
  158. * @return array status_code, response, header
  159. *
  160. * @throws PrestaShopWebserviceException
  161. */
  162. protected function executeRequest($url, $curl_params = array())
  163. {
  164. $defaultParams = $this->getCurlDefaultParams();
  165. dol_syslog("curl_init url=".$url);
  166. $session = curl_init($url);
  167. $curl_options = array();
  168. foreach ($defaultParams as $defkey => $defval) {
  169. if (isset($curl_params[$defkey])) {
  170. $curl_options[$defkey] = $curl_params[$defkey];
  171. } else {
  172. $curl_options[$defkey] = $defaultParams[$defkey];
  173. }
  174. }
  175. foreach ($curl_params as $defkey => $defval) {
  176. if (!isset($curl_options[$defkey])) {
  177. $curl_options[$defkey] = $curl_params[$defkey];
  178. }
  179. }
  180. dol_syslog("curl curl_options = ".var_export($curl_options, true));
  181. curl_setopt_array($session, $curl_options);
  182. $response = curl_exec($session);
  183. $index = strpos($response, "\r\n\r\n");
  184. if ($index === false && $curl_params[CURLOPT_CUSTOMREQUEST] != 'HEAD') {
  185. throw new PrestaShopWebserviceException('Bad HTTP response ' . $response . curl_error($session));
  186. }
  187. $header = substr($response, 0, $index);
  188. $body = substr($response, $index + 4);
  189. $headerArrayTmp = explode("\n", $header);
  190. $headerArray = array();
  191. foreach ($headerArrayTmp as &$headerItem) {
  192. $tmp = explode(':', $headerItem);
  193. $tmp = array_map('trim', $tmp);
  194. if (count($tmp) == 2) {
  195. $headerArray[$tmp[0]] = $tmp[1];
  196. }
  197. }
  198. if (array_key_exists('PSWS-Version', $headerArray)) {
  199. $this->version = $headerArray['PSWS-Version'];
  200. if (
  201. version_compare(PrestaShopWebservice::psCompatibleVersionsMin, $headerArray['PSWS-Version']) == 1 ||
  202. version_compare(PrestaShopWebservice::psCompatibleVersionsMax, $headerArray['PSWS-Version']) == -1
  203. ) {
  204. throw new PrestaShopWebserviceException(
  205. 'This library is not compatible with this version of PrestaShop. Please upgrade/downgrade this library'
  206. );
  207. }
  208. }
  209. if ($this->debug) {
  210. $this->printDebug('HTTP REQUEST HEADER', curl_getinfo($session, CURLINFO_HEADER_OUT));
  211. $this->printDebug('HTTP RESPONSE HEADER', $header);
  212. }
  213. $status_code = curl_getinfo($session, CURLINFO_HTTP_CODE);
  214. if ($status_code === 0) {
  215. throw new PrestaShopWebserviceException('CURL Error: ' . curl_error($session));
  216. }
  217. curl_close($session);
  218. if ($this->debug) {
  219. if ($curl_params[CURLOPT_CUSTOMREQUEST] == 'PUT' || $curl_params[CURLOPT_CUSTOMREQUEST] == 'POST') {
  220. $this->printDebug('XML SENT', urldecode($curl_params[CURLOPT_POSTFIELDS]));
  221. }
  222. if ($curl_params[CURLOPT_CUSTOMREQUEST] != 'DELETE' && $curl_params[CURLOPT_CUSTOMREQUEST] != 'HEAD') {
  223. $this->printDebug('RETURN HTTP BODY', $body);
  224. }
  225. }
  226. return array('status_code' => $status_code, 'response' => $body, 'header' => $header);
  227. }
  228. /**
  229. * Output debug info
  230. *
  231. * @param string $title Title
  232. * @param string $content Content
  233. * @return void
  234. */
  235. public function printDebug($title, $content)
  236. {
  237. if (php_sapi_name() == 'cli') {
  238. echo $title . PHP_EOL . $content;
  239. } else {
  240. echo '<div style="display:table;background:#CCC;font-size:8pt;padding:7px"><h6 style="font-size:9pt;margin:0">'
  241. . $title
  242. . '</h6><pre>'
  243. . htmlentities($content)
  244. . '</pre></div>';
  245. }
  246. }
  247. /**
  248. * Return version
  249. *
  250. * @return string Version
  251. */
  252. public function getVersion()
  253. {
  254. return $this->version;
  255. }
  256. /**
  257. * Load XML from string. Can throw exception
  258. *
  259. * @param string $response String from a CURL response
  260. *
  261. * @return SimpleXMLElement status_code, response
  262. * @throws PrestaShopWebserviceException
  263. */
  264. protected function parseXML($response)
  265. {
  266. if ($response != '') {
  267. libxml_clear_errors();
  268. libxml_use_internal_errors(true);
  269. $xml = simplexml_load_string(trim($response), 'SimpleXMLElement', LIBXML_NOCDATA);
  270. if (libxml_get_errors()) {
  271. $msg = var_export(libxml_get_errors(), true);
  272. libxml_clear_errors();
  273. throw new PrestaShopWebserviceException('HTTP XML response is not parsable: ' . $msg);
  274. }
  275. return $xml;
  276. } else {
  277. throw new PrestaShopWebserviceException('HTTP response is empty');
  278. }
  279. }
  280. /**
  281. * Add (POST) a resource
  282. * <p>Unique parameter must take : <br><br>
  283. * 'resource' => Resource name<br>
  284. * 'postXml' => Full XML string to add resource<br><br>
  285. * Examples are given in the tutorial</p>
  286. *
  287. * @param array $options
  288. *
  289. * @return SimpleXMLElement status_code, response
  290. * @throws PrestaShopWebserviceException
  291. */
  292. public function add($options)
  293. {
  294. $xml = '';
  295. if (isset($options['resource'], $options['postXml']) || isset($options['url'], $options['postXml'])) {
  296. $url = (isset($options['resource']) ? $this->url . '/api/' . $options['resource'] : $options['url']);
  297. $xml = $options['postXml'];
  298. if (isset($options['id_shop'])) {
  299. $url .= '&id_shop=' . $options['id_shop'];
  300. }
  301. if (isset($options['id_group_shop'])) {
  302. $url .= '&id_group_shop=' . $options['id_group_shop'];
  303. }
  304. } else {
  305. throw new PrestaShopWebserviceException('Bad parameters given');
  306. }
  307. $request = $this->executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => $xml));
  308. $this->checkStatusCode($request);
  309. return $this->parseXML($request['response']);
  310. }
  311. /**
  312. * Retrieve (GET) a resource
  313. * <p>Unique parameter must take : <br><br>
  314. * 'url' => Full URL for a GET request of Webservice (ex: https://mystore.com/api/customers/1/)<br>
  315. * OR<br>
  316. * 'resource' => Resource name,<br>
  317. * 'id' => ID of a resource you want to get<br><br>
  318. * </p>
  319. * <code>
  320. * <?php
  321. * require_once('./PrestaShopWebservice.php');
  322. * try
  323. * {
  324. * $ws = new PrestaShopWebservice('https://mystore.com/', 'ZQ88PRJX5VWQHCWE4EE7SQ7HPNX00RAJ', false);
  325. * $xml = $ws->get(array('resource' => 'orders', 'id' => 1));
  326. * // Here in $xml, a SimpleXMLElement object you can parse
  327. * foreach ($xml->children()->children() as $attName => $attValue)
  328. * echo $attName.' = '.$attValue.'<br />';
  329. * }
  330. * catch (PrestaShopWebserviceException $ex)
  331. * {
  332. * echo 'Error : '.$ex->getMessage();
  333. * }
  334. * ?>
  335. * </code>
  336. *
  337. * @param array $options Array representing resource to get.
  338. *
  339. * @return SimpleXMLElement status_code, response
  340. * @throws PrestaShopWebserviceException
  341. */
  342. public function get($options)
  343. {
  344. if (isset($options['url'])) {
  345. $url = $options['url'];
  346. } elseif (isset($options['resource'])) {
  347. $url = $this->url . '/api/' . $options['resource'];
  348. $url_params = array();
  349. if (isset($options['id'])) {
  350. $url .= '/' . $options['id'];
  351. }
  352. $params = array('filter', 'display', 'sort', 'limit', 'id_shop', 'id_group_shop', 'schema', 'language', 'date', 'price');
  353. foreach ($params as $p) {
  354. foreach ($options as $k => $o) {
  355. if (strpos($k, $p) !== false) {
  356. $url_params[$k] = $options[$k];
  357. }
  358. }
  359. }
  360. if (count($url_params) > 0) {
  361. $url .= '?' . http_build_query($url_params);
  362. }
  363. } else {
  364. throw new PrestaShopWebserviceException('Bad parameters given');
  365. }
  366. $request = $this->executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'GET'));
  367. $this->checkStatusCode($request);// check the response validity
  368. return $this->parseXML($request['response']);
  369. }
  370. /**
  371. * Head method (HEAD) a resource
  372. *
  373. * @param array $options Array representing resource for head request.
  374. *
  375. * @return SimpleXMLElement status_code, response
  376. * @throws PrestaShopWebserviceException
  377. */
  378. public function head($options)
  379. {
  380. if (isset($options['url'])) {
  381. $url = $options['url'];
  382. } elseif (isset($options['resource'])) {
  383. $url = $this->url . '/api/' . $options['resource'];
  384. $url_params = array();
  385. if (isset($options['id'])) {
  386. $url .= '/' . $options['id'];
  387. }
  388. $params = array('filter', 'display', 'sort', 'limit');
  389. foreach ($params as $p) {
  390. foreach ($options as $k => $o) {
  391. if (strpos($k, $p) !== false) {
  392. $url_params[$k] = $options[$k];
  393. }
  394. }
  395. }
  396. if (count($url_params) > 0) {
  397. $url .= '?' . http_build_query($url_params);
  398. }
  399. } else {
  400. throw new PrestaShopWebserviceException('Bad parameters given');
  401. }
  402. $request = $this->executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'HEAD', CURLOPT_NOBODY => true));
  403. $this->checkStatusCode($request);// check the response validity
  404. return $request['header'];
  405. }
  406. /**
  407. * Edit (PUT) a resource
  408. * <p>Unique parameter must take : <br><br>
  409. * 'resource' => Resource name ,<br>
  410. * 'id' => ID of a resource you want to edit,<br>
  411. * 'putXml' => Modified XML string of a resource<br><br>
  412. * Examples are given in the tutorial</p>
  413. *
  414. * @param array $options Array representing resource to edit.
  415. *
  416. * @return SimpleXMLElement
  417. * @throws PrestaShopWebserviceException
  418. */
  419. public function edit($options)
  420. {
  421. $xml = '';
  422. if (isset($options['url'])) {
  423. $url = $options['url'];
  424. } elseif ((isset($options['resource'], $options['id']) || isset($options['url'])) && $options['putXml']) {
  425. $url = (isset($options['url']) ? $options['url'] :
  426. $this->url . '/api/' . $options['resource'] . '/' . $options['id']);
  427. $xml = $options['putXml'];
  428. if (isset($options['id_shop'])) {
  429. $url .= '&id_shop=' . $options['id_shop'];
  430. }
  431. if (isset($options['id_group_shop'])) {
  432. $url .= '&id_group_shop=' . $options['id_group_shop'];
  433. }
  434. } else {
  435. throw new PrestaShopWebserviceException('Bad parameters given');
  436. }
  437. $request = $this->executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'PUT', CURLOPT_POSTFIELDS => $xml));
  438. $this->checkStatusCode($request);// check the response validity
  439. return $this->parseXML($request['response']);
  440. }
  441. /**
  442. * Delete (DELETE) a resource.
  443. * Unique parameter must take : <br><br>
  444. * 'resource' => Resource name<br>
  445. * 'id' => ID or array which contains IDs of a resource(s) you want to delete<br><br>
  446. * <code>
  447. * <?php
  448. * require_once('./PrestaShopWebservice.php');
  449. * try
  450. * {
  451. * $ws = new PrestaShopWebservice('https://mystore.com/', 'ZQ88PRJX5VWQHCWE4EE7SQ7HPNX00RAJ', false);
  452. * $xml = $ws->delete(array('resource' => 'orders', 'id' => 1));
  453. * // Following code will not be executed if an exception is thrown.
  454. * echo 'Successfully deleted.';
  455. * }
  456. * catch (PrestaShopWebserviceException $ex)
  457. * {
  458. * echo 'Error : '.$ex->getMessage();
  459. * }
  460. * ?>
  461. * </code>
  462. *
  463. * @param array $options Array representing resource to delete.
  464. *
  465. * @return bool
  466. * @throws PrestaShopWebserviceException
  467. */
  468. public function delete($options)
  469. {
  470. if (isset($options['url'])) {
  471. $url = $options['url'];
  472. } elseif (isset($options['resource']) && isset($options['id'])) {
  473. $url = (is_array($options['id']))
  474. ? $this->url . '/api/' . $options['resource'] . '/?id=[' . implode(',', $options['id']) . ']'
  475. : $this->url . '/api/' . $options['resource'] . '/' . $options['id'];
  476. } else {
  477. throw new PrestaShopWebserviceException('Bad parameters given');
  478. }
  479. if (isset($options['id_shop'])) {
  480. $url .= '&id_shop=' . $options['id_shop'];
  481. }
  482. if (isset($options['id_group_shop'])) {
  483. $url .= '&id_group_shop=' . $options['id_group_shop'];
  484. }
  485. $request = $this->executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'DELETE'));
  486. $this->checkStatusCode($request);// check the response validity
  487. return true;
  488. }
  489. }
  490. /**
  491. * @package PrestaShopWebservice
  492. */
  493. class PrestaShopWebserviceException extends Exception
  494. {
  495. }