dolibarr 21.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) 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 $production_mode = getDolGlobalBool('API_PRODUCTION_MODE');
60 $this->r = new Restler($production_mode, $refreshCache);
61
62 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
63 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
64
65 $urlwithouturlrootautodetect = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim(DOL_MAIN_URL_ROOT));
66 $urlwithrootautodetect = $urlwithouturlroot.DOL_URL_ROOT; // This is to use local domain autodetected by dolibarr from url
67
68 $this->r->setBaseUrls($urlwithouturlroot, $urlwithouturlrootautodetect);
69 $this->r->setAPIVersion(1);
70 //$this->r->setSupportedFormats('json');
71 //$this->r->setSupportedFormats('jsonFormat');
72 }
73
74 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
83 protected function _checkValForAPI($field, $value, $object)
84 {
85 // phpcs:enable
86 if (!is_array($value)) {
87 // Sanitize the value using its type declared into ->fields of $object
88 if (!empty($object->fields) && !empty($object->fields[$field]) && !empty($object->fields[$field]['type'])) {
89 if (strpos($object->fields[$field]['type'], 'int') || strpos($object->fields[$field]['type'], 'double') || in_array($object->fields[$field]['type'], array('real', 'price', 'stock'))) {
90 return sanitizeVal($value, 'int');
91 }
92 if ($object->fields[$field]['type'] == 'html') {
93 return sanitizeVal($value, 'restricthtml');
94 }
95 if ($object->fields[$field]['type'] == 'select') {
96 // Check values are in the list of possible 'options'
97 // TODO
98 }
99 if ($object->fields[$field]['type'] == 'sellist' || $object->fields[$field]['type'] == 'checkbox') {
100 // TODO
101 }
102 if ($object->fields[$field]['type'] == 'boolean' || $object->fields[$field]['type'] == 'radio') {
103 // TODO
104 }
105 if ($object->fields[$field]['type'] == 'email') {
106 return sanitizeVal($value, 'email');
107 }
108 if ($object->fields[$field]['type'] == 'password') {
109 return sanitizeVal($value, 'none');
110 }
111 // Others will use 'alphanohtml'
112 }
113
114 if (in_array($field, array('note', 'note_private', 'note_public', 'desc', 'description'))) {
115 return sanitizeVal($value, 'restricthtml');
116 } else {
117 return sanitizeVal($value, 'alphanohtml');
118 }
119 } else { // Example when $field = 'extrafields' and $value = content of $object->array_options
120 $newarrayvalue = array();
121 foreach ($value as $tmpkey => $tmpvalue) {
122 $newarrayvalue[$tmpkey] = $this->_checkValForAPI($tmpkey, $tmpvalue, $object);
123 }
124
125 return $newarrayvalue;
126 }
127 }
128
129 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
137 protected function _filterObjectProperties($object, $properties)
138 {
139 // phpcs:enable
140 // If properties is empty, we return all properties
141 if (empty($properties)) {
142 return $object;
143 }
144
145 // Copy of exploded array for efficiency
146 $arr_properties = explode(',', $properties);
147 $magic_properties = array();
148 $real_properties = get_object_vars($object);
149
150 // Unsetting real properties may unset magic properties.
151 // We keep a copy of the requested magic properties
152 foreach ($arr_properties as $key) {
153 if (!array_key_exists($key, $real_properties)) {
154 // Not a real property,
155 // check if $key is a magic property (we want to keep '$obj->$key')
156 if (property_exists($object, $key) && isset($object->$key)) {
157 $magic_properties[$key] = $object->$key;
158 }
159 }
160 }
161
162 // Filter real properties (may indirectly unset magic properties)
163 foreach (get_object_vars($object) as $key => $value) {
164 if (!in_array($key, $arr_properties)) {
165 unset($object->$key);
166 }
167 }
168
169 // Restore the magic properties
170 foreach ($magic_properties as $key => $value) {
171 $object->$key = $value;
172 }
173
174 return $object;
175 }
176
177 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
188 protected function _cleanObjectDatas($object)
189 {
190 // phpcs:enable
191 // Remove $db object property for object
192 unset($object->db);
193 unset($object->isextrafieldmanaged);
194 unset($object->ismultientitymanaged);
195 unset($object->restrictiononfksoc);
196 unset($object->table_rowid);
197 unset($object->pass);
198 unset($object->pass_indatabase);
199
200 // Remove linkedObjects. We should already have and keep only linkedObjectsIds that avoid huge responses
201 unset($object->linkedObjects);
202 //unset($object->lines[$i]->linked_objects); // This is the array to create linked object during create
203
204 unset($object->fields);
205 unset($object->oldline);
206
207 unset($object->error);
208 unset($object->errors);
209 unset($object->errorhidden);
210
211 unset($object->ref_previous);
212 unset($object->ref_next);
213 unset($object->imgWidth);
214 unset($object->imgHeight);
215 unset($object->barcode_type_code);
216 unset($object->barcode_type_label);
217
218 unset($object->mode_reglement); // We use mode_reglement_id now
219 unset($object->cond_reglement); // We use cond_reglement_id now
220 unset($object->note); // We use note_public or note_private now
221 unset($object->contact); // We use contact_id now
222 unset($object->thirdparty); // We use thirdparty_id or fk_soc or socid now
223
224 unset($object->projet); // Should be fk_project
225 unset($object->project); // Should be fk_project
226 unset($object->fk_projet); // Should be fk_project
227 unset($object->author); // Should be fk_user_author
228 unset($object->timespent_old_duration);
229 unset($object->timespent_id);
230 unset($object->timespent_duration);
231 unset($object->timespent_date);
232 unset($object->timespent_datehour);
233 unset($object->timespent_withhour);
234 unset($object->timespent_fk_user);
235 unset($object->timespent_note);
236 unset($object->fk_delivery_address);
237 unset($object->model_pdf);
238 unset($object->sendtoid);
239 unset($object->name_bis);
240 unset($object->newref);
241 unset($object->oldref);
242 unset($object->alreadypaid);
243 unset($object->openid);
244 unset($object->fk_bank);
245 unset($object->showphoto_on_popup);
246 unset($object->nb);
247 unset($object->nbphoto);
248 unset($object->output);
249 unset($object->tpl);
250 //unset($object->libelle);
251
252 unset($object->stats_propale);
253 unset($object->stats_commande);
254 unset($object->stats_contrat);
255 unset($object->stats_facture);
256 unset($object->stats_commande_fournisseur);
257 unset($object->stats_reception);
258 unset($object->stats_mrptoconsume);
259 unset($object->stats_mrptoproduce);
260
261 unset($object->fieldsforcombobox);
262 unset($object->regeximgext);
263
264 unset($object->skip_update_total);
265 unset($object->context);
266 unset($object->next_prev_filter);
267
268 unset($object->region);
269 unset($object->region_code);
270 unset($object->country);
271 unset($object->state);
272 unset($object->state_code);
273 unset($object->fk_departement);
274 unset($object->departement);
275 unset($object->departement_code);
276
277 unset($object->libelle_statut);
278 unset($object->libelle_paiement);
279 unset($object->labelStatus);
280 unset($object->labelStatusShort);
281
282 unset($object->actionmsg);
283 unset($object->actionmsg2);
284
285 unset($object->prefix_comm);
286
287 if (!isset($object->table_element) || ! in_array($object->table_element, array('expensereport_det', 'ticket'))) {
288 unset($object->comments);
289 }
290
291 unset($object->origin_object);
292 unset($object->origin);
293 unset($object->element);
294 unset($object->element_for_permission);
295 unset($object->fk_element);
296 unset($object->table_element);
297 unset($object->table_element_line);
298 unset($object->class_element_line);
299 unset($object->picto);
300 unset($object->linked_objects);
301
302 // Remove the $oldcopy property because it is not supported by the JSON
303 // encoder. The following error is generated when trying to serialize
304 // it: "Error encoding/decoding JSON: Type is not supported"
305 // Note: Event if this property was correctly handled by the JSON
306 // encoder, it should be ignored because keeping it would let the API
307 // have a very strange behavior: calling PUT and then GET on the same
308 // resource would give different results:
309 // PUT /objects/{id} -> returns object with oldcopy = previous version of the object
310 // GET /objects/{id} -> returns object with oldcopy empty
311 unset($object->oldcopy);
312
313 // If object has lines, remove $db property
314 if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) {
315 $nboflines = count($object->lines);
316 for ($i = 0; $i < $nboflines; $i++) {
317 $this->_cleanObjectDatas($object->lines[$i]);
318
319 unset($object->lines[$i]->contact);
320 unset($object->lines[$i]->contact_id);
321 unset($object->lines[$i]->country);
322 unset($object->lines[$i]->country_id);
323 unset($object->lines[$i]->country_code);
324 unset($object->lines[$i]->mode_reglement_id);
325 unset($object->lines[$i]->mode_reglement_code);
326 unset($object->lines[$i]->mode_reglement);
327 unset($object->lines[$i]->cond_reglement_id);
328 unset($object->lines[$i]->cond_reglement_code);
329 unset($object->lines[$i]->cond_reglement);
330 unset($object->lines[$i]->fk_delivery_address);
331 unset($object->lines[$i]->fk_projet);
332 unset($object->lines[$i]->fk_project);
333 unset($object->lines[$i]->thirdparty);
334 unset($object->lines[$i]->user);
335 unset($object->lines[$i]->model_pdf);
336 unset($object->lines[$i]->note_public);
337 unset($object->lines[$i]->note_private);
338 unset($object->lines[$i]->fk_incoterms);
339 unset($object->lines[$i]->label_incoterms);
340 unset($object->lines[$i]->location_incoterms);
341 unset($object->lines[$i]->name);
342 unset($object->lines[$i]->lastname);
343 unset($object->lines[$i]->firstname);
344 unset($object->lines[$i]->civility_id);
345 unset($object->lines[$i]->fk_multicurrency);
346 unset($object->lines[$i]->multicurrency_code);
347 unset($object->lines[$i]->shipping_method_id);
348 }
349 }
350
351 if (!empty($object->thirdparty) && is_object($object->thirdparty)) {
352 $this->_cleanObjectDatas($object->thirdparty);
353 }
354
355 if (!empty($object->product) && is_object($object->product)) {
356 $this->_cleanObjectDatas($object->product);
357 }
358
359 return $object;
360 }
361
362 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
374 protected static function _checkAccessToResource($resource, $resource_id = 0, $dbtablename = '', $feature2 = '', $dbt_keyfield = 'fk_soc', $dbt_select = 'rowid')
375 {
376 // phpcs:enable
377 // Features/modules to check
378 $featuresarray = array($resource);
379 if (preg_match('/&/', $resource)) {
380 $featuresarray = explode("&", $resource);
381 } elseif (preg_match('/\|/', $resource)) {
382 $featuresarray = explode("|", $resource);
383 }
384
385 // More subfeatures to check
386 if (!empty($feature2)) {
387 $feature2 = explode("|", $feature2);
388 }
389
390 return checkUserAccessToObject(DolibarrApiAccess::$user, $featuresarray, $resource_id, $dbtablename, $feature2, $dbt_keyfield, $dbt_select);
391 }
392
393 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
402 protected function _checkFilters($sqlfilters, &$error = '')
403 {
404 // phpcs:enable
405 $firstandlastparenthesis = 0;
406 return dolCheckFilters($sqlfilters, $error, $firstandlastparenthesis);
407 }
408
409 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
410 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
420 protected static function _forge_criteria_callback($matches)
421 {
422 return dolForgeSQLCriteriaCallback($matches);
423 }
424}
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:83
_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.
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.
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
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.