28 use Luracast\Restler\Format\UploadFormat;
30 if (!defined(
'NOCSRFCHECK')) {
31 define(
'NOCSRFCHECK',
'1');
33 if (!defined(
'NOTOKENRENEWAL')) {
34 define(
'NOTOKENRENEWAL',
'1');
36 if (!defined(
'NOREQUIREMENU')) {
37 define(
'NOREQUIREMENU',
'1');
39 if (!defined(
'NOREQUIREHTML')) {
40 define(
'NOREQUIREHTML',
'1');
42 if (!defined(
'NOREQUIREAJAX')) {
43 define(
'NOREQUIREAJAX',
'1');
45 if (!defined(
"NOLOGIN")) {
46 define(
"NOLOGIN",
'1');
48 if (!defined(
"NOSESSION")) {
49 define(
"NOSESSION",
'1');
54 if (!empty($_SERVER[
'HTTP_DOLAPIENTITY'])) {
55 define(
"DOLENTITY", (
int) $_SERVER[
'HTTP_DOLAPIENTITY']);
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);
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');
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');
79 header(
'X-Frame-Options: SAMEORIGIN');
83 if (!$res && file_exists(
"../main.inc.php")) {
84 $res = include
'../main.inc.php';
87 die(
"Include of main fails");
90 require_once DOL_DOCUMENT_ROOT.
'/includes/restler/framework/Luracast/Restler/AutoLoader.php';
92 call_user_func(
function () {
93 $loader = Luracast\Restler\AutoLoader::instance();
94 spl_autoload_register($loader);
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';
103 $url = $_SERVER[
'PHP_SELF'];
104 if (preg_match(
'/api\/index\.php$/', $url)) {
105 $url = $_SERVER[
'PHP_SELF'].(empty($_SERVER[
'PATH_INFO']) ? $_SERVER[
'ORIG_PATH_INFO'] : $_SERVER[
'PATH_INFO']);
108 if (!empty($conf->global->MAIN_NGINX_FIX)) {
109 $url = (isset($_SERVER[
'SCRIPT_URI']) && $_SERVER[
"SCRIPT_URI"] !==
null) ? $_SERVER[
"SCRIPT_URI"] : $_SERVER[
'PHP_SELF'];
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");
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>';
147 preg_match(
'/index\.php\/([^\/]+)(.*)$/', $url, $reg);
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';
168 if (!empty($conf->global->MAIN_API_DEBUG)) {
170 $r->onCall(
function () use ($r) {
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');
188 $api->r->addAPIClass(
'Luracast\\Restler\\Explorer');
190 $api->r->setSupportedFormats(
'JsonFormat',
'XmlFormat',
'UploadFormat');
191 $api->r->addAuthenticationClass(
'DolibarrApiAccess',
'');
194 UploadFormat::$allowedMimeTypes = array(
'image/jpeg',
'image/png',
'text/plain',
'application/octet-stream');
198 if (!empty($conf->global->API_RESTRICT_ON_IP)) {
199 $allowedip = explode(
' ', $conf->global->API_RESTRICT_ON_IP);
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);
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')) {
215 $listofapis = array();
218 foreach ($modulesdir as $dir) {
220 dol_syslog(
"Scan directory ".$dir.
" for module descriptor files, then search for API files");
223 if (is_resource($handle)) {
224 while (($file = readdir($handle)) !==
false) {
226 if (is_readable($dir.$file) && preg_match(
"/^mod(.*)\.class\.php$/i", $file, $regmod)) {
227 $module = strtolower($regmod[1]);
229 $modulenameforenabled = $module;
230 if ($module ==
'propale') {
231 $modulenameforenabled =
'propal';
233 if ($module ==
'supplierproposal') {
234 $modulenameforenabled =
'supplier_proposal';
236 if ($module ==
'ficheinter') {
237 $modulenameforenabled =
'ficheinter';
240 dol_syslog(
"Found module file ".$file.
" - module=".$module.
" - modulenameforenabled=".$modulenameforenabled.
" - moduledirforclass=".$moduledirforclass);
255 if (is_resource($handle_part)) {
256 while (($file_searched = readdir($handle_part)) !==
false) {
257 if ($file_searched ==
'api_access.class.php') {
262 if ($file_searched ==
'api_login.class.php' && !empty($conf->global->MAIN_MODULE_API_LOGIN_DISABLED)) {
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')) {
275 $listofapis[strtolower($classname.
'Api')] = $classname.
'Api';
276 } elseif (class_exists($classname)) {
278 $listofapis[strtolower($classname)] = $classname;
280 dol_syslog(
"We found an api_xxx file (".$file_searched.
") but class ".$classname.
" does not exists after loading file", LOG_WARNING);
294 foreach ($listofapis as $apiname => $classname) {
295 $api->r->addAPIClass($classname, $apiname);
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') {
305 $moduleobject = $regbis[2];
308 $moduleobject = strtolower($moduleobject);
312 dol_syslog(
"Load a dedicated API file moduleobject=".$moduleobject.
" moduledirforclass=".$moduledirforclass);
314 $tmpmodule = $moduleobject;
315 if ($tmpmodule !=
'api') {
316 $tmpmodule = preg_replace(
'/api$/i',
'', $tmpmodule);
318 $classfile = str_replace(
'_',
'', $tmpmodule);
321 if ($moduleobject ==
'supplierproposals') {
322 $classfile =
'supplier_proposals';
324 if ($moduleobject ==
'supplierorders') {
325 $classfile =
'supplier_orders';
327 if ($moduleobject ==
'supplierinvoices') {
328 $classfile =
'supplier_invoices';
330 if ($moduleobject ==
'ficheinter') {
331 $classfile =
'interventions';
333 if ($moduleobject ==
'interventions') {
334 $classfile =
'interventions';
337 $dir_part_file =
dol_buildpath(
'/'.$moduledirforclass.
'/class/api_'.$classfile.
'.class.php', 0, 2);
339 $classname = ucwords($moduleobject);
343 if (!empty($conf->global->API_ENDPOINT_RULES)) {
344 $listofendpoints = explode(
',', $conf->global->API_ENDPOINT_RULES);
345 $endpointisallowed =
false;
347 foreach ($listofendpoints as $endpointrule) {
348 $tmparray = explode(
':', $endpointrule);
349 if (($classfile == $tmparray[0] || $classfile.
'api' == $tmparray[0]) && $tmparray[1] == 1) {
350 $endpointisallowed =
true;
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');
364 dol_syslog(
'Search api file /'.$moduledirforclass.
'/class/api_'.$classfile.
'.class.php => dir_part_file='.$dir_part_file.
' classname='.$classname);
367 if ($dir_part_file) {
368 $res = include_once $dir_part_file;
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)');
378 if (class_exists($classname)) {
379 $api->r->addAPIClass($classname);
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++;
395 if (strpos($_SERVER[
'HTTP_ACCEPT_ENCODING'],
'bz') !==
false && is_callable(
'bzcompress')) {
396 $foundonealgorithm++;
398 if (strpos($_SERVER[
'HTTP_ACCEPT_ENCODING'],
'gzip') !==
false && is_callable(
'gzencode')) {
399 $foundonealgorithm++;
401 if (!$foundonealgorithm) {
402 $usecompression =
false;
408 Luracast\Restler\Defaults::$returnResponse = $usecompression;
412 $result = $api->r->handle();
414 if (Luracast\Restler\Defaults::$returnResponse) {
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);
426 header(
'Content-Encoding: text/html');
427 print
"No compression method found. Try to disable compression by adding API_DISABLE_COMPRESSION=1";
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.