dolibarr 23.0.3
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 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;
26
27require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
28
33{
37 protected $db;
38
42 public $r;
43
51 public function __construct($db, $cachedir = '', $refreshCache = false)
52 {
53 global $conf, $dolibarr_main_url_root;
54
55 if (empty($cachedir)) {
56 $cachedir = $conf->api->dir_temp;
57 }
58 Defaults::$cacheDirectory = $cachedir;
59
60 $this->db = $db;
61
62 $production_mode = getDolGlobalBool('API_PRODUCTION_MODE');
63
64 if ($production_mode) {
65 // Create the directory Defaults::$cacheDirectory if it does not exist. If dir does not exist, using production_mode generates an error 500.
66 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
67 if (!dol_is_dir(Defaults::$cacheDirectory)) {
68 dol_mkdir(Defaults::$cacheDirectory, DOL_DATA_ROOT);
69 }
70 if (getDolGlobalString('MAIN_API_DEBUG')) {
71 dol_syslog("Debug API construct::cacheDirectory=".Defaults::$cacheDirectory, LOG_DEBUG, 0, '_api');
72 }
73 }
74
75 $this->r = new Restler($production_mode, $refreshCache);
76
77 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
78 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
79
80 $urlwithouturlrootautodetect = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim(DOL_MAIN_URL_ROOT));
81 $urlwithrootautodetect = $urlwithouturlroot.DOL_URL_ROOT; // This is to use local domain autodetected by dolibarr from url
82
83 $this->r->setBaseUrls($urlwithouturlroot, $urlwithouturlrootautodetect);
84 $this->r->setAPIVersion(1);
85 //$this->r->setSupportedFormats('json');
86 //$this->r->setSupportedFormats('jsonFormat');
87 }
88
89 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
98 protected function _checkValForAPI($field, $value, $object)
99 {
100 // phpcs:enable
101 if (!is_array($value)) {
102 // Sanitize the value using its type declared into ->fields of $object
103 if (!empty($object->fields) && !empty($object->fields[$field]) && !empty($object->fields[$field]['type'])) {
104 if (strpos($object->fields[$field]['type'], 'int') || strpos($object->fields[$field]['type'], 'double') || in_array($object->fields[$field]['type'], array('real', 'price', 'stock'))) {
105 return sanitizeVal($value, 'int');
106 }
107 if ($object->fields[$field]['type'] == 'html') {
108 return sanitizeVal($value, 'restricthtml');
109 }
110 if ($object->fields[$field]['type'] == 'select') {
111 // Check values are in the list of possible 'options'
112 // TODO
113 }
114 if ($object->fields[$field]['type'] == 'sellist' || $object->fields[$field]['type'] == 'checkbox') {
115 // TODO
116 }
117 if ($object->fields[$field]['type'] == 'boolean' || $object->fields[$field]['type'] == 'radio') {
118 // TODO
119 }
120 if ($object->fields[$field]['type'] == 'email') {
121 return sanitizeVal($value, 'email');
122 }
123 if ($object->fields[$field]['type'] == 'password') {
124 return sanitizeVal($value, 'none');
125 }
126 // Others will use 'alphanohtml'
127 }
128
129 // In case of a field with unknown type (legacy code), we use its name to have a chance to sanitize it
130 if (preg_match('/^fk_/i', $field)) {
131 // We accept only integer
132 return sanitizeVal($value, 'int');
133 }
134
135 if (in_array($field, array('note', 'note_private', 'note_public', 'desc', 'description'))) {
136 return sanitizeVal($value, 'restricthtml');
137 } else {
138 return sanitizeVal($value, 'alphanohtml');
139 }
140 } else { // Example when $field = 'extrafields' and $value = content of $object->array_options
141 $newarrayvalue = array();
142 foreach ($value as $tmpkey => $tmpvalue) {
143 $newarrayvalue[$tmpkey] = $this->_checkValForAPI($tmpkey, $tmpvalue, $object);
144 }
145
146 return $newarrayvalue;
147 }
148 }
149
150 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
162 protected function _filterObjectProperties($object, $properties)
163 {
164 // phpcs:enable
165 // If properties is empty, we return all properties
166 if (empty($properties)) {
167 return $object;
168 }
169
170 // Copy of exploded array for efficiency
171 $arr_properties = explode(',', $properties);
172 $magic_properties = array();
173 $real_properties = get_object_vars($object);
174
175 // Unsetting real properties may unset magic properties.
176 // We keep a copy of the requested magic properties
177 foreach ($arr_properties as $key) {
178 if (!array_key_exists($key, $real_properties)) {
179 // Not a real property,
180 // check if $key is a magic property (we want to keep '$obj->$key')
181 if (property_exists($object, $key) && isset($object->$key)) {
182 $magic_properties[$key] = $object->$key;
183 }
184 }
185 }
186
187 // Filter real properties (may indirectly unset magic properties)
188 foreach (get_object_vars($object) as $key => $value) {
189 if (!in_array($key, $arr_properties)) {
190 unset($object->$key);
191 }
192 }
193
194 // Restore the magic properties
195 foreach ($magic_properties as $key => $value) {
196 $object->$key = $value;
197 }
198
199 return $object;
200 }
201
202 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
213 protected function _cleanObjectDatas($object)
214 {
215 // phpcs:enable
216 // Remove $db object property for object
217 unset($object->db);
218 unset($object->isextrafieldmanaged);
219 unset($object->ismultientitymanaged);
220 unset($object->restrictiononfksoc);
221 unset($object->table_rowid);
222 unset($object->pass);
223 unset($object->pass_indatabase);
224
225 // Remove linkedObjects. We should already have and keep only linkedObjectsIds that avoid huge responses
226 unset($object->linkedObjects);
227 //unset($object->lines[$i]->linked_objects); // This is the array to create linked object during create
228
229 unset($object->fields);
230 unset($object->oldline);
231
232 unset($object->error);
233 unset($object->errors);
234 unset($object->errorhidden);
235 unset($object->warnings);
236 unset($object->TRIGGER_PREFIX);
237
238 unset($object->ref_previous);
239 unset($object->ref_next);
240 unset($object->imgWidth);
241 unset($object->imgHeight);
242 unset($object->barcode_type_code);
243 unset($object->barcode_type_label);
244
245 unset($object->mode_reglement); // We use mode_reglement_id now
246 unset($object->cond_reglement); // We use cond_reglement_id now
247 unset($object->note); // We use note_public or note_private now
248 unset($object->contact); // We use contact_id now
249 unset($object->thirdparty); // We use thirdparty_id or fk_soc or socid now
250
251 unset($object->project); // Should be fk_project
252 unset($object->fk_projet); // Should be fk_project
253 unset($object->author); // Should be fk_user_author
254 unset($object->timespent_old_duration);
255 unset($object->timespent_id);
256 unset($object->timespent_duration);
257 unset($object->timespent_date);
258 unset($object->timespent_datehour);
259 unset($object->timespent_withhour);
260 unset($object->timespent_fk_user);
261 unset($object->timespent_note);
262 unset($object->fk_delivery_address);
263 //unset($object->model_pdf);
264 unset($object->sendtoid);
265 unset($object->name_bis);
266 unset($object->newref);
267 unset($object->oldref);
268 unset($object->alreadypaid);
269 unset($object->openid);
270 unset($object->fk_bank);
271 unset($object->showphoto_on_popup);
272 unset($object->nb);
273 unset($object->nbphoto);
274 unset($object->output);
275 unset($object->tpl);
276 //unset($object->libelle);
277
278 unset($object->stats_propale);
279 unset($object->stats_commande);
280 unset($object->stats_contrat);
281 unset($object->stats_facture);
282 unset($object->stats_commande_fournisseur);
283 unset($object->stats_reception);
284 unset($object->stats_mrptoconsume);
285 unset($object->stats_mrptoproduce);
286
287 unset($object->fieldsforcombobox);
288 unset($object->regeximgext);
289
290 unset($object->skip_update_total);
291 unset($object->context);
292 unset($object->next_prev_filter);
293
294 unset($object->region);
295 unset($object->region_code);
296 unset($object->country);
297 unset($object->state);
298 unset($object->state_code);
299 unset($object->departement);
300 unset($object->departement_code);
301
302 unset($object->libelle_statut);
303 unset($object->libelle_paiement);
304 unset($object->labelStatus);
305 unset($object->labelStatusShort);
306
307 unset($object->actionmsg);
308 unset($object->actionmsg2);
309
310 unset($object->prefix_comm);
311
312 if (!isset($object->table_element) || ! in_array($object->table_element, array('expensereport_det', 'ticket'))) {
313 unset($object->comments);
314 }
315
316 unset($object->origin_object);
317 unset($object->origin);
318 unset($object->element);
319 unset($object->element_for_permission);
320 unset($object->fk_element);
321 unset($object->table_element);
322 unset($object->table_element_line);
323 unset($object->class_element_line);
324 unset($object->picto);
325 unset($object->linked_objects);
326
327 // Remove the $oldcopy property because it is not supported by the JSON
328 // encoder. The following error is generated when trying to serialize
329 // it: "Error encoding/decoding JSON: Type is not supported"
330 // Note: Event if this property was correctly handled by the JSON
331 // encoder, it should be ignored because keeping it would let the API
332 // have a very strange behavior: calling PUT and then GET on the same
333 // resource would give different results:
334 // PUT /objects/{id} -> returns object with oldcopy = previous version of the object
335 // GET /objects/{id} -> returns object with oldcopy empty
336 unset($object->oldcopy);
337
338 // If object has lines, remove $db property
339 if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) {
340 $nboflines = count($object->lines);
341 for ($i = 0; $i < $nboflines; $i++) {
342 $this->_cleanObjectDatas($object->lines[$i]);
343
344 unset($object->lines[$i]->contact);
345 unset($object->lines[$i]->contact_id);
346 unset($object->lines[$i]->country);
347 unset($object->lines[$i]->country_id);
348 unset($object->lines[$i]->country_code);
349 unset($object->lines[$i]->mode_reglement_id);
350 unset($object->lines[$i]->mode_reglement_code);
351 unset($object->lines[$i]->mode_reglement);
352 unset($object->lines[$i]->cond_reglement_id);
353 unset($object->lines[$i]->cond_reglement_code);
354 unset($object->lines[$i]->cond_reglement);
355 unset($object->lines[$i]->fk_delivery_address);
356 unset($object->lines[$i]->fk_projet);
357 unset($object->lines[$i]->fk_project);
358 unset($object->lines[$i]->thirdparty);
359 unset($object->lines[$i]->user);
360 unset($object->lines[$i]->model_pdf);
361 unset($object->lines[$i]->note_public);
362 unset($object->lines[$i]->note_private);
363 unset($object->lines[$i]->fk_incoterms);
364 unset($object->lines[$i]->label_incoterms);
365 unset($object->lines[$i]->location_incoterms);
366 unset($object->lines[$i]->name);
367 unset($object->lines[$i]->lastname);
368 unset($object->lines[$i]->firstname);
369 unset($object->lines[$i]->civility_id);
370 unset($object->lines[$i]->fk_multicurrency);
371 unset($object->lines[$i]->multicurrency_code);
372 unset($object->lines[$i]->shipping_method_id);
373 }
374 }
375
376 if (!empty($object->thirdparty) && is_object($object->thirdparty)) {
377 $this->_cleanObjectDatas($object->thirdparty);
378 }
379
380 if (!empty($object->product) && is_object($object->product)) {
381 $this->_cleanObjectDatas($object->product);
382 }
383
384 return $object;
385 }
386
387 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
399 protected static function _checkAccessToResource($resource, $resource_id = 0, $dbtablename = '', $feature2 = '', $dbt_keyfield = 'fk_soc', $dbt_select = 'rowid')
400 {
401 // phpcs:enable
402 // Features/modules to check
403 $featuresarray = array($resource);
404 if (preg_match('/&/', $resource)) {
405 $featuresarray = explode("&", $resource);
406 } elseif (preg_match('/\|/', $resource)) {
407 $featuresarray = explode("|", $resource);
408 }
409
410 // More subfeatures to check
411 if (!empty($feature2)) {
412 $feature2 = explode("|", $feature2);
413 }
414
415 return checkUserAccessToObject(DolibarrApiAccess::$user, $featuresarray, $resource_id, $dbtablename, $feature2, $dbt_keyfield, $dbt_select);
416 }
417
418 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
427 protected function _checkFilters($sqlfilters, &$error = '')
428 {
429 // phpcs:enable
430 $firstandlastparenthesis = 0;
431 return dolCheckFilters($sqlfilters, $error, $firstandlastparenthesis);
432 }
433
434 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
435 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
445 protected static function _forge_criteria_callback($matches)
446 {
447 return dolForgeSQLCriteriaCallback($matches);
448 }
449}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
global $dolibarr_main_url_root
Class for API REST v1.
Definition api.class.php:33
__construct($db, $cachedir='', $refreshCache=false)
Constructor.
Definition api.class.php:51
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid')
Check access by user to a given resource.
_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.
Definition api.class.php:98
_cleanObjectDatas($object)
Clean sensitive object data @phpstan-template T.
static _forge_criteria_callback($matches)
Function to forge a SQL criteria from a Generic filter string.
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.