PSWebServiceLibrary.class.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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 PSCOMPATIBLEVERSIONMIN = '1.4.0.0';
  43. const PSCOMPATIBLEVERSIONMAX = '1.6.99.99';
  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. *
  75. * @param int $status_code Status code of an HTTP return
  76. */
  77. protected function checkStatusCode($status_code)
  78. {
  79. $error_label = 'This call to PrestaShop Web Services failed and returned an HTTP status of %d. That means: %s.';
  80. switch($status_code)
  81. {
  82. case 200:
  83. case 201:
  84. break;
  85. case 204:
  86. throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'No content'));
  87. case 400:
  88. throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'Bad Request'));
  89. case 401:
  90. throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'Unauthorized'));
  91. case 404:
  92. throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'Not Found'));
  93. case 405:
  94. throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'Method Not Allowed'));
  95. case 500:
  96. throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'Internal Server Error'));
  97. default:
  98. throw new PrestaShopWebserviceException('This call to PrestaShop Web Services returned an unexpected HTTP status of:' . $status_code);
  99. }
  100. }
  101. /**
  102. * Handles a CURL request to PrestaShop Webservice. Can throw exception.
  103. *
  104. * @param string $url Resource name
  105. * @param mixed $curl_params CURL parameters (sent to curl_set_opt)
  106. * @return array status_code, response
  107. */
  108. public function executeRequest($url, $curl_params = array())
  109. {
  110. $defaultParams = array(
  111. CURLOPT_HEADER => true,
  112. CURLOPT_RETURNTRANSFER => true,
  113. CURLINFO_HEADER_OUT => true,
  114. CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
  115. CURLOPT_USERPWD => $this->key.':',
  116. CURLOPT_HTTPHEADER => array( 'Expect:' )
  117. );
  118. $session = curl_init($url);
  119. $curl_options = array();
  120. foreach ($defaultParams as $defkey => $defval)
  121. {
  122. if (isset($curl_params[$defkey]))
  123. $curl_options[$defkey] = $curl_params[$defkey];
  124. else
  125. $curl_options[$defkey] = $defaultParams[$defkey];
  126. }
  127. foreach ($curl_params as $defkey => $defval)
  128. if (!isset($curl_options[$defkey]))
  129. $curl_options[$defkey] = $curl_params[$defkey];
  130. curl_setopt_array($session, $curl_options);
  131. $response = curl_exec($session);
  132. $index = strpos($response, "\r\n\r\n");
  133. if ($index === false && $curl_params[CURLOPT_CUSTOMREQUEST] != 'HEAD')
  134. throw new PrestaShopWebserviceException('Bad HTTP response');
  135. $header = substr($response, 0, $index);
  136. $body = substr($response, $index + 4);
  137. $headerArrayTmp = explode("\n", $header);
  138. $headerArray = array();
  139. foreach ($headerArrayTmp as &$headerItem)
  140. {
  141. $tmp = explode(':', $headerItem);
  142. $tmp = array_map('trim', $tmp);
  143. if (count($tmp) == 2)
  144. $headerArray[$tmp[0]] = $tmp[1];
  145. }
  146. if (array_key_exists('PSWS-Version', $headerArray))
  147. {
  148. $this->version = $headerArray['PSWS-Version'];
  149. if (
  150. version_compare(PrestaShopWebservice::PSCOMPATIBLEVERSIONMIN, $headerArray['PSWS-Version']) == 1 ||
  151. version_compare(PrestaShopWebservice::PSCOMPATIBLEVERSIONMAX, $headerArray['PSWS-Version']) == -1
  152. )
  153. throw new PrestaShopWebserviceException('This library is not compatible with this version of PrestaShop. Please upgrade/downgrade this library');
  154. }
  155. if ($this->debug)
  156. {
  157. $this->printDebug('HTTP REQUEST HEADER', curl_getinfo($session, CURLINFO_HEADER_OUT));
  158. $this->printDebug('HTTP RESPONSE HEADER', $header);
  159. }
  160. $status_code = curl_getinfo($session, CURLINFO_HTTP_CODE);
  161. if ($status_code === 0)
  162. throw new PrestaShopWebserviceException('CURL Error: '.curl_error($session));
  163. curl_close($session);
  164. if ($this->debug)
  165. {
  166. if ($curl_params[CURLOPT_CUSTOMREQUEST] == 'PUT' || $curl_params[CURLOPT_CUSTOMREQUEST] == 'POST')
  167. $this->printDebug('XML SENT', urldecode($curl_params[CURLOPT_POSTFIELDS]));
  168. if ($curl_params[CURLOPT_CUSTOMREQUEST] != 'DELETE' && $curl_params[CURLOPT_CUSTOMREQUEST] != 'HEAD')
  169. $this->printDebug('RETURN HTTP BODY', $body);
  170. }
  171. return array('status_code' => $status_code, 'response' => $body, 'header' => $header);
  172. }
  173. /**
  174. * Output debug info
  175. *
  176. * @param string $title Title
  177. * @param string $content Content
  178. * @return void
  179. */
  180. public function printDebug($title, $content)
  181. {
  182. 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>';
  183. }
  184. /**
  185. * Return version
  186. *
  187. * @return string Version
  188. */
  189. public function getVersion()
  190. {
  191. return $this->version;
  192. }
  193. /**
  194. * Load XML from string. Can throw exception
  195. *
  196. * @param string $response String from a CURL response
  197. * @return SimpleXMLElement status_code, response
  198. */
  199. protected function parseXML($response)
  200. {
  201. if ($response != '')
  202. {
  203. libxml_clear_errors();
  204. libxml_use_internal_errors(true);
  205. $xml = simplexml_load_string($response,'SimpleXMLElement', LIBXML_NOCDATA);
  206. if (libxml_get_errors())
  207. {
  208. $msg = var_export(libxml_get_errors(), true);
  209. libxml_clear_errors();
  210. throw new PrestaShopWebserviceException('HTTP XML response is not parsable: '.$msg);
  211. }
  212. return $xml;
  213. }
  214. else
  215. throw new PrestaShopWebserviceException('HTTP response is empty');
  216. }
  217. /**
  218. * Add (POST) a resource
  219. * <p>Unique parameter must take : <br><br>
  220. * 'resource' => Resource name<br>
  221. * 'postXml' => Full XML string to add resource<br><br>
  222. * Examples are given in the tutorial</p>
  223. *
  224. * @param array $options Options
  225. * @return SimpleXMLElement status_code, response
  226. */
  227. public function add($options)
  228. {
  229. $xml = '';
  230. if (isset($options['resource'], $options['postXml']) || isset($options['url'], $options['postXml']))
  231. {
  232. $url = (isset($options['resource']) ? $this->url.'/api/'.$options['resource'] : $options['url']);
  233. $xml = $options['postXml'];
  234. if (isset($options['id_shop']))
  235. $url .= '&id_shop='.$options['id_shop'];
  236. if (isset($options['id_group_shop']))
  237. $url .= '&id_group_shop='.$options['id_group_shop'];
  238. }
  239. else
  240. throw new PrestaShopWebserviceException('Bad parameters given');
  241. $request = self::executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => $xml));
  242. self::checkStatusCode($request['status_code']);
  243. return self::parseXML($request['response']);
  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. $params = array('filter', 'display', 'sort', 'limit', 'id_shop', 'id_group_shop');
  284. foreach ($params as $p)
  285. foreach ($options as $k => $o)
  286. if (strpos($k, $p) !== false)
  287. $url_params[$k] = $options[$k];
  288. if (count($url_params) > 0)
  289. $url .= '?'.http_build_query($url_params);
  290. }
  291. else
  292. throw new PrestaShopWebserviceException('Bad parameters given ');
  293. $request = self::executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'GET'));
  294. self::checkStatusCode($request['status_code']);// check the response validity
  295. return self::parseXML($request['response']);
  296. }
  297. /**
  298. * Head method (HEAD) a resource
  299. *
  300. * @param array $options Array representing resource for head request.
  301. * @return SimpleXMLElement status_code, response
  302. */
  303. public function head($options)
  304. {
  305. if (isset($options['url']))
  306. $url = $options['url'];
  307. elseif (isset($options['resource']))
  308. {
  309. $url = $this->url.'/api/'.$options['resource'];
  310. $url_params = array();
  311. if (isset($options['id']))
  312. $url .= '/'.$options['id'];
  313. $params = array('filter', 'display', 'sort', 'limit');
  314. foreach ($params as $p)
  315. foreach ($options as $k => $o)
  316. if (strpos($k, $p) !== false)
  317. $url_params[$k] = $options[$k];
  318. if (count($url_params) > 0)
  319. $url .= '?'.http_build_query($url_params);
  320. }
  321. else
  322. throw new PrestaShopWebserviceException('Bad parameters given');
  323. $request = self::executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'HEAD', CURLOPT_NOBODY => true));
  324. self::checkStatusCode($request['status_code']);// check the response validity
  325. return $request['header'];
  326. }
  327. /**
  328. * Edit (PUT) a resource
  329. * <p>Unique parameter must take : <br><br>
  330. * 'resource' => Resource name ,<br>
  331. * 'id' => ID of a resource you want to edit,<br>
  332. * 'putXml' => Modified XML string of a resource<br><br>
  333. * Examples are given in the tutorial</p>
  334. *
  335. * @param array $options Array representing resource to edit.
  336. * @return SimpleXMLElement status_code, response
  337. */
  338. public function edit($options)
  339. {
  340. $xml = '';
  341. if (isset($options['url']))
  342. $url = $options['url'];
  343. elseif ((isset($options['resource'], $options['id']) || isset($options['url'])) && $options['putXml'])
  344. {
  345. $url = (isset($options['url']) ? $options['url'] : $this->url.'/api/'.$options['resource'].'/'.$options['id']);
  346. $xml = $options['putXml'];
  347. if (isset($options['id_shop']))
  348. $url .= '&id_shop='.$options['id_shop'];
  349. if (isset($options['id_group_shop']))
  350. $url .= '&id_group_shop='.$options['id_group_shop'];
  351. }
  352. else
  353. throw new PrestaShopWebserviceException('Bad parameters given');
  354. $request = self::executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'PUT', CURLOPT_POSTFIELDS => $xml));
  355. self::checkStatusCode($request['status_code']);// check the response validity
  356. return self::parseXML($request['response']);
  357. }
  358. }
  359. /**
  360. * @package PrestaShopWebservice
  361. */
  362. class PrestaShopWebserviceException extends Exception
  363. {
  364. }