PageRenderTime 55ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/modules/elegend_pro/PSWebServiceLibrary.php

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