api.class.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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 = (!getDolGlobalString('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 mixed $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. if (!is_array($value)) {
  78. // TODO Use type detected in $object->fields if $object known and we can
  79. if (in_array($field, array('note', 'note_private', 'note_public', 'desc', 'description'))) {
  80. return sanitizeVal($value, 'restricthtml');
  81. } else {
  82. return sanitizeVal($value, 'alphanohtml');
  83. }
  84. } else {
  85. // TODO Recall _checkValForAPI for each element of array
  86. return $value;
  87. }
  88. }
  89. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  90. /**
  91. * Filter properties that will be returned on object
  92. *
  93. * @param Object $object Object to clean
  94. * @param String $properties Comma separated list of properties names
  95. * @return Object Object with cleaned properties
  96. */
  97. protected function _filterObjectProperties($object, $properties)
  98. {
  99. // If properties is empty, we return all properties
  100. if (empty($properties)) {
  101. return $object;
  102. }
  103. // Else we filter properties
  104. foreach (get_object_vars($object) as $key => $value) {
  105. if (!in_array($key, explode(',', $properties))) {
  106. unset($object->$key);
  107. }
  108. }
  109. return $object;
  110. }
  111. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  112. /**
  113. * Clean sensible object datas
  114. *
  115. * @param Object $object Object to clean
  116. * @return Object Object with cleaned properties
  117. */
  118. protected function _cleanObjectDatas($object)
  119. {
  120. // phpcs:enable
  121. // Remove $db object property for object
  122. unset($object->db);
  123. unset($object->isextrafieldmanaged);
  124. unset($object->ismultientitymanaged);
  125. unset($object->restrictiononfksoc);
  126. unset($object->table_rowid);
  127. unset($object->pass);
  128. unset($object->pass_indatabase);
  129. // Remove linkedObjects. We should already have and keep only linkedObjectsIds that avoid huge responses
  130. unset($object->linkedObjects);
  131. //unset($object->lines[$i]->linked_objects); // This is the array to create linked object during create
  132. unset($object->fields);
  133. unset($object->oldline);
  134. unset($object->error);
  135. unset($object->errors);
  136. unset($object->errorhidden);
  137. unset($object->ref_previous);
  138. unset($object->ref_next);
  139. unset($object->imgWidth);
  140. unset($object->imgHeight);
  141. unset($object->barcode_type_code);
  142. unset($object->barcode_type_label);
  143. unset($object->mode_reglement); // We use mode_reglement_id now
  144. unset($object->cond_reglement); // We use cond_reglement_id now
  145. unset($object->note); // We use note_public or note_private now
  146. unset($object->contact); // We use contact_id now
  147. unset($object->thirdparty); // We use thirdparty_id or fk_soc or socid now
  148. unset($object->projet); // Should be fk_project
  149. unset($object->project); // Should be fk_project
  150. unset($object->fk_projet); // Should be fk_project
  151. unset($object->author); // Should be fk_user_author
  152. unset($object->timespent_old_duration);
  153. unset($object->timespent_id);
  154. unset($object->timespent_duration);
  155. unset($object->timespent_date);
  156. unset($object->timespent_datehour);
  157. unset($object->timespent_withhour);
  158. unset($object->timespent_fk_user);
  159. unset($object->timespent_note);
  160. unset($object->fk_delivery_address);
  161. unset($object->modelpdf);
  162. unset($object->sendtoid);
  163. unset($object->name_bis);
  164. unset($object->newref);
  165. unset($object->alreadypaid);
  166. unset($object->openid);
  167. //unset($object->labelStatus);
  168. //unset($object->labelStatusShort);
  169. unset($object->stats_propale);
  170. unset($object->stats_commande);
  171. unset($object->stats_contrat);
  172. unset($object->stats_facture);
  173. unset($object->stats_commande_fournisseur);
  174. unset($object->stats_reception);
  175. unset($object->stats_mrptoconsume);
  176. unset($object->stats_mrptoproduce);
  177. unset($object->element);
  178. unset($object->element_for_permission);
  179. unset($object->fk_element);
  180. unset($object->table_element);
  181. unset($object->table_element_line);
  182. unset($object->class_element_line);
  183. unset($object->picto);
  184. unset($object->fieldsforcombobox);
  185. unset($object->regeximgext);
  186. unset($object->skip_update_total);
  187. unset($object->context);
  188. unset($object->next_prev_filter);
  189. unset($object->region);
  190. unset($object->region_code);
  191. unset($object->country);
  192. unset($object->state);
  193. unset($object->state_code);
  194. unset($object->departement);
  195. unset($object->departement_code);
  196. unset($object->libelle_statut);
  197. unset($object->libelle_paiement);
  198. unset($object->prefix_comm);
  199. if (!isset($object->table_element) || $object->table_element != 'ticket') {
  200. unset($object->comments);
  201. }
  202. // Remove the $oldcopy property because it is not supported by the JSON
  203. // encoder. The following error is generated when trying to serialize
  204. // it: "Error encoding/decoding JSON: Type is not supported"
  205. // Note: Event if this property was correctly handled by the JSON
  206. // encoder, it should be ignored because keeping it would let the API
  207. // have a very strange behavior: calling PUT and then GET on the same
  208. // resource would give different results:
  209. // PUT /objects/{id} -> returns object with oldcopy = previous version of the object
  210. // GET /objects/{id} -> returns object with oldcopy empty
  211. unset($object->oldcopy);
  212. // If object has lines, remove $db property
  213. if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) {
  214. $nboflines = count($object->lines);
  215. for ($i = 0; $i < $nboflines; $i++) {
  216. $this->_cleanObjectDatas($object->lines[$i]);
  217. unset($object->lines[$i]->contact);
  218. unset($object->lines[$i]->contact_id);
  219. unset($object->lines[$i]->country);
  220. unset($object->lines[$i]->country_id);
  221. unset($object->lines[$i]->country_code);
  222. unset($object->lines[$i]->mode_reglement_id);
  223. unset($object->lines[$i]->mode_reglement_code);
  224. unset($object->lines[$i]->mode_reglement);
  225. unset($object->lines[$i]->cond_reglement_id);
  226. unset($object->lines[$i]->cond_reglement_code);
  227. unset($object->lines[$i]->cond_reglement);
  228. unset($object->lines[$i]->fk_delivery_address);
  229. unset($object->lines[$i]->fk_projet);
  230. unset($object->lines[$i]->fk_project);
  231. unset($object->lines[$i]->thirdparty);
  232. unset($object->lines[$i]->user);
  233. unset($object->lines[$i]->model_pdf);
  234. unset($object->lines[$i]->modelpdf);
  235. unset($object->lines[$i]->note_public);
  236. unset($object->lines[$i]->note_private);
  237. unset($object->lines[$i]->fk_incoterms);
  238. unset($object->lines[$i]->label_incoterms);
  239. unset($object->lines[$i]->location_incoterms);
  240. unset($object->lines[$i]->name);
  241. unset($object->lines[$i]->lastname);
  242. unset($object->lines[$i]->firstname);
  243. unset($object->lines[$i]->civility_id);
  244. unset($object->lines[$i]->fk_multicurrency);
  245. unset($object->lines[$i]->multicurrency_code);
  246. unset($object->lines[$i]->shipping_method_id);
  247. }
  248. }
  249. if (!empty($object->thirdparty) && is_object($object->thirdparty)) {
  250. $this->_cleanObjectDatas($object->thirdparty);
  251. }
  252. if (!empty($object->product) && is_object($object->product)) {
  253. $this->_cleanObjectDatas($object->product);
  254. }
  255. return $object;
  256. }
  257. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  258. /**
  259. * Check access by user to a given resource
  260. *
  261. * @param string $resource element to check
  262. * @param int $resource_id Object ID if we want to check a particular record (optional) is linked to a owned thirdparty (optional).
  263. * @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)
  264. * @param string $feature2 Feature to check, second level of permission (optional). Can be or check with 'level1|level2'.
  265. * @param string $dbt_keyfield Field name for socid foreign key if not fk_soc. Not used if objectid is null (optional)
  266. * @param string $dbt_select Field name for select if not rowid. Not used if objectid is null (optional)
  267. * @return bool
  268. */
  269. protected static function _checkAccessToResource($resource, $resource_id = 0, $dbtablename = '', $feature2 = '', $dbt_keyfield = 'fk_soc', $dbt_select = 'rowid')
  270. {
  271. // phpcs:enable
  272. // Features/modules to check
  273. $featuresarray = array($resource);
  274. if (preg_match('/&/', $resource)) {
  275. $featuresarray = explode("&", $resource);
  276. } elseif (preg_match('/\|/', $resource)) {
  277. $featuresarray = explode("|", $resource);
  278. }
  279. // More subfeatures to check
  280. if (!empty($feature2)) {
  281. $feature2 = explode("|", $feature2);
  282. }
  283. return checkUserAccessToObject(DolibarrApiAccess::$user, $featuresarray, $resource_id, $dbtablename, $feature2, $dbt_keyfield, $dbt_select);
  284. }
  285. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  286. /**
  287. * Return if a $sqlfilters parameter is valid
  288. * Function no more used. Kept for backward compatibility with old APIs of modules
  289. *
  290. * @param string $sqlfilters sqlfilter string
  291. * @param string $error Error message
  292. * @return boolean|string True if valid, False if not valid
  293. */
  294. protected function _checkFilters($sqlfilters, &$error = '')
  295. {
  296. // phpcs:enable
  297. return dolCheckFilters($sqlfilters, $error);
  298. }
  299. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  300. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  301. /**
  302. * Function to forge a SQL criteria from a Generic filter string.
  303. * Function no more used. Kept for backward compatibility with old APIs of modules
  304. *
  305. * @param array $matches Array of found string by regex search.
  306. * Each entry is 1 and only 1 criteria.
  307. * 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"
  308. * @return string Forged criteria. Example: "t.field like 'abc%'"
  309. */
  310. protected static function _forge_criteria_callback($matches)
  311. {
  312. return dolForgeCriteriaCallback($matches);
  313. }
  314. }