dolibarr 20.0.0
index.php
Go to the documentation of this file.
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) 2017 Regis Houssin <regis.houssin@inodbox.com>
5 * Copyright (C) 2021 Alexis LAURIER <contact@alexislaurier.fr>
6 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.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
29use Luracast\Restler\Format\UploadFormat;
30
31if (!defined('NOCSRFCHECK')) {
32 define('NOCSRFCHECK', '1'); // Do not check anti CSRF attack test
33}
34if (!defined('NOTOKENRENEWAL')) {
35 define('NOTOKENRENEWAL', '1'); // Do not check anti POST attack test
36}
37if (!defined('NOREQUIREMENU')) {
38 define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu
39}
40if (!defined('NOREQUIREHTML')) {
41 define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php
42}
43if (!defined('NOREQUIREAJAX')) {
44 define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library
45}
46if (!defined("NOLOGIN")) {
47 define("NOLOGIN", '1'); // If this page is public (can be called outside logged session)
48}
49if (!defined("NOSESSION")) {
50 define("NOSESSION", '1');
51}
52if (!defined("NODEFAULTVALUES")) {
53 define("NODEFAULTVALUES", '1');
54}
55
56// Force entity if a value is provided into HTTP header. Otherwise, will use the entity of user of token used.
57if (!empty($_SERVER['HTTP_DOLAPIENTITY'])) {
58 define("DOLENTITY", (int) $_SERVER['HTTP_DOLAPIENTITY']);
59}
60
61// Response for preflight requests (used by browser when into a CORS context)
62if (!empty($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == 'OPTIONS' && !empty($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
63 header('Access-Control-Allow-Origin: *');
64 header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
65 header('Access-Control-Allow-Headers: Content-Type, Authorization, api_key, DOLAPIKEY');
66 http_response_code(204);
67 exit;
68}
69
70// When we request url to get the json file, we accept Cross site so we can include the descriptor into an external tool.
71if (preg_match('/\/explorer\/swagger\.json/', $_SERVER["PHP_SELF"])) {
72 header('Access-Control-Allow-Origin: *');
73 header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
74 header('Access-Control-Allow-Headers: Content-Type, Authorization, api_key, DOLAPIKEY');
75}
76// When we request url to get an API, we accept Cross site so we can make js API call inside another website
77if (preg_match('/\/api\/index\.php/', $_SERVER["PHP_SELF"])) {
78 header('Access-Control-Allow-Origin: *');
79 header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
80 header('Access-Control-Allow-Headers: Content-Type, Authorization, api_key, DOLAPIKEY');
81}
82header('X-Frame-Options: SAMEORIGIN');
83
84
85$res = 0;
86if (!$res && file_exists("../main.inc.php")) {
87 $res = include '../main.inc.php';
88}
89if (!$res) {
90 die("Include of main fails");
91}
92
93require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/AutoLoader.php';
94
95call_user_func(
99 static function () {
100 $loader = Luracast\Restler\AutoLoader::instance();
101 spl_autoload_register($loader);
102 return $loader;
103 }
104);
105
106require_once DOL_DOCUMENT_ROOT.'/api/class/api.class.php';
107require_once DOL_DOCUMENT_ROOT.'/api/class/api_access.class.php';
108require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
109
110
111$url = $_SERVER['PHP_SELF'];
112if (preg_match('/api\/index\.php$/', $url)) { // sometimes $_SERVER['PHP_SELF'] is 'api\/index\.php' instead of 'api\/index\.php/explorer.php' or 'api\/index\.php/method'
113 $url = $_SERVER['PHP_SELF'].(empty($_SERVER['PATH_INFO']) ? $_SERVER['ORIG_PATH_INFO'] : $_SERVER['PATH_INFO']);
114}
115// Fix for some NGINX setups (this should not be required even with NGINX, however setup of NGINX are often mysterious and this may help is such cases)
116if (getDolGlobalString('MAIN_NGINX_FIX')) {
117 $url = (isset($_SERVER['SCRIPT_URI']) && $_SERVER["SCRIPT_URI"] !== null) ? $_SERVER["SCRIPT_URI"] : $_SERVER['PHP_SELF'];
118}
119
120// Enable and test if module Api is enabled
121if (!isModEnabled('api')) {
122 $langs->load("admin");
123 dol_syslog("Call of Dolibarr API interfaces with module API REST are disabled");
124 print $langs->trans("WarningModuleNotActive", 'Api').'.<br><br>';
125 print $langs->trans("ToActivateModule");
126 //session_destroy();
127 exit(0);
128}
129
130// Test if explorer is not disabled
131if (preg_match('/api\/index\.php\/explorer/', $url) && getDolGlobalString('API_EXPLORER_DISABLED')) {
132 $langs->load("admin");
133 dol_syslog("Call Dolibarr API interfaces with module API REST disabled");
134 print $langs->trans("WarningAPIExplorerDisabled").'.<br><br>';
135 //session_destroy();
136 exit(0);
137}
138
139
140// This 2 lines are useful only if we want to exclude some Urls from the explorer
141//use Luracast\Restler\Explorer;
142//Explorer::$excludedPaths = array('/categories');
143
144
145// Analyze URLs
146// index.php/explorer do a redirect to index.php/explorer/
147// index.php/explorer/ called by swagger to build explorer page index.php/explorer/index.html
148// index.php/explorer/.../....png|.css|.js called by swagger for resources to build explorer page
149// index.php/explorer/resources.json called by swagger to get list of all services
150// index.php/explorer/resources.json/xxx called by swagger to get detail of services xxx
151// index.php/xxx called by any REST client to run API
152
153
154$reg = array();
155preg_match('/index\.php\/([^\/]+)(.*)$/', $url, $reg);
156// .../index.php/categories?sortfield=t.rowid&sortorder=ASC
157
158
159$hookmanager->initHooks(array('api'));
160
161// When in production mode, a file api/temp/routes.php is created with the API available of current call.
162// But, if we set $refreshcache to false, so it may have only one API in the routes.php file if we make a call for one API without
163// using the explorer. And when we make another call for another API, the API is not into the api/temp/routes.php and a 404 is returned.
164// So we force refresh to each call.
165$refreshcache = (getDolGlobalString('API_PRODUCTION_DO_NOT_ALWAYS_REFRESH_CACHE') ? false : true);
166if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $reg[2] == '/swagger.json/root' || $reg[2] == '/resources.json' || $reg[2] == '/resources.json/root')) {
167 $refreshcache = true;
168 if (!is_writable($conf->api->dir_temp)) {
169 print 'Erreur temp dir api/temp not writable';
170 header('HTTP/1.1 500 temp dir api/temp not writable');
171 exit(0);
172 }
173}
174
175$api = new DolibarrApi($db, '', $refreshcache);
176//var_dump($api->r->apiVersionMap);
177
178// If MAIN_API_DEBUG is set to 1, we save logs into file "dolibarr_api.log"
179if (getDolGlobalString('MAIN_API_DEBUG')) {
180 $r = $api->r;
181 $r->onCall(function () use ($r) {
182 // Don't log Luracast Restler Explorer resources calls
183 //if (!preg_match('/^explorer/', $r->url)) {
184 // 'method' => $api->r->requestMethod,
185 // 'url' => $api->r->url,
186 // 'route' => $api->r->apiMethodInfo->className.'::'.$api->r->apiMethodInfo->methodName,
187 // 'version' => $api->r->getRequestedApiVersion(),
188 // 'data' => $api->r->getRequestData(),
189 //dol_syslog("Debug API input ".var_export($r, true), LOG_DEBUG, 0, '_api');
190 dol_syslog("Debug API url ".var_export($r->url, true), LOG_DEBUG, 0, '_api');
191 dol_syslog("Debug API input ".var_export($r->getRequestData(), true), LOG_DEBUG, 0, '_api');
192 //}
193 });
194}
195
196
197// Enable the Restler API Explorer.
198// See https://github.com/Luracast/Restler-API-Explorer for more info.
199$api->r->addAPIClass('Luracast\\Restler\\Explorer');
200
201$api->r->setSupportedFormats('JsonFormat', 'XmlFormat', 'UploadFormat'); // 'YamlFormat'
202$api->r->addAuthenticationClass('DolibarrApiAccess', '');
203
204// Define accepted mime types
205UploadFormat::$allowedMimeTypes = array('image/jpeg', 'image/png', 'text/plain', 'application/octet-stream');
206
207
208// Restrict API to some IPs
209if (getDolGlobalString('API_RESTRICT_ON_IP')) {
210 $allowedip = explode(' ', getDolGlobalString('API_RESTRICT_ON_IP'));
211 $ipremote = getUserRemoteIP();
212 if (!in_array($ipremote, $allowedip)) {
213 dol_syslog('Remote ip is '.$ipremote.', not into list ' . getDolGlobalString('API_RESTRICT_ON_IP'));
214 print 'APIs are not allowed from the IP '.$ipremote;
215 header('HTTP/1.1 503 API not allowed from your IP '.$ipremote);
216 //session_destroy();
217 exit(0);
218 }
219}
220
221
222// Call Explorer file for all APIs definitions (this part is slow)
223if (!empty($reg[1]) && $reg[1] == 'explorer' && ($reg[2] == '/swagger.json' || $reg[2] == '/swagger.json/root' || $reg[2] == '/resources.json' || $reg[2] == '/resources.json/root')) {
224 // Scan all API files to load them
225
226 $listofapis = array();
227
228 $modulesdir = dolGetModulesDirs();
229 foreach ($modulesdir as $dir) {
230 // Search available module
231 dol_syslog("Scan directory ".$dir." for module descriptor files, then search for API files");
232
233 $handle = @opendir(dol_osencode($dir));
234 if (is_resource($handle)) {
235 while (($file = readdir($handle)) !== false) {
236 $regmod = array();
237 if (is_readable($dir.$file) && preg_match("/^mod(.*)\.class\.php$/i", $file, $regmod)) {
238 $module = strtolower($regmod[1]);
239 $moduledirforclass = getModuleDirForApiClass($module);
240 $modulenameforenabled = $module;
241 if ($module == 'propale') {
242 $modulenameforenabled = 'propal';
243 } elseif ($module == 'supplierproposal') {
244 $modulenameforenabled = 'supplier_proposal';
245 } elseif ($module == 'ficheinter') {
246 $modulenameforenabled = 'intervention';
247 }
248
249 dol_syslog("Found module file ".$file." - module=".$module." - modulenameforenabled=".$modulenameforenabled." - moduledirforclass=".$moduledirforclass);
250
251 // Defined if module is enabled
252 $enabled = true;
253 if (!isModEnabled($modulenameforenabled)) {
254 $enabled = false;
255 }
256
257 if ($enabled) {
258 // If exists, load the API class for enable module
259 // Search files named api_<object>.class.php into /htdocs/<module>/class directory
260 // @todo : use getElementProperties() function ?
261 $dir_part = dol_buildpath('/'.$moduledirforclass.'/class/');
262
263 $handle_part = @opendir(dol_osencode($dir_part));
264 if (is_resource($handle_part)) {
265 while (($file_searched = readdir($handle_part)) !== false) {
266 if ($file_searched == 'api_access.class.php') {
267 continue;
268 }
269
270 //$conf->global->API_DISABLE_LOGIN_API = 1;
271 if ($file_searched == 'api_login.class.php' && getDolGlobalString('API_DISABLE_LOGIN_API')) {
272 continue;
273 }
274
275 //dol_syslog("We scan to search api file with into ".$dir_part.$file_searched);
276
277 $regapi = array();
278 if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i", $file_searched, $regapi)) {
279 $classname = ucwords($regapi[1]);
280 $classname = str_replace('_', '', $classname);
281 require_once $dir_part.$file_searched;
282 if (class_exists($classname.'Api')) {
283 //dol_syslog("Found API by index.php: classname=".$classname."Api for module ".$dir." into ".$dir_part.$file_searched);
284 $listofapis[strtolower($classname.'Api')] = $classname.'Api';
285 } elseif (class_exists($classname)) {
286 //dol_syslog("Found API by index.php: classname=".$classname." for module ".$dir." into ".$dir_part.$file_searched);
287 $listofapis[strtolower($classname)] = $classname;
288 } else {
289 dol_syslog("We found an api_xxx file (".$file_searched.") but class ".$classname." does not exists after loading file", LOG_WARNING);
290 }
291 }
292 }
293 }
294 }
295 }
296 }
297 }
298 }
299
300 // Sort the classes before adding them to Restler.
301 // The Restler API Explorer shows the classes in the order they are added and it's a mess if they are not sorted.
302 asort($listofapis);
303 foreach ($listofapis as $apiname => $classname) {
304 $api->r->addAPIClass($classname, $apiname);
305 }
306 //var_dump($api->r);
307}
308
309// Call one APIs or one definition of an API
310$regbis = array();
311if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' && $reg[2] != '/resources.json' && preg_match('/^\/(swagger|resources)\.json\/(.+)$/', $reg[2], $regbis) && $regbis[2] != 'root'))) {
312 $moduleobject = $reg[1];
313 if ($moduleobject == 'explorer') { // If we call page to explore details of a service
314 $moduleobject = $regbis[2];
315 }
316
317 $moduleobject = strtolower($moduleobject);
318 $moduledirforclass = getModuleDirForApiClass($moduleobject);
319
320 // Load a dedicated API file
321 dol_syslog("Load a dedicated API file moduleobject=".$moduleobject." moduledirforclass=".$moduledirforclass);
322
323 $tmpmodule = $moduleobject;
324 if ($tmpmodule != 'api') {
325 $tmpmodule = preg_replace('/api$/i', '', $tmpmodule);
326 }
327 $classfile = str_replace('_', '', $tmpmodule);
328
329 // Special cases that does not match name rules conventions
330 if ($moduleobject == 'supplierproposals') {
331 $classfile = 'supplier_proposals';
332 }
333 if ($moduleobject == 'supplierorders') {
334 $classfile = 'supplier_orders';
335 }
336 if ($moduleobject == 'supplierinvoices') {
337 $classfile = 'supplier_invoices';
338 }
339 if ($moduleobject == 'ficheinter') {
340 $classfile = 'interventions';
341 }
342 if ($moduleobject == 'interventions') {
343 $classfile = 'interventions';
344 }
345
346 $dir_part_file = dol_buildpath('/'.$moduledirforclass.'/class/api_'.$classfile.'.class.php', 0, 2);
347
348 $classname = ucwords($moduleobject);
349
350 // Test rules on endpoints. For example:
351 // $conf->global->API_ENDPOINT_RULES = 'endpoint1:1,endpoint2:1,...'
352 if (getDolGlobalString('API_ENDPOINT_RULES')) {
353 $listofendpoints = explode(',', getDolGlobalString('API_ENDPOINT_RULES'));
354 $endpointisallowed = false;
355
356 foreach ($listofendpoints as $endpointrule) {
357 $tmparray = explode(':', $endpointrule);
358 if (($classfile == $tmparray[0] || $classfile.'api' == $tmparray[0]) && $tmparray[1] == 1) {
359 $endpointisallowed = true;
360 break;
361 }
362 }
363
364 if (! $endpointisallowed) {
365 dol_syslog('The API with endpoint /'.$classfile.' is forbidden by config API_ENDPOINT_RULES', LOG_WARNING);
366 print 'The API with endpoint /'.$classfile.' is forbidden by config API_ENDPOINT_RULES';
367 header('HTTP/1.1 501 API is forbidden by API_ENDPOINT_RULES');
368 //session_destroy();
369 exit(0);
370 }
371 }
372
373 dol_syslog('Search api file /'.$moduledirforclass.'/class/api_'.$classfile.'.class.php => dir_part_file='.$dir_part_file.', classname='.$classname);
374
375 $res = false;
376 if ($dir_part_file) {
377 $res = include_once $dir_part_file;
378 }
379 if (!$res) {
380 dol_syslog('Failed to make include_once '.$dir_part_file, LOG_WARNING);
381 print 'API not found (failed to include API file)';
382 header('HTTP/1.1 501 API not found (failed to include API file)');
383 //session_destroy();
384 exit(0);
385 }
386
387 if (class_exists($classname)) {
388 $api->r->addAPIClass($classname);
389 }
390}
391
392
393//var_dump($api->r->apiVersionMap);
394//exit;
395
396// We do not want that restler outputs data if we use native compression (default behaviour) but we want to have it returned into a string.
397// If API_DISABLE_COMPRESSION is set, returnResponse is false => It use default handling so output result directly.
398$usecompression = (!getDolGlobalString('API_DISABLE_COMPRESSION') && !empty($_SERVER['HTTP_ACCEPT_ENCODING']));
399$foundonealgorithm = 0;
400if ($usecompression) {
401 if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'br') !== false && function_exists('brotli_compress')) {
402 $foundonealgorithm++;
403 }
404 if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'bz') !== false && function_exists('bzcompress')) {
405 $foundonealgorithm++;
406 }
407 if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false && function_exists('gzencode')) {
408 $foundonealgorithm++;
409 }
410 if (!$foundonealgorithm) {
411 $usecompression = false;
412 }
413}
414
415//dol_syslog('We found some compression algorithm: '.$foundonealgorithm.' -> usecompression='.$usecompression, LOG_DEBUG);
416
417Luracast\Restler\Defaults::$returnResponse = $usecompression;
418
419// Call API (we suppose we found it).
420// The handle will use the file api/temp/routes.php to get data to run the API. If the file exists and the entry for API is not found, it will return 404.
421$responsedata = $api->r->handle();
422
423if (Luracast\Restler\Defaults::$returnResponse) {
424 // We try to compress the data received data
425 if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'br') !== false && function_exists('brotli_compress') && defined('BROTLI_TEXT')) {
426 header('Content-Encoding: br');
427 $result = brotli_compress($responsedata, 11, constant('BROTLI_TEXT'));
428 } elseif (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'bz') !== false && function_exists('bzcompress')) {
429 header('Content-Encoding: bz');
430 $result = bzcompress($responsedata, 9);
431 } elseif (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false && function_exists('gzencode')) {
432 header('Content-Encoding: gzip');
433 $result = gzencode($responsedata, 9);
434 } else {
435 header('Content-Encoding: text/html');
436 print "No compression method found. Try to disable compression by adding API_DISABLE_COMPRESSION=1";
437 exit(0);
438 }
439
440 // Restler did not output data yet, we return it now
441 echo $result;
442}
443
444if (getDolGlobalInt("API_ENABLE_COUNT_CALLS") && $api->r->responseCode == 200) {
445 $error = 0;
446 $db->begin();
447 $userid = DolibarrApiAccess::$user->id;
448
449 $sql = "SELECT up.value";
450 $sql .= " FROM ".MAIN_DB_PREFIX."user_param as up";
451 $sql .= " WHERE up.param = 'API_COUNT_CALL'";
452 $sql .= " AND up.fk_user = ".((int) $userid);
453 $sql .= " AND up.entity = ".((int) $conf->entity);
454
455 $result = $db->query($sql);
456 if ($result) {
457 $updateapi = false;
458 $nbrows = $db->num_rows($result);
459 if ($nbrows == 0) {
460 $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."user_param";
461 $sql2 .= " (fk_user, entity, param, value)";
462 $sql2 .= " VALUES (".((int) $userid).", ".((int) $conf->entity).", 'API_COUNT_CALL', 1)";
463 } else {
464 $updateapi = true;
465 $sql2 = "UPDATE ".MAIN_DB_PREFIX."user_param as up";
466 $sql2 .= " SET up.value = up.value + 1";
467 $sql2 .= " WHERE up.param = 'API_COUNT_CALL'";
468 $sql2 .= " AND up.fk_user = ".((int) $userid);
469 $sql2 .= " AND up.entity = ".((int) $conf->entity);
470 }
471
472 $result2 = $db->query($sql2);
473 if (!$result2) {
474 $modeapicall = $updateapi ? 'updating' : 'inserting';
475 dol_syslog('Error while '.$modeapicall. ' API_COUNT_CALL for user '.$userid, LOG_ERR);
476 $error++;
477 }
478 } else {
479 dol_syslog('Error on select API_COUNT_CALL for user '.$userid, LOG_ERR);
480 $error++;
481 }
482
483 if ($error) {
484 $db->rollback();
485 } else {
486 $db->commit();
487 }
488}
489
490// Call API termination method
491$apiMethodInfo = &$api->r->apiMethodInfo;
492$terminateCall = '_terminate_' . $apiMethodInfo->methodName . '_' . $api->r->responseFormat->getExtension();
493if (method_exists($apiMethodInfo->className, $terminateCall)) {
494 // Now flush output buffers so that response data is sent to the client even if we still have action to do in a termination method.
495 ob_end_flush();
496
497 // If you're using PHP-FPM, this function will allow you to send the response and then continue processing
498 if (function_exists('fastcgi_finish_request')) {
499 fastcgi_finish_request();
500 }
501
502 // Call a termination method. Warning: This method can do I/O, sync but must not make output.
503 call_user_func(array(Luracast\Restler\Scope::get($apiMethodInfo->className), $terminateCall), $responsedata);
504}
505
506//session_destroy();
Class for API REST v1.
Definition api.class.php:30
getModuleDirForApiClass($moduleobject)
Get name of directory where the api_...class.php file is stored.
dolGetModulesDirs($subdir='')
Return list of directories that contain modules.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
getUserRemoteIP()
Return the IP of remote user.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.