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