30use Luracast\Restler\Format\UploadFormat;
38@ini_set(
'display_errors',
'0');
39@ini_set(
'log_errors',
'1');
41if (!defined(
'NOCSRFCHECK')) {
42 define(
'NOCSRFCHECK',
'1');
44if (!defined(
'NOTOKENRENEWAL')) {
45 define(
'NOTOKENRENEWAL',
'1');
47if (!defined(
'NOREQUIREMENU')) {
48 define(
'NOREQUIREMENU',
'1');
50if (!defined(
'NOREQUIREHTML')) {
51 define(
'NOREQUIREHTML',
'1');
53if (!defined(
'NOREQUIREAJAX')) {
54 define(
'NOREQUIREAJAX',
'1');
56if (!defined(
"NOLOGIN")) {
57 define(
"NOLOGIN",
'1');
59if (!defined(
"NOSESSION")) {
60 define(
"NOSESSION",
'1');
62if (!defined(
"NODEFAULTVALUES")) {
63 define(
"NODEFAULTVALUES",
'1');
67if (!empty($_SERVER[
'HTTP_DOLAPIENTITY'])) {
68 define(
"DOLENTITY", (
int) $_SERVER[
'HTTP_DOLAPIENTITY']);
72if (!empty($_SERVER[
'REQUEST_METHOD']) && $_SERVER[
'REQUEST_METHOD'] ==
'OPTIONS' && !empty($_SERVER[
'HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
73 header(
'Access-Control-Allow-Origin: *');
74 header(
'Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
75 header(
'Access-Control-Allow-Headers: Content-Type, Authorization, api_key, DOLAPIKEY, DOLAPIENTITY');
76 http_response_code(204);
81if (preg_match(
'/\/explorer\/swagger\.json/', $_SERVER[
"PHP_SELF"])) {
82 header(
'Access-Control-Allow-Origin: *');
83 header(
'Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
84 header(
'Access-Control-Allow-Headers: Content-Type, Authorization, api_key, DOLAPIKEY, DOLAPIENTITY');
87if (preg_match(
'/\/api\/index\.php/', $_SERVER[
"PHP_SELF"])) {
88 header(
'Access-Control-Allow-Origin: *');
89 header(
'Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
90 header(
'Access-Control-Allow-Headers: Content-Type, Authorization, api_key, DOLAPIKEY, DOLAPIENTITY');
92header(
'X-Frame-Options: SAMEORIGIN');
96if (!$res && file_exists(
"../main.inc.php")) {
97 $res = include
'../main.inc.php';
100 die(
"Include of main fails");
112require_once DOL_DOCUMENT_ROOT.
'/includes/restler/framework/Luracast/Restler/AutoLoader.php';
119 $loader = Luracast\Restler\AutoLoader::instance();
120 spl_autoload_register($loader);
125require_once DOL_DOCUMENT_ROOT.
'/api/class/api.class.php';
126require_once DOL_DOCUMENT_ROOT.
'/api/class/api_access.class.php';
127require_once DOL_DOCUMENT_ROOT.
'/core/lib/functions2.lib.php';
131global $dolibarr_allow_unsecured_select_in_extrafields_filter;
132$dolibarr_allow_unsecured_select_in_extrafields_filter = 0;
135$url = $_SERVER[
'PHP_SELF'];
136if (preg_match(
'/api\/index\.php$/', $url)) {
137 $url = $_SERVER[
'PHP_SELF'].(empty($_SERVER[
'PATH_INFO']) ? $_SERVER[
'ORIG_PATH_INFO'] : $_SERVER[
'PATH_INFO']);
141 $url = (isset($_SERVER[
'SCRIPT_URI']) && $_SERVER[
"SCRIPT_URI"] !==
null) ? $_SERVER[
"SCRIPT_URI"] : $_SERVER[
'PHP_SELF'];
146 $langs->load(
"admin");
147 dol_syslog(
"Call of Dolibarr API interfaces with module API REST are disabled");
148 print $langs->trans(
"WarningModuleNotActive",
'Api').
'.<br><br>';
149 print $langs->trans(
"ToActivateModule");
155if (preg_match(
'/api\/index\.php\/explorer/', $url) &&
getDolGlobalString(
'API_EXPLORER_DISABLED')) {
156 $langs->load(
"admin");
157 dol_syslog(
"Call Dolibarr API interfaces with module API REST disabled");
158 print $langs->trans(
"WarningAPIExplorerDisabled").
'.<br><br>';
179preg_match(
'/index\.php\/([^\/]+)(.*)$/', $url, $reg);
183$hookmanager->initHooks(array(
'api'));
189$refreshcache = (
getDolGlobalString(
'API_PRODUCTION_DO_NOT_ALWAYS_REFRESH_CACHE') ? false :
true);
190if (!empty($reg[1]) && $reg[1] ==
'explorer' && ($reg[2] ==
'/swagger.json' || $reg[2] ==
'/swagger.json/root' || $reg[2] ==
'/resources.json' || $reg[2] ==
'/resources.json/root')) {
191 $refreshcache =
true;
192 if (!is_writable(
$conf->api->dir_temp)) {
193 dol_syslog(
"ErrorFailedToWriteInApiTempDirectory ".
$conf->api->dir_temp, LOG_ERR);
194 print
'Erreur temp dir api/temp not writable';
195 header(
'HTTP/1.1 500 temp dir api/temp not writable');
206 $r->onCall(
function () use ($r) {
224$api->r->addAPIClass(
'Luracast\\Restler\\Explorer');
226$api->r->setSupportedFormats(
'JsonFormat',
'XmlFormat',
'UploadFormat');
227$api->r->addAuthenticationClass(
'DolibarrApiAccess',
'');
230UploadFormat::$allowedMimeTypes = array(
'image/jpeg',
'image/png',
'text/plain',
'application/octet-stream');
237 if (!in_array($ipremote, $allowedip)) {
239 print
'APIs are not allowed from the IP '.$ipremote;
240 header(
'HTTP/1.1 503 API not allowed from your IP '.$ipremote);
248if (!empty($reg[1]) && $reg[1] ==
'explorer' && ($reg[2] ==
'/swagger.json' || $reg[2] ==
'/swagger.json/root' || $reg[2] ==
'/resources.json' || $reg[2] ==
'/resources.json/root')) {
251 $listofapis = array();
254 foreach ($modulesdir as $dir) {
256 dol_syslog(
"Scan directory ".$dir.
" for module descriptor files, then search for API files");
259 if (is_resource($handle)) {
260 while (($file = readdir($handle)) !==
false) {
262 if (is_readable($dir.$file) && preg_match(
"/^mod(.*)\.class\.php$/i", $file, $regmod)) {
263 $module = strtolower($regmod[1]);
265 $modulenameforenabled = $module;
266 if ($module ==
'propale') {
267 $modulenameforenabled =
'propal';
268 } elseif ($module ==
'supplierproposal') {
269 $modulenameforenabled =
'supplier_proposal';
270 } elseif ($module ==
'ficheinter') {
271 $modulenameforenabled =
'intervention';
273 $modulenameforenabled =
'service';
276 dol_syslog(
"Found module file ".$file.
" - module=".$module.
" - modulenameforenabled=".$modulenameforenabled.
" - moduledirforclass=".$moduledirforclass);
291 if (is_resource($handle_part)) {
292 while (($file_searched = readdir($handle_part)) !==
false) {
293 if ($file_searched ==
'api_access.class.php') {
304 if (is_readable($dir_part.$file_searched) && preg_match(
"/^api_(.*)\.class\.php$/i", $file_searched, $regapi)) {
305 $classname = ucwords($regapi[1]);
306 $classname = str_replace(
'_',
'', $classname);
307 require_once $dir_part.$file_searched;
308 if (class_exists($classname.
'Api')) {
310 $listofapis[strtolower($classname.
'Api')] = $classname.
'Api';
311 } elseif (class_exists($classname)) {
313 $listofapis[strtolower($classname)] = $classname;
315 dol_syslog(
"We found an api_xxx file (".$file_searched.
") but class ".$classname.
" does not exists after loading file", LOG_WARNING);
329 foreach ($listofapis as $apiname => $classname) {
330 $api->r->addAPIClass($classname, $apiname);
337if (!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'))) {
338 $moduleobject = $reg[1];
339 if ($moduleobject ==
'explorer') {
340 $moduleobject = $regbis[2];
343 $moduleobject = strtolower($moduleobject);
347 dol_syslog(
"Load a dedicated API file moduleobject=".$moduleobject.
" moduledirforclass=".$moduledirforclass);
349 $tmpmodule = $moduleobject;
350 if ($tmpmodule !=
'api') {
351 $tmpmodule = preg_replace(
'/api$/i',
'', $tmpmodule);
353 $classfile = str_replace(
'_',
'', $tmpmodule);
356 if ($moduleobject ==
'supplierproposals') {
357 $classfile =
'supplier_proposals';
359 if ($moduleobject ==
'supplierorders') {
360 $classfile =
'supplier_orders';
362 if ($moduleobject ==
'supplierinvoices') {
363 $classfile =
'supplier_invoices';
365 if ($moduleobject ==
'ficheinter') {
366 $classfile =
'interventions';
368 if ($moduleobject ==
'interventions') {
369 $classfile =
'interventions';
372 $dir_part_file =
dol_buildpath(
'/'.$moduledirforclass.
'/class/api_'.$classfile.
'.class.php', 0, 2);
374 $classname = ucwords($moduleobject);
380 $endpointisallowed =
false;
382 foreach ($listofendpoints as $endpointrule) {
383 $tmparray = explode(
':', $endpointrule);
384 if (($classfile == $tmparray[0] || $classfile.
'api' == $tmparray[0]) && $tmparray[1] == 1) {
385 $endpointisallowed =
true;
390 if (! $endpointisallowed) {
391 dol_syslog(
'The API with endpoint /'.$classfile.
' is forbidden by config API_ENDPOINT_RULES', LOG_WARNING);
392 print
'The API with endpoint /'.$classfile.
' is forbidden by config API_ENDPOINT_RULES';
393 header(
'HTTP/1.1 501 API is forbidden by API_ENDPOINT_RULES');
399 $parameters = array(
'url' => $url,
'ip' =>
getUserRemoteIP(),
'moduleobject' => $moduleobject,
'classfile' => $classfile,
'classname' => $classname);
401 $action = $api->r->requestMethod;
403 $reshook = $hookmanager->executeHooks(
'beforeApiCall', $parameters,
$object, $action);
405 dol_syslog(
'beforeapicall Failed to call hook '.$hookmanager->error, LOG_ERR);
408 dol_syslog(
'Search api file /'.$moduledirforclass.
'/class/api_'.$classfile.
'.class.php => dir_part_file='.$dir_part_file.
', classname='.$classname);
411 if ($dir_part_file) {
412 $res = include_once $dir_part_file;
415 dol_syslog(
'Failed to make include_once '.$dir_part_file, LOG_WARNING);
416 print
'API not found (failed to include API file)';
417 header(
'HTTP/1.1 501 API not found (failed to include API file)');
422 if (class_exists($classname)) {
423 $api->r->addAPIClass($classname);
433$usecompression = (!
getDolGlobalString(
'API_DISABLE_COMPRESSION') && !empty($_SERVER[
'HTTP_ACCEPT_ENCODING']));
434$foundonealgorithm = 0;
435if ($usecompression) {
436 if (strpos($_SERVER[
'HTTP_ACCEPT_ENCODING'],
'br') !==
false && function_exists(
'brotli_compress')) {
437 $foundonealgorithm++;
439 if (strpos($_SERVER[
'HTTP_ACCEPT_ENCODING'],
'bz') !==
false && function_exists(
'bzcompress')) {
440 $foundonealgorithm++;
442 if (strpos($_SERVER[
'HTTP_ACCEPT_ENCODING'],
'gzip') !==
false && function_exists(
'gzencode')) {
443 $foundonealgorithm++;
445 if (!$foundonealgorithm) {
446 $usecompression =
false;
452 dol_syslog(
'We found some compression algorithm: '.$foundonealgorithm.
' -> usecompression='.(
int) $usecompression, LOG_DEBUG, 0,
'_api');
456Luracast\Restler\Defaults::$returnResponse = $usecompression;
460$responsedata = $api->r->handle();
462if (Luracast\Restler\Defaults::$returnResponse) {
464 if (strpos($_SERVER[
'HTTP_ACCEPT_ENCODING'],
'br') !==
false && function_exists(
'brotli_compress') && defined(
'BROTLI_TEXT')) {
465 header(
'Content-Encoding: br');
466 $result = brotli_compress($responsedata, 11, constant(
'BROTLI_TEXT'));
467 } elseif (strpos($_SERVER[
'HTTP_ACCEPT_ENCODING'],
'bz') !==
false && function_exists(
'bzcompress')) {
468 header(
'Content-Encoding: bz');
469 $result = bzcompress($responsedata, 9);
470 } elseif (strpos($_SERVER[
'HTTP_ACCEPT_ENCODING'],
'gzip') !==
false && function_exists(
'gzencode')) {
471 header(
'Content-Encoding: gzip');
472 $result = gzencode($responsedata, 9);
474 header(
'Content-Encoding: text/html');
475 print
"No compression method found. Try to disable compression by adding API_DISABLE_COMPRESSION=1";
483if ((
getDolGlobalInt(
"API_ENABLE_COUNT_CALLS") || !empty($dolibarr_api_count_always_enabled)) && $api->r->responseCode == 200) {
486 $userid = DolibarrApiAccess::$user->id;
488 $sql =
"SELECT up.value";
489 $sql .=
" FROM ".MAIN_DB_PREFIX.
"user_param as up";
490 $sql .=
" WHERE up.param = 'API_COUNT_CALL'";
491 $sql .=
" AND up.fk_user = ".((int) $userid);
492 $sql .=
" AND up.entity = ".((int)
$conf->entity);
494 $result =
$db->query($sql);
497 $nbrows =
$db->num_rows($result);
499 $sql2 =
"INSERT INTO ".MAIN_DB_PREFIX.
"user_param";
500 $sql2 .=
" (fk_user, entity, param, value)";
501 $sql2 .=
" VALUES (".((int) $userid).
", ".((int)
$conf->entity).
", 'API_COUNT_CALL', 1)";
504 $sql2 =
"UPDATE ".MAIN_DB_PREFIX.
"user_param as up";
505 $sql2 .=
" SET up.value = up.value + 1";
506 $sql2 .=
" WHERE up.param = 'API_COUNT_CALL'";
507 $sql2 .=
" AND up.fk_user = ".((int) $userid);
508 $sql2 .=
" AND up.entity = ".((int)
$conf->entity);
511 $result2 =
$db->query($sql2);
513 $modeapicall = $updateapi ?
'updating' :
'inserting';
514 dol_syslog(
'Error while '.$modeapicall.
' API_COUNT_CALL for user '.$userid, LOG_ERR);
518 dol_syslog(
'Error on select API_COUNT_CALL for user '.$userid, LOG_ERR);
530$apiMethodInfo = &$api->r->apiMethodInfo;
531$terminateCall =
'_terminate_' . $apiMethodInfo->methodName .
'_' . $api->r->responseFormat->getExtension();
532if (method_exists($apiMethodInfo->className, $terminateCall)) {
537 if (function_exists(
'fastcgi_finish_request')) {
538 fastcgi_finish_request();
542 call_user_func(array(Luracast\Restler\Scope::get($apiMethodInfo->className), $terminateCall), $responsedata);
if(! $sortfield) if(! $sortorder) $object
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.
if(!function_exists( 'utf8_encode')) if(!function_exists('utf8_decode')) if(!function_exists( 'str_starts_with')) if(!function_exists('str_ends_with')) if(!function_exists( 'str_contains')) formatLogObject($data)
Return a string serialized to be output on log with dol_syslog() An option allow to output log in one...
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
getUserRemoteIP($trusted=0)
Return the real IP of remote user.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.