dolibarr 22.0.5
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 {
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 if (in_array($field, array('note', 'note_private', 'note_public', 'desc', 'description'))) {
130 return sanitizeVal($value, 'restricthtml');
131 } else {
132 return sanitizeVal($value, 'alphanohtml');
133 }
134 } else { // Example when $field = 'extrafields' and $value = content of $object->array_options
135 $newarrayvalue = array();
136 foreach ($value as $tmpkey => $tmpvalue) {
137 $newarrayvalue[$tmpkey] = $this->_checkValForAPI($tmpkey, $tmpvalue, $object);
138 }
139
140 return $newarrayvalue;
141 }
142 }
143
144 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
156 protected function _filterObjectProperties($object, $properties)
157 {
158 // phpcs:enable
159 // If properties is empty, we return all properties
160 if (empty($properties)) {
161 return $object;
162 }
163
164 // Copy of exploded array for efficiency
165 $arr_properties = explode(',', $properties);
166 $magic_properties = array();
167 $real_properties = get_object_vars($object);
168
169 // Unsetting real properties may unset magic properties.
170 // We keep a copy of the requested magic properties
171 foreach ($arr_properties as $key) {
172 if (!array_key_exists($key, $real_properties)) {
173 // Not a real property,
174 // check if $key is a magic property (we want to keep '$obj->$key')
175 if (property_exists($object, $key) && isset($object->$key)) {
176 $magic_properties[$key] = $object->$key;
177 }
178 }
179 }
180
181 // Filter real properties (may indirectly unset magic properties)
182 foreach (get_object_vars($object) as $key => $value) {
183 if (!in_array($key, $arr_properties)) {
184 unset($object->$key);
185 }
186 }
187
188 // Restore the magic properties
189 foreach ($magic_properties as $key => $value) {
190 $object->$key = $value;
191 }
192
193 return $object;
194 }
195
196 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
207 protected function _cleanObjectDatas($object)
208 {
209 // phpcs:enable
210 // Remove $db object property for object
211 unset($object->db);
212 unset($object->isextrafieldmanaged);
213 unset($object->ismultientitymanaged);
214 unset($object->restrictiononfksoc);
215 unset($object->table_rowid);
216 unset($object->pass);
217 unset($object->pass_indatabase);
218
219 // Remove linkedObjects. We should already have and keep only linkedObjectsIds that avoid huge responses
220 unset($object->linkedObjects);
221 //unset($object->lines[$i]->linked_objects); // This is the array to create linked object during create
222
223 unset($object->fields);
224 unset($object->oldline);
225
226 unset($object->error);
227 unset($object->errors);
228 unset($object->errorhidden);
229
230 unset($object->ref_previous);
231 unset($object->ref_next);
232 unset($object->imgWidth);
233 unset($object->imgHeight);
234 unset($object->barcode_type_code);
235 unset($object->barcode_type_label);
236
237 unset($object->mode_reglement); // We use mode_reglement_id now
238 unset($object->cond_reglement); // We use cond_reglement_id now
239 unset($object->note); // We use note_public or note_private now
240 unset($object->contact); // We use contact_id now
241 unset($object->thirdparty); // We use thirdparty_id or fk_soc or socid now
242
243 unset($object->projet); // Should be fk_project
244 unset($object->project); // Should be fk_project
245 unset($object->fk_projet); // Should be fk_project
246 unset($object->author); // Should be fk_user_author
247 unset($object->timespent_old_duration);
248 unset($object->timespent_id);
249 unset($object->timespent_duration);
250 unset($object->timespent_date);
251 unset($object->timespent_datehour);
252 unset($object->timespent_withhour);
253 unset($object->timespent_fk_user);
254 unset($object->timespent_note);
255 unset($object->fk_delivery_address);
256 unset($object->model_pdf);
257 unset($object->sendtoid);
258 unset($object->name_bis);
259 unset($object->newref);
260 unset($object->oldref);
261 unset($object->alreadypaid);
262 unset($object->openid);
263 unset($object->fk_bank);
264 unset($object->showphoto_on_popup);
265 unset($object->nb);
266 unset($object->nbphoto);
267 unset($object->output);
268 unset($object->tpl);
269 //unset($object->libelle);
270
271 unset($object->stats_propale);
272 unset($object->stats_commande);
273 unset($object->stats_contrat);
274 unset($object->stats_facture);
275 unset($object->stats_commande_fournisseur);
276 unset($object->stats_reception);
277 unset($object->stats_mrptoconsume);
278 unset($object->stats_mrptoproduce);
279
280 unset($object->fieldsforcombobox);
281 unset($object->regeximgext);
282
283 unset($object->skip_update_total);
284 unset($object->context);
285 unset($object->next_prev_filter);
286
287 unset($object->region);
288 unset($object->region_code);
289 unset($object->country);
290 unset($object->state);
291 unset($object->state_code);
292 unset($object->departement);
293 unset($object->departement_code);
294
295 unset($object->libelle_statut);
296 unset($object->libelle_paiement);
297 unset($object->labelStatus);
298 unset($object->labelStatusShort);
299
300 unset($object->actionmsg);
301 unset($object->actionmsg2);
302
303 unset($object->prefix_comm);
304
305 if (!isset($object->table_element) || ! in_array($object->table_element, array('expensereport_det', 'ticket'))) {
306 unset($object->comments);
307 }
308
309 unset($object->origin_object);
310 unset($object->origin);
311 unset($object->element);
312 unset($object->element_for_permission);
313 unset($object->fk_element);
314 unset($object->table_element);
315 unset($object->table_element_line);
316 unset($object->class_element_line);
317 unset($object->picto);
318 unset($object->linked_objects);
319
320 // Remove the $oldcopy property because it is not supported by the JSON
321 // encoder. The following error is generated when trying to serialize
322 // it: "Error encoding/decoding JSON: Type is not supported"
323 // Note: Event if this property was correctly handled by the JSON
324 // encoder, it should be ignored because keeping it would let the API
325 // have a very strange behavior: calling PUT and then GET on the same
326 // resource would give different results:
327 // PUT /objects/{id} -> returns object with oldcopy = previous version of the object
328 // GET /objects/{id} -> returns object with oldcopy empty
329 unset($object->oldcopy);
330
331 // If object has lines, remove $db property
332 if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) {
333 $nboflines = count($object->lines);
334 for ($i = 0; $i < $nboflines; $i++) {
335 $this->_cleanObjectDatas($object->lines[$i]);
336
337 unset($object->lines[$i]->contact);
338 unset($object->lines[$i]->contact_id);
339 unset($object->lines[$i]->country);
340 unset($object->lines[$i]->country_id);
341 unset($object->lines[$i]->country_code);
342 unset($object->lines[$i]->mode_reglement_id);
343 unset($object->lines[$i]->mode_reglement_code);
344 unset($object->lines[$i]->mode_reglement);
345 unset($object->lines[$i]->cond_reglement_id);
346 unset($object->lines[$i]->cond_reglement_code);
347 unset($object->lines[$i]->cond_reglement);
348 unset($object->lines[$i]->fk_delivery_address);
349 unset($object->lines[$i]->fk_projet);
350 unset($object->lines[$i]->fk_project);
351 unset($object->lines[$i]->thirdparty);
352 unset($object->lines[$i]->user);
353 unset($object->lines[$i]->model_pdf);
354 unset($object->lines[$i]->note_public);
355 unset($object->lines[$i]->note_private);
356 unset($object->lines[$i]->fk_incoterms);
357 unset($object->lines[$i]->label_incoterms);
358 unset($object->lines[$i]->location_incoterms);
359 unset($object->lines[$i]->name);
360 unset($object->lines[$i]->lastname);
361 unset($object->lines[$i]->firstname);
362 unset($object->lines[$i]->civility_id);
363 unset($object->lines[$i]->fk_multicurrency);
364 unset($object->lines[$i]->multicurrency_code);
365 unset($object->lines[$i]->shipping_method_id);
366 }
367 }
368
369 if (!empty($object->thirdparty) && is_object($object->thirdparty)) {
370 $this->_cleanObjectDatas($object->thirdparty);
371 }
372
373 if (!empty($object->product) && is_object($object->product)) {
374 $this->_cleanObjectDatas($object->product);
375 }
376
377 return $object;
378 }
379
380 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
392 protected static function _checkAccessToResource($resource, $resource_id = 0, $dbtablename = '', $feature2 = '', $dbt_keyfield = 'fk_soc', $dbt_select = 'rowid')
393 {
394 // phpcs:enable
395 // Features/modules to check
396 $featuresarray = array($resource);
397 if (preg_match('/&/', $resource)) {
398 $featuresarray = explode("&", $resource);
399 } elseif (preg_match('/\|/', $resource)) {
400 $featuresarray = explode("|", $resource);
401 }
402
403 // More subfeatures to check
404 if (!empty($feature2)) {
405 $feature2 = explode("|", $feature2);
406 }
407
408 return checkUserAccessToObject(DolibarrApiAccess::$user, $featuresarray, $resource_id, $dbtablename, $feature2, $dbt_keyfield, $dbt_select);
409 }
410
411 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
420 protected function _checkFilters($sqlfilters, &$error = '')
421 {
422 // phpcs:enable
423 $firstandlastparenthesis = 0;
424 return dolCheckFilters($sqlfilters, $error, $firstandlastparenthesis);
425 }
426
427 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
428 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
438 protected static function _forge_criteria_callback($matches)
439 {
440 return dolForgeSQLCriteriaCallback($matches);
441 }
442}
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:67
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 of Object.
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)
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
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.