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