dolibarr 20.0.5
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 } elseif ($module == 'product' && !isModEnabled('product') && isModEnabled('service')) {
248 $modulenameforenabled = 'service';
249 }
250
251 dol_syslog("Found module file ".$file." - module=".$module." - modulenameforenabled=".$modulenameforenabled." - moduledirforclass=".$moduledirforclass);
252
253 // Defined if module is enabled
254 $enabled = true;
255 if (!isModEnabled($modulenameforenabled)) {
256 $enabled = false;
257 }
258
259 if ($enabled) {
260 // If exists, load the API class for enable module
261 // Search files named api_<object>.class.php into /htdocs/<module>/class directory
262 // @todo : use getElementProperties() function ?
263 $dir_part = dol_buildpath('/'.$moduledirforclass.'/class/');
264
265 $handle_part = @opendir(dol_osencode($dir_part));
266 if (is_resource($handle_part)) {
267 while (($file_searched = readdir($handle_part)) !== false) {
268 if ($file_searched == 'api_access.class.php') {
269 continue;
270 }
271
272 //$conf->global->API_DISABLE_LOGIN_API = 1;
273 if ($file_searched == 'api_login.class.php' && getDolGlobalString('API_DISABLE_LOGIN_API')) {
274 continue;
275 }
276
277 //dol_syslog("We scan to search api file with into ".$dir_part.$file_searched);
278
279 $regapi = array();
280 if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i", $file_searched, $regapi)) {
281 $classname = ucwords($regapi[1]);
282 $classname = str_replace('_', '', $classname);
283 require_once $dir_part.$file_searched;
284 if (class_exists($classname.'Api')) {
285 //dol_syslog("Found API by index.php: classname=".$classname."Api for module ".$dir." into ".$dir_part.$file_searched);
286 $listofapis[strtolower($classname.'Api')] = $classname.'Api';
287 } elseif (class_exists($classname)) {
288 //dol_syslog("Found API by index.php: classname=".$classname." for module ".$dir." into ".$dir_part.$file_searched);
289 $listofapis[strtolower($classname)] = $classname;
290 } else {
291 dol_syslog("We found an api_xxx file (".$file_searched.") but class ".$classname." does not exists after loading file", LOG_WARNING);
292 }
293 }
294 }
295 }
296 }
297 }
298 }
299 }
300 }
301
302 // Sort the classes before adding them to Restler.
303 // The Restler API Explorer shows the classes in the order they are added and it's a mess if they are not sorted.
304 asort($listofapis);
305 foreach ($listofapis as $apiname => $classname) {
306 $api->r->addAPIClass($classname, $apiname);
307 }
308 //var_dump($api->r);
309}
310
311// Call one APIs or one definition of an API
312$regbis = array();
313if (!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'))) {
314 $moduleobject = $reg[1];
315 if ($moduleobject == 'explorer') { // If we call page to explore details of a service
316 $moduleobject = $regbis[2];
317 }
318
319 $moduleobject = strtolower($moduleobject);
320 $moduledirforclass = getModuleDirForApiClass($moduleobject);
321
322 // Load a dedicated API file
323 dol_syslog("Load a dedicated API file moduleobject=".$moduleobject." moduledirforclass=".$moduledirforclass);
324
325 $tmpmodule = $moduleobject;
326 if ($tmpmodule != 'api') {
327 $tmpmodule = preg_replace('/api$/i', '', $tmpmodule);
328 }
329 $classfile = str_replace('_', '', $tmpmodule);
330
331 // Special cases that does not match name rules conventions
332 if ($moduleobject == 'supplierproposals') {
333 $classfile = 'supplier_proposals';
334 }
335 if ($moduleobject == 'supplierorders') {
336 $classfile = 'supplier_orders';
337 }
338 if ($moduleobject == 'supplierinvoices') {
339 $classfile = 'supplier_invoices';
340 }
341 if ($moduleobject == 'ficheinter') {
342 $classfile = 'interventions';
343 }
344 if ($moduleobject == 'interventions') {
345 $classfile = 'interventions';
346 }
347
348 $dir_part_file = dol_buildpath('/'.$moduledirforclass.'/class/api_'.$classfile.'.class.php', 0, 2);
349
350 $classname = ucwords($moduleobject);
351
352 // Test rules on endpoints. For example:
353 // $conf->global->API_ENDPOINT_RULES = 'endpoint1:1,endpoint2:1,...'
354 if (getDolGlobalString('API_ENDPOINT_RULES')) {
355 $listofendpoints = explode(',', getDolGlobalString('API_ENDPOINT_RULES'));
356 $endpointisallowed = false;
357
358 foreach ($listofendpoints as $endpointrule) {
359 $tmparray = explode(':', $endpointrule);
360 if (($classfile == $tmparray[0] || $classfile.'api' == $tmparray[0]) && $tmparray[1] == 1) {
361 $endpointisallowed = true;
362 break;
363 }
364 }
365
366 if (! $endpointisallowed) {
367 dol_syslog('The API with endpoint /'.$classfile.' is forbidden by config API_ENDPOINT_RULES', LOG_WARNING);
368 print 'The API with endpoint /'.$classfile.' is forbidden by config API_ENDPOINT_RULES';
369 header('HTTP/1.1 501 API is forbidden by API_ENDPOINT_RULES');
370 //session_destroy();
371 exit(0);
372 }
373 }
374
375 dol_syslog('Search api file /'.$moduledirforclass.'/class/api_'.$classfile.'.class.php => dir_part_file='.$dir_part_file.', classname='.$classname);
376
377 $res = false;
378 if ($dir_part_file) {
379 $res = include_once $dir_part_file;
380 }
381 if (!$res) {
382 dol_syslog('Failed to make include_once '.$dir_part_file, LOG_WARNING);
383 print 'API not found (failed to include API file)';
384 header('HTTP/1.1 501 API not found (failed to include API file)');
385 //session_destroy();
386 exit(0);
387 }
388
389 if (class_exists($classname)) {
390 $api->r->addAPIClass($classname);
391 }
392}
393
394
395//var_dump($api->r->apiVersionMap);
396//exit;
397
398// 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.
399// If API_DISABLE_COMPRESSION is set, returnResponse is false => It use default handling so output result directly.
400$usecompression = (!getDolGlobalString('API_DISABLE_COMPRESSION') && !empty($_SERVER['HTTP_ACCEPT_ENCODING']));
401$foundonealgorithm = 0;
402if ($usecompression) {
403 if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'br') !== false && function_exists('brotli_compress')) {
404 $foundonealgorithm++;
405 }
406 if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'bz') !== false && function_exists('bzcompress')) {
407 $foundonealgorithm++;
408 }
409 if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false && function_exists('gzencode')) {
410 $foundonealgorithm++;
411 }
412 if (!$foundonealgorithm) {
413 $usecompression = false;
414 }
415}
416
417//dol_syslog('We found some compression algorithm: '.$foundonealgorithm.' -> usecompression='.$usecompression, LOG_DEBUG);
418
419Luracast\Restler\Defaults::$returnResponse = $usecompression;
420
421// Call API (we suppose we found it).
422// 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.
423$responsedata = $api->r->handle();
424
425if (Luracast\Restler\Defaults::$returnResponse) {
426 // We try to compress the data received data
427 if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'br') !== false && function_exists('brotli_compress') && defined('BROTLI_TEXT')) {
428 header('Content-Encoding: br');
429 $result = brotli_compress($responsedata, 11, constant('BROTLI_TEXT'));
430 } elseif (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'bz') !== false && function_exists('bzcompress')) {
431 header('Content-Encoding: bz');
432 $result = bzcompress($responsedata, 9);
433 } elseif (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false && function_exists('gzencode')) {
434 header('Content-Encoding: gzip');
435 $result = gzencode($responsedata, 9);
436 } else {
437 header('Content-Encoding: text/html');
438 print "No compression method found. Try to disable compression by adding API_DISABLE_COMPRESSION=1";
439 exit(0);
440 }
441
442 // Restler did not output data yet, we return it now
443 echo $result;
444}
445
446if (getDolGlobalInt("API_ENABLE_COUNT_CALLS") && $api->r->responseCode == 200) {
447 $error = 0;
448 $db->begin();
449 $userid = DolibarrApiAccess::$user->id;
450
451 $sql = "SELECT up.value";
452 $sql .= " FROM ".MAIN_DB_PREFIX."user_param as up";
453 $sql .= " WHERE up.param = 'API_COUNT_CALL'";
454 $sql .= " AND up.fk_user = ".((int) $userid);
455 $sql .= " AND up.entity = ".((int) $conf->entity);
456
457 $result = $db->query($sql);
458 if ($result) {
459 $updateapi = false;
460 $nbrows = $db->num_rows($result);
461 if ($nbrows == 0) {
462 $sql2 = "INSERT INTO ".MAIN_DB_PREFIX."user_param";
463 $sql2 .= " (fk_user, entity, param, value)";
464 $sql2 .= " VALUES (".((int) $userid).", ".((int) $conf->entity).", 'API_COUNT_CALL', 1)";
465 } else {
466 $updateapi = true;
467 $sql2 = "UPDATE ".MAIN_DB_PREFIX."user_param as up";
468 $sql2 .= " SET up.value = up.value + 1";
469 $sql2 .= " WHERE up.param = 'API_COUNT_CALL'";
470 $sql2 .= " AND up.fk_user = ".((int) $userid);
471 $sql2 .= " AND up.entity = ".((int) $conf->entity);
472 }
473
474 $result2 = $db->query($sql2);
475 if (!$result2) {
476 $modeapicall = $updateapi ? 'updating' : 'inserting';
477 dol_syslog('Error while '.$modeapicall. ' API_COUNT_CALL for user '.$userid, LOG_ERR);
478 $error++;
479 }
480 } else {
481 dol_syslog('Error on select API_COUNT_CALL for user '.$userid, LOG_ERR);
482 $error++;
483 }
484
485 if ($error) {
486 $db->rollback();
487 } else {
488 $db->commit();
489 }
490}
491
492// Call API termination method
493$apiMethodInfo = &$api->r->apiMethodInfo;
494$terminateCall = '_terminate_' . $apiMethodInfo->methodName . '_' . $api->r->responseFormat->getExtension();
495if (method_exists($apiMethodInfo->className, $terminateCall)) {
496 // 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.
497 ob_end_flush();
498
499 // If you're using PHP-FPM, this function will allow you to send the response and then continue processing
500 if (function_exists('fastcgi_finish_request')) {
501 fastcgi_finish_request();
502 }
503
504 // Call a termination method. Warning: This method can do I/O, sync but must not make output.
505 call_user_func(array(Luracast\Restler\Scope::get($apiMethodInfo->className), $terminateCall), $responsedata);
506}
507
508//session_destroy();
Class for API REST v1.
Definition api.class.php:31
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.