dolibarr 19.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) 2025 William Mead <william@m34d.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\RestException;
23use Luracast\Restler\Defaults;
24use Luracast\Restler\Format\UploadFormat;
25
26require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
27
32{
36 protected $db;
37
41 public $r;
42
50 public function __construct($db, $cachedir = '', $refreshCache = false)
51 {
52 global $conf, $dolibarr_main_url_root;
53
54 if (empty($cachedir)) {
55 $cachedir = $conf->api->dir_temp;
56 }
57 Defaults::$cacheDirectory = $cachedir;
58
59 $this->db = $db;
60
61 $production_mode = (getDolGlobalString('API_PRODUCTION_MODE') ? true : false);
62
63 if ($production_mode) {
64 // Create the directory Defaults::$cacheDirectory if it does not exist. If dir does not exist, using production_mode generates an error 500.
65 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
66 if (!dol_is_dir(Defaults::$cacheDirectory)) {
67 dol_mkdir(Defaults::$cacheDirectory, DOL_DATA_ROOT);
68 }
69 if (getDolGlobalString('MAIN_API_DEBUG')) {
70 dol_syslog("Debug API construct::cacheDirectory=".Defaults::$cacheDirectory, LOG_DEBUG, 0, '_api');
71 }
72 }
73
74 $this->r = new Restler($production_mode, $refreshCache);
75
76 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
77 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
78
79 $urlwithouturlrootautodetect = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim(DOL_MAIN_URL_ROOT));
80 $urlwithrootautodetect = $urlwithouturlroot.DOL_URL_ROOT; // This is to use local domain autodetected by dolibarr from url
81
82 $this->r->setBaseUrls($urlwithouturlroot, $urlwithouturlrootautodetect);
83 $this->r->setAPIVersion(1);
84 //$this->r->setSupportedFormats('json');
85 //$this->r->setSupportedFormats('jsonFormat');
86 }
87
88 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
99 protected function _checkValForAPI($field, $value, $object)
100 {
101 // phpcs:enable
102 if (!is_array($value)) {
103 // TODO Use type detected in $object->fields if $object known and we can
104 if (in_array($field, array('note', 'note_private', 'note_public', 'desc', 'description'))) {
105 return sanitizeVal($value, 'restricthtml');
106 } else {
107 return sanitizeVal($value, 'alphanohtml');
108 }
109 } else {
110 // TODO Recall _checkValForAPI for each element of array
111
112 return $value;
113 }
114 }
115
116 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
124 protected function _filterObjectProperties($object, $properties)
125 {
126 // If properties is empty, we return all properties
127 if (empty($properties)) {
128 return $object;
129 }
130 // Else we filter properties
131 foreach (get_object_vars($object) as $key => $value) {
132 if (!in_array($key, explode(',', $properties))) {
133 unset($object->$key);
134 }
135 }
136 return $object;
137 }
138
139 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
146 protected function _cleanObjectDatas($object)
147 {
148 // phpcs:enable
149 // Remove $db object property for object
150 unset($object->db);
151 unset($object->isextrafieldmanaged);
152 unset($object->ismultientitymanaged);
153 unset($object->restrictiononfksoc);
154 unset($object->table_rowid);
155 unset($object->pass);
156 unset($object->pass_indatabase);
157
158 // Remove linkedObjects. We should already have and keep only linkedObjectsIds that avoid huge responses
159 unset($object->linkedObjects);
160 //unset($object->lines[$i]->linked_objects); // This is the array to create linked object during create
161
162 unset($object->fields);
163 unset($object->oldline);
164
165 unset($object->error);
166 unset($object->errors);
167 unset($object->errorhidden);
168
169 unset($object->ref_previous);
170 unset($object->ref_next);
171 unset($object->imgWidth);
172 unset($object->imgHeight);
173 unset($object->barcode_type_code);
174 unset($object->barcode_type_label);
175
176 unset($object->mode_reglement); // We use mode_reglement_id now
177 unset($object->cond_reglement); // We use cond_reglement_id now
178 unset($object->note); // We use note_public or note_private now
179 unset($object->contact); // We use contact_id now
180 unset($object->thirdparty); // We use thirdparty_id or fk_soc or socid now
181
182 unset($object->projet); // Should be fk_project
183 unset($object->project); // Should be fk_project
184 unset($object->fk_projet); // Should be fk_project
185 unset($object->author); // Should be fk_user_author
186 unset($object->timespent_old_duration);
187 unset($object->timespent_id);
188 unset($object->timespent_duration);
189 unset($object->timespent_date);
190 unset($object->timespent_datehour);
191 unset($object->timespent_withhour);
192 unset($object->timespent_fk_user);
193 unset($object->timespent_note);
194 unset($object->fk_delivery_address);
195 unset($object->modelpdf);
196 unset($object->sendtoid);
197 unset($object->name_bis);
198 unset($object->newref);
199 unset($object->alreadypaid);
200 unset($object->openid);
201
202 //unset($object->labelStatus);
203 //unset($object->labelStatusShort);
204
205 unset($object->stats_propale);
206 unset($object->stats_commande);
207 unset($object->stats_contrat);
208 unset($object->stats_facture);
209 unset($object->stats_commande_fournisseur);
210 unset($object->stats_reception);
211 unset($object->stats_mrptoconsume);
212 unset($object->stats_mrptoproduce);
213
214 unset($object->fieldsforcombobox);
215 unset($object->regeximgext);
216
217 unset($object->skip_update_total);
218 unset($object->context);
219 unset($object->next_prev_filter);
220
221 unset($object->region);
222 unset($object->region_code);
223 unset($object->country);
224 unset($object->state);
225 unset($object->state_code);
226 unset($object->departement);
227 unset($object->departement_code);
228
229 unset($object->libelle_statut);
230 unset($object->libelle_paiement);
231
232 unset($object->prefix_comm);
233
234 if (!isset($object->table_element) || ! in_array($object->table_element, array('expensereport_det', 'ticket'))) {
235 unset($object->comments);
236 }
237
238 unset($object->element);
239 unset($object->element_for_permission);
240 unset($object->fk_element);
241 unset($object->table_element);
242 unset($object->table_element_line);
243 unset($object->class_element_line);
244 unset($object->picto);
245
246 // Remove the $oldcopy property because it is not supported by the JSON
247 // encoder. The following error is generated when trying to serialize
248 // it: "Error encoding/decoding JSON: Type is not supported"
249 // Note: Event if this property was correctly handled by the JSON
250 // encoder, it should be ignored because keeping it would let the API
251 // have a very strange behavior: calling PUT and then GET on the same
252 // resource would give different results:
253 // PUT /objects/{id} -> returns object with oldcopy = previous version of the object
254 // GET /objects/{id} -> returns object with oldcopy empty
255 unset($object->oldcopy);
256
257 // If object has lines, remove $db property
258 if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) {
259 $nboflines = count($object->lines);
260 for ($i = 0; $i < $nboflines; $i++) {
261 $this->_cleanObjectDatas($object->lines[$i]);
262
263 unset($object->lines[$i]->contact);
264 unset($object->lines[$i]->contact_id);
265 unset($object->lines[$i]->country);
266 unset($object->lines[$i]->country_id);
267 unset($object->lines[$i]->country_code);
268 unset($object->lines[$i]->mode_reglement_id);
269 unset($object->lines[$i]->mode_reglement_code);
270 unset($object->lines[$i]->mode_reglement);
271 unset($object->lines[$i]->cond_reglement_id);
272 unset($object->lines[$i]->cond_reglement_code);
273 unset($object->lines[$i]->cond_reglement);
274 unset($object->lines[$i]->fk_delivery_address);
275 unset($object->lines[$i]->fk_projet);
276 unset($object->lines[$i]->fk_project);
277 unset($object->lines[$i]->thirdparty);
278 unset($object->lines[$i]->user);
279 unset($object->lines[$i]->model_pdf);
280 unset($object->lines[$i]->modelpdf);
281 unset($object->lines[$i]->note_public);
282 unset($object->lines[$i]->note_private);
283 unset($object->lines[$i]->fk_incoterms);
284 unset($object->lines[$i]->label_incoterms);
285 unset($object->lines[$i]->location_incoterms);
286 unset($object->lines[$i]->name);
287 unset($object->lines[$i]->lastname);
288 unset($object->lines[$i]->firstname);
289 unset($object->lines[$i]->civility_id);
290 unset($object->lines[$i]->fk_multicurrency);
291 unset($object->lines[$i]->multicurrency_code);
292 unset($object->lines[$i]->shipping_method_id);
293 }
294 }
295
296 if (!empty($object->thirdparty) && is_object($object->thirdparty)) {
297 $this->_cleanObjectDatas($object->thirdparty);
298 }
299
300 if (!empty($object->product) && is_object($object->product)) {
301 $this->_cleanObjectDatas($object->product);
302 }
303
304 return $object;
305 }
306
307 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
319 protected static function _checkAccessToResource($resource, $resource_id = 0, $dbtablename = '', $feature2 = '', $dbt_keyfield = 'fk_soc', $dbt_select = 'rowid')
320 {
321 // phpcs:enable
322 // Features/modules to check
323 $featuresarray = array($resource);
324 if (preg_match('/&/', $resource)) {
325 $featuresarray = explode("&", $resource);
326 } elseif (preg_match('/\|/', $resource)) {
327 $featuresarray = explode("|", $resource);
328 }
329
330 // More subfeatures to check
331 if (!empty($feature2)) {
332 $feature2 = explode("|", $feature2);
333 }
334
335 return checkUserAccessToObject(DolibarrApiAccess::$user, $featuresarray, $resource_id, $dbtablename, $feature2, $dbt_keyfield, $dbt_select);
336 }
337
338 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
347 protected function _checkFilters($sqlfilters, &$error = '')
348 {
349 // phpcs:enable
350
351 return dolCheckFilters($sqlfilters, $error);
352 }
353
354 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
355 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
365 protected static function _forge_criteria_callback($matches)
366 {
367 return dolForgeCriteriaCallback($matches);
368 }
369}
Class for API REST v1.
Definition api.class.php:32
__construct($db, $cachedir='', $refreshCache=false)
Constructor.
Definition api.class.php:50
_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:99
_cleanObjectDatas($object)
Clean sensible object datas.
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='')
Return if a $sqlfilters parameter has a valid balance of parenthesis.
dolForgeCriteriaCallback($matches)
Function to forge a SQL criteria from a Dolibarr filter syntax string.
getDolGlobalString($key, $default='')
Return 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.