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