dolibarr 21.0.4
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) 2020 Frédéric France <frederic.france@netlogic.fr>
5 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
6 * Copyright (C) 2025 William Mead <william@m34d.com>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
22use Luracast\Restler\Restler;
23use Luracast\Restler\Defaults;
24
25require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
26
31{
35 protected $db;
36
40 public $r;
41
49 public function __construct($db, $cachedir = '', $refreshCache = false)
50 {
51 global $conf, $dolibarr_main_url_root;
52
53 if (empty($cachedir)) {
54 $cachedir = $conf->api->dir_temp;
55 }
56 Defaults::$cacheDirectory = $cachedir;
57
58 $this->db = $db;
59
60 $production_mode = getDolGlobalBool('API_PRODUCTION_MODE');
61
62 if ($production_mode) {
63 // Create the directory Defaults::$cacheDirectory if it does not exist. If dir does not exist, using production_mode generates an error 500.
64 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
65 if (!dol_is_dir(Defaults::$cacheDirectory)) {
66 dol_mkdir(Defaults::$cacheDirectory, DOL_DATA_ROOT);
67 }
68 if (getDolGlobalString('MAIN_API_DEBUG')) {
69 dol_syslog("Debug API construct::cacheDirectory=".Defaults::$cacheDirectory, LOG_DEBUG, 0, '_api');
70 }
71 }
72
73 $this->r = new Restler($production_mode, $refreshCache);
74
75 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
76 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
77
78 $urlwithouturlrootautodetect = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim(DOL_MAIN_URL_ROOT));
79 $urlwithrootautodetect = $urlwithouturlroot.DOL_URL_ROOT; // This is to use local domain autodetected by dolibarr from url
80
81 $this->r->setBaseUrls($urlwithouturlroot, $urlwithouturlrootautodetect);
82 $this->r->setAPIVersion(1);
83 //$this->r->setSupportedFormats('json');
84 //$this->r->setSupportedFormats('jsonFormat');
85 }
86
87 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
96 protected function _checkValForAPI($field, $value, $object)
97 {
98 // phpcs:enable
99 if (!is_array($value)) {
100 // Sanitize the value using its type declared into ->fields of $object
101 if (!empty($object->fields) && !empty($object->fields[$field]) && !empty($object->fields[$field]['type'])) {
102 if (strpos($object->fields[$field]['type'], 'int') || strpos($object->fields[$field]['type'], 'double') || in_array($object->fields[$field]['type'], array('real', 'price', 'stock'))) {
103 return sanitizeVal($value, 'int');
104 }
105 if ($object->fields[$field]['type'] == 'html') {
106 return sanitizeVal($value, 'restricthtml');
107 }
108 if ($object->fields[$field]['type'] == 'select') {
109 // Check values are in the list of possible 'options'
110 // TODO
111 }
112 if ($object->fields[$field]['type'] == 'sellist' || $object->fields[$field]['type'] == 'checkbox') {
113 // TODO
114 }
115 if ($object->fields[$field]['type'] == 'boolean' || $object->fields[$field]['type'] == 'radio') {
116 // TODO
117 }
118 if ($object->fields[$field]['type'] == 'email') {
119 return sanitizeVal($value, 'email');
120 }
121 if ($object->fields[$field]['type'] == 'password') {
122 return sanitizeVal($value, 'none');
123 }
124 // Others will use 'alphanohtml'
125 }
126
127 if (in_array($field, array('note', 'note_private', 'note_public', 'desc', 'description'))) {
128 return sanitizeVal($value, 'restricthtml');
129 } else {
130 return sanitizeVal($value, 'alphanohtml');
131 }
132 } else { // Example when $field = 'extrafields' and $value = content of $object->array_options
133 $newarrayvalue = array();
134 foreach ($value as $tmpkey => $tmpvalue) {
135 $newarrayvalue[$tmpkey] = $this->_checkValForAPI($tmpkey, $tmpvalue, $object);
136 }
137
138 return $newarrayvalue;
139 }
140 }
141
142 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
150 protected function _filterObjectProperties($object, $properties)
151 {
152 // phpcs:enable
153 // If properties is empty, we return all properties
154 if (empty($properties)) {
155 return $object;
156 }
157
158 // Copy of exploded array for efficiency
159 $arr_properties = explode(',', $properties);
160 $magic_properties = array();
161 $real_properties = get_object_vars($object);
162
163 // Unsetting real properties may unset magic properties.
164 // We keep a copy of the requested magic properties
165 foreach ($arr_properties as $key) {
166 if (!array_key_exists($key, $real_properties)) {
167 // Not a real property,
168 // check if $key is a magic property (we want to keep '$obj->$key')
169 if (property_exists($object, $key) && isset($object->$key)) {
170 $magic_properties[$key] = $object->$key;
171 }
172 }
173 }
174
175 // Filter real properties (may indirectly unset magic properties)
176 foreach (get_object_vars($object) as $key => $value) {
177 if (!in_array($key, $arr_properties)) {
178 unset($object->$key);
179 }
180 }
181
182 // Restore the magic properties
183 foreach ($magic_properties as $key => $value) {
184 $object->$key = $value;
185 }
186
187 return $object;
188 }
189
190 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
201 protected function _cleanObjectDatas($object)
202 {
203 // phpcs:enable
204 // Remove $db object property for object
205 unset($object->db);
206 unset($object->isextrafieldmanaged);
207 unset($object->ismultientitymanaged);
208 unset($object->restrictiononfksoc);
209 unset($object->table_rowid);
210 unset($object->pass);
211 unset($object->pass_indatabase);
212
213 // Remove linkedObjects. We should already have and keep only linkedObjectsIds that avoid huge responses
214 unset($object->linkedObjects);
215 //unset($object->lines[$i]->linked_objects); // This is the array to create linked object during create
216
217 unset($object->fields);
218 unset($object->oldline);
219
220 unset($object->error);
221 unset($object->errors);
222 unset($object->errorhidden);
223
224 unset($object->ref_previous);
225 unset($object->ref_next);
226 unset($object->imgWidth);
227 unset($object->imgHeight);
228 unset($object->barcode_type_code);
229 unset($object->barcode_type_label);
230
231 unset($object->mode_reglement); // We use mode_reglement_id now
232 unset($object->cond_reglement); // We use cond_reglement_id now
233 unset($object->note); // We use note_public or note_private now
234 unset($object->contact); // We use contact_id now
235 unset($object->thirdparty); // We use thirdparty_id or fk_soc or socid now
236
237 unset($object->projet); // Should be fk_project
238 unset($object->project); // Should be fk_project
239 unset($object->fk_projet); // Should be fk_project
240 unset($object->author); // Should be fk_user_author
241 unset($object->timespent_old_duration);
242 unset($object->timespent_id);
243 unset($object->timespent_duration);
244 unset($object->timespent_date);
245 unset($object->timespent_datehour);
246 unset($object->timespent_withhour);
247 unset($object->timespent_fk_user);
248 unset($object->timespent_note);
249 unset($object->fk_delivery_address);
250 unset($object->model_pdf);
251 unset($object->sendtoid);
252 unset($object->name_bis);
253 unset($object->newref);
254 unset($object->oldref);
255 unset($object->alreadypaid);
256 unset($object->openid);
257 unset($object->fk_bank);
258 unset($object->showphoto_on_popup);
259 unset($object->nb);
260 unset($object->nbphoto);
261 unset($object->output);
262 unset($object->tpl);
263 //unset($object->libelle);
264
265 unset($object->stats_propale);
266 unset($object->stats_commande);
267 unset($object->stats_contrat);
268 unset($object->stats_facture);
269 unset($object->stats_commande_fournisseur);
270 unset($object->stats_reception);
271 unset($object->stats_mrptoconsume);
272 unset($object->stats_mrptoproduce);
273
274 unset($object->fieldsforcombobox);
275 unset($object->regeximgext);
276
277 unset($object->skip_update_total);
278 unset($object->context);
279 unset($object->next_prev_filter);
280
281 unset($object->region);
282 unset($object->region_code);
283 unset($object->country);
284 unset($object->state);
285 unset($object->state_code);
286 unset($object->fk_departement);
287 unset($object->departement);
288 unset($object->departement_code);
289
290 unset($object->libelle_statut);
291 unset($object->libelle_paiement);
292 unset($object->labelStatus);
293 unset($object->labelStatusShort);
294
295 unset($object->actionmsg);
296 unset($object->actionmsg2);
297
298 unset($object->prefix_comm);
299
300 if (!isset($object->table_element) || ! in_array($object->table_element, array('expensereport_det', 'ticket'))) {
301 unset($object->comments);
302 }
303
304 unset($object->origin_object);
305 unset($object->origin);
306 unset($object->element);
307 unset($object->element_for_permission);
308 unset($object->fk_element);
309 unset($object->table_element);
310 unset($object->table_element_line);
311 unset($object->class_element_line);
312 unset($object->picto);
313 unset($object->linked_objects);
314
315 // Remove the $oldcopy property because it is not supported by the JSON
316 // encoder. The following error is generated when trying to serialize
317 // it: "Error encoding/decoding JSON: Type is not supported"
318 // Note: Event if this property was correctly handled by the JSON
319 // encoder, it should be ignored because keeping it would let the API
320 // have a very strange behavior: calling PUT and then GET on the same
321 // resource would give different results:
322 // PUT /objects/{id} -> returns object with oldcopy = previous version of the object
323 // GET /objects/{id} -> returns object with oldcopy empty
324 unset($object->oldcopy);
325
326 // If object has lines, remove $db property
327 if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) {
328 $nboflines = count($object->lines);
329 for ($i = 0; $i < $nboflines; $i++) {
330 $this->_cleanObjectDatas($object->lines[$i]);
331
332 unset($object->lines[$i]->contact);
333 unset($object->lines[$i]->contact_id);
334 unset($object->lines[$i]->country);
335 unset($object->lines[$i]->country_id);
336 unset($object->lines[$i]->country_code);
337 unset($object->lines[$i]->mode_reglement_id);
338 unset($object->lines[$i]->mode_reglement_code);
339 unset($object->lines[$i]->mode_reglement);
340 unset($object->lines[$i]->cond_reglement_id);
341 unset($object->lines[$i]->cond_reglement_code);
342 unset($object->lines[$i]->cond_reglement);
343 unset($object->lines[$i]->fk_delivery_address);
344 unset($object->lines[$i]->fk_projet);
345 unset($object->lines[$i]->fk_project);
346 unset($object->lines[$i]->thirdparty);
347 unset($object->lines[$i]->user);
348 unset($object->lines[$i]->model_pdf);
349 unset($object->lines[$i]->note_public);
350 unset($object->lines[$i]->note_private);
351 unset($object->lines[$i]->fk_incoterms);
352 unset($object->lines[$i]->label_incoterms);
353 unset($object->lines[$i]->location_incoterms);
354 unset($object->lines[$i]->name);
355 unset($object->lines[$i]->lastname);
356 unset($object->lines[$i]->firstname);
357 unset($object->lines[$i]->civility_id);
358 unset($object->lines[$i]->fk_multicurrency);
359 unset($object->lines[$i]->multicurrency_code);
360 unset($object->lines[$i]->shipping_method_id);
361 }
362 }
363
364 if (!empty($object->thirdparty) && is_object($object->thirdparty)) {
365 $this->_cleanObjectDatas($object->thirdparty);
366 }
367
368 if (!empty($object->product) && is_object($object->product)) {
369 $this->_cleanObjectDatas($object->product);
370 }
371
372 return $object;
373 }
374
375 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
387 protected static function _checkAccessToResource($resource, $resource_id = 0, $dbtablename = '', $feature2 = '', $dbt_keyfield = 'fk_soc', $dbt_select = 'rowid')
388 {
389 // phpcs:enable
390 // Features/modules to check
391 $featuresarray = array($resource);
392 if (preg_match('/&/', $resource)) {
393 $featuresarray = explode("&", $resource);
394 } elseif (preg_match('/\|/', $resource)) {
395 $featuresarray = explode("|", $resource);
396 }
397
398 // More subfeatures to check
399 if (!empty($feature2)) {
400 $feature2 = explode("|", $feature2);
401 }
402
403 return checkUserAccessToObject(DolibarrApiAccess::$user, $featuresarray, $resource_id, $dbtablename, $feature2, $dbt_keyfield, $dbt_select);
404 }
405
406 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
415 protected function _checkFilters($sqlfilters, &$error = '')
416 {
417 // phpcs:enable
418 $firstandlastparenthesis = 0;
419 return dolCheckFilters($sqlfilters, $error, $firstandlastparenthesis);
420 }
421
422 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
423 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
433 protected static function _forge_criteria_callback($matches)
434 {
435 return dolForgeSQLCriteriaCallback($matches);
436 }
437}
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:66
Class for API REST v1.
Definition api.class.php:31
__construct($db, $cachedir='', $refreshCache=false)
Constructor.
Definition api.class.php:49
_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:96
_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.