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