29use Luracast\Restler\Format\UploadFormat;
31if (!defined(
'NOCSRFCHECK')) {
32 define(
'NOCSRFCHECK',
'1');
34if (!defined(
'NOTOKENRENEWAL')) {
35 define(
'NOTOKENRENEWAL',
'1');
37if (!defined(
'NOREQUIREMENU')) {
38 define(
'NOREQUIREMENU',
'1');
40if (!defined(
'NOREQUIREHTML')) {
41 define(
'NOREQUIREHTML',
'1');
43if (!defined(
'NOREQUIREAJAX')) {
44 define(
'NOREQUIREAJAX',
'1');
46if (!defined(
"NOLOGIN")) {
47 define(
"NOLOGIN",
'1');
49if (!defined(
"NOSESSION")) {
50 define(
"NOSESSION",
'1');
52if (!defined(
"NODEFAULTVALUES")) {
53 define(
"NODEFAULTVALUES",
'1');
57if (!empty($_SERVER[
'HTTP_DOLAPIENTITY'])) {
58 define(
"DOLENTITY", (
int) $_SERVER[
'HTTP_DOLAPIENTITY']);
62if (!empty($_SERVER[
'REQUEST_METHOD']) && $_SERVER[
'REQUEST_METHOD'] ==
'OPTIONS' && !empty($_SERVER[
'HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
63 header(
'Access-Control-Allow-Origin: *');
64 header(
'Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
65 header(
'Access-Control-Allow-Headers: Content-Type, Authorization, api_key, DOLAPIKEY');
66 http_response_code(204);
71if (preg_match(
'/\/explorer\/swagger\.json/', $_SERVER[
"PHP_SELF"])) {
72 header(
'Access-Control-Allow-Origin: *');
73 header(
'Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
74 header(
'Access-Control-Allow-Headers: Content-Type, Authorization, api_key, DOLAPIKEY');
77if (preg_match(
'/\/api\/index\.php/', $_SERVER[
"PHP_SELF"])) {
78 header(
'Access-Control-Allow-Origin: *');
79 header(
'Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
80 header(
'Access-Control-Allow-Headers: Content-Type, Authorization, api_key, DOLAPIKEY');
82header(
'X-Frame-Options: SAMEORIGIN');
86if (!$res && file_exists(
"../main.inc.php")) {
87 $res = include
'../main.inc.php';
90 die(
"Include of main fails");
93require_once DOL_DOCUMENT_ROOT.
'/includes/restler/framework/Luracast/Restler/AutoLoader.php';
100 $loader = Luracast\Restler\AutoLoader::instance();
101 spl_autoload_register($loader);
106require_once DOL_DOCUMENT_ROOT.
'/api/class/api.class.php';
107require_once DOL_DOCUMENT_ROOT.
'/api/class/api_access.class.php';
108require_once DOL_DOCUMENT_ROOT.
'/core/lib/functions2.lib.php';
111$url = $_SERVER[
'PHP_SELF'];
112if (preg_match(
'/api\/index\.php$/', $url)) {
113 $url = $_SERVER[
'PHP_SELF'].(empty($_SERVER[
'PATH_INFO']) ? $_SERVER[
'ORIG_PATH_INFO'] : $_SERVER[
'PATH_INFO']);
117 $url = (isset($_SERVER[
'SCRIPT_URI']) && $_SERVER[
"SCRIPT_URI"] !==
null) ? $_SERVER[
"SCRIPT_URI"] : $_SERVER[
'PHP_SELF'];
121if (!isModEnabled(
'api')) {
122 $langs->load(
"admin");
123 dol_syslog(
"Call of Dolibarr API interfaces with module API REST are disabled");
124 print $langs->trans(
"WarningModuleNotActive",
'Api').
'.<br><br>';
125 print $langs->trans(
"ToActivateModule");
131if (preg_match(
'/api\/index\.php\/explorer/', $url) &&
getDolGlobalString(
'API_EXPLORER_DISABLED')) {
132 $langs->load(
"admin");
133 dol_syslog(
"Call Dolibarr API interfaces with module API REST disabled");
134 print $langs->trans(
"WarningAPIExplorerDisabled").
'.<br><br>';
155preg_match(
'/index\.php\/([^\/]+)(.*)$/', $url, $reg);
159$hookmanager->initHooks(array(
'api'));
165$refreshcache = (
getDolGlobalString(
'API_PRODUCTION_DO_NOT_ALWAYS_REFRESH_CACHE') ? false :
true);
166if (!empty($reg[1]) && $reg[1] ==
'explorer' && ($reg[2] ==
'/swagger.json' || $reg[2] ==
'/swagger.json/root' || $reg[2] ==
'/resources.json' || $reg[2] ==
'/resources.json/root')) {
167 $refreshcache =
true;
168 if (!is_writable($conf->api->dir_temp)) {
169 print
'Erreur temp dir api/temp not writable';
170 header(
'HTTP/1.1 500 temp dir api/temp not writable');
181 $r->onCall(
function () use ($r) {
190 dol_syslog(
"Debug API url ".var_export($r->url,
true), LOG_DEBUG, 0,
'_api');
191 dol_syslog(
"Debug API input ".var_export($r->getRequestData(),
true), LOG_DEBUG, 0,
'_api');
199$api->r->addAPIClass(
'Luracast\\Restler\\Explorer');
201$api->r->setSupportedFormats(
'JsonFormat',
'XmlFormat',
'UploadFormat');
202$api->r->addAuthenticationClass(
'DolibarrApiAccess',
'');
205UploadFormat::$allowedMimeTypes = array(
'image/jpeg',
'image/png',
'text/plain',
'application/octet-stream');
212 if (!in_array($ipremote, $allowedip)) {
214 print
'APIs are not allowed from the IP '.$ipremote;
215 header(
'HTTP/1.1 503 API not allowed from your IP '.$ipremote);
223if (!empty($reg[1]) && $reg[1] ==
'explorer' && ($reg[2] ==
'/swagger.json' || $reg[2] ==
'/swagger.json/root' || $reg[2] ==
'/resources.json' || $reg[2] ==
'/resources.json/root')) {
226 $listofapis = array();
229 foreach ($modulesdir as $dir) {
231 dol_syslog(
"Scan directory ".$dir.
" for module descriptor files, then search for API files");
234 if (is_resource($handle)) {
235 while (($file = readdir($handle)) !==
false) {
237 if (is_readable($dir.$file) && preg_match(
"/^mod(.*)\.class\.php$/i", $file, $regmod)) {
238 $module = strtolower($regmod[1]);
240 $modulenameforenabled = $module;
241 if ($module ==
'propale') {
242 $modulenameforenabled =
'propal';
243 } elseif ($module ==
'supplierproposal') {
244 $modulenameforenabled =
'supplier_proposal';
245 } elseif ($module ==
'ficheinter') {
246 $modulenameforenabled =
'intervention';
249 dol_syslog(
"Found module file ".$file.
" - module=".$module.
" - modulenameforenabled=".$modulenameforenabled.
" - moduledirforclass=".$moduledirforclass);
253 if (!isModEnabled($modulenameforenabled)) {
264 if (is_resource($handle_part)) {
265 while (($file_searched = readdir($handle_part)) !==
false) {
266 if ($file_searched ==
'api_access.class.php') {
271 if ($file_searched ==
'api_login.class.php' &&
getDolGlobalString(
'API_DISABLE_LOGIN_API')) {
278 if (is_readable($dir_part.$file_searched) && preg_match(
"/^api_(.*)\.class\.php$/i", $file_searched, $regapi)) {
279 $classname = ucwords($regapi[1]);
280 $classname = str_replace(
'_',
'', $classname);
281 require_once $dir_part.$file_searched;
282 if (class_exists($classname.
'Api')) {
284 $listofapis[strtolower($classname.
'Api')] = $classname.
'Api';
285 } elseif (class_exists($classname)) {
287 $listofapis[strtolower($classname)] = $classname;
289 dol_syslog(
"We found an api_xxx file (".$file_searched.
") but class ".$classname.
" does not exists after loading file", LOG_WARNING);
303 foreach ($listofapis as $apiname => $classname) {
304 $api->r->addAPIClass($classname, $apiname);
311if (!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'))) {
312 $moduleobject = $reg[1];
313 if ($moduleobject ==
'explorer') {
314 $moduleobject = $regbis[2];
317 $moduleobject = strtolower($moduleobject);
321 dol_syslog(
"Load a dedicated API file moduleobject=".$moduleobject.
" moduledirforclass=".$moduledirforclass);
323 $tmpmodule = $moduleobject;
324 if ($tmpmodule !=
'api') {
325 $tmpmodule = preg_replace(
'/api$/i',
'', $tmpmodule);
327 $classfile = str_replace(
'_',
'', $tmpmodule);
330 if ($moduleobject ==
'supplierproposals') {
331 $classfile =
'supplier_proposals';
333 if ($moduleobject ==
'supplierorders') {
334 $classfile =
'supplier_orders';
336 if ($moduleobject ==
'supplierinvoices') {
337 $classfile =
'supplier_invoices';
339 if ($moduleobject ==
'ficheinter') {
340 $classfile =
'interventions';
342 if ($moduleobject ==
'interventions') {
343 $classfile =
'interventions';
346 $dir_part_file =
dol_buildpath(
'/'.$moduledirforclass.
'/class/api_'.$classfile.
'.class.php', 0, 2);
348 $classname = ucwords($moduleobject);
354 $endpointisallowed =
false;
356 foreach ($listofendpoints as $endpointrule) {
357 $tmparray = explode(
':', $endpointrule);
358 if (($classfile == $tmparray[0] || $classfile.
'api' == $tmparray[0]) && $tmparray[1] == 1) {
359 $endpointisallowed =
true;
364 if (! $endpointisallowed) {
365 dol_syslog(
'The API with endpoint /'.$classfile.
' is forbidden by config API_ENDPOINT_RULES', LOG_WARNING);
366 print
'The API with endpoint /'.$classfile.
' is forbidden by config API_ENDPOINT_RULES';
367 header(
'HTTP/1.1 501 API is forbidden by API_ENDPOINT_RULES');
373 dol_syslog(
'Search api file /'.$moduledirforclass.
'/class/api_'.$classfile.
'.class.php => dir_part_file='.$dir_part_file.
', classname='.$classname);
376 if ($dir_part_file) {
377 $res = include_once $dir_part_file;
380 dol_syslog(
'Failed to make include_once '.$dir_part_file, LOG_WARNING);
381 print
'API not found (failed to include API file)';
382 header(
'HTTP/1.1 501 API not found (failed to include API file)');
387 if (class_exists($classname)) {
388 $api->r->addAPIClass($classname);
398$usecompression = (!
getDolGlobalString(
'API_DISABLE_COMPRESSION') && !empty($_SERVER[
'HTTP_ACCEPT_ENCODING']));
399$foundonealgorithm = 0;
400if ($usecompression) {
401 if (strpos($_SERVER[
'HTTP_ACCEPT_ENCODING'],
'br') !==
false && function_exists(
'brotli_compress')) {
402 $foundonealgorithm++;
404 if (strpos($_SERVER[
'HTTP_ACCEPT_ENCODING'],
'bz') !==
false && function_exists(
'bzcompress')) {
405 $foundonealgorithm++;
407 if (strpos($_SERVER[
'HTTP_ACCEPT_ENCODING'],
'gzip') !==
false && function_exists(
'gzencode')) {
408 $foundonealgorithm++;
410 if (!$foundonealgorithm) {
411 $usecompression =
false;
417Luracast\Restler\Defaults::$returnResponse = $usecompression;
421$responsedata = $api->r->handle();
423if (Luracast\Restler\Defaults::$returnResponse) {
425 if (strpos($_SERVER[
'HTTP_ACCEPT_ENCODING'],
'br') !==
false && function_exists(
'brotli_compress') && defined(
'BROTLI_TEXT')) {
426 header(
'Content-Encoding: br');
427 $result = brotli_compress($responsedata, 11, constant(
'BROTLI_TEXT'));
428 } elseif (strpos($_SERVER[
'HTTP_ACCEPT_ENCODING'],
'bz') !==
false && function_exists(
'bzcompress')) {
429 header(
'Content-Encoding: bz');
430 $result = bzcompress($responsedata, 9);
431 } elseif (strpos($_SERVER[
'HTTP_ACCEPT_ENCODING'],
'gzip') !==
false && function_exists(
'gzencode')) {
432 header(
'Content-Encoding: gzip');
433 $result = gzencode($responsedata, 9);
435 header(
'Content-Encoding: text/html');
436 print
"No compression method found. Try to disable compression by adding API_DISABLE_COMPRESSION=1";
444if (
getDolGlobalInt(
"API_ENABLE_COUNT_CALLS") && $api->r->responseCode == 200) {
447 $userid = DolibarrApiAccess::$user->id;
449 $sql =
"SELECT up.value";
450 $sql .=
" FROM ".MAIN_DB_PREFIX.
"user_param as up";
451 $sql .=
" WHERE up.param = 'API_COUNT_CALL'";
452 $sql .=
" AND up.fk_user = ".((int) $userid);
453 $sql .=
" AND up.entity = ".((int) $conf->entity);
455 $result = $db->query($sql);
458 $nbrows = $db->num_rows($result);
460 $sql2 =
"INSERT INTO ".MAIN_DB_PREFIX.
"user_param";
461 $sql2 .=
" (fk_user, entity, param, value)";
462 $sql2 .=
" VALUES (".((int) $userid).
", ".((int) $conf->entity).
", 'API_COUNT_CALL', 1)";
465 $sql2 =
"UPDATE ".MAIN_DB_PREFIX.
"user_param as up";
466 $sql2 .=
" SET up.value = up.value + 1";
467 $sql2 .=
" WHERE up.param = 'API_COUNT_CALL'";
468 $sql2 .=
" AND up.fk_user = ".((int) $userid);
469 $sql2 .=
" AND up.entity = ".((int) $conf->entity);
472 $result2 = $db->query($sql2);
474 $modeapicall = $updateapi ?
'updating' :
'inserting';
475 dol_syslog(
'Error while '.$modeapicall.
' API_COUNT_CALL for user '.$userid, LOG_ERR);
479 dol_syslog(
'Error on select API_COUNT_CALL for user '.$userid, LOG_ERR);
491$apiMethodInfo = &$api->r->apiMethodInfo;
492$terminateCall =
'_terminate_' . $apiMethodInfo->methodName .
'_' . $api->r->responseFormat->getExtension();
493if (method_exists($apiMethodInfo->className, $terminateCall)) {
498 if (function_exists(
'fastcgi_finish_request')) {
499 fastcgi_finish_request();
503 call_user_func(array(Luracast\Restler\Scope::get($apiMethodInfo->className), $terminateCall), $responsedata);
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.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
getUserRemoteIP()
Return the IP of remote user.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.