30use Luracast\Restler\Format\UploadFormat;
32if (!defined(
'NOCSRFCHECK')) {
33 define(
'NOCSRFCHECK',
'1');
35if (!defined(
'NOTOKENRENEWAL')) {
36 define(
'NOTOKENRENEWAL',
'1');
38if (!defined(
'NOREQUIREMENU')) {
39 define(
'NOREQUIREMENU',
'1');
41if (!defined(
'NOREQUIREHTML')) {
42 define(
'NOREQUIREHTML',
'1');
44if (!defined(
'NOREQUIREAJAX')) {
45 define(
'NOREQUIREAJAX',
'1');
47if (!defined(
"NOLOGIN")) {
48 define(
"NOLOGIN",
'1');
50if (!defined(
"NOSESSION")) {
51 define(
"NOSESSION",
'1');
53if (!defined(
"NODEFAULTVALUES")) {
54 define(
"NODEFAULTVALUES",
'1');
58if (!empty($_SERVER[
'HTTP_DOLAPIENTITY'])) {
59 define(
"DOLENTITY", (
int) $_SERVER[
'HTTP_DOLAPIENTITY']);
63if (!empty($_SERVER[
'REQUEST_METHOD']) && $_SERVER[
'REQUEST_METHOD'] ==
'OPTIONS' && !empty($_SERVER[
'HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
64 header(
'Access-Control-Allow-Origin: *');
65 header(
'Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
66 header(
'Access-Control-Allow-Headers: Content-Type, Authorization, api_key, DOLAPIKEY');
67 http_response_code(204);
72if (preg_match(
'/\/explorer\/swagger\.json/', $_SERVER[
"PHP_SELF"])) {
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');
78if (preg_match(
'/\/api\/index\.php/', $_SERVER[
"PHP_SELF"])) {
79 header(
'Access-Control-Allow-Origin: *');
80 header(
'Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
81 header(
'Access-Control-Allow-Headers: Content-Type, Authorization, api_key, DOLAPIKEY');
83header(
'X-Frame-Options: SAMEORIGIN');
87if (!$res && file_exists(
"../main.inc.php")) {
88 $res = include
'../main.inc.php';
91 die(
"Include of main fails");
94require_once DOL_DOCUMENT_ROOT.
'/includes/restler/framework/Luracast/Restler/AutoLoader.php';
101 $loader = Luracast\Restler\AutoLoader::instance();
102 spl_autoload_register($loader);
107require_once DOL_DOCUMENT_ROOT.
'/api/class/api.class.php';
108require_once DOL_DOCUMENT_ROOT.
'/api/class/api_access.class.php';
109require_once DOL_DOCUMENT_ROOT.
'/core/lib/functions2.lib.php';
120$conf->global->MAIN_DISALLOW_UNSECURED_SELECT_INTO_EXTRAFIELDS_FILTER = 1;
123$url = $_SERVER[
'PHP_SELF'];
124if (preg_match(
'/api\/index\.php$/', $url)) {
125 $url = $_SERVER[
'PHP_SELF'].(empty($_SERVER[
'PATH_INFO']) ? $_SERVER[
'ORIG_PATH_INFO'] : $_SERVER[
'PATH_INFO']);
129 $url = (isset($_SERVER[
'SCRIPT_URI']) && $_SERVER[
"SCRIPT_URI"] !==
null) ? $_SERVER[
"SCRIPT_URI"] : $_SERVER[
'PHP_SELF'];
133if (!isModEnabled(
'api')) {
134 $langs->load(
"admin");
135 dol_syslog(
"Call of Dolibarr API interfaces with module API REST are disabled");
136 print $langs->trans(
"WarningModuleNotActive",
'Api').
'.<br><br>';
137 print $langs->trans(
"ToActivateModule");
143if (preg_match(
'/api\/index\.php\/explorer/', $url) &&
getDolGlobalString(
'API_EXPLORER_DISABLED')) {
144 $langs->load(
"admin");
145 dol_syslog(
"Call Dolibarr API interfaces with module API REST disabled");
146 print $langs->trans(
"WarningAPIExplorerDisabled").
'.<br><br>';
167preg_match(
'/index\.php\/([^\/]+)(.*)$/', $url, $reg);
171$hookmanager->initHooks(array(
'api'));
177$refreshcache = (
getDolGlobalString(
'API_PRODUCTION_DO_NOT_ALWAYS_REFRESH_CACHE') ? false :
true);
178if (!empty($reg[1]) && $reg[1] ==
'explorer' && ($reg[2] ==
'/swagger.json' || $reg[2] ==
'/swagger.json/root' || $reg[2] ==
'/resources.json' || $reg[2] ==
'/resources.json/root')) {
179 $refreshcache =
true;
180 if (!is_writable(
$conf->api->dir_temp)) {
181 dol_syslog(
"ErrorFailedToWriteInApiTempDirectory ".
$conf->api->dir_temp, LOG_ERR);
182 print
'Erreur temp dir api/temp not writable';
183 header(
'HTTP/1.1 500 temp dir api/temp not writable');
194 $r->onCall(
function () use ($r) {
203 dol_syslog(
"Debug API url ".var_export($r->url,
true), LOG_DEBUG, 0,
'_api');
204 dol_syslog(
"Debug API input ".var_export($r->getRequestData(),
true), LOG_DEBUG, 0,
'_api');
212$api->r->addAPIClass(
'Luracast\\Restler\\Explorer');
214$api->r->setSupportedFormats(
'JsonFormat',
'XmlFormat',
'UploadFormat');
215$api->r->addAuthenticationClass(
'DolibarrApiAccess',
'');
218UploadFormat::$allowedMimeTypes = array(
'image/jpeg',
'image/png',
'text/plain',
'application/octet-stream');
225 if (!in_array($ipremote, $allowedip)) {
227 print
'APIs are not allowed from the IP '.$ipremote;
228 header(
'HTTP/1.1 503 API not allowed from your IP '.$ipremote);
236if (!empty($reg[1]) && $reg[1] ==
'explorer' && ($reg[2] ==
'/swagger.json' || $reg[2] ==
'/swagger.json/root' || $reg[2] ==
'/resources.json' || $reg[2] ==
'/resources.json/root')) {
239 $listofapis = array();
242 foreach ($modulesdir as $dir) {
244 dol_syslog(
"Scan directory ".$dir.
" for module descriptor files, then search for API files");
247 if (is_resource($handle)) {
248 while (($file = readdir($handle)) !==
false) {
250 if (is_readable($dir.$file) && preg_match(
"/^mod(.*)\.class\.php$/i", $file, $regmod)) {
251 $module = strtolower($regmod[1]);
253 $modulenameforenabled = $module;
254 if ($module ==
'propale') {
255 $modulenameforenabled =
'propal';
256 } elseif ($module ==
'supplierproposal') {
257 $modulenameforenabled =
'supplier_proposal';
258 } elseif ($module ==
'ficheinter') {
259 $modulenameforenabled =
'intervention';
260 } elseif ($module ==
'product' && !isModEnabled(
'product') && isModEnabled(
'service')) {
261 $modulenameforenabled =
'service';
264 dol_syslog(
"Found module file ".$file.
" - module=".$module.
" - modulenameforenabled=".$modulenameforenabled.
" - moduledirforclass=".$moduledirforclass);
268 if (!isModEnabled($modulenameforenabled)) {
279 if (is_resource($handle_part)) {
280 while (($file_searched = readdir($handle_part)) !==
false) {
281 if ($file_searched ==
'api_access.class.php') {
286 if ($file_searched ==
'api_login.class.php' &&
getDolGlobalString(
'API_DISABLE_LOGIN_API')) {
293 if (is_readable($dir_part.$file_searched) && preg_match(
"/^api_(.*)\.class\.php$/i", $file_searched, $regapi)) {
294 $classname = ucwords($regapi[1]);
295 $classname = str_replace(
'_',
'', $classname);
296 require_once $dir_part.$file_searched;
297 if (class_exists($classname.
'Api')) {
299 $listofapis[strtolower($classname.
'Api')] = $classname.
'Api';
300 } elseif (class_exists($classname)) {
302 $listofapis[strtolower($classname)] = $classname;
304 dol_syslog(
"We found an api_xxx file (".$file_searched.
") but class ".$classname.
" does not exists after loading file", LOG_WARNING);
318 foreach ($listofapis as $apiname => $classname) {
319 $api->r->addAPIClass($classname, $apiname);
326if (!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'))) {
327 $moduleobject = $reg[1];
328 if ($moduleobject ==
'explorer') {
329 $moduleobject = $regbis[2];
332 $moduleobject = strtolower($moduleobject);
336 dol_syslog(
"Load a dedicated API file moduleobject=".$moduleobject.
" moduledirforclass=".$moduledirforclass);
338 $tmpmodule = $moduleobject;
339 if ($tmpmodule !=
'api') {
340 $tmpmodule = preg_replace(
'/api$/i',
'', $tmpmodule);
342 $classfile = str_replace(
'_',
'', $tmpmodule);
345 if ($moduleobject ==
'supplierproposals') {
346 $classfile =
'supplier_proposals';
348 if ($moduleobject ==
'supplierorders') {
349 $classfile =
'supplier_orders';
351 if ($moduleobject ==
'supplierinvoices') {
352 $classfile =
'supplier_invoices';
354 if ($moduleobject ==
'ficheinter') {
355 $classfile =
'interventions';
357 if ($moduleobject ==
'interventions') {
358 $classfile =
'interventions';
360 if ($moduleobject ==
'eventattendees') {
361 $moduledirforclass =
'eventorganization';
364 $dir_part_file =
dol_buildpath(
'/'.$moduledirforclass.
'/class/api_'.$classfile.
'.class.php', 0, 2);
366 $classname = ucwords($moduleobject);
372 $endpointisallowed =
false;
374 foreach ($listofendpoints as $endpointrule) {
375 $tmparray = explode(
':', $endpointrule);
376 if (($classfile == $tmparray[0] || $classfile.
'api' == $tmparray[0]) && $tmparray[1] == 1) {
377 $endpointisallowed =
true;
382 if (! $endpointisallowed) {
383 dol_syslog(
'The API with endpoint /'.$classfile.
' is forbidden by config API_ENDPOINT_RULES', LOG_WARNING);
384 print
'The API with endpoint /'.$classfile.
' is forbidden by config API_ENDPOINT_RULES';
385 header(
'HTTP/1.1 501 API is forbidden by API_ENDPOINT_RULES');
391 $parameters = array(
'url' => $url,
'ip' =>
getUserRemoteIP(),
'moduleobject' => $moduleobject,
'classfile' => $classfile,
'classname' => $classname);
393 $action = $api->r->requestMethod;
395 $reshook = $hookmanager->executeHooks(
'beforeApiCall', $parameters,
$object, $action);
397 dol_syslog(
'beforeapicall Failed to call hook '.$hookmanager->error, LOG_ERR);
400 dol_syslog(
'Search api file /'.$moduledirforclass.
'/class/api_'.$classfile.
'.class.php => dir_part_file='.$dir_part_file.
', classname='.$classname);
403 if ($dir_part_file) {
404 $res = include_once $dir_part_file;
407 dol_syslog(
'Failed to make include_once '.$dir_part_file, LOG_WARNING);
408 print
'API not found (failed to include API file)';
409 header(
'HTTP/1.1 501 API not found (failed to include API file)');
414 if (class_exists($classname)) {
415 $api->r->addAPIClass($classname);
425$usecompression = (!
getDolGlobalString(
'API_DISABLE_COMPRESSION') && !empty($_SERVER[
'HTTP_ACCEPT_ENCODING']));
426$foundonealgorithm = 0;
427if ($usecompression) {
428 if (strpos($_SERVER[
'HTTP_ACCEPT_ENCODING'],
'br') !==
false && function_exists(
'brotli_compress')) {
429 $foundonealgorithm++;
431 if (strpos($_SERVER[
'HTTP_ACCEPT_ENCODING'],
'bz') !==
false && function_exists(
'bzcompress')) {
432 $foundonealgorithm++;
434 if (strpos($_SERVER[
'HTTP_ACCEPT_ENCODING'],
'gzip') !==
false && function_exists(
'gzencode')) {
435 $foundonealgorithm++;
437 if (!$foundonealgorithm) {
438 $usecompression =
false;
444Luracast\Restler\Defaults::$returnResponse = $usecompression;
448$responsedata = $api->r->handle();
450if (Luracast\Restler\Defaults::$returnResponse) {
452 if (strpos($_SERVER[
'HTTP_ACCEPT_ENCODING'],
'br') !==
false && function_exists(
'brotli_compress') && defined(
'BROTLI_TEXT')) {
453 header(
'Content-Encoding: br');
454 $result = brotli_compress($responsedata, 11, constant(
'BROTLI_TEXT'));
455 } elseif (strpos($_SERVER[
'HTTP_ACCEPT_ENCODING'],
'bz') !==
false && function_exists(
'bzcompress')) {
456 header(
'Content-Encoding: bz');
457 $result = bzcompress($responsedata, 9);
458 } elseif (strpos($_SERVER[
'HTTP_ACCEPT_ENCODING'],
'gzip') !==
false && function_exists(
'gzencode')) {
459 header(
'Content-Encoding: gzip');
460 $result = gzencode($responsedata, 9);
462 header(
'Content-Encoding: text/html');
463 print
"No compression method found. Try to disable compression by adding API_DISABLE_COMPRESSION=1";
471if (
getDolGlobalInt(
"API_ENABLE_COUNT_CALLS") && $api->r->responseCode == 200) {
474 $userid = DolibarrApiAccess::$user->id;
476 $sql =
"SELECT up.value";
477 $sql .=
" FROM ".MAIN_DB_PREFIX.
"user_param as up";
478 $sql .=
" WHERE up.param = 'API_COUNT_CALL'";
479 $sql .=
" AND up.fk_user = ".((int) $userid);
480 $sql .=
" AND up.entity = ".((int)
$conf->entity);
482 $result = $db->query($sql);
485 $nbrows = $db->num_rows($result);
487 $sql2 =
"INSERT INTO ".MAIN_DB_PREFIX.
"user_param";
488 $sql2 .=
" (fk_user, entity, param, value)";
489 $sql2 .=
" VALUES (".((int) $userid).
", ".((int)
$conf->entity).
", 'API_COUNT_CALL', 1)";
492 $sql2 =
"UPDATE ".MAIN_DB_PREFIX.
"user_param as up";
493 $sql2 .=
" SET up.value = up.value + 1";
494 $sql2 .=
" WHERE up.param = 'API_COUNT_CALL'";
495 $sql2 .=
" AND up.fk_user = ".((int) $userid);
496 $sql2 .=
" AND up.entity = ".((int)
$conf->entity);
499 $result2 = $db->query($sql2);
501 $modeapicall = $updateapi ?
'updating' :
'inserting';
502 dol_syslog(
'Error while '.$modeapicall.
' API_COUNT_CALL for user '.$userid, LOG_ERR);
506 dol_syslog(
'Error on select API_COUNT_CALL for user '.$userid, LOG_ERR);
518$apiMethodInfo = &$api->r->apiMethodInfo;
519$terminateCall =
'_terminate_' . $apiMethodInfo->methodName .
'_' . $api->r->responseFormat->getExtension();
520if (method_exists($apiMethodInfo->className, $terminateCall)) {
525 if (function_exists(
'fastcgi_finish_request')) {
526 fastcgi_finish_request();
530 call_user_func(array(Luracast\Restler\Scope::get($apiMethodInfo->className), $terminateCall), $responsedata);
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $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.
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.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...