api.class.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. <?php
  2. /* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
  3. * Copyright (C) 2016 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2020 Frédéric France <frederic.france@netlogic.fr>
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. use Luracast\Restler\Restler;
  20. use Luracast\Restler\RestException;
  21. use Luracast\Restler\Defaults;
  22. use Luracast\Restler\Format\UploadFormat;
  23. require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
  24. /**
  25. * Class for API REST v1
  26. */
  27. class DolibarrApi
  28. {
  29. /**
  30. * @var DoliDb $db Database object
  31. */
  32. protected $db;
  33. /**
  34. * @var Restler $r Restler object
  35. */
  36. public $r;
  37. /**
  38. * Constructor
  39. *
  40. * @param DoliDb $db Database handler
  41. * @param string $cachedir Cache dir
  42. * @param boolean $refreshCache Update cache
  43. */
  44. public function __construct($db, $cachedir = '', $refreshCache = false)
  45. {
  46. global $conf, $dolibarr_main_url_root;
  47. if (empty($cachedir)) {
  48. $cachedir = $conf->api->dir_temp;
  49. }
  50. Defaults::$cacheDirectory = $cachedir;
  51. $this->db = $db;
  52. $production_mode = (empty($conf->global->API_PRODUCTION_MODE) ? false : true);
  53. $this->r = new Restler($production_mode, $refreshCache);
  54. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  55. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  56. $urlwithouturlrootautodetect = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim(DOL_MAIN_URL_ROOT));
  57. $urlwithrootautodetect = $urlwithouturlroot.DOL_URL_ROOT; // This is to use local domain autodetected by dolibarr from url
  58. $this->r->setBaseUrls($urlwithouturlroot, $urlwithouturlrootautodetect);
  59. $this->r->setAPIVersion(1);
  60. //$this->r->setSupportedFormats('json');
  61. //$this->r->setSupportedFormats('jsonFormat');
  62. }
  63. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  64. /**
  65. * Check and convert a string depending on its type/name.
  66. *
  67. * Display a short message an return a http code 200
  68. *
  69. * @param string $field Field name
  70. * @param string $value Value to check/clean
  71. * @param Object $object Object
  72. * @return string Value cleaned
  73. */
  74. protected function _checkValForAPI($field, $value, $object)
  75. {
  76. // phpcs:enable
  77. // TODO Use type detected in $object->fields
  78. if (in_array($field, array('note', 'note_private', 'note_public', 'desc', 'description'))) {
  79. return sanitizeVal($value, 'restricthtml');
  80. } else {
  81. return sanitizeVal($value, 'alphanohtml');
  82. }
  83. }
  84. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  85. /**
  86. * Clean sensible object datas
  87. *
  88. * @param Object $object Object to clean
  89. * @return Object Object with cleaned properties
  90. */
  91. protected function _cleanObjectDatas($object)
  92. {
  93. // phpcs:enable
  94. // Remove $db object property for object
  95. unset($object->db);
  96. unset($object->isextrafieldmanaged);
  97. unset($object->ismultientitymanaged);
  98. unset($object->restrictiononfksoc);
  99. unset($object->table_rowid);
  100. unset($object->pass);
  101. unset($object->pass_indatabase);
  102. // Remove linkedObjects. We should already have and keep only linkedObjectsIds that avoid huge responses
  103. unset($object->linkedObjects);
  104. //unset($object->lines[$i]->linked_objects); // This is the array to create linked object during create
  105. unset($object->fields);
  106. unset($object->oldline);
  107. unset($object->error);
  108. unset($object->errors);
  109. unset($object->errorhidden);
  110. unset($object->ref_previous);
  111. unset($object->ref_next);
  112. unset($object->imgWidth);
  113. unset($object->imgHeight);
  114. unset($object->barcode_type_code);
  115. unset($object->barcode_type_label);
  116. unset($object->mode_reglement); // We use mode_reglement_id now
  117. unset($object->cond_reglement); // We use cond_reglement_id now
  118. unset($object->note); // We use note_public or note_private now
  119. unset($object->contact); // We use contact_id now
  120. unset($object->thirdparty); // We use thirdparty_id or fk_soc or socid now
  121. unset($object->projet); // Should be fk_project
  122. unset($object->project); // Should be fk_project
  123. unset($object->fk_projet); // Should be fk_project
  124. unset($object->author); // Should be fk_user_author
  125. unset($object->timespent_old_duration);
  126. unset($object->timespent_id);
  127. unset($object->timespent_duration);
  128. unset($object->timespent_date);
  129. unset($object->timespent_datehour);
  130. unset($object->timespent_withhour);
  131. unset($object->timespent_fk_user);
  132. unset($object->timespent_note);
  133. unset($object->fk_delivery_address);
  134. unset($object->modelpdf);
  135. unset($object->sendtoid);
  136. unset($object->name_bis);
  137. unset($object->newref);
  138. unset($object->alreadypaid);
  139. unset($object->openid);
  140. unset($object->statuts);
  141. unset($object->statuts_short);
  142. unset($object->statuts_logo);
  143. unset($object->statuts_long);
  144. //unset($object->labelStatus);
  145. //unset($object->labelStatusShort);
  146. unset($object->stats_propale);
  147. unset($object->stats_commande);
  148. unset($object->stats_contrat);
  149. unset($object->stats_facture);
  150. unset($object->stats_commande_fournisseur);
  151. unset($object->stats_reception);
  152. unset($object->stats_mrptoconsume);
  153. unset($object->stats_mrptoproduce);
  154. unset($object->element);
  155. unset($object->element_for_permission);
  156. unset($object->fk_element);
  157. unset($object->table_element);
  158. unset($object->table_element_line);
  159. unset($object->class_element_line);
  160. unset($object->picto);
  161. unset($object->fieldsforcombobox);
  162. unset($object->regeximgext);
  163. unset($object->skip_update_total);
  164. unset($object->context);
  165. unset($object->next_prev_filter);
  166. unset($object->region);
  167. unset($object->region_code);
  168. unset($object->country);
  169. unset($object->state);
  170. unset($object->state_code);
  171. unset($object->departement);
  172. unset($object->departement_code);
  173. unset($object->libelle_statut);
  174. unset($object->libelle_paiement);
  175. unset($object->prefix_comm);
  176. if (!isset($object->table_element) || $object->table_element != 'ticket') {
  177. unset($object->comments);
  178. }
  179. // Remove the $oldcopy property because it is not supported by the JSON
  180. // encoder. The following error is generated when trying to serialize
  181. // it: "Error encoding/decoding JSON: Type is not supported"
  182. // Note: Event if this property was correctly handled by the JSON
  183. // encoder, it should be ignored because keeping it would let the API
  184. // have a very strange behavior: calling PUT and then GET on the same
  185. // resource would give different results:
  186. // PUT /objects/{id} -> returns object with oldcopy = previous version of the object
  187. // GET /objects/{id} -> returns object with oldcopy empty
  188. unset($object->oldcopy);
  189. // If object has lines, remove $db property
  190. if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) {
  191. $nboflines = count($object->lines);
  192. for ($i = 0; $i < $nboflines; $i++) {
  193. $this->_cleanObjectDatas($object->lines[$i]);
  194. unset($object->lines[$i]->contact);
  195. unset($object->lines[$i]->contact_id);
  196. unset($object->lines[$i]->country);
  197. unset($object->lines[$i]->country_id);
  198. unset($object->lines[$i]->country_code);
  199. unset($object->lines[$i]->mode_reglement_id);
  200. unset($object->lines[$i]->mode_reglement_code);
  201. unset($object->lines[$i]->mode_reglement);
  202. unset($object->lines[$i]->cond_reglement_id);
  203. unset($object->lines[$i]->cond_reglement_code);
  204. unset($object->lines[$i]->cond_reglement);
  205. unset($object->lines[$i]->fk_delivery_address);
  206. unset($object->lines[$i]->fk_projet);
  207. unset($object->lines[$i]->fk_project);
  208. unset($object->lines[$i]->thirdparty);
  209. unset($object->lines[$i]->user);
  210. unset($object->lines[$i]->model_pdf);
  211. unset($object->lines[$i]->modelpdf);
  212. unset($object->lines[$i]->note_public);
  213. unset($object->lines[$i]->note_private);
  214. unset($object->lines[$i]->fk_incoterms);
  215. unset($object->lines[$i]->label_incoterms);
  216. unset($object->lines[$i]->location_incoterms);
  217. unset($object->lines[$i]->name);
  218. unset($object->lines[$i]->lastname);
  219. unset($object->lines[$i]->firstname);
  220. unset($object->lines[$i]->civility_id);
  221. unset($object->lines[$i]->fk_multicurrency);
  222. unset($object->lines[$i]->multicurrency_code);
  223. unset($object->lines[$i]->shipping_method_id);
  224. }
  225. }
  226. if (!empty($object->thirdparty) && is_object($object->thirdparty)) {
  227. $this->_cleanObjectDatas($object->thirdparty);
  228. }
  229. if (!empty($object->product) && is_object($object->product)) {
  230. $this->_cleanObjectDatas($object->product);
  231. }
  232. return $object;
  233. }
  234. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  235. /**
  236. * Check access by user to a given resource
  237. *
  238. * @param string $resource element to check
  239. * @param int $resource_id Object ID if we want to check a particular record (optional) is linked to a owned thirdparty (optional).
  240. * @param string $dbtablename 'TableName&SharedElement' with Tablename is table where object is stored. SharedElement is an optional key to define where to check entity. Not used if objectid is null (optional)
  241. * @param string $feature2 Feature to check, second level of permission (optional). Can be or check with 'level1|level2'.
  242. * @param string $dbt_keyfield Field name for socid foreign key if not fk_soc. Not used if objectid is null (optional)
  243. * @param string $dbt_select Field name for select if not rowid. Not used if objectid is null (optional)
  244. * @return bool
  245. */
  246. protected static function _checkAccessToResource($resource, $resource_id = 0, $dbtablename = '', $feature2 = '', $dbt_keyfield = 'fk_soc', $dbt_select = 'rowid')
  247. {
  248. // phpcs:enable
  249. // Features/modules to check
  250. $featuresarray = array($resource);
  251. if (preg_match('/&/', $resource)) {
  252. $featuresarray = explode("&", $resource);
  253. } elseif (preg_match('/\|/', $resource)) {
  254. $featuresarray = explode("|", $resource);
  255. }
  256. // More subfeatures to check
  257. if (!empty($feature2)) {
  258. $feature2 = explode("|", $feature2);
  259. }
  260. return checkUserAccessToObject(DolibarrApiAccess::$user, $featuresarray, $resource_id, $dbtablename, $feature2, $dbt_keyfield, $dbt_select);
  261. }
  262. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  263. /**
  264. * Return if a $sqlfilters parameter is valid
  265. * Function no more used. Kept for backward compatibility with old APIs of modules
  266. *
  267. * @param string $sqlfilters sqlfilter string
  268. * @param string $error Error message
  269. * @return boolean|string True if valid, False if not valid
  270. */
  271. protected function _checkFilters($sqlfilters, &$error = '')
  272. {
  273. // phpcs:enable
  274. return dolCheckFilters($sqlfilters, $error);
  275. }
  276. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  277. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  278. /**
  279. * Function to forge a SQL criteria from a Generic filter string.
  280. * Function no more used. Kept for backward compatibility with old APIs of modules
  281. *
  282. * @param array $matches Array of found string by regex search.
  283. * Each entry is 1 and only 1 criteria.
  284. * Example: "t.ref:like:'SO-%'", "t.date_creation:<:'20160101'", "t.date_creation:<:'2016-01-01 12:30:00'", "t.nature:is:NULL", "t.field2:isnot:NULL"
  285. * @return string Forged criteria. Example: "t.field like 'abc%'"
  286. */
  287. protected static function _forge_criteria_callback($matches)
  288. {
  289. return dolForgeCriteriaCallback($matches);
  290. }
  291. }