PageRenderTime 27ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/sauvegarde/stage/API-web_service/controleur/PSWebServiceLibrary.php

https://gitlab.com/ptisky/SAVE
PHP | 411 lines | 229 code | 35 blank | 147 comment | 48 complexity | 02384f2d8245da425baead13cf39db2d 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.6';
  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. ini_set('max_execution_time', 300);
  122. $index = strpos($response, "\r\n\r\n");
  123. if ($index === false && $curl_params[CURLOPT_CUSTOMREQUEST] != 'HEAD')
  124. throw new PrestaShopWebserviceException('Bad HTTP response');
  125. $header = substr($response, 0, $index);
  126. $body = substr($response, $index + 4);
  127. $headerArrayTmp = explode("\n", $header);
  128. $headerArray = array();
  129. foreach ($headerArrayTmp as &$headerItem)
  130. {
  131. $tmp = explode(':', $headerItem);
  132. $tmp = array_map('trim', $tmp);
  133. if (count($tmp) == 2)
  134. $headerArray[$tmp[0]] = $tmp[1];
  135. }
  136. if (array_key_exists('PSWS-Version', $headerArray))
  137. {
  138. $this->version = $headerArray['PSWS-Version'];
  139. if (
  140. version_compare(PrestaShopWebservice::psCompatibleVersionsMin, $headerArray['PSWS-Version']) == 1 ||
  141. version_compare(PrestaShopWebservice::psCompatibleVersionsMax, $headerArray['PSWS-Version']) == -1
  142. )
  143. throw new PrestaShopWebserviceException('This library is not compatible with this version of PrestaShop. Please upgrade/downgrade this library');
  144. }
  145. if ($this->debug)
  146. {
  147. $this->printDebug('HTTP REQUEST HEADER', curl_getinfo($session, CURLINFO_HEADER_OUT));
  148. $this->printDebug('HTTP RESPONSE HEADER', $header);
  149. }
  150. $status_code = curl_getinfo($session, CURLINFO_HTTP_CODE);
  151. if ($status_code === 0)
  152. throw new PrestaShopWebserviceException('CURL Error: '.curl_error($session));
  153. curl_close($session);
  154. if ($this->debug)
  155. {
  156. if ($curl_params[CURLOPT_CUSTOMREQUEST] == 'PUT' || $curl_params[CURLOPT_CUSTOMREQUEST] == 'POST')
  157. $this->printDebug('XML SENT', urldecode($curl_params[CURLOPT_POSTFIELDS]));
  158. if ($curl_params[CURLOPT_CUSTOMREQUEST] != 'DELETE' && $curl_params[CURLOPT_CUSTOMREQUEST] != 'HEAD')
  159. $this->printDebug('RETURN HTTP BODY', $body);
  160. }
  161. return array('status_code' => $status_code, 'response' => $body, 'header' => $header);
  162. }
  163. public function printDebug($title, $content)
  164. {
  165. 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>';
  166. }
  167. public function getVersion()
  168. {
  169. return $this->version;
  170. }
  171. /**
  172. * Load XML from string. Can throw exception
  173. * @param string $response String from a CURL response
  174. * @return SimpleXMLElement status_code, response
  175. */
  176. protected function parseXML($response)
  177. {
  178. if ($response != '')
  179. {
  180. libxml_clear_errors();
  181. libxml_use_internal_errors(true);
  182. $xml = simplexml_load_string($response,'SimpleXMLElement', LIBXML_NOCDATA);
  183. if (libxml_get_errors())
  184. {
  185. $msg = var_export(libxml_get_errors(), true);
  186. libxml_clear_errors();
  187. throw new PrestaShopWebserviceException('HTTP XML response is not parsable: '.$msg);
  188. }
  189. return $xml;
  190. }
  191. else
  192. throw new PrestaShopWebserviceException('HTTP response is empty');
  193. }
  194. /**
  195. * Add (POST) a resource
  196. * <p>Unique parameter must take : <br><br>
  197. * 'resource' => Resource name<br>
  198. * 'postXml' => Full XML string to add resource<br><br>
  199. * Examples are given in the tutorial</p>
  200. * @param array $options
  201. * @return SimpleXMLElement status_code, response
  202. */
  203. public function add($options)
  204. {
  205. $xml = '';
  206. if (isset($options['resource'], $options['postXml']) || isset($options['url'], $options['postXml']))
  207. {
  208. $url = (isset($options['resource']) ? $this->url.'/api/'.$options['resource'] : $options['url']);
  209. $xml = $options['postXml'];
  210. if (isset($options['id_shop']))
  211. $url .= '&id_shop='.$options['id_shop'];
  212. if (isset($options['id_group_shop']))
  213. $url .= '&id_group_shop='.$options['id_group_shop'];
  214. }
  215. else
  216. throw new PrestaShopWebserviceException('Bad parameters given');
  217. $request = self::executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => $xml));
  218. self::checkStatusCode($request['status_code']);
  219. return self::parseXML($request['response']);
  220. }
  221. /**
  222. * Retrieve (GET) a resource
  223. * <p>Unique parameter must take : <br><br>
  224. * 'url' => Full URL for a GET request of Webservice (ex: http://mystore.com/api/customers/1/)<br>
  225. * OR<br>
  226. * 'resource' => Resource name,<br>
  227. * 'id' => ID of a resource you want to get<br><br>
  228. * </p>
  229. * <code>
  230. * <?php
  231. * require_once('./PrestaShopWebservice.php');
  232. * try
  233. * {
  234. * $ws = new PrestaShopWebservice('http://mystore.com/', 'ZQ88PRJX5VWQHCWE4EE7SQ7HPNX00RAJ', false);
  235. * $xml = $ws->get(array('resource' => 'orders', 'id' => 1));
  236. * // Here in $xml, a SimpleXMLElement object you can parse
  237. * foreach ($xml->children()->children() as $attName => $attValue)
  238. * echo $attName.' = '.$attValue.'<br />';
  239. * }
  240. * catch (PrestaShopWebserviceException $ex)
  241. * {
  242. * echo 'Error : '.$ex->getMessage();
  243. * }
  244. * ?>
  245. * </code>
  246. * @param array $options Array representing resource to get.
  247. * @return SimpleXMLElement status_code, response
  248. */
  249. public function get($options)
  250. {
  251. if (isset($options['url']))
  252. $url = $options['url'];
  253. elseif (isset($options['resource']))
  254. {
  255. $url = $this->url.'/api/'.$options['resource'];
  256. $url_params = array();
  257. if (isset($options['id']))
  258. $url .= '/'.$options['id'];
  259. $params = array('filter', 'display', 'sort', 'limit', 'id_shop', 'id_group_shop');
  260. foreach ($params as $p)
  261. foreach ($options as $k => $o)
  262. if (strpos($k, $p) !== false)
  263. $url_params[$k] = $options[$k];
  264. if (count($url_params) > 0)
  265. $url .= '?'.http_build_query($url_params);
  266. }
  267. else
  268. throw new PrestaShopWebserviceException('Bad parameters given');
  269. $request = self::executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'GET'));
  270. self::checkStatusCode($request['status_code']);// check the response validity
  271. return self::parseXML($request['response']);
  272. }
  273. /**
  274. * Head method (HEAD) a resource
  275. *
  276. * @param array $options Array representing resource for head request.
  277. * @return SimpleXMLElement status_code, response
  278. */
  279. public function head($options)
  280. {
  281. if (isset($options['url']))
  282. $url = $options['url'];
  283. elseif (isset($options['resource']))
  284. {
  285. $url = $this->url.'/api/'.$options['resource'];
  286. $url_params = array();
  287. if (isset($options['id']))
  288. $url .= '/'.$options['id'];
  289. $params = array('filter', 'display', 'sort', 'limit');
  290. foreach ($params as $p)
  291. foreach ($options as $k => $o)
  292. if (strpos($k, $p) !== false)
  293. $url_params[$k] = $options[$k];
  294. if (count($url_params) > 0)
  295. $url .= '?'.http_build_query($url_params);
  296. }
  297. else
  298. throw new PrestaShopWebserviceException('Bad parameters given');
  299. $request = self::executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'HEAD', CURLOPT_NOBODY => true));
  300. self::checkStatusCode($request['status_code']);// check the response validity
  301. return $request['header'];
  302. }
  303. /**
  304. * Edit (PUT) a resource
  305. * <p>Unique parameter must take : <br><br>
  306. * 'resource' => Resource name ,<br>
  307. * 'id' => ID of a resource you want to edit,<br>
  308. * 'putXml' => Modified XML string of a resource<br><br>
  309. * Examples are given in the tutorial</p>
  310. * @param array $options Array representing resource to edit.
  311. */
  312. public function edit($options)
  313. {
  314. $xml = '';
  315. if (isset($options['url']))
  316. $url = $options['url'];
  317. elseif ((isset($options['resource'], $options['id']) || isset($options['url'])) && $options['putXml'])
  318. {
  319. $url = (isset($options['url']) ? $options['url'] : $this->url.'/api/'.$options['resource'].'/'.$options['id']);
  320. $xml = $options['putXml'];
  321. if (isset($options['id_shop']))
  322. $url .= '&id_shop='.$options['id_shop'];
  323. if (isset($options['id_group_shop']))
  324. $url .= '&id_group_shop='.$options['id_group_shop'];
  325. }
  326. else
  327. throw new PrestaShopWebserviceException('Bad parameters given');
  328. $request = self::executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'PUT', CURLOPT_POSTFIELDS => $xml));
  329. self::checkStatusCode($request['status_code']);// check the response validity
  330. return self::parseXML($request['response']);
  331. }
  332. /**
  333. * Delete (DELETE) a resource.
  334. * Unique parameter must take : <br><br>
  335. * 'resource' => Resource name<br>
  336. * 'id' => ID or array which contains IDs of a resource(s) you want to delete<br><br>
  337. * <code>
  338. * <?php
  339. * require_once('./PrestaShopWebservice.php');
  340. * try
  341. * {
  342. * $ws = new PrestaShopWebservice('http://mystore.com/', 'ZQ88PRJX5VWQHCWE4EE7SQ7HPNX00RAJ', false);
  343. * $xml = $ws->delete(array('resource' => 'orders', 'id' => 1));
  344. * // Following code will not be executed if an exception is thrown.
  345. * echo 'Successfully deleted.';
  346. * }
  347. * catch (PrestaShopWebserviceException $ex)
  348. * {
  349. * echo 'Error : '.$ex->getMessage();
  350. * }
  351. * ?>
  352. * </code>
  353. * @param array $options Array representing resource to delete.
  354. */
  355. public function delete($options)
  356. {
  357. if (isset($options['url']))
  358. $url = $options['url'];
  359. elseif (isset($options['resource']) && isset($options['id']))
  360. if (is_array($options['id']))
  361. $url = $this->url.'/api/'.$options['resource'].'/?id=['.implode(',', $options['id']).']';
  362. else
  363. $url = $this->url.'/api/'.$options['resource'].'/'.$options['id'];
  364. if (isset($options['id_shop']))
  365. $url .= '&id_shop='.$options['id_shop'];
  366. if (isset($options['id_group_shop']))
  367. $url .= '&id_group_shop='.$options['id_group_shop'];
  368. $request = self::executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'DELETE'));
  369. self::checkStatusCode($request['status_code']);// check the response validity
  370. return true;
  371. }
  372. }
  373. /**
  374. * @package PrestaShopWebservice
  375. */
  376. class PrestaShopWebserviceException extends Exception { }