dolibarr 25.0.0-alpha
api.class.php
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) 2015 Jean-François Ferry <jfefe@aternatik.fr>
5 * Copyright (C) 2016 Laurent Destailleur <eldy@users.sourceforge.net>
6 * Copyright (C) 2020-2025 Frédéric France <frederic.france@free.fr>
7 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
8 * Copyright (C) 2025-2026 William Mead <william@m34d.com>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 3 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 */
23
24use Luracast\Restler\Restler;
25use Luracast\Restler\Defaults;
26use Luracast\Restler\RestException;
27
28require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
29
30
35{
39 protected $db;
40
44 public $r;
45
53 public function __construct($db, $cachedir = '', $refreshCache = false)
54 {
56
57 if (empty($cachedir)) {
58 $cachedir = $conf->api->dir_temp;
59 }
60 Defaults::$cacheDirectory = $cachedir;
61
62 $this->db = $db;
63
64 $production_mode = getDolGlobalBool('API_PRODUCTION_MODE');
65
66 if ($production_mode) {
67 // Create the directory Defaults::$cacheDirectory if it does not exist. If dir does not exist, using production_mode generates an error 500.
68 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
69 if (!dol_is_dir(Defaults::$cacheDirectory)) {
70 dol_mkdir(Defaults::$cacheDirectory, DOL_DATA_ROOT);
71 }
72 if (getDolGlobalString('MAIN_API_DEBUG')) {
73 dol_syslog("Debug API construct::cacheDirectory=".Defaults::$cacheDirectory, LOG_DEBUG, 0, '_api');
74 }
75 }
76
77 $this->r = new Restler($production_mode, $refreshCache);
78
79 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
80 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
81
82 $urlwithouturlrootautodetect = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim(DOL_MAIN_URL_ROOT));
83 $urlwithrootautodetect = $urlwithouturlroot.DOL_URL_ROOT; // This is to use local domain autodetected by dolibarr from url
84
85 $this->r->setBaseUrls($urlwithouturlroot, $urlwithouturlrootautodetect);
86 $this->r->setAPIVersion(1);
87 //$this->r->setSupportedFormats('json');
88 //$this->r->setSupportedFormats('jsonFormat');
89 }
90
91 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
101 protected function _checkValForAPI($field, $value, $object)
102 {
103 // phpcs:enable
104 if (!preg_match('/^[a-zA-Z0-9_]+$/', $field)) {
105 throw new RestException(400, 'Parameter '.$field.' is not allowed in request');
106 }
107
108 if (!is_array($value)) {
109 // Make protected values for forbidden properties
110 if (in_array($field, array(
111 'db', 'table_element', 'table_rowid', 'table_ref_field', 'table_element_line', 'element', 'fk_element', 'element_for_permission', 'class_element_line',
112 'fields', 'TRIGGER_PREFIX', 'picto',
113 'restrictiononfksoc', 'ismultientitymanaged', 'isextrafieldmanaged',
114 'module', 'error', 'errorhidden', 'errors', 'warning', 'warnings', 'validateFieldsErrors',
115 'oldcopy', 'oldref', 'newref', 'context',
116 'actionmsg', 'actionmsg2', 'thirdparty', 'user',
117 'tpl', 'extraparams',
118 'childtables', 'childtablesoncascade'
119 ))) {
120 throw new RestException(400, 'Parameter '.$field.' is not allowed in request');
121 }
122 if (in_array($field, array('specimen'))) {
123 // Allowed but not used
124 dol_syslog('Debug API _checkValForAPI, found use of field specimen', LOG_DEBUG, 0, '_api');
125 }
126
127 // Sanitize the value using its type declared into ->fields of $object
128 if (!empty($object->fields) && !empty($object->fields[$field]) && !empty($object->fields[$field]['type'])) {
129 if (strpos($object->fields[$field]['type'], 'int') === 0 || strpos($object->fields[$field]['type'], 'double') === 0 || in_array($object->fields[$field]['type'], array('real', 'price', 'stock'))) {
130 return sanitizeVal($value, 'int');
131 }
132 if ($object->fields[$field]['type'] == 'html') {
133 return sanitizeVal($value, 'restricthtml');
134 }
135 if ($object->fields[$field]['type'] == 'select') {
136 // Check values are in the list of possible 'options'
137 return sanitizeVal($value, 'alphanohtml');
138 }
139 if ($object->fields[$field]['type'] == 'sellist' || $object->fields[$field]['type'] == 'checkbox') {
140 return sanitizeVal($value, 'alphanohtml');
141 }
142 if ($object->fields[$field]['type'] == 'boolean' || $object->fields[$field]['type'] == 'radio') {
143 return sanitizeVal($value, 'alphanohtml');
144 }
145 if ($object->fields[$field]['type'] == 'email') {
146 return sanitizeVal($value, 'email');
147 }
148 if ($object->fields[$field]['type'] == 'password') {
149 return sanitizeVal($value, 'password');
150 }
151 // Others will use 'alphanohtml'
152 }
153
154 // In case of a field with unknown type (legacy code), we use other tricks to guess a more accurate type
155
156 // We try to use its name to have a chance to sanitize it
157 if (preg_match('/^fk_/i', $field)) {
158 // We accept only integer
159 return sanitizeVal($value, 'int');
160 }
161 if (in_array($field, array('note', 'note_private', 'note_public', 'desc', 'description'))) {
162 return sanitizeVal($value, 'restricthtml');
163 }
164
165 return sanitizeVal($value, 'alphanohtml');
166 } else { // Example when $field = 'extrafields' and $value = content of $object->array_options
167 $newarrayvalue = array();
168 foreach ($value as $tmpkey => $tmpvalue) {
169 $newarrayvalue[$tmpkey] = $this->_checkValForAPI($tmpkey, $tmpvalue, $object);
170 }
171
172 return $newarrayvalue;
173 }
174 }
175
176 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
185 protected function _checkValExtrafieldsForAPI($field, $value, $object)
186 {
187 // phpcs:enable
188 global $extrafields;
189
190 if (!preg_match('/^[a-zA-Z0-9_]+$/', $field)) {
191 throw new RestException(400, 'Parameter '.$field.' is not allowed in request');
192 }
193
194 if (!is_array($value)) {
195 // Sanitize the value using its type declared into ->fields of $object
196 $typeOfExtraField = '';
197 if (!empty($extrafields->attributes) && !empty($extrafields->attributes[$object->table_element])
198 && !empty($extrafields->attributes[$object->table_element]['type'])
199 && !empty($extrafields->attributes[$object->table_element]['type'][$field])) {
200 $typeOfExtraField = $extrafields->attributes[$object->table_element]['type'][$field];
201 }
202
203 if ($typeOfExtraField) {
204 if (strpos($typeOfExtraField, 'int') === 0 || strpos($typeOfExtraField, 'double') === 0 || in_array($typeOfExtraField, array('real', 'price', 'stock'))) {
205 return sanitizeVal($value, 'int');
206 }
207 if ($typeOfExtraField == 'html') {
208 return sanitizeVal($value, 'restricthtml');
209 }
210 if ($typeOfExtraField == 'select') {
211 // TODO Check values are in the list of possible 'options'
212 return sanitizeVal($value, 'alphanohtml');
213 }
214 if ($typeOfExtraField == 'sellist' || $typeOfExtraField == 'checkbox') {
215 return sanitizeVal($value, 'alphanohtml');
216 }
217 if ($typeOfExtraField == 'boolean' || $typeOfExtraField == 'radio') {
218 return sanitizeVal($value, 'alphanohtml');
219 }
220 if ($typeOfExtraField == 'email') {
221 return sanitizeVal($value, 'email');
222 }
223 if ($typeOfExtraField == 'password') {
224 return sanitizeVal($value, 'password');
225 }
226 // Others will use 'alphanohtml'
227 }
228
229 return sanitizeVal($value, 'alphanohtml');
230 } else { // Example when $field = 'extrafields' and $value = content of $object->array_options
231 $newarrayvalue = array();
232 foreach ($value as $tmpkey => $tmpvalue) {
233 $newarrayvalue[$tmpkey] = $this->_checkValExtrafieldsForAPI($tmpkey, $tmpvalue, $object);
234 }
235
236 return $newarrayvalue;
237 }
238 }
239
240 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
252 protected function _filterObjectProperties($object, $properties)
253 {
254 // phpcs:enable
255 // If properties is empty, we return all properties
256 if (empty($properties)) {
257 return $object;
258 }
259
260 // Copy of exploded array for efficiency
261 $arr_properties = explode(',', $properties);
262 $magic_properties = array();
263 $real_properties = get_object_vars($object);
264
265 // Unsetting real properties may unset magic properties.
266 // We keep a copy of the requested magic properties
267 foreach ($arr_properties as $key) {
268 if (!array_key_exists($key, $real_properties)) {
269 // Not a real property,
270 // check if $key is a magic property (we want to keep '$obj->$key')
271 if (property_exists($object, $key) && isset($object->$key)) {
272 $magic_properties[$key] = $object->$key;
273 }
274 }
275 }
276
277 // Filter real properties (may indirectly unset magic properties)
278 foreach (get_object_vars($object) as $key => $value) {
279 if (!in_array($key, $arr_properties)) {
280 unset($object->$key);
281 }
282 }
283
284 // Restore the magic properties
285 foreach ($magic_properties as $key => $value) {
286 $object->$key = $value;
287 }
288
289 return $object;
290 }
291
292 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
303 protected function _cleanObjectDatas($object)
304 {
305 // phpcs:enable
306 // Remove $db object property for object
307 unset($object->db);
308 unset($object->isextrafieldmanaged);
309 unset($object->ismultientitymanaged);
310 unset($object->restrictiononfksoc);
311 unset($object->table_rowid);
312 unset($object->pass);
313 unset($object->pass_indatabase);
314 unset($object->pass_indatabase_crypted);
315
316 // Remove linkedObjects. We should already have and keep only linkedObjectsIds that avoid huge responses
317 unset($object->linkedObjects);
318 //unset($object->lines[$i]->linked_objects); // This is the array to create linked object during create
319
320 unset($object->fields);
321 unset($object->oldline);
322
323 unset($object->error);
324 unset($object->errors);
325 unset($object->errorhidden);
326 unset($object->warning);
327 unset($object->warnings);
328 unset($object->TRIGGER_PREFIX);
329
330 unset($object->ref_previous);
331 unset($object->ref_next);
332 unset($object->imgWidth);
333 unset($object->imgHeight);
334 unset($object->barcode_type_code);
335 unset($object->barcode_type_label);
336
337 unset($object->mode_reglement); // We use mode_reglement_id now
338 unset($object->cond_reglement); // We use cond_reglement_id now
339 unset($object->note); // We use note_public or note_private now
340 unset($object->contact); // We use contact_id now
341 unset($object->thirdparty); // We use thirdparty_id or fk_soc or socid now
342
343 unset($object->project); // Should be fk_project
344 unset($object->fk_projet); // Should be fk_project
345 unset($object->author); // Should be fk_user_author
346 unset($object->timespent_old_duration);
347 unset($object->timespent_id);
348 unset($object->timespent_duration);
349 unset($object->timespent_date);
350 unset($object->timespent_datehour);
351 unset($object->timespent_withhour);
352 unset($object->timespent_fk_user);
353 unset($object->timespent_note);
354 unset($object->fk_delivery_address);
355 unset($object->fk_multicurrency);
356 //unset($object->model_pdf);
357 unset($object->sendtoid);
358 unset($object->name_bis);
359 unset($object->newref);
360 unset($object->oldref);
361 unset($object->alreadypaid);
362 unset($object->openid);
363 unset($object->fk_bank);
364 unset($object->showphoto_on_popup);
365 unset($object->nb);
366 unset($object->nbphoto);
367 unset($object->output);
368 unset($object->tpl);
369 //unset($object->libelle);
370
371 unset($object->stats_propale);
372 unset($object->stats_commande);
373 unset($object->stats_contrat);
374 unset($object->stats_facture);
375 unset($object->stats_commande_fournisseur);
376 unset($object->stats_reception);
377 unset($object->stats_mrptoconsume);
378 unset($object->stats_mrptoproduce);
379
380 unset($object->fieldsforcombobox);
381 unset($object->regeximgext);
382
383 unset($object->skip_update_total);
384 unset($object->context);
385 unset($object->next_prev_filter);
386
387 unset($object->region);
388 unset($object->region_code);
389 unset($object->country);
390 unset($object->state);
391 unset($object->state_code);
392 unset($object->departement);
393 unset($object->departement_code);
394
395 unset($object->libelle_statut);
396 unset($object->libelle_paiement);
397 unset($object->labelStatus);
398 unset($object->labelStatusShort);
399
400 unset($object->actionmsg);
401 unset($object->actionmsg2);
402
403 unset($object->prefix_comm);
404
405 if (!isset($object->table_element) || ! in_array($object->table_element, array('expensereport_det', 'ticket'))) {
406 unset($object->comments);
407 }
408
409 unset($object->module);
410 unset($object->origin_object);
411 unset($object->origin);
412 unset($object->element);
413 unset($object->element_for_permission);
414 unset($object->fk_element);
415 unset($object->table_element);
416 unset($object->table_element_line);
417 unset($object->class_element_line);
418 unset($object->picto);
419 unset($object->linked_objects);
420
421 // Remove the $oldcopy property because it is not supported by the JSON
422 // encoder. The following error is generated when trying to serialize
423 // it: "Error encoding/decoding JSON: Type is not supported"
424 // Note: Event if this property was correctly handled by the JSON
425 // encoder, it should be ignored because keeping it would let the API
426 // have a very strange behavior: calling PUT and then GET on the same
427 // resource would give different results:
428 // PUT /objects/{id} -> returns object with oldcopy = previous version of the object
429 // GET /objects/{id} -> returns object with oldcopy empty
430 unset($object->oldcopy);
431
432 // If object has lines, remove $db property
433 if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) {
434 $nboflines = count($object->lines);
435 for ($i = 0; $i < $nboflines; $i++) {
436 $this->_cleanObjectDatas($object->lines[$i]);
437
438 unset($object->lines[$i]->contact);
439 unset($object->lines[$i]->contact_id);
440 unset($object->lines[$i]->country);
441 unset($object->lines[$i]->country_id);
442 unset($object->lines[$i]->country_code);
443 unset($object->lines[$i]->deposit_percent);
444 unset($object->lines[$i]->mode_reglement_id);
445 unset($object->lines[$i]->mode_reglement_code);
446 unset($object->lines[$i]->mode_reglement);
447 unset($object->lines[$i]->cond_reglement_id);
448 unset($object->lines[$i]->cond_reglement_supplier_id);
449 unset($object->lines[$i]->cond_reglement_code);
450 unset($object->lines[$i]->cond_reglement);
451 unset($object->lines[$i]->fk_delivery_address);
452 unset($object->lines[$i]->fk_projet);
453 unset($object->lines[$i]->fk_project);
454
455 unset($object->lines[$i]->thirdparty);
456 unset($object->lines[$i]->user);
457 unset($object->lines[$i]->product);
458
459 unset($object->lines[$i]->model_pdf);
460 unset($object->lines[$i]->note_public);
461 unset($object->lines[$i]->note_private);
462 unset($object->lines[$i]->fk_incoterms);
463 unset($object->lines[$i]->label_incoterms);
464 unset($object->lines[$i]->location_incoterms);
465 unset($object->lines[$i]->name);
466 unset($object->lines[$i]->lastname);
467 unset($object->lines[$i]->firstname);
468 unset($object->lines[$i]->civility_id);
469 unset($object->lines[$i]->fk_multicurrency);
470 unset($object->lines[$i]->multicurrency_code);
471 unset($object->lines[$i]->shipping_method_id);
472 }
473 }
474
475 if (!empty($object->thirdparty) && is_object($object->thirdparty)) {
476 $this->_cleanObjectDatas($object->thirdparty);
477 }
478
479 if (!empty($object->product) && is_object($object->product)) {
480 $this->_cleanObjectDatas($object->product);
481 }
482
483 return $object;
484 }
485
486 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
499 protected static function _checkAccessToResource($resource, $resource_id = 0, $dbtablename = '', $feature2 = '', $dbt_keyfield = 'fk_soc', $dbt_select = 'rowid', $parenttableforentity = '')
500 {
501 // phpcs:enable
502 // Features/modules to check
503 $featuresarray = array($resource);
504 if (preg_match('/&/', $resource)) {
505 $featuresarray = explode("&", $resource);
506 } elseif (preg_match('/\|/', $resource)) {
507 $featuresarray = explode("|", $resource);
508 }
509
510 // More subfeatures to check
511 if (!empty($feature2)) {
512 $feature2 = explode("|", $feature2);
513 }
514
515 return checkUserAccessToObject(DolibarrApiAccess::$user, $featuresarray, $resource_id, $dbtablename, $feature2, $dbt_keyfield, $dbt_select, $parenttableforentity);
516 }
517
518 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
527 protected function _checkFilters($sqlfilters, &$error = '')
528 {
529 // phpcs:enable
530 $firstandlastparenthesis = 0;
531 return dolCheckFilters($sqlfilters, $error, $firstandlastparenthesis);
532 }
533
534 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
535 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
545 protected static function _forge_criteria_callback($matches)
546 {
547 return dolForgeSQLCriteriaCallback($matches);
548 }
549}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
global $dolibarr_main_url_root
Class for API REST v1.
Definition api.class.php:35
__construct($db, $cachedir='', $refreshCache=false)
Constructor.
Definition api.class.php:53
_checkValExtrafieldsForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
_checkFilters($sqlfilters, &$error='')
Return if a $sqlfilters parameter is valid Function no more used.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
_cleanObjectDatas($object)
Clean sensitive object data @phpstan-template T.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $parenttableforentity='')
Check access by user to a given resource.
static _forge_criteria_callback($matches)
Function to forge a SQL criteria from a Generic filter string.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
dol_is_dir($folder)
Test if filename is a directory.
dolCheckFilters($sqlfilters, &$error='', &$parenthesislevel=0)
Return if a $sqlfilters parameter has a valid balance of parenthesis.
dolForgeSQLCriteriaCallback($matches)
Function to forge a SQL criteria from a USF (Universal Filter Syntax) string.
getDolGlobalBool($key, $default=false)
Return a Dolibarr global constant boolean value.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
checkUserAccessToObject($user, array $featuresarray, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='', $dbt_select='rowid', $parenttableforentity='')
Check that access by a given user to an object is ok.