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

/classes/webservice/WebserviceRequest.php

https://gitlab.com/staging06/myproject
PHP | 1089 lines | 723 code | 79 blank | 287 comment | 159 complexity | e149f0c555ca717d852536ed267df3e7 MD5 | raw file
  1. <?php
  2. /*
  3. * 2007-2015 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-2010 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. */
  26. class WebserviceRequestCore
  27. {
  28. const HTTP_GET = 1;
  29. const HTTP_POST = 2;
  30. const HTTP_PUT = 4;
  31. protected $_available_languages = null;
  32. /**
  33. * Errors triggered at execution
  34. * @var array
  35. */
  36. public $errors = array();
  37. /**
  38. * Set if return should display content or not
  39. * @var bool
  40. */
  41. protected $_outputEnabled = true;
  42. /**
  43. * Set if the management is specific or if it is classic (entity management)
  44. * @var WebserviceSpecificManagementImages|WebserviceSpecificManagementSearch|false
  45. */
  46. protected $objectSpecificManagement = false;
  47. /**
  48. * Base PrestaShop webservice URL
  49. * @var string
  50. */
  51. public $wsUrl;
  52. /**
  53. * PrestaShop Webservice Documentation URL
  54. * @var string
  55. */
  56. protected $_docUrl = 'http://doc.prestashop.com/display/PS16/Using+the+PrestaShop+Web+Service';
  57. /**
  58. * Set if the authentication key was checked
  59. * @var bool
  60. */
  61. protected $_authenticated = false;
  62. /**
  63. * HTTP Method to support
  64. * @var string
  65. */
  66. public $method;
  67. /**
  68. * The segment of the URL
  69. * @var array
  70. */
  71. public $urlSegment = array();
  72. /**
  73. * The segment list of the URL after the "api" segment
  74. * @var array
  75. */
  76. public $urlFragments = array();
  77. /**
  78. * The time in microseconds of the start of the execution of the web service request
  79. * @var int
  80. */
  81. protected $_startTime = 0;
  82. /**
  83. * The list of each resources manageable via web service
  84. * @var array
  85. */
  86. public $resourceList;
  87. /**
  88. * The configuration parameters of the current resource
  89. * @var array
  90. */
  91. public $resourceConfiguration;
  92. /**
  93. * The permissions for the current key
  94. * @var array
  95. */
  96. public $keyPermissions;
  97. /**
  98. * The XML string to display if web service call succeed
  99. * @var string
  100. */
  101. protected $specificOutput = '';
  102. /**
  103. * The list of objects to display
  104. * @var array
  105. */
  106. public $objects;
  107. /**
  108. * The current object to support, it extends the PrestaShop ObjectModel
  109. * @var ObjectModel
  110. */
  111. protected $_object;
  112. /**
  113. * The schema to display.
  114. * If null, no schema have to be displayed and normal management has to be performed
  115. * @var string
  116. */
  117. public $schemaToDisplay;
  118. /**
  119. * The fields to display. These fields will be displayed when retrieving objects
  120. * @var string
  121. */
  122. public $fieldsToDisplay = 'minimum';
  123. /**
  124. * If we are in PUT or POST case, we use this attribute to store the xml string value during process
  125. * @var string
  126. */
  127. protected $_inputXml;
  128. /**
  129. * Object instance for singleton
  130. * @var WebserviceRequest
  131. */
  132. protected static $_instance;
  133. /**
  134. * Key used for authentication
  135. * @var string
  136. */
  137. protected $_key;
  138. /**
  139. * This is used to have a deeper tree diagram.
  140. * @var int
  141. */
  142. public $depth = 0;
  143. /**
  144. * Name of the output format
  145. * @var string
  146. */
  147. protected $outputFormat = 'xml';
  148. /**
  149. * The object to build the output.
  150. * @var WebserviceOutputBuilder
  151. */
  152. protected $objOutput;
  153. /**
  154. * Save the class name for override used in getInstance()
  155. * @var string
  156. */
  157. public static $ws_current_classname;
  158. public static $shopIDs;
  159. public function getOutputEnabled()
  160. {
  161. return $this->_outputEnabled;
  162. }
  163. public function setOutputEnabled($bool)
  164. {
  165. if (Validate::isBool($bool)) {
  166. $this->_outputEnabled = $bool;
  167. }
  168. return $this;
  169. }
  170. /**
  171. * Get WebserviceRequest object instance (Singleton)
  172. *
  173. * @return object WebserviceRequest instance
  174. */
  175. public static function getInstance()
  176. {
  177. if (!isset(self::$_instance)) {
  178. self::$_instance = new WebserviceRequest::$ws_current_classname();
  179. }
  180. return self::$_instance;
  181. }
  182. /*
  183. protected function getOutputObject($type)
  184. {
  185. switch ($type)
  186. {
  187. case 'XML' :
  188. default :
  189. $obj_render = new WebserviceOutputXML();
  190. break;
  191. }
  192. return $obj_render;
  193. }
  194. */
  195. protected function getOutputObject($type)
  196. {
  197. // set header param in header or as get param
  198. $headers = self::getallheaders();
  199. if (isset($headers['Io-Format'])) {
  200. $type = $headers['Io-Format'];
  201. } elseif (isset($headers['Output-Format'])) {
  202. $type = $headers['Output-Format'];
  203. } elseif (isset($_GET['output_format'])) {
  204. $type = $_GET['output_format'];
  205. } elseif (isset($_GET['io_format'])) {
  206. $type = $_GET['io_format'];
  207. }
  208. $this->outputFormat = $type;
  209. switch ($type) {
  210. case 'JSON' :
  211. require_once dirname(__FILE__).'/WebserviceOutputJSON.php';
  212. $obj_render = new WebserviceOutputJSON();
  213. break;
  214. case 'XML' :
  215. default :
  216. $obj_render = new WebserviceOutputXML();
  217. break;
  218. }
  219. return $obj_render;
  220. }
  221. public static function getResources()
  222. {
  223. $resources = array(
  224. 'addresses' => array('description' => 'The Customer, Manufacturer and Customer addresses','class' => 'Address'),
  225. 'carriers' => array('description' => 'The Carriers','class' => 'Carrier'),
  226. 'carts' => array('description' => 'Customer\'s carts', 'class' => 'Cart'),
  227. 'cart_rules' => array('description' => 'Cart rules management', 'class' => 'CartRule'),
  228. 'categories' => array('description' => 'The product categories','class' => 'Category'),
  229. 'combinations' => array('description' => 'The product combinations','class' => 'Combination'),
  230. 'configurations' => array('description' => 'Shop configuration', 'class' => 'Configuration'),
  231. 'contacts' => array('description' => 'Shop contacts','class' => 'Contact'),
  232. 'countries' => array('description' => 'The countries','class' => 'Country'),
  233. 'currencies' => array('description' => 'The currencies', 'class' => 'Currency'),
  234. 'customers' => array('description' => 'The e-shop\'s customers','class' => 'Customer'),
  235. 'customer_threads' => array('description' => 'Customer services threads','class' => 'CustomerThread'),
  236. 'customer_messages' => array('description' => 'Customer services messages','class' => 'CustomerMessage'),
  237. 'deliveries' => array('description' => 'Product delivery', 'class' => 'Delivery'),
  238. 'groups' => array('description' => 'The customer\'s groups','class' => 'Group'),
  239. 'guests' => array('description' => 'The guests', 'class' => 'Guest'),
  240. 'images' => array('description' => 'The images', 'specific_management' => true),
  241. 'image_types' => array('description' => 'The image types', 'class' => 'ImageType'),
  242. 'languages' => array('description' => 'Shop languages', 'class' => 'Language'),
  243. 'manufacturers' => array('description' => 'The product manufacturers','class' => 'Manufacturer'),
  244. 'order_carriers' => array('description' => 'The Order carriers','class' => 'OrderCarrier'),
  245. 'order_details' => array('description' => 'Details of an order', 'class' => 'OrderDetail'),
  246. 'order_discounts' => array('description' => 'Discounts of an order', 'class' => 'OrderDiscount'),
  247. 'order_histories' => array('description' => 'The Order histories','class' => 'OrderHistory'),
  248. 'order_invoices' => array('description' => 'The Order invoices','class' => 'OrderInvoice'),
  249. 'orders' => array('description' => 'The Customers orders','class' => 'Order'),
  250. 'order_payments' => array('description' => 'The Order payments','class' => 'OrderPayment'),
  251. 'order_states' => array('description' => 'The Order statuses','class' => 'OrderState'),
  252. 'order_slip' => array('description' => 'The Order slips', 'class' => 'OrderSlip'),
  253. 'price_ranges' => array('description' => 'Price ranges', 'class' => 'RangePrice'),
  254. 'product_features' => array('description' => 'The product features','class' => 'Feature'),
  255. 'product_feature_values' => array('description' => 'The product feature values','class' => 'FeatureValue'),
  256. 'product_options' => array('description' => 'The product options','class' => 'AttributeGroup'),
  257. 'product_option_values' => array('description' => 'The product options value','class' => 'Attribute'),
  258. 'products' => array('description' => 'The products','class' => 'Product'),
  259. 'states' => array('description' => 'The available states of countries','class' => 'State'),
  260. 'stores' => array('description' => 'The stores', 'class' => 'Store'),
  261. 'suppliers' => array('description' => 'The product suppliers','class' => 'Supplier'),
  262. 'tags' => array('description' => 'The Products tags','class' => 'Tag'),
  263. 'translated_configurations' => array('description' => 'Shop configuration', 'class' => 'TranslatedConfiguration'),
  264. 'weight_ranges' => array('description' => 'Weight ranges', 'class' => 'RangeWeight'),
  265. 'zones' => array('description' => 'The Countries zones','class' => 'Zone'),
  266. 'employees' => array('description' => 'The Employees', 'class' => 'Employee'),
  267. 'search' => array('description' => 'Search', 'specific_management' => true, 'forbidden_method' => array('PUT', 'POST', 'DELETE')),
  268. 'content_management_system' => array('description' => 'Content management system', 'class' => 'CMS'),
  269. 'shops' => array('description' => 'Shops from multi-shop feature', 'class' => 'Shop'),
  270. 'shop_groups' => array('description' => 'Shop groups from multi-shop feature', 'class' => 'ShopGroup'),
  271. 'taxes' => array('description' => 'The tax rate', 'class' => 'Tax'),
  272. 'stock_movements' => array('description' => 'Stock movements', 'class' => 'StockMvtWS', 'forbidden_method' => array('PUT', 'POST', 'DELETE')),
  273. 'stock_movement_reasons' => array('description' => 'Stock movement reason', 'class' => 'StockMvtReason'),
  274. 'warehouses' => array('description' => 'Warehouses', 'class' => 'Warehouse', 'forbidden_method' => array('DELETE')),
  275. 'stocks' => array('description' => 'Stocks', 'class' => 'Stock', 'forbidden_method' => array('PUT', 'POST', 'DELETE')),
  276. 'stock_availables' => array('description' => 'Available quantities', 'class' => 'StockAvailable', 'forbidden_method' => array('POST', 'DELETE')),
  277. 'warehouse_product_locations' => array('description' => 'Location of products in warehouses', 'class' => 'WarehouseProductLocation', 'forbidden_method' => array('PUT', 'POST', 'DELETE')),
  278. 'supply_orders' => array('description' => 'Supply Orders', 'class' => 'SupplyOrder', 'forbidden_method' => array('PUT', 'POST', 'DELETE')),
  279. 'supply_order_details' => array('description' => 'Supply Order Details', 'class' => 'SupplyOrderDetail', 'forbidden_method' => array('PUT', 'POST', 'DELETE')),
  280. 'supply_order_states' => array('description' => 'Supply Order Statuses', 'class' => 'SupplyOrderState', 'forbidden_method' => array('PUT', 'POST', 'DELETE')),
  281. 'supply_order_histories' => array('description' => 'Supply Order Histories', 'class' => 'SupplyOrderHistory', 'forbidden_method' => array('PUT', 'POST', 'DELETE')),
  282. 'supply_order_receipt_histories' => array('description' => 'Supply Order Receipt Histories', 'class' => 'SupplyOrderReceiptHistory', 'forbidden_method' => array('PUT', 'POST', 'DELETE')),
  283. 'product_suppliers' => array('description' => 'Product Suppliers', 'class' => 'ProductSupplier'),
  284. 'tax_rules' => array('description' => 'Tax rules entity', 'class' => 'TaxRule'),
  285. 'tax_rule_groups' => array('description' => 'Tax rule groups', 'class' => 'TaxRulesGroup'),
  286. 'specific_prices' => array('description' => 'Specific price management', 'class' => 'SpecificPrice'),
  287. 'specific_price_rules' => array('description' => 'Specific price management', 'class' => 'SpecificPriceRule'),
  288. 'shop_urls' => array('description' => 'Shop URLs from multi-shop feature', 'class' => 'ShopUrl'),
  289. 'product_customization_fields' => array('description' => 'Customization Field', 'class' => 'CustomizationField'),
  290. 'customizations' => array('description' => 'Customization values', 'class' => 'Customization'),
  291. );
  292. ksort($resources);
  293. return $resources;
  294. }
  295. /* @todo Check how get parameters */
  296. /* @todo : set this method out */
  297. /**
  298. * This method is used for calculate the price for products on the output details
  299. *
  300. * @param $field
  301. * @param $entity_object
  302. * @param $ws_params
  303. * @return array field parameters.
  304. */
  305. public function getPriceForProduct($field, $entity_object, $ws_params)
  306. {
  307. if (is_int($entity_object->id)) {
  308. $arr_return = $this->specificPriceForProduct($entity_object, array('default_price'=>''));
  309. $field['value'] = $arr_return['default_price']['value'];
  310. }
  311. return $field;
  312. }
  313. /* @todo : set this method out */
  314. /**
  315. * This method is used for calculate the price for products on a virtual fields
  316. *
  317. * @param $entity_object
  318. * @param array $parameters
  319. * @return array
  320. */
  321. public function specificPriceForProduct($entity_object, $parameters)
  322. {
  323. foreach (array_keys($parameters) as $name) {
  324. $parameters[$name]['object_id'] = $entity_object->id;
  325. }
  326. $arr_return = $this->specificPriceCalculation($parameters);
  327. return $arr_return;
  328. }
  329. public function specificPriceCalculation($parameters)
  330. {
  331. $arr_return = array();
  332. foreach ($parameters as $name => $value) {
  333. $id_shop = (int)Context::getContext()->shop->id;
  334. $id_country = (int)(isset($value['country']) ? $value['country'] : (Configuration::get('PS_COUNTRY_DEFAULT')));
  335. $id_state = (int)(isset($value['state']) ? $value['state'] : 0);
  336. $id_currency = (int)(isset($value['currency']) ? $value['currency'] : Configuration::get('PS_CURRENCY_DEFAULT'));
  337. $id_group = (int)(isset($value['group']) ? $value['group'] : (int)Configuration::get('PS_CUSTOMER_GROUP'));
  338. $quantity = (int)(isset($value['quantity']) ? $value['quantity'] : 1);
  339. $use_tax = (int)(isset($value['use_tax']) ? $value['use_tax'] : Configuration::get('PS_TAX'));
  340. $decimals = (int)(isset($value['decimals']) ? $value['decimals'] : Configuration::get('PS_PRICE_ROUND_MODE'));
  341. $id_product_attribute = (int)(isset($value['product_attribute']) ? $value['product_attribute'] : null);
  342. $only_reduc = (int)(isset($value['only_reduction']) ? $value['only_reduction'] : false);
  343. $use_reduc = (int)(isset($value['use_reduction']) ? $value['use_reduction'] : true);
  344. $use_ecotax = (int)(isset($value['use_ecotax']) ? $value['use_ecotax'] : Configuration::get('PS_USE_ECOTAX'));
  345. $specific_price_output = null;
  346. $id_county = (int)(isset($value['county']) ? $value['county'] : 0);
  347. $return_value = Product::priceCalculation($id_shop, $value['object_id'], $id_product_attribute, $id_country, $id_state, $id_county, $id_currency, $id_group, $quantity,
  348. $use_tax, $decimals, $only_reduc, $use_reduc, $use_ecotax, $specific_price_output, null);
  349. $arr_return[$name] = array('sqlId'=>strtolower($name), 'value'=>sprintf('%f', $return_value));
  350. }
  351. return $arr_return;
  352. }
  353. /* @todo : set this method out */
  354. /**
  355. * This method is used for calculate the price for products on a virtual fields
  356. *
  357. * @param $entity_object
  358. * @param array $parameters
  359. * @return array
  360. */
  361. public function specificPriceForCombination($entity_object, $parameters)
  362. {
  363. foreach (array_keys($parameters) as $name) {
  364. $parameters[$name]['object_id'] = $entity_object->id_product;
  365. $parameters[$name]['product_attribute'] = $entity_object->id;
  366. }
  367. $arr_return = $this->specificPriceCalculation($parameters);
  368. return $arr_return;
  369. }
  370. /**
  371. * Start Webservice request
  372. * Check webservice activation
  373. * Check autentication
  374. * Check resource
  375. * Check HTTP Method
  376. * Execute the action
  377. * Display the result
  378. *
  379. * @param string $key
  380. * @param string $method
  381. * @param string $url
  382. * @param string $params
  383. * @param string $inputXml
  384. *
  385. * @return array Returns an array of results (headers, content, type of resource...)
  386. */
  387. public function fetch($key, $method, $url, $params, $bad_class_name, $inputXml = null)
  388. {
  389. // Time logger
  390. $this->_startTime = microtime(true);
  391. $this->objects = array();
  392. // Error handler
  393. set_error_handler(array($this, 'webserviceErrorHandler'));
  394. ini_set('html_errors', 'off');
  395. // Two global vars, for compatibility with the PS core...
  396. global $webservice_call, $display_errors;
  397. $webservice_call = true;
  398. $display_errors = strtolower(ini_get('display_errors')) != 'off';
  399. // __PS_BASE_URI__ is from Shop::$current_base_uri
  400. $this->wsUrl = Tools::getHttpHost(true).__PS_BASE_URI__.'api/';
  401. // set the output object which manage the content and header structure and informations
  402. $this->objOutput = new WebserviceOutputBuilder($this->wsUrl);
  403. $this->_key = trim($key);
  404. $this->outputFormat = isset($params['output_format']) ? $params['output_format'] : $this->outputFormat;
  405. // Set the render object to build the output on the asked format (XML, JSON, CSV, ...)
  406. $this->objOutput->setObjectRender($this->getOutputObject($this->outputFormat));
  407. $this->params = $params;
  408. // Check webservice activation and request authentication
  409. if ($this->webserviceChecks()) {
  410. if ($bad_class_name) {
  411. $this->setError(500, 'Class "'.htmlspecialchars($bad_class_name).'" not found. Please update the class_name field in the webservice_account table.', 126);
  412. }
  413. // parse request url
  414. $this->method = $method;
  415. $this->urlSegment = explode('/', $url);
  416. $this->urlFragments = $params;
  417. $this->_inputXml = $inputXml;
  418. $this->depth = isset($this->urlFragments['depth']) ? (int)$this->urlFragments['depth'] : $this->depth;
  419. try {
  420. // Method below set a particular fonction to use on the price field for products entity
  421. // @see WebserviceRequest::getPriceForProduct() method
  422. // @see WebserviceOutputBuilder::setSpecificField() method
  423. //$this->objOutput->setSpecificField($this, 'getPriceForProduct', 'price', 'products');
  424. if (isset($this->urlFragments['price'])) {
  425. $this->objOutput->setVirtualField($this, 'specificPriceForCombination', 'combinations', $this->urlFragments['price']);
  426. $this->objOutput->setVirtualField($this, 'specificPriceForProduct', 'products', $this->urlFragments['price']);
  427. }
  428. } catch (Exception $e) {
  429. $this->setError(500, $e->getMessage(), $e->getCode());
  430. }
  431. if (isset($this->urlFragments['language'])) {
  432. $this->_available_languages = $this->filterLanguage();
  433. } else {
  434. $this->_available_languages = Language::getIDs();
  435. }
  436. if (empty($this->_available_languages)) {
  437. $this->setError(400, 'language is not available', 81);
  438. }
  439. // Need to set available languages for the render object.
  440. // Thus we can filter i18n field for the output
  441. // @see WebserviceOutputXML::renderField() method for example
  442. $this->objOutput->objectRender->setLanguages($this->_available_languages);
  443. // check method and resource
  444. if (empty($this->errors) && $this->checkResource() && $this->checkHTTPMethod()) {
  445. // The resource list is necessary for build the output
  446. $this->objOutput->setWsResources($this->resourceList);
  447. // if the resource is a core entity...
  448. if (!isset($this->resourceList[$this->urlSegment[0]]['specific_management']) || !$this->resourceList[$this->urlSegment[0]]['specific_management']) {
  449. // load resource configuration
  450. if ($this->urlSegment[0] != '') {
  451. /** @var ObjectModel $object */
  452. $object = new $this->resourceList[$this->urlSegment[0]]['class']();
  453. if (isset($this->resourceList[$this->urlSegment[0]]['parameters_attribute'])) {
  454. $this->resourceConfiguration = $object->getWebserviceParameters($this->resourceList[$this->urlSegment[0]]['parameters_attribute']);
  455. } else {
  456. $this->resourceConfiguration = $object->getWebserviceParameters();
  457. }
  458. }
  459. $success = false;
  460. // execute the action
  461. switch ($this->method) {
  462. case 'GET':
  463. case 'HEAD':
  464. if ($this->executeEntityGetAndHead()) {
  465. $success = true;
  466. }
  467. break;
  468. case 'POST':
  469. if ($this->executeEntityPost()) {
  470. $success = true;
  471. }
  472. break;
  473. case 'PUT':
  474. if ($this->executeEntityPut()) {
  475. $success = true;
  476. }
  477. break;
  478. case 'DELETE':
  479. $this->executeEntityDelete();
  480. break;
  481. }
  482. // Need to set an object for the WebserviceOutputBuilder object in any case
  483. // because schema need to get webserviceParameters of this object
  484. if (isset($object)) {
  485. $this->objects['empty'] = $object;
  486. }
  487. }
  488. // if the management is specific
  489. else {
  490. $specificObjectName = 'WebserviceSpecificManagement'.ucfirst(Tools::toCamelCase($this->urlSegment[0]));
  491. if (!class_exists($specificObjectName)) {
  492. $this->setError(501, sprintf('The specific management class is not implemented for the "%s" entity.', $this->urlSegment[0]), 124);
  493. } else {
  494. $this->objectSpecificManagement = new $specificObjectName();
  495. $this->objectSpecificManagement->setObjectOutput($this->objOutput)
  496. ->setWsObject($this);
  497. try {
  498. $this->objectSpecificManagement->manage();
  499. } catch (WebserviceException $e) {
  500. if ($e->getType() == WebserviceException::DID_YOU_MEAN) {
  501. $this->setErrorDidYouMean($e->getStatus(), $e->getMessage(), $e->getWrongValue(), $e->getAvailableValues(), $e->getCode());
  502. } elseif ($e->getType() == WebserviceException::SIMPLE) {
  503. $this->setError($e->getStatus(), $e->getMessage(), $e->getCode());
  504. }
  505. }
  506. }
  507. }
  508. }
  509. }
  510. $return = $this->returnOutput();
  511. unset($webservice_call);
  512. unset($display_errors);
  513. return $return;
  514. }
  515. protected function webserviceChecks()
  516. {
  517. return ($this->isActivated() && $this->authenticate() && $this->groupShopExists($this->params) && $this->shopExists($this->params) && $this->shopHasRight($this->_key));
  518. }
  519. /**
  520. * Set a webservice error
  521. *
  522. * @param int $status
  523. * @param string $label
  524. * @param int $code
  525. * @return void
  526. */
  527. public function setError($status, $label, $code)
  528. {
  529. global $display_errors;
  530. if (!isset($display_errors)) {
  531. $display_errors = strtolower(ini_get('display_errors')) != 'off';
  532. }
  533. if (isset($this->objOutput)) {
  534. $this->objOutput->setStatus($status);
  535. }
  536. $this->errors[] = $display_errors ? array($code, $label) : 'Internal error. To see this error please display the PHP errors.';
  537. }
  538. /**
  539. * Set a webservice error and propose a new value near from the available values
  540. *
  541. * @param int $num
  542. * @param string $label
  543. * @param array $value
  544. * @param array $values
  545. * @param int $code
  546. * @return void
  547. */
  548. public function setErrorDidYouMean($num, $label, $value, $available_values, $code)
  549. {
  550. $this->setError($num, $label.'. Did you mean: "'.$this->getClosest($value, $available_values).'"?'.(count($available_values) > 1 ? ' The full list is: "'.implode('", "', $available_values).'"' : ''), $code);
  551. }
  552. /**
  553. * Return the nearest value picked in the values list
  554. *
  555. * @param string $input
  556. * @param array $words
  557. * @return string
  558. */
  559. protected function getClosest($input, $words)
  560. {
  561. $shortest = -1;
  562. foreach ($words as $word) {
  563. $lev = levenshtein($input, $word);
  564. if ($lev == 0) {
  565. $closest = $word;
  566. $shortest = 0;
  567. break;
  568. }
  569. if ($lev <= $shortest || $shortest < 0) {
  570. $closest = $word;
  571. $shortest = $lev;
  572. }
  573. }
  574. return $closest;
  575. }
  576. /**
  577. * Used to replace the default PHP error handler, in order to display PHP errors in a XML format
  578. *
  579. * @param string $errno contains the level of the error raised, as an integer
  580. * @param array $errstr contains the error message, as a string
  581. * @param array $errfile errfile, which contains the filename that the error was raised in, as a string
  582. * @param array $errline errline, which contains the line number the error was raised at, as an integer
  583. * @return bool Always return true to avoid the default PHP error handler
  584. */
  585. public function webserviceErrorHandler($errno, $errstr, $errfile, $errline)
  586. {
  587. $display_errors = strtolower(ini_get('display_errors')) != 'off';
  588. if (!(error_reporting() & $errno) || $display_errors) {
  589. return;
  590. }
  591. $errortype = array(
  592. E_ERROR => 'Error',
  593. E_WARNING => 'Warning',
  594. E_PARSE => 'Parse',
  595. E_NOTICE => 'Notice',
  596. E_CORE_ERROR => 'Core Error',
  597. E_CORE_WARNING => 'Core Warning',
  598. E_COMPILE_ERROR => 'Compile Error',
  599. E_COMPILE_WARNING => 'Compile Warning',
  600. E_USER_ERROR => 'Error',
  601. E_USER_WARNING => 'User warning',
  602. E_USER_NOTICE => 'User notice',
  603. E_STRICT => 'Runtime Notice',
  604. E_RECOVERABLE_ERROR => 'Recoverable error'
  605. );
  606. $type = (isset($errortype[$errno]) ? $errortype[$errno] : 'Unknown error');
  607. Tools::error_log('[PHP '.$type.' #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')');
  608. switch ($errno) {
  609. case E_ERROR:
  610. WebserviceRequest::getInstance()->setError(500, '[PHP Error #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')', 2);
  611. break;
  612. case E_WARNING:
  613. WebserviceRequest::getInstance()->setError(500, '[PHP Warning #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')', 3);
  614. break;
  615. case E_PARSE:
  616. WebserviceRequest::getInstance()->setError(500, '[PHP Parse #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')', 4);
  617. break;
  618. case E_NOTICE:
  619. WebserviceRequest::getInstance()->setError(500, '[PHP Notice #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')', 5);
  620. break;
  621. case E_CORE_ERROR:
  622. WebserviceRequest::getInstance()->setError(500, '[PHP Core #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')', 6);
  623. break;
  624. case E_CORE_WARNING:
  625. WebserviceRequest::getInstance()->setError(500, '[PHP Core warning #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')', 7);
  626. break;
  627. case E_COMPILE_ERROR:
  628. WebserviceRequest::getInstance()->setError(500, '[PHP Compile #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')', 8);
  629. break;
  630. case E_COMPILE_WARNING:
  631. WebserviceRequest::getInstance()->setError(500, '[PHP Compile warning #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')', 9);
  632. break;
  633. case E_USER_ERROR:
  634. WebserviceRequest::getInstance()->setError(500, '[PHP Error #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')', 10);
  635. break;
  636. case E_USER_WARNING:
  637. WebserviceRequest::getInstance()->setError(500, '[PHP User warning #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')', 11);
  638. break;
  639. case E_USER_NOTICE:
  640. WebserviceRequest::getInstance()->setError(500, '[PHP User notice #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')', 12);
  641. break;
  642. case E_STRICT:
  643. WebserviceRequest::getInstance()->setError(500, '[PHP Strict #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')', 13);
  644. break;
  645. case E_RECOVERABLE_ERROR:
  646. WebserviceRequest::getInstance()->setError(500, '[PHP Recoverable error #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')', 14);
  647. break;
  648. default:
  649. WebserviceRequest::getInstance()->setError(500, '[PHP Unknown error #'.$errno.'] '.$errstr.' ('.$errfile.', line '.$errline.')', 15);
  650. }
  651. return true;
  652. }
  653. /**
  654. * Check if there is one or more error
  655. *
  656. * @return bool
  657. */
  658. protected function hasErrors()
  659. {
  660. return (bool)$this->errors;
  661. }
  662. /**
  663. * Check request authentication
  664. *
  665. * @return bool
  666. */
  667. protected function authenticate()
  668. {
  669. if (!$this->hasErrors()) {
  670. if (is_null($this->_key)) {
  671. $this->setError(401, 'Please enter the authentication key as the login. No password required', 16);
  672. } else {
  673. if (empty($this->_key)) {
  674. $this->setError(401, 'Authentication key is empty', 17);
  675. } elseif (strlen($this->_key) != '32') {
  676. $this->setError(401, 'Invalid authentication key format', 18);
  677. } else {
  678. if (WebserviceKey::isKeyActive($this->_key)) {
  679. $this->keyPermissions = WebserviceKey::getPermissionForAccount($this->_key);
  680. } else {
  681. $this->setError(401, 'Authentification key is not active', 20);
  682. }
  683. if (!$this->keyPermissions) {
  684. $this->setError(401, 'No permission for this authentication key', 21);
  685. }
  686. }
  687. }
  688. if ($this->hasErrors()) {
  689. header('WWW-Authenticate: Basic realm="Welcome to PrestaShop Webservice, please enter the authentication key as the login. No password required."');
  690. $this->objOutput->setStatus(401);
  691. return false;
  692. } else {
  693. // only now we can say the access is authenticated
  694. $this->_authenticated = true;
  695. return true;
  696. }
  697. }
  698. }
  699. /**
  700. * Check webservice activation
  701. *
  702. * @return bool
  703. */
  704. protected function isActivated()
  705. {
  706. if (!Configuration::get('PS_WEBSERVICE')) {
  707. $this->setError(503, 'The PrestaShop webservice is disabled. Please activate it in the PrestaShop Back Office', 22);
  708. return false;
  709. }
  710. return true;
  711. }
  712. protected function shopHasRight($key)
  713. {
  714. $sql = 'SELECT 1
  715. FROM '._DB_PREFIX_.'webservice_account wsa LEFT JOIN '._DB_PREFIX_.'webservice_account_shop wsas ON (wsa.id_webservice_account = wsas.id_webservice_account)
  716. WHERE wsa.key = \''.pSQL($key).'\'';
  717. foreach (self::$shopIDs as $id_shop) {
  718. $OR[] = ' wsas.id_shop = '.(int)$id_shop.' ';
  719. }
  720. $sql .= ' AND ('.implode('OR', $OR).') ';
  721. if (!Db::getInstance()->getValue($sql)) {
  722. $this->setError(403, 'No permission for this key on this shop', 132);
  723. return false;
  724. }
  725. return true;
  726. }
  727. protected function shopExists($params)
  728. {
  729. if (count(self::$shopIDs)) {
  730. return true;
  731. }
  732. if (isset($params['id_shop'])) {
  733. if ($params['id_shop'] != 'all' && is_numeric($params['id_shop'])) {
  734. Shop::setContext(Shop::CONTEXT_SHOP, (int)$params['id_shop']);
  735. self::$shopIDs[] = (int)$params['id_shop'];
  736. return true;
  737. } elseif ($params['id_shop'] == 'all') {
  738. Shop::setContext(Shop::CONTEXT_ALL);
  739. self::$shopIDs = Shop::getShops(true, null, true);
  740. return true;
  741. }
  742. } else {
  743. self::$shopIDs[] = Context::getContext()->shop->id;
  744. return true;
  745. }
  746. $this->setError(404, 'This shop id does not exist', 999);
  747. return false;
  748. }
  749. protected function groupShopExists($params)
  750. {
  751. if (isset($params['id_group_shop']) && is_numeric($params['id_group_shop'])) {
  752. Shop::setContext(Shop::CONTEXT_GROUP, (int)$params['id_group_shop']);
  753. self::$shopIDs = Shop::getShops(true, (int)$params['id_group_shop'], true);
  754. if (count(self::$shopIDs) == 0) {
  755. // @FIXME Set ErrorCode !
  756. $this->setError(500, 'This group shop doesn\'t have shops', 999);
  757. return false;
  758. }
  759. }
  760. // id_group_shop isn't mandatory
  761. return true;
  762. }
  763. /**
  764. * Check HTTP method
  765. *
  766. * @return bool
  767. */
  768. protected function checkHTTPMethod()
  769. {
  770. if (!in_array($this->method, array('GET', 'POST', 'PUT', 'DELETE', 'HEAD'))) {
  771. $this->setError(405, 'Method '.$this->method.' is not valid', 23);
  772. } elseif (isset($this->urlSegment[0]) && isset($this->resourceList[$this->urlSegment[0]]['forbidden_method']) && in_array($this->method, $this->resourceList[$this->urlSegment[0]]['forbidden_method'])) {
  773. $this->setError(405, 'Method '.$this->method.' is not allowed for the resource '.$this->urlSegment[0], 101);
  774. } elseif ($this->urlSegment[0] && !in_array($this->method, $this->keyPermissions[$this->urlSegment[0]])) {
  775. $this->setError(405, 'Method '.$this->method.' is not allowed for the resource '.$this->urlSegment[0].' with this authentication key', 25);
  776. } else {
  777. return true;
  778. }
  779. return false;
  780. }
  781. /**
  782. * Check resource validity
  783. *
  784. * @return bool
  785. */
  786. protected function checkResource()
  787. {
  788. $this->resourceList = $this->getResources();
  789. $resourceNames = array_keys($this->resourceList);
  790. if ($this->urlSegment[0] == '') {
  791. $this->resourceConfiguration['objectsNodeName'] = 'resources';
  792. } elseif (in_array($this->urlSegment[0], $resourceNames)) {
  793. if (!in_array($this->urlSegment[0], array_keys($this->keyPermissions))) {
  794. $this->setError(401, 'Resource of type "'.$this->urlSegment[0].'" is not allowed with this authentication key', 26);
  795. return false;
  796. }
  797. } else {
  798. $this->setErrorDidYouMean(400, 'Resource of type "'.$this->urlSegment[0].'" does not exists', $this->urlSegment[0], $resourceNames, 27);
  799. return false;
  800. }
  801. return true;
  802. }
  803. protected function setObjects()
  804. {
  805. $objects = array();
  806. $arr_avoid_id = array();
  807. $ids = array();
  808. if (isset($this->urlFragments['id'])) {
  809. preg_match('#^\[(.*)\]$#Ui', $this->urlFragments['id'], $matches);
  810. if (count($matches) > 1) {
  811. $ids = explode(',', $matches[1]);
  812. }
  813. } else {
  814. $ids[] = (int)$this->urlSegment[1];
  815. }
  816. if (!empty($ids)) {
  817. foreach ($ids as $id) {
  818. $object = new $this->resourceConfiguration['retrieveData']['className']((int)$id);
  819. if (!$object->id) {
  820. $arr_avoid_id[] = $id;
  821. } else {
  822. $objects[] = $object;
  823. }
  824. }
  825. }
  826. if (!empty($arr_avoid_id) || empty($ids)) {
  827. $this->setError(404, 'Id(s) not exists: '.implode(', ', $arr_avoid_id), 87);
  828. $this->_outputEnabled = true;
  829. }
  830. }
  831. protected function parseDisplayFields($str)
  832. {
  833. $bracket_level = 0;
  834. $part = array();
  835. $tmp = '';
  836. $str_len = strlen($str);
  837. for ($i = 0; $i < $str_len; $i++) {
  838. if ($str[$i] == ',' && $bracket_level == 0) {
  839. $part[] = $tmp;
  840. $tmp = '';
  841. } else {
  842. $tmp .= $str[$i];
  843. }
  844. if ($str[$i] == '[') {
  845. $bracket_level++;
  846. }
  847. if ($str[$i] == ']') {
  848. $bracket_level--;
  849. }
  850. }
  851. if ($tmp != '') {
  852. $part[] = $tmp;
  853. }
  854. $fields = array();
  855. foreach ($part as $str) {
  856. $field_name = trim(substr($str, 0, (strpos($str, '[') === false ? strlen($str) : strpos($str, '['))));
  857. if (!isset($fields[$field_name])) {
  858. $fields[$field_name] = null;
  859. }
  860. if (strpos($str, '[') !== false) {
  861. $sub_fields = substr($str, strpos($str, '[') + 1, strlen($str) - strpos($str, '[') - 2);
  862. $tmp_array = array();
  863. if (strpos($sub_fields, ',') !== false) {
  864. $tmp_array = explode(',', $sub_fields);
  865. } else {
  866. $tmp_array = array($sub_fields);
  867. }
  868. $fields[$field_name] = (is_array($fields[$field_name])) ? array_merge($fields[$field_name], $tmp_array) : $tmp_array;
  869. }
  870. }
  871. return $fields;
  872. }
  873. public function setFieldsToDisplay()
  874. {
  875. // set the fields to display in the list : "full", "minimum", "field_1", "field_1,field_2,field_3"
  876. if (isset($this->urlFragments['display'])) {
  877. $this->fieldsToDisplay = $this->urlFragments['display'];
  878. if ($this->fieldsToDisplay != 'full' && $this->fieldsToDisplay != 'minimum') {
  879. preg_match('#^\[(.*)\]$#Ui', $this->fieldsToDisplay, $matches);
  880. if (count($matches)) {
  881. $error = false;
  882. $fieldsToTest = $this->parseDisplayFields($matches[1]);
  883. foreach ($fieldsToTest as $field_name => $part) {
  884. // in case it is not an association
  885. if (!is_array($part)) {
  886. // We have to allow new specific field for price calculation too
  887. $error = (!isset($this->resourceConfiguration['fields'][$field_name]) && !isset($this->urlFragments['price'][$field_name]));
  888. } else {
  889. // if this association does not exists
  890. if (!array_key_exists($field_name, $this->resourceConfiguration['associations'])) {
  891. $error = true;
  892. }
  893. foreach ($part as $field) {
  894. if ($field != 'id' && !array_key_exists($field, $this->resourceConfiguration['associations'][$field_name]['fields'])) {
  895. $error = true;
  896. break;
  897. }
  898. }
  899. }
  900. if ($error) {
  901. $this->setError(400, 'Unable to display this field "'.$field_name.(is_array($part) ? ' (details : '.var_export($part, true).')' : '').'". However, these are available: '.implode(', ', array_keys($this->resourceConfiguration['fields'])), 35);
  902. return false;
  903. }
  904. }
  905. $this->fieldsToDisplay = $fieldsToTest;
  906. } else {
  907. $this->setError(400, 'The \'display\' syntax is wrong. You can set \'full\' or \'[field_1,field_2,field_3,...]\'. These are available: '.implode(', ', array_keys($this->resourceConfiguration['fields'])), 36);
  908. return false;
  909. }
  910. }
  911. }
  912. return true;
  913. }
  914. protected function manageFilters()
  915. {
  916. // filtered fields which can not use filters : hidden_fields
  917. $available_filters = array();
  918. // filtered i18n fields which can use filters
  919. $i18n_available_filters = array();
  920. foreach ($this->resourceConfiguration['fields'] as $fieldName => $field) {
  921. if ((!isset($this->resourceConfiguration['hidden_fields']) ||
  922. (isset($this->resourceConfiguration['hidden_fields']) && !in_array($fieldName, $this->resourceConfiguration['hidden_fields'])))) {
  923. if ((!isset($field['i18n']) ||
  924. (isset($field['i18n']) && !$field['i18n']))) {
  925. $available_filters[] = $fieldName;
  926. } else {
  927. $i18n_available_filters[] = $fieldName;
  928. }
  929. }
  930. }
  931. // Date feature : date=1
  932. if (!empty($this->urlFragments['date']) && $this->urlFragments['date']) {
  933. if (!in_array('date_add', $available_filters)) {
  934. $available_filters[] = 'date_add';
  935. }
  936. if (!in_array('date_upd', $available_filters)) {
  937. $available_filters[] = 'date_upd';
  938. }
  939. if (!array_key_exists('date_add', $this->resourceConfiguration['fields'])) {
  940. $this->resourceConfiguration['fields']['date_add'] = array('sqlId' => 'date_add');
  941. }
  942. if (!array_key_exists('date_upd', $this->resourceConfiguration['fields'])) {
  943. $this->resourceConfiguration['fields']['date_upd'] = array('sqlId' => 'date_upd');
  944. }
  945. } else {
  946. foreach ($available_filters as $key => $value) {
  947. if ($value == 'date_add' || $value == 'date_upd') {
  948. unset($available_filters[$key]);
  949. }
  950. }
  951. }
  952. //construct SQL filter
  953. $sql_filter = '';
  954. $sql_join = '';
  955. if ($this->urlFragments) {
  956. $schema = 'schema';
  957. // if we have to display the schema
  958. if (isset($this->urlFragments[$schema])) {
  959. if ($this->urlFragments[$schema] == 'blank' || $this->urlFragments[$schema] == 'synopsis') {
  960. $this->schemaToDisplay = $this->urlFragments[$schema];
  961. return true;
  962. } else {
  963. $this->setError(400, 'Please select a schema of type \'synopsis\' to get the whole schema informations (which fields are required, which kind of content...) or \'blank\' to get an empty schema to fill before using POST request', 28);
  964. return false;
  965. }
  966. } else {
  967. // if there are filters
  968. if (isset($this->urlFragments['filter'])) {
  969. foreach ($this->urlFragments['filter'] as $field => $url_param) {
  970. if ($field != 'sort' && $field != 'limit') {
  971. if (!in_array($field, $available_filters)) {
  972. // if there are linked tables
  973. if (isset($this->resourceConfiguration['linked_tables']) && isset($this->resourceConfiguration['linked_tables'][$field])) {
  974. // contruct SQL join for linked tables
  975. $sql_join .= 'LEFT JOIN `'.bqSQL(_DB_PREFIX_.$this->resourceConfiguration['linked_tables'][$field]['table']).'` '.bqSQL($field).' ON (main.`'.bqSQL($this->resourceConfiguration['fields']['id']['sqlId']).'` = '.bqSQL($field).'.`'.bqSQL($this->resourceConfiguration['fields']['id']['sqlId']).'`)'."\n";
  976. // construct SQL filter for linked tables
  977. foreach ($url_param as $field2 => $value) {
  978. if (isset($this->resourceConfiguration['linked_tables'][$field]['fields'][$field2])) {
  979. $linked_field = $this->resourceConfiguration['linked_tables'][$field]['fields'][$field2];
  980. $sql_filter .= $this->getSQLRetrieveFilter($linked_field['sqlId'], $value, $field.'.');
  981. } else {
  982. $list = array_keys($this->resourceConfiguration['linked_tables'][$field]['fields']);
  983. $this->setErrorDidYouMean(400, 'This filter does not exist for this linked table', $field2, $list, 29);
  984. return false;
  985. }
  986. }
  987. } elseif ($url_param != '' && in_array($field, $i18n_available_filters)) {
  988. if (!is_array($url_param)) {
  989. $url_param = array($url_param);
  990. }
  991. $sql_join .= 'LEFT JOIN `'.bqSQL(_DB_PREFIX_.$this->resourceConfiguration['retrieveData']['table']).'_lang` AS main_i18n ON (main.`'.pSQL($this->resourceConfiguration['fields']['id']['sqlId']).'` = main_i18n.`'.bqSQL($this->resourceConfiguration['fields']['id']['sqlId']).'`)'."\n";
  992. foreach ($url_param as $field2 => $value) {
  993. $linked_field = $this->resourceConfiguration['fields'][$field];
  994. $sql_filter .= $this->getSQLRetrieveFilter($linked_field['sqlId'], $value, 'main_i18n.');
  995. $language_filter = '['.implode('|', $this->_available_languages).']';
  996. $sql_filter .= $this->getSQLRetrieveFilter('id_lang', $language_filter, 'main_i18n.');
  997. }
  998. }
  999. // if there are filters on linked tables but there are no linked table
  1000. elseif (is_array($url_param)) {
  1001. if (isset($this->resourceConfiguration['linked_tables'])) {
  1002. $this->setErrorDidYouMean(400, 'This linked table does not exist', $field, array_keys($this->resourceConfiguration['linked_tables']), 30);
  1003. } else {
  1004. $this->setError(400, 'There is no existing linked table for this resource', 31);
  1005. }
  1006. return false;
  1007. } else {
  1008. $this->setErrorDidYouMean(400, 'This filter does not exist', $field, $available_filters, 32);
  1009. return false;
  1010. }