dolibarr 18.0.8
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{
33
37 protected $db;
38
42 public $r;
43
51 public function __construct($db, $cachedir = '', $refreshCache = false)
52 {
53 global $conf, $dolibarr_main_url_root;
54
55 if (empty($cachedir)) {
56 $cachedir = $conf->api->dir_temp;
57 }
58 Defaults::$cacheDirectory = $cachedir;
59
60 $this->db = $db;
61 $production_mode = (empty($conf->global->API_PRODUCTION_MODE) ? false : true);
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 // TODO Use type detected in $object->fields
103 if (in_array($field, array('note', 'note_private', 'note_public', 'desc', 'description'))) {
104 return sanitizeVal($value, 'restricthtml');
105 } else {
106 return sanitizeVal($value, 'alphanohtml');
107 }
108 }
109
110 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
117 protected function _cleanObjectDatas($object)
118 {
119 // phpcs:enable
120 // Remove $db object property for object
121 unset($object->db);
122 unset($object->isextrafieldmanaged);
123 unset($object->ismultientitymanaged);
124 unset($object->restrictiononfksoc);
125 unset($object->table_rowid);
126 unset($object->pass);
127 unset($object->pass_indatabase);
128
129 // Remove linkedObjects. We should already have and keep only linkedObjectsIds that avoid huge responses
130 unset($object->linkedObjects);
131 //unset($object->lines[$i]->linked_objects); // This is the array to create linked object during create
132
133 unset($object->fields);
134 unset($object->oldline);
135
136 unset($object->error);
137 unset($object->errors);
138 unset($object->errorhidden);
139
140 unset($object->ref_previous);
141 unset($object->ref_next);
142 unset($object->imgWidth);
143 unset($object->imgHeight);
144 unset($object->barcode_type_code);
145 unset($object->barcode_type_label);
146
147 unset($object->mode_reglement); // We use mode_reglement_id now
148 unset($object->cond_reglement); // We use cond_reglement_id now
149 unset($object->note); // We use note_public or note_private now
150 unset($object->contact); // We use contact_id now
151 unset($object->thirdparty); // We use thirdparty_id or fk_soc or socid now
152
153 unset($object->projet); // Should be fk_project
154 unset($object->project); // Should be fk_project
155 unset($object->fk_projet); // Should be fk_project
156 unset($object->author); // Should be fk_user_author
157 unset($object->timespent_old_duration);
158 unset($object->timespent_id);
159 unset($object->timespent_duration);
160 unset($object->timespent_date);
161 unset($object->timespent_datehour);
162 unset($object->timespent_withhour);
163 unset($object->timespent_fk_user);
164 unset($object->timespent_note);
165 unset($object->fk_delivery_address);
166 unset($object->modelpdf);
167 unset($object->sendtoid);
168 unset($object->name_bis);
169 unset($object->newref);
170 unset($object->alreadypaid);
171 unset($object->openid);
172
173 unset($object->statuts);
174 unset($object->statuts_short);
175 unset($object->statuts_logo);
176 unset($object->statuts_long);
177
178 //unset($object->labelStatus);
179 //unset($object->labelStatusShort);
180
181 unset($object->stats_propale);
182 unset($object->stats_commande);
183 unset($object->stats_contrat);
184 unset($object->stats_facture);
185 unset($object->stats_commande_fournisseur);
186 unset($object->stats_reception);
187 unset($object->stats_mrptoconsume);
188 unset($object->stats_mrptoproduce);
189
190 unset($object->fieldsforcombobox);
191 unset($object->regeximgext);
192
193 unset($object->skip_update_total);
194 unset($object->context);
195 unset($object->next_prev_filter);
196
197 unset($object->region);
198 unset($object->region_code);
199 unset($object->country);
200 unset($object->state);
201 unset($object->state_code);
202 unset($object->departement);
203 unset($object->departement_code);
204
205 unset($object->libelle_statut);
206 unset($object->libelle_paiement);
207
208 unset($object->prefix_comm);
209
210 if (!isset($object->table_element) || ! in_array($object->table_element, array('expensereport_det', 'ticket'))) {
211 unset($object->comments);
212 }
213
214 unset($object->element);
215 unset($object->element_for_permission);
216 unset($object->fk_element);
217 unset($object->table_element);
218 unset($object->table_element_line);
219 unset($object->class_element_line);
220 unset($object->picto);
221
222 // Remove the $oldcopy property because it is not supported by the JSON
223 // encoder. The following error is generated when trying to serialize
224 // it: "Error encoding/decoding JSON: Type is not supported"
225 // Note: Event if this property was correctly handled by the JSON
226 // encoder, it should be ignored because keeping it would let the API
227 // have a very strange behavior: calling PUT and then GET on the same
228 // resource would give different results:
229 // PUT /objects/{id} -> returns object with oldcopy = previous version of the object
230 // GET /objects/{id} -> returns object with oldcopy empty
231 unset($object->oldcopy);
232
233 // If object has lines, remove $db property
234 if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) {
235 $nboflines = count($object->lines);
236 for ($i = 0; $i < $nboflines; $i++) {
237 $this->_cleanObjectDatas($object->lines[$i]);
238
239 unset($object->lines[$i]->contact);
240 unset($object->lines[$i]->contact_id);
241 unset($object->lines[$i]->country);
242 unset($object->lines[$i]->country_id);
243 unset($object->lines[$i]->country_code);
244 unset($object->lines[$i]->mode_reglement_id);
245 unset($object->lines[$i]->mode_reglement_code);
246 unset($object->lines[$i]->mode_reglement);
247 unset($object->lines[$i]->cond_reglement_id);
248 unset($object->lines[$i]->cond_reglement_code);
249 unset($object->lines[$i]->cond_reglement);
250 unset($object->lines[$i]->fk_delivery_address);
251 unset($object->lines[$i]->fk_projet);
252 unset($object->lines[$i]->fk_project);
253 unset($object->lines[$i]->thirdparty);
254 unset($object->lines[$i]->user);
255 unset($object->lines[$i]->model_pdf);
256 unset($object->lines[$i]->modelpdf);
257 unset($object->lines[$i]->note_public);
258 unset($object->lines[$i]->note_private);
259 unset($object->lines[$i]->fk_incoterms);
260 unset($object->lines[$i]->label_incoterms);
261 unset($object->lines[$i]->location_incoterms);
262 unset($object->lines[$i]->name);
263 unset($object->lines[$i]->lastname);
264 unset($object->lines[$i]->firstname);
265 unset($object->lines[$i]->civility_id);
266 unset($object->lines[$i]->fk_multicurrency);
267 unset($object->lines[$i]->multicurrency_code);
268 unset($object->lines[$i]->shipping_method_id);
269 }
270 }
271
272 if (!empty($object->thirdparty) && is_object($object->thirdparty)) {
273 $this->_cleanObjectDatas($object->thirdparty);
274 }
275
276 if (!empty($object->product) && is_object($object->product)) {
277 $this->_cleanObjectDatas($object->product);
278 }
279
280 return $object;
281 }
282
283 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
295 protected static function _checkAccessToResource($resource, $resource_id = 0, $dbtablename = '', $feature2 = '', $dbt_keyfield = 'fk_soc', $dbt_select = 'rowid')
296 {
297 // phpcs:enable
298 // Features/modules to check
299 $featuresarray = array($resource);
300 if (preg_match('/&/', $resource)) {
301 $featuresarray = explode("&", $resource);
302 } elseif (preg_match('/\|/', $resource)) {
303 $featuresarray = explode("|", $resource);
304 }
305
306 // More subfeatures to check
307 if (!empty($feature2)) {
308 $feature2 = explode("|", $feature2);
309 }
310
311 return checkUserAccessToObject(DolibarrApiAccess::$user, $featuresarray, $resource_id, $dbtablename, $feature2, $dbt_keyfield, $dbt_select);
312 }
313
314 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
323 protected function _checkFilters($sqlfilters, &$error = '')
324 {
325 // phpcs:enable
326
327 return dolCheckFilters($sqlfilters, $error);
328 }
329
330 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
331 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
341 protected static function _forge_criteria_callback($matches)
342 {
343 return dolForgeCriteriaCallback($matches);
344 }
345}
Class for API REST v1.
Definition api.class.php:32
__construct($db, $cachedir='', $refreshCache=false)
Constructor.
Definition api.class.php:51
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.