PSWebServiceLibrary.class.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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. * 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-2013 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 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.7.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. public function __construct($url, $key, $debug = true)
  65. {
  66. if (!extension_loaded('curl')) {
  67. throw new PrestaShopWebserviceException('Please activate the PHP extension \'curl\' to allow use of PrestaShop webservice library');
  68. }
  69. $this->url = $url;
  70. $this->key = $key;
  71. $this->debug = $debug;
  72. $this->version = 'unknown';
  73. }
  74. /**
  75. * Take the status code and throw an exception if the server didn't return 200 or 201 code
  76. *
  77. * @param int $status_code Status code of an HTTP return
  78. * @return void
  79. */
  80. protected function checkStatusCode($status_code)
  81. {
  82. $error_label = 'This call to PrestaShop Web Services failed and returned an HTTP status of %d. That means: %s.';
  83. switch ($status_code) {
  84. case 200:
  85. case 201:
  86. break;
  87. case 204:
  88. throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'No content'));
  89. case 400:
  90. throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'Bad Request'));
  91. case 401:
  92. throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'Unauthorized'));
  93. case 404:
  94. throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'Not Found'));
  95. case 405:
  96. throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'Method Not Allowed'));
  97. case 500:
  98. throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'Internal Server Error'));
  99. default:
  100. throw new PrestaShopWebserviceException('This call to PrestaShop Web Services returned an unexpected HTTP status of:'.$status_code);
  101. }
  102. }
  103. /**
  104. * Handles a CURL request to PrestaShop Webservice. Can throw exception.
  105. *
  106. * @param string $url Resource name
  107. * @param mixed $curl_params CURL parameters (sent to curl_set_opt)
  108. * @return array status_code, response
  109. */
  110. public function executeRequest($url, $curl_params = array())
  111. {
  112. $defaultParams = array(
  113. CURLOPT_HEADER => true,
  114. CURLOPT_RETURNTRANSFER => true,
  115. CURLINFO_HEADER_OUT => true,
  116. CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
  117. CURLOPT_USERPWD => $this->key.':',
  118. CURLOPT_HTTPHEADER => array('Expect:')
  119. );
  120. dol_syslog("curl_init url=".$url);
  121. $session = curl_init($url);
  122. $curl_options = array();
  123. foreach ($defaultParams as $defkey => $defval) {
  124. if (isset($curl_params[$defkey])) {
  125. $curl_options[$defkey] = $curl_params[$defkey];
  126. } else {
  127. $curl_options[$defkey] = $defaultParams[$defkey];
  128. }
  129. }
  130. foreach ($curl_params as $defkey => $defval) {
  131. if (!isset($curl_options[$defkey])) {
  132. $curl_options[$defkey] = $curl_params[$defkey];
  133. }
  134. }
  135. dol_syslog("curl curl_options = ".var_export($curl_options, true));
  136. curl_setopt_array($session, $curl_options);
  137. $response = curl_exec($session);
  138. $index = strpos($response, "\r\n\r\n");
  139. if ($index === false && $curl_params[CURLOPT_CUSTOMREQUEST] != 'HEAD') {
  140. throw new PrestaShopWebserviceException('Bad HTTP response');
  141. }
  142. $header = substr($response, 0, $index);
  143. $body = substr($response, $index + 4);
  144. $headerArrayTmp = explode("\n", $header);
  145. $headerArray = array();
  146. foreach ($headerArrayTmp as &$headerItem) {
  147. $tmp = explode(':', $headerItem);
  148. $tmp = array_map('trim', $tmp);
  149. if (count($tmp) == 2) {
  150. $headerArray[$tmp[0]] = $tmp[1];
  151. }
  152. }
  153. if (array_key_exists('PSWS-Version', $headerArray)) {
  154. $this->version = $headerArray['PSWS-Version'];
  155. if (version_compare(PrestaShopWebservice::PSCOMPATIBLEVERSIONMIN, $headerArray['PSWS-Version']) == 1 ||
  156. version_compare(PrestaShopWebservice::PSCOMPATIBLEVERSIONMAX, $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. $this->printDebug('HTTP REQUEST HEADER', curl_getinfo($session, CURLINFO_HEADER_OUT));
  163. $this->printDebug('HTTP RESPONSE HEADER', $header);
  164. }
  165. $status_code = curl_getinfo($session, CURLINFO_HTTP_CODE);
  166. if ($status_code === 0) {
  167. throw new PrestaShopWebserviceException('CURL Error: '.curl_error($session));
  168. }
  169. curl_close($session);
  170. if ($this->debug) {
  171. if ($curl_params[CURLOPT_CUSTOMREQUEST] == 'PUT' || $curl_params[CURLOPT_CUSTOMREQUEST] == 'POST') {
  172. $this->printDebug('XML SENT', urldecode($curl_params[CURLOPT_POSTFIELDS]));
  173. }
  174. if ($curl_params[CURLOPT_CUSTOMREQUEST] != 'DELETE' && $curl_params[CURLOPT_CUSTOMREQUEST] != 'HEAD') {
  175. $this->printDebug('RETURN HTTP BODY', $body);
  176. }
  177. }
  178. return array('status_code' => $status_code, 'response' => $body, 'header' => $header);
  179. }
  180. /**
  181. * Output debug info
  182. *
  183. * @param string $title Title
  184. * @param string $content Content
  185. * @return void
  186. */
  187. public function printDebug($title, $content)
  188. {
  189. echo '<div style="display:table;background:#CCC;font-size:8pt;padding:7px"><h6 style="font-size:9pt;margin:0">'.dol_escape_htmltag($title).'</h6><pre>'.dol_escape_htmltag($content).'</pre></div>';
  190. }
  191. /**
  192. * Return version
  193. *
  194. * @return string Version
  195. */
  196. public function getVersion()
  197. {
  198. return $this->version;
  199. }
  200. /**
  201. * Load XML from string. Can throw exception
  202. *
  203. * @param string $response String from a CURL response
  204. * @return SimpleXMLElement|boolean status_code, response
  205. *
  206. * @throw PrestaShopWebserviceException
  207. */
  208. protected function parseXML($response)
  209. {
  210. if ($response != '') {
  211. libxml_clear_errors();
  212. libxml_use_internal_errors(true);
  213. if (!function_exists('simplexml_load_string')) {
  214. throw new PrestaShopWebserviceException('Method simplexml_load_string not available. Your PHP does not support xml.');
  215. }
  216. $xml = simplexml_load_string($response, 'SimpleXMLElement', LIBXML_NOCDATA|LIBXML_NONET);
  217. if (libxml_get_errors()) {
  218. $msg = var_export(libxml_get_errors(), true);
  219. libxml_clear_errors();
  220. throw new PrestaShopWebserviceException('HTTP XML response is not parsable: '.$msg);
  221. }
  222. return $xml;
  223. } else {
  224. throw new PrestaShopWebserviceException('HTTP response is empty');
  225. }
  226. }
  227. /**
  228. * Add (POST) a resource
  229. * <p>Unique parameter must take : <br><br>
  230. * 'resource' => Resource name<br>
  231. * 'postXml' => Full XML string to add resource<br><br>
  232. * Examples are given in the tutorial</p>
  233. *
  234. * @param array $options Options
  235. * @return SimpleXMLElement|boolean status_code, response
  236. *
  237. * @throw PrestaShopWebserviceException
  238. */
  239. public function add($options)
  240. {
  241. $xml = '';
  242. $url = '';
  243. if (isset($options['resource'], $options['postXml']) || isset($options['url'], $options['postXml'])) {
  244. $url = (isset($options['resource']) ? $this->url.'/api/'.$options['resource'] : $options['url']);
  245. $xml = $options['postXml'];
  246. if (isset($options['id_shop'])) {
  247. $url .= '&id_shop='.$options['id_shop'];
  248. }
  249. if (isset($options['id_group_shop'])) {
  250. $url .= '&id_group_shop='.$options['id_group_shop'];
  251. }
  252. } else {
  253. throw new PrestaShopWebserviceException('Bad parameters given');
  254. }
  255. $request = $this->executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'POST', CURLOPT_POSTFIELDS => $xml));
  256. $this->checkStatusCode($request['status_code']);
  257. return $this->parseXML($request['response']);
  258. }
  259. /**
  260. * Retrieve (GET) a resource
  261. * <p>Unique parameter must take : <br><br>
  262. * 'url' => Full URL for a GET request of Webservice (ex: http://mystore.com/api/customers/1/)<br>
  263. * OR<br>
  264. * 'resource' => Resource name,<br>
  265. * 'id' => ID of a resource you want to get<br><br>
  266. * </p>
  267. * <code>
  268. * <?php
  269. * require_once './PrestaShopWebservice.php';
  270. * try
  271. * {
  272. * $ws = new PrestaShopWebservice('http://mystore.com/', 'ZQ88PRJX5VWQHCWE4EE7SQ7HPNX00RAJ', false);
  273. * $xml = $ws->get(array('resource' => 'orders', 'id' => 1));
  274. * // Here in $xml, a SimpleXMLElement object you can parse
  275. * foreach ($xml->children()->children() as $attName => $attValue)
  276. * echo $attName.' = '.$attValue.'<br>';
  277. * }
  278. * catch (PrestaShopWebserviceException $ex)
  279. * {
  280. * echo 'Error : '.$ex->getMessage();
  281. * }
  282. * ?>
  283. * </code>
  284. * @param array $options Array representing resource to get.
  285. * @return SimpleXMLElement|boolean status_code, response
  286. *
  287. * @throw PrestaShopWebserviceException
  288. */
  289. public function get($options)
  290. {
  291. if (isset($options['url'])) {
  292. $url = $options['url'];
  293. } elseif (isset($options['resource'])) {
  294. $url = $this->url.'/api/'.$options['resource'];
  295. $url_params = array();
  296. if (isset($options['id'])) {
  297. $url .= '/'.$options['id'];
  298. }
  299. // @CHANGE LDR
  300. //$params = array('filter', 'display', 'sort', 'limit', 'id_shop', 'id_group_shop');
  301. $params = array('filter', 'display', 'sort', 'limit', 'id_shop', 'id_group_shop', 'date');
  302. foreach ($params as $p) {
  303. foreach ($options as $k => $o) {
  304. if (strpos($k, $p) !== false) {
  305. $url_params[$k] = $options[$k];
  306. }
  307. }
  308. }
  309. if (count($url_params) > 0) {
  310. $url .= '?'.http_build_query($url_params);
  311. }
  312. } else {
  313. throw new PrestaShopWebserviceException('Bad parameters given ');
  314. }
  315. $request = $this->executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'GET'));
  316. $this->checkStatusCode($request['status_code']); // check the response validity
  317. return $this->parseXML($request['response']);
  318. }
  319. /**
  320. * Head method (HEAD) a resource
  321. *
  322. * @param array $options Array representing resource for head request.
  323. * @return SimpleXMLElement status_code, response
  324. *
  325. * @throw PrestaShopWebserviceException
  326. */
  327. public function head($options)
  328. {
  329. if (isset($options['url'])) {
  330. $url = $options['url'];
  331. } elseif (isset($options['resource'])) {
  332. $url = $this->url.'/api/'.$options['resource'];
  333. $url_params = array();
  334. if (isset($options['id'])) {
  335. $url .= '/'.$options['id'];
  336. }
  337. $params = array('filter', 'display', 'sort', 'limit');
  338. foreach ($params as $p) {
  339. foreach ($options as $k => $o) {
  340. if (strpos($k, $p) !== false) {
  341. $url_params[$k] = $options[$k];
  342. }
  343. }
  344. }
  345. if (count($url_params) > 0) {
  346. $url .= '?'.http_build_query($url_params);
  347. }
  348. } else {
  349. throw new PrestaShopWebserviceException('Bad parameters given');
  350. }
  351. $request = $this->executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'HEAD', CURLOPT_NOBODY => true));
  352. $this->checkStatusCode($request['status_code']); // check the response validity
  353. return $request['header'];
  354. }
  355. /**
  356. * Edit (PUT) a resource
  357. * <p>Unique parameter must take : <br><br>
  358. * 'resource' => Resource name ,<br>
  359. * 'id' => ID of a resource you want to edit,<br>
  360. * 'putXml' => Modified XML string of a resource<br><br>
  361. * Examples are given in the tutorial</p>
  362. *
  363. * @param array $options Array representing resource to edit.
  364. * @return SimpleXMLElement|boolean status_code, response
  365. *
  366. * @throw PrestaShopWebserviceException
  367. */
  368. public function edit($options)
  369. {
  370. $xml = '';
  371. if (isset($options['url'])) {
  372. $url = $options['url'];
  373. } elseif ((isset($options['resource'], $options['id']) || isset($options['url'])) && $options['putXml']) {
  374. $url = (isset($options['url']) ? $options['url'] : $this->url.'/api/'.$options['resource'].'/'.$options['id']);
  375. $xml = $options['putXml'];
  376. if (isset($options['id_shop'])) {
  377. $url .= '&id_shop='.$options['id_shop'];
  378. }
  379. if (isset($options['id_group_shop'])) {
  380. $url .= '&id_group_shop='.$options['id_group_shop'];
  381. }
  382. } else {
  383. throw new PrestaShopWebserviceException('Bad parameters given');
  384. }
  385. $request = $this->executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'PUT', CURLOPT_POSTFIELDS => $xml));
  386. $this->checkStatusCode($request['status_code']); // check the response validity
  387. return $this->parseXML($request['response']);
  388. }
  389. }
  390. /**
  391. * @package PrestaShopWebservice
  392. */
  393. class PrestaShopWebserviceException extends Exception
  394. {
  395. }