index.php 17 KB

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