Advertisement
Guest User

PSWebServiceLibrary.php

a guest
Feb 18th, 2020
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.21 KB | None | 0 0
  1. <?php
  2. /*
  3. * 2007-2013 PrestaShop
  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. * http://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 http://www.prestashop.com for more information.
  20. *
  21. * @author PrestaShop SA <contact@prestashop.com>
  22. * @copyright 2007-2013 PrestaShop SA
  23. * @license http://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. /**
  30. * @package PrestaShopWebservice
  31. */
  32. class PrestaShopWebservice
  33. {
  34.  
  35. /** @var string Shop URL */
  36. protected $url;
  37.  
  38. /** @var string Authentification key */
  39. protected $key;
  40.  
  41. /** @var boolean is debug activated */
  42. protected $debug;
  43.  
  44. /** @var string PS version */
  45. protected $version;
  46.  
  47. /** @var array compatible versions of PrestaShop Webservice */
  48. const psCompatibleVersionsMin = '1.4.0.0';
  49. const psCompatibleVersionsMax = '1.6.1.24';
  50.  
  51. /**
  52. * PrestaShopWebservice constructor. Throw an exception when CURL is not installed/activated
  53. * <code>
  54. * <?php
  55. * require_once('./PrestaShopWebservice.php');
  56. * try
  57. * {
  58. * $ws = new PrestaShopWebservice('http://mystore.com/', 'ZQ88PRJX5VWQHCWE4EE7SQ7HPNX00RAJ', false);
  59. * // Now we have a webservice object to play with
  60. * }
  61. * catch (PrestaShopWebserviceException $ex)
  62. * {
  63. * echo 'Error : '.$ex->getMessage();
  64. * }
  65. * ?>
  66. * </code>
  67. * @param string $url Root URL for the shop
  68. * @param string $key Authentification key
  69. * @param mixed $debug Debug mode Activated (true) or deactivated (false)
  70. */
  71. function __construct($url, $key, $debug = true) {
  72. if (!extension_loaded('curl'))
  73. throw new PrestaShopWebserviceException('Please activate the PHP extension \'curl\' to allow use of PrestaShop webservice library');
  74. $this->url = $url;
  75. $this->key = $key;
  76. $this->debug = $debug;
  77. $this->version = 'unknown';
  78. }
  79.  
  80. /**
  81. * Take the status code and throw an exception if the server didn't return 200 or 201 code
  82. * @param int $status_code Status code of an HTTP return
  83. */
  84. protected function checkStatusCode($status_code)
  85. {
  86. $error_label = 'This call to PrestaShop Web Services failed and returned an HTTP status of %d. That means: %s.';
  87. switch($status_code)
  88. {
  89. case 200: case 201: break;
  90. case 204: throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'No content'));break;
  91. case 400: throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'Bad Request'));break;
  92. case 401: throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'Unauthorized'));break;
  93. case 404: throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'Not Found'));break;
  94. case 405: throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'Method Not Allowed'));break;
  95. case 500: throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'Internal Server Error'));break;
  96. default: throw new PrestaShopWebserviceException('This call to PrestaShop Web Services returned an unexpected HTTP status of:' . $status_code);
  97. }
  98. }
  99. /**
  100. * Handles a CURL request to PrestaShop Webservice. Can throw exception.
  101. * @param string $url Resource name
  102. * @param mixed $curl_params CURL parameters (sent to curl_set_opt)
  103. * @return array status_code, response
  104. */
  105. protected function executeRequest($url, $curl_params = array())
  106. {
  107. $defaultParams = array(
  108. CURLOPT_HEADER => TRUE,
  109. CURLOPT_RETURNTRANSFER => TRUE,
  110. CURLINFO_HEADER_OUT => TRUE,
  111. CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
  112. CURLOPT_USERPWD => $this->key.':',
  113. CURLOPT_HTTPHEADER => array( 'Expect:' )
  114. );
  115.  
  116. $session = curl_init($url);
  117.  
  118. $curl_options = array();
  119. foreach ($defaultParams as $defkey => $defval)
  120. {
  121. if (isset($curl_params[$defkey]))
  122. $curl_options[$defkey] = $curl_params[$defkey];
  123. else
  124. $curl_options[$defkey] = $defaultParams[$defkey];
  125. }
  126. foreach ($curl_params as $defkey => $defval)
  127. if (!isset($curl_options[$defkey]))
  128. $curl_options[$defkey] = $curl_params[$defkey];
  129.  
  130. curl_setopt_array($session, $curl_options);
  131. $response = curl_exec($session);
  132.  
  133. $index = strpos($response, "\r\n\r\n");
  134. if ($index === false && $curl_params[CURLOPT_CUSTOMREQUEST] != 'HEAD')
  135. throw new PrestaShopWebserviceException('Bad HTTP response');
  136.  
  137. $header = substr($response, 0, $index);
  138. $body = substr($response, $index + 4);
  139.  
  140. $headerArrayTmp = explode("\n", $header);
  141.  
  142. $headerArray = array();
  143. foreach ($headerArrayTmp as &$headerItem)
  144. {
  145. $tmp = explode(':', $headerItem);
  146. $tmp = array_map('trim', $tmp);
  147. if (count($tmp) == 2)
  148. $headerArray[$tmp[0]] = $tmp[1];
  149. }
  150.  
  151. if (array_key_exists('PSWS-Version', $headerArray))
  152. {
  153. $this->version = $headerArray['PSWS-Version'];
  154. if (
  155. version_compare(PrestaShopWebservice::psCompatibleVersionsMin, $headerArray['PSWS-Version']) == 1 ||
  156. version_compare(PrestaShopWebservice::psCompatibleVersionsMax, $headerArray['PSWS-Version']) == -1
  157. )
  158. throw new PrestaShopWebserviceException('This library is not compatible with this version of PrestaShop. Please upgrade/downgrade this library');
  159. }
  160.  
  161. if ($this->debug)
  162. {
  163. $this->printDebug('HTTP REQUEST HEADER', curl_getinfo($session, CURLINFO_HEADER_OUT));
  164. $this->printDebug('HTTP RESPONSE HEADER', $header);
  165.  
  166. }
  167. $status_code = curl_getinfo($session, CURLINFO_HTTP_CODE);
  168. if ($status_code === 0)
  169. throw new PrestaShopWebserviceException('CURL Error: '.curl_error($session));
  170. curl_close($session);
  171. if ($this->debug)
  172. {
  173. if ($curl_params[CURLOPT_CUSTOMREQUEST] == 'PUT' || $curl_params[CURLOPT_CUSTOMREQUEST] == 'POST')
  174. $this->printDebug('XML SENT', urldecode($curl_params[CURLOPT_POSTFIELDS]));
  175. if ($curl_params[CURLOPT_CUSTOMREQUEST] != 'DELETE' && $curl_params[CURLOPT_CUSTOMREQUEST] != 'HEAD')
  176. $this->printDebug('RETURN HTTP BODY', $body);
  177. }
  178. return array('status_code' => $status_code, 'response' => $body, 'header' => $header);
  179. }
  180.  
  181. public function printDebug($title, $content)
  182. {
  183. 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>';
  184. }
  185.  
  186. public function getVersion()
  187. {
  188. return $this->version;
  189. }
  190.  
  191. /**
  192. * Load XML from string. Can throw exception
  193. * @param string $response String from a CURL response
  194. * @return SimpleXMLElement status_code, response
  195. */
  196. protected function parseXML($response)
  197. {
  198. if ($response != '')
  199. {
  200. libxml_clear_errors();
  201. libxml_use_internal_errors(true);
  202. $xml = simplexml_load_string($response,'SimpleXMLElement', LIBXML_NOCDATA);
  203. if (libxml_get_errors())
  204. {
  205. $msg = var_export(libxml_get_errors(), true);
  206. libxml_clear_errors();
  207. throw new PrestaShopWebserviceException('HTTP XML response is not parsable: '.$msg);
  208. }
  209. return $xml;
  210. }
  211. else
  212. throw new PrestaShopWebserviceException('HTTP response is empty');
  213. }
  214.  
  215. /**
  216. * Add (POST) a resource
  217. * <p>Unique parameter must take : <br><br>
  218. * 'resource' => Resource name<br>
  219. * 'postXml' => Full XML string to add resource<br><br>
  220. * Examples are given in the tutorial</p>
  221. * @param array $options
  222. * @return SimpleXMLElement status_code, response
  223. */
  224. public function add($options)
  225. {
  226. $xml = '';
  227.  
  228. if (isset($options['resource'], $options['postXml']) || isset($options['url'], $options['postXml']))
  229. {
  230. $url = (isset($options['resource']) ? $this->url.'/api/'.$options['resource'] : $options['url']);
  231. $xml = $options['postXml'];
  232. if (isset($options['id_shop']))
  233. $url .= '&id_shop='.$options['id_shop'];
  234. if (isset($options['id_group_shop']))
  235. $url .= '&id_group_shop='.$options['id_group_shop'];
  236. }
  237. else
  238. throw new PrestaShopWebserviceException('Bad parameters given');
  239. $request = self::executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => $xml));
  240.  
  241. self::checkStatusCode($request['status_code']);
  242. return self::parseXML($request['response']);
  243. }
  244.  
  245. /**
  246. * Retrieve (GET) a resource
  247. * <p>Unique parameter must take : <br><br>
  248. * 'url' => Full URL for a GET request of Webservice (ex: http://mystore.com/api/customers/1/)<br>
  249. * OR<br>
  250. * 'resource' => Resource name,<br>
  251. * 'id' => ID of a resource you want to get<br><br>
  252. * </p>
  253. * <code>
  254. * <?php
  255. * require_once('./PrestaShopWebservice.php');
  256. * try
  257. * {
  258. * $ws = new PrestaShopWebservice('http://mystore.com/', 'ZQ88PRJX5VWQHCWE4EE7SQ7HPNX00RAJ', false);
  259. * $xml = $ws->get(array('resource' => 'orders', 'id' => 1));
  260. * // Here in $xml, a SimpleXMLElement object you can parse
  261. * foreach ($xml->children()->children() as $attName => $attValue)
  262. * echo $attName.' = '.$attValue.'<br />';
  263. * }
  264. * catch (PrestaShopWebserviceException $ex)
  265. * {
  266. * echo 'Error : '.$ex->getMessage();
  267. * }
  268. * ?>
  269. * </code>
  270. * @param array $options Array representing resource to get.
  271. * @return SimpleXMLElement status_code, response
  272. */
  273. public function get($options)
  274. {
  275. if (isset($options['url']))
  276. $url = $options['url'];
  277. elseif (isset($options['resource']))
  278. {
  279. $url = $this->url.'/api/'.$options['resource'];
  280. $url_params = array();
  281. if (isset($options['id']))
  282. $url .= '/'.$options['id'];
  283.  
  284. $params = array('filter', 'display', 'sort', 'limit', 'id_shop', 'id_group_shop');
  285. foreach ($params as $p)
  286. foreach ($options as $k => $o)
  287. if (strpos($k, $p) !== false)
  288. $url_params[$k] = $options[$k];
  289. if (count($url_params) > 0)
  290. $url .= '?'.http_build_query($url_params);
  291. }
  292. else
  293. throw new PrestaShopWebserviceException('Bad parameters given');
  294.  
  295. $request = self::executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'GET'));
  296.  
  297. self::checkStatusCode($request['status_code']);// check the response validity
  298. return self::parseXML($request['response']);
  299. }
  300.  
  301. /**
  302. * Head method (HEAD) a resource
  303. *
  304. * @param array $options Array representing resource for head request.
  305. * @return SimpleXMLElement status_code, response
  306. */
  307. public function head($options)
  308. {
  309. if (isset($options['url']))
  310. $url = $options['url'];
  311. elseif (isset($options['resource']))
  312. {
  313. $url = $this->url.'/api/'.$options['resource'];
  314. $url_params = array();
  315. if (isset($options['id']))
  316. $url .= '/'.$options['id'];
  317.  
  318. $params = array('filter', 'display', 'sort', 'limit');
  319. foreach ($params as $p)
  320. foreach ($options as $k => $o)
  321. if (strpos($k, $p) !== false)
  322. $url_params[$k] = $options[$k];
  323. if (count($url_params) > 0)
  324. $url .= '?'.http_build_query($url_params);
  325. }
  326. else
  327. throw new PrestaShopWebserviceException('Bad parameters given');
  328. $request = self::executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'HEAD', CURLOPT_NOBODY => true));
  329. self::checkStatusCode($request['status_code']);// check the response validity
  330. return $request['header'];
  331. }
  332. /**
  333. * Edit (PUT) a resource
  334. * <p>Unique parameter must take : <br><br>
  335. * 'resource' => Resource name ,<br>
  336. * 'id' => ID of a resource you want to edit,<br>
  337. * 'putXml' => Modified XML string of a resource<br><br>
  338. * Examples are given in the tutorial</p>
  339. * @param array $options Array representing resource to edit.
  340. */
  341. public function edit($options)
  342. {
  343. $xml = '';
  344. if (isset($options['url']))
  345. $url = $options['url'];
  346. elseif ((isset($options['resource'], $options['id']) || isset($options['url'])) && $options['putXml'])
  347. {
  348. $url = (isset($options['url']) ? $options['url'] : $this->url.'/api/'.$options['resource'].'/'.$options['id']);
  349. $xml = $options['putXml'];
  350. if (isset($options['id_shop']))
  351. $url .= '&id_shop='.$options['id_shop'];
  352. if (isset($options['id_group_shop']))
  353. $url .= '&id_group_shop='.$options['id_group_shop'];
  354. }
  355. else
  356. throw new PrestaShopWebserviceException('Bad parameters given');
  357.  
  358. $request = self::executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'PUT', CURLOPT_POSTFIELDS => $xml));
  359. self::checkStatusCode($request['status_code']);// check the response validity
  360. return self::parseXML($request['response']);
  361. }
  362.  
  363. /**
  364. * Delete (DELETE) a resource.
  365. * Unique parameter must take : <br><br>
  366. * 'resource' => Resource name<br>
  367. * 'id' => ID or array which contains IDs of a resource(s) you want to delete<br><br>
  368. * <code>
  369. * <?php
  370. * require_once('./PrestaShopWebservice.php');
  371. * try
  372. * {
  373. * $ws = new PrestaShopWebservice('http://mystore.com/', 'ZQ88PRJX5VWQHCWE4EE7SQ7HPNX00RAJ', false);
  374. * $xml = $ws->delete(array('resource' => 'orders', 'id' => 1));
  375. * // Following code will not be executed if an exception is thrown.
  376. * echo 'Successfully deleted.';
  377. * }
  378. * catch (PrestaShopWebserviceException $ex)
  379. * {
  380. * echo 'Error : '.$ex->getMessage();
  381. * }
  382. * ?>
  383. * </code>
  384. * @param array $options Array representing resource to delete.
  385. */
  386. public function delete($options)
  387. {
  388. if (isset($options['url']))
  389. $url = $options['url'];
  390. elseif (isset($options['resource']) && isset($options['id']))
  391. if (is_array($options['id']))
  392. $url = $this->url.'/api/'.$options['resource'].'/?id=['.implode(',', $options['id']).']';
  393. else
  394. $url = $this->url.'/api/'.$options['resource'].'/'.$options['id'];
  395. if (isset($options['id_shop']))
  396. $url .= '&id_shop='.$options['id_shop'];
  397. if (isset($options['id_group_shop']))
  398. $url .= '&id_group_shop='.$options['id_group_shop'];
  399. $request = self::executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'DELETE'));
  400. self::checkStatusCode($request['status_code']);// check the response validity
  401. return true;
  402. }
  403.  
  404.  
  405. }
  406.  
  407. /**
  408. * @package PrestaShopWebservice
  409. */
  410. class PrestaShopWebserviceException extends Exception { }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement