index.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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. /**
  21. * \defgroup api Module DolibarrApi
  22. * \brief API loader
  23. * Search files htdocs/<module>/class/api_<module>.class.php
  24. * \file htdocs/api/index.php
  25. */
  26. use Luracast\Restler\Format\UploadFormat;
  27. if (!defined('NOCSRFCHECK')) {
  28. define('NOCSRFCHECK', '1'); // Do not check anti CSRF attack test
  29. }
  30. if (!defined('NOTOKENRENEWAL')) {
  31. define('NOTOKENRENEWAL', '1'); // Do not check anti POST attack test
  32. }
  33. if (!defined('NOREQUIREMENU')) {
  34. define('NOREQUIREMENU', '1'); // If there is no need to load and show top and left menu
  35. }
  36. if (!defined('NOREQUIREHTML')) {
  37. define('NOREQUIREHTML', '1'); // If we don't need to load the html.form.class.php
  38. }
  39. if (!defined('NOREQUIREAJAX')) {
  40. define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library
  41. }
  42. if (!defined("NOLOGIN")) {
  43. define("NOLOGIN", '1'); // If this page is public (can be called outside logged session)
  44. }
  45. if (!defined("NOSESSION")) {
  46. define("NOSESSION", '1');
  47. }
  48. // Force entity if a value is provided into HTTP header. Otherwise, will use the entity of user of token used.
  49. if (!empty($_SERVER['HTTP_DOLAPIENTITY'])) {
  50. define("DOLENTITY", (int) $_SERVER['HTTP_DOLAPIENTITY']);
  51. }
  52. // Response for preflight requests (used by browser when into a CORS context)
  53. if (!empty($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == 'OPTIONS' && !empty($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
  54. header('Access-Control-Allow-Origin: *');
  55. header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
  56. header('Access-Control-Allow-Headers: Content-Type, Authorization, api_key, DOLAPIKEY');
  57. http_response_code(204);
  58. exit;
  59. }
  60. // When we request url to get the json file, we accept Cross site so we can include the descriptor into an external tool.
  61. if (preg_match('/\/explorer\/swagger\.json/', $_SERVER["PHP_SELF"])) {
  62. header('Access-Control-Allow-Origin: *');
  63. header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
  64. header('Access-Control-Allow-Headers: Content-Type, Authorization, api_key, DOLAPIKEY');
  65. }
  66. // When we request url to get an API, we accept Cross site so we can make js API call inside another website
  67. if (preg_match('/\/api\/index\.php/', $_SERVER["PHP_SELF"])) {
  68. header('Access-Control-Allow-Origin: *');
  69. header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
  70. header('Access-Control-Allow-Headers: Content-Type, Authorization, api_key, DOLAPIKEY');
  71. }
  72. header('X-Frame-Options: SAMEORIGIN');
  73. $res = 0;
  74. if (!$res && file_exists("../main.inc.php")) {
  75. $res = include '../main.inc.php';
  76. }
  77. if (!$res) {
  78. die("Include of main fails");
  79. }
  80. require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/AutoLoader.php';
  81. call_user_func(function () {
  82. $loader = Luracast\Restler\AutoLoader::instance();
  83. spl_autoload_register($loader);
  84. return $loader;
  85. });
  86. require_once DOL_DOCUMENT_ROOT.'/api/class/api.class.php';
  87. require_once DOL_DOCUMENT_ROOT.'/api/class/api_access.class.php';
  88. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  89. $url = $_SERVER['PHP_SELF'];
  90. 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'
  91. $url = $_SERVER['PHP_SELF'].(empty($_SERVER['PATH_INFO']) ? $_SERVER['ORIG_PATH_INFO'] : $_SERVER['PATH_INFO']);
  92. }
  93. // 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)
  94. if (!empty($conf->global->MAIN_NGINX_FIX)) {
  95. $url = (isset($_SERVER['SCRIPT_URI']) && $_SERVER["SCRIPT_URI"] !== null) ? $_SERVER["SCRIPT_URI"] : $_SERVER['PHP_SELF'];
  96. }
  97. // Enable and test if module Api is enabled
  98. if (empty($conf->global->MAIN_MODULE_API)) {
  99. $langs->load("admin");
  100. dol_syslog("Call of Dolibarr API interfaces with module API REST are disabled");
  101. print $langs->trans("WarningModuleNotActive", 'Api').'.<br><br>';
  102. print $langs->trans("ToActivateModule");
  103. //session_destroy();
  104. exit(0);
  105. }
  106. // Test if explorer is not disabled
  107. if (preg_match('/api\/index\.php\/explorer/', $url) && !empty($conf->global->API_EXPLORER_DISABLED)) {
  108. $langs->load("admin");
  109. dol_syslog("Call Dolibarr API interfaces with module API REST disabled");
  110. print $langs->trans("WarningAPIExplorerDisabled").'.<br><br>';
  111. //session_destroy();
  112. exit(0);
  113. }
  114. // This 2 lines are usefull only if we want to exclude some Urls from the explorer
  115. //use Luracast\Restler\Explorer;
  116. //Explorer::$excludedPaths = array('/categories');
  117. // Analyze URLs
  118. // index.php/explorer do a redirect to index.php/explorer/
  119. // index.php/explorer/ called by swagger to build explorer page index.php/explorer/index.html
  120. // index.php/explorer/.../....png|.css|.js called by swagger for resources to build explorer page
  121. // index.php/explorer/resources.json called by swagger to get list of all services
  122. // index.php/explorer/resources.json/xxx called by swagger to get detail of services xxx
  123. // index.php/xxx called by any REST client to run API
  124. $reg = array();
  125. preg_match('/index\.php\/([^\/]+)(.*)$/', $url, $reg);
  126. // .../index.php/categories?sortfield=t.rowid&sortorder=ASC
  127. // When in production mode, a file api/temp/routes.php is created with the API available of current call.
  128. // 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
  129. // 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.
  130. // So we force refresh to each call.
  131. $refreshcache = (empty($conf->global->API_PRODUCTION_DO_NOT_ALWAYS_REFRESH_CACHE) ? true : false);
  132. 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')) {
  133. $refreshcache = true;
  134. if (!is_writable($conf->api->dir_temp)) {
  135. print 'Erreur temp dir api/temp not writable';
  136. exit(0);
  137. }
  138. }
  139. $api = new DolibarrApi($db, '', $refreshcache);
  140. //var_dump($api->r->apiVersionMap);
  141. // If MAIN_API_DEBUG is set to 1, we save logs into file "dolibarr_api.log"
  142. if (!empty($conf->global->MAIN_API_DEBUG)) {
  143. $r = $api->r;
  144. $r->onCall(function () use ($r) {
  145. // Don't log Luracast Restler Explorer recources calls
  146. //if (!preg_match('/^explorer/', $r->url)) {
  147. // 'method' => $api->r->requestMethod,
  148. // 'url' => $api->r->url,
  149. // 'route' => $api->r->apiMethodInfo->className.'::'.$api->r->apiMethodInfo->methodName,
  150. // 'version' => $api->r->getRequestedApiVersion(),
  151. // 'data' => $api->r->getRequestData(),
  152. //dol_syslog("Debug API input ".var_export($r, true), LOG_DEBUG, 0, '_api');
  153. dol_syslog("Debug API url ".var_export($r->url, true), LOG_DEBUG, 0, '_api');
  154. dol_syslog("Debug API input ".var_export($r->getRequestData(), true), LOG_DEBUG, 0, '_api');
  155. //}
  156. });
  157. }
  158. // Enable the Restler API Explorer.
  159. // See https://github.com/Luracast/Restler-API-Explorer for more info.
  160. $api->r->addAPIClass('Luracast\\Restler\\Explorer');
  161. $api->r->setSupportedFormats('JsonFormat', 'XmlFormat', 'UploadFormat'); // 'YamlFormat'
  162. $api->r->addAuthenticationClass('DolibarrApiAccess', '');
  163. // Define accepted mime types
  164. UploadFormat::$allowedMimeTypes = array('image/jpeg', 'image/png', 'text/plain', 'application/octet-stream');
  165. // Restrict API to some IPs
  166. if (!empty($conf->global->API_RESTRICT_ON_IP)) {
  167. $allowedip = explode(' ', $conf->global->API_RESTRICT_ON_IP);
  168. $ipremote = getUserRemoteIP();
  169. if (!in_array($ipremote, $allowedip)) {
  170. dol_syslog('Remote ip is '.$ipremote.', not into list '.$conf->global->API_RESTRICT_ON_IP);
  171. print 'APIs are not allowed from the IP '.$ipremote;
  172. header('HTTP/1.1 503 API not allowed from your IP '.$ipremote);
  173. //session_destroy();
  174. exit(0);
  175. }
  176. }
  177. // Call Explorer file for all APIs definitions (this part is slow)
  178. 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')) {
  179. // Scan all API files to load them
  180. $listofapis = array();
  181. $modulesdir = dolGetModulesDirs();
  182. foreach ($modulesdir as $dir) {
  183. // Search available module
  184. dol_syslog("Scan directory ".$dir." for module descriptor files, then search for API files");
  185. $handle = @opendir(dol_osencode($dir));
  186. if (is_resource($handle)) {
  187. while (($file = readdir($handle)) !== false) {
  188. $regmod = array();
  189. if (is_readable($dir.$file) && preg_match("/^mod(.*)\.class\.php$/i", $file, $regmod)) {
  190. $module = strtolower($regmod[1]);
  191. $moduledirforclass = getModuleDirForApiClass($module);
  192. $modulenameforenabled = $module;
  193. if ($module == 'propale') {
  194. $modulenameforenabled = 'propal';
  195. }
  196. if ($module == 'supplierproposal') {
  197. $modulenameforenabled = 'supplier_proposal';
  198. }
  199. if ($module == 'ficheinter') {
  200. $modulenameforenabled = 'ficheinter';
  201. }
  202. dol_syslog("Found module file ".$file." - module=".$module." - modulenameforenabled=".$modulenameforenabled." - moduledirforclass=".$moduledirforclass);
  203. // Defined if module is enabled
  204. $enabled = true;
  205. if (!isModEnabled($modulenameforenabled)) {
  206. $enabled = false;
  207. }
  208. if ($enabled) {
  209. // If exists, load the API class for enable module
  210. // Search files named api_<object>.class.php into /htdocs/<module>/class directory
  211. // @todo : use getElementProperties() function ?
  212. $dir_part = dol_buildpath('/'.$moduledirforclass.'/class/');
  213. $handle_part = @opendir(dol_osencode($dir_part));
  214. if (is_resource($handle_part)) {
  215. while (($file_searched = readdir($handle_part)) !== false) {
  216. if ($file_searched == 'api_access.class.php') {
  217. continue;
  218. }
  219. //$conf->global->MAIN_MODULE_API_LOGIN_DISABLED = 1;
  220. if ($file_searched == 'api_login.class.php' && !empty($conf->global->MAIN_MODULE_API_LOGIN_DISABLED)) {
  221. continue;
  222. }
  223. //dol_syslog("We scan to search api file with into ".$dir_part.$file_searched);
  224. $regapi = array();
  225. if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i", $file_searched, $regapi)) {
  226. $classname = ucwords($regapi[1]);
  227. $classname = str_replace('_', '', $classname);
  228. require_once $dir_part.$file_searched;
  229. if (class_exists($classname.'Api')) {
  230. //dol_syslog("Found API by index.php: classname=".$classname."Api for module ".$dir." into ".$dir_part.$file_searched);
  231. $listofapis[strtolower($classname.'Api')] = $classname.'Api';
  232. } elseif (class_exists($classname)) {
  233. //dol_syslog("Found API by index.php: classname=".$classname." for module ".$dir." into ".$dir_part.$file_searched);
  234. $listofapis[strtolower($classname)] = $classname;
  235. } else {
  236. dol_syslog("We found an api_xxx file (".$file_searched.") but class ".$classname." does not exists after loading file", LOG_WARNING);
  237. }
  238. }
  239. }
  240. }
  241. }
  242. }
  243. }
  244. }
  245. }
  246. // Sort the classes before adding them to Restler.
  247. // The Restler API Explorer shows the classes in the order they are added and it's a mess if they are not sorted.
  248. asort($listofapis);
  249. foreach ($listofapis as $apiname => $classname) {
  250. $api->r->addAPIClass($classname, $apiname);
  251. }
  252. //var_dump($api->r);
  253. }
  254. // Call one APIs or one definition of an API
  255. $regbis = array();
  256. 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'))) {
  257. $moduleobject = $reg[1];
  258. if ($moduleobject == 'explorer') { // If we call page to explore details of a service
  259. $moduleobject = $regbis[2];
  260. }
  261. $moduleobject = strtolower($moduleobject);
  262. $moduledirforclass = getModuleDirForApiClass($moduleobject);
  263. // Load a dedicated API file
  264. dol_syslog("Load a dedicated API file moduleobject=".$moduleobject." moduledirforclass=".$moduledirforclass);
  265. $tmpmodule = $moduleobject;
  266. if ($tmpmodule != 'api') {
  267. $tmpmodule = preg_replace('/api$/i', '', $tmpmodule);
  268. }
  269. $classfile = str_replace('_', '', $tmpmodule);
  270. // Special cases that does not match name rules conventions
  271. if ($moduleobject == 'supplierproposals') {
  272. $classfile = 'supplier_proposals';
  273. }
  274. if ($moduleobject == 'supplierorders') {
  275. $classfile = 'supplier_orders';
  276. }
  277. if ($moduleobject == 'supplierinvoices') {
  278. $classfile = 'supplier_invoices';
  279. }
  280. if ($moduleobject == 'ficheinter') {
  281. $classfile = 'interventions';
  282. }
  283. if ($moduleobject == 'interventions') {
  284. $classfile = 'interventions';
  285. }
  286. $dir_part_file = dol_buildpath('/'.$moduledirforclass.'/class/api_'.$classfile.'.class.php', 0, 2);
  287. $classname = ucwords($moduleobject);
  288. // Test rules on endpoints. For example:
  289. // $conf->global->API_ENDPOINT_RULES = 'endpoint1:1,endpoint2:1,...'
  290. if (!empty($conf->global->API_ENDPOINT_RULES)) {
  291. $listofendpoints = explode(',', $conf->global->API_ENDPOINT_RULES);
  292. $endpointisallowed = false;
  293. foreach ($listofendpoints as $endpointrule) {
  294. $tmparray = explode(':', $endpointrule);
  295. if (($classfile == $tmparray[0] || $classfile.'api' == $tmparray[0]) && $tmparray[1] == 1) {
  296. $endpointisallowed = true;
  297. break;
  298. }
  299. }
  300. if (! $endpointisallowed) {
  301. dol_syslog('The API with endpoint /'.$classfile.' is forbidden by config API_ENDPOINT_RULES', LOG_WARNING);
  302. print 'The API with endpoint /'.$classfile.' is forbidden by config API_ENDPOINT_RULES';
  303. header('HTTP/1.1 501 API is forbidden by API_ENDPOINT_RULES');
  304. //session_destroy();
  305. exit(0);
  306. }
  307. }
  308. dol_syslog('Search api file /'.$moduledirforclass.'/class/api_'.$classfile.'.class.php => dir_part_file='.$dir_part_file.' classname='.$classname);
  309. $res = false;
  310. if ($dir_part_file) {
  311. $res = include_once $dir_part_file;
  312. }
  313. if (!$res) {
  314. dol_syslog('Failed to make include_once '.$dir_part_file, LOG_WARNING);
  315. print 'API not found (failed to include API file)';
  316. header('HTTP/1.1 501 API not found (failed to include API file)');
  317. //session_destroy();
  318. exit(0);
  319. }
  320. if (class_exists($classname)) {
  321. $api->r->addAPIClass($classname);
  322. }
  323. }
  324. //var_dump($api->r->apiVersionMap);
  325. //exit;
  326. // 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.
  327. // If API_DISABLE_COMPRESSION is set, returnResponse is false => It use default handling so output result directly.
  328. $usecompression = (empty($conf->global->API_DISABLE_COMPRESSION) && !empty($_SERVER['HTTP_ACCEPT_ENCODING']));
  329. $foundonealgorithm = 0;
  330. if ($usecompression) {
  331. if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'br') !== false && is_callable('brotli_compress')) {
  332. $foundonealgorithm++;
  333. }
  334. if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'bz') !== false && is_callable('bzcompress')) {
  335. $foundonealgorithm++;
  336. }
  337. if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false && is_callable('gzencode')) {
  338. $foundonealgorithm++;
  339. }
  340. if (!$foundonealgorithm) {
  341. $usecompression = false;
  342. }
  343. }
  344. //dol_syslog('We found some compression algoithm: '.$foundonealgorithm.' -> usecompression='.$usecompression, LOG_DEBUG);
  345. Luracast\Restler\Defaults::$returnResponse = $usecompression;
  346. // Call API (we suppose we found it).
  347. // 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.
  348. $result = $api->r->handle();
  349. if (Luracast\Restler\Defaults::$returnResponse) {
  350. // We try to compress the data received data
  351. if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'br') !== false && is_callable('brotli_compress') && defined('BROTLI_TEXT')) {
  352. header('Content-Encoding: br');
  353. $result = brotli_compress($result, 11, constant('BROTLI_TEXT'));
  354. } elseif (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'bz') !== false && is_callable('bzcompress')) {
  355. header('Content-Encoding: bz');
  356. $result = bzcompress($result, 9);
  357. } elseif (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false && is_callable('gzencode')) {
  358. header('Content-Encoding: gzip');
  359. $result = gzencode($result, 9);
  360. } else {
  361. header('Content-Encoding: text/html');
  362. print "No compression method found. Try to disable compression by adding API_DISABLE_COMPRESSION=1";
  363. exit(0);
  364. }
  365. // Restler did not output data yet, we return it now
  366. echo $result;
  367. }
  368. //session_destroy();