index.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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'].$_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. // Enable the Restler API Explorer.
  137. // See https://github.com/Luracast/Restler-API-Explorer for more info.
  138. $api->r->addAPIClass('Luracast\\Restler\\Explorer');
  139. $api->r->setSupportedFormats('JsonFormat', 'XmlFormat', 'UploadFormat'); // 'YamlFormat'
  140. $api->r->addAuthenticationClass('DolibarrApiAccess', '');
  141. // Define accepted mime types
  142. UploadFormat::$allowedMimeTypes = array('image/jpeg', 'image/png', 'text/plain', 'application/octet-stream');
  143. // Restrict API to some IPs
  144. if (!empty($conf->global->API_RESTRICT_ON_IP)) {
  145. $allowedip = explode(' ', $conf->global->API_RESTRICT_ON_IP);
  146. $ipremote = getUserRemoteIP();
  147. if (!in_array($ipremote, $allowedip)) {
  148. dol_syslog('Remote ip is '.$ipremote.', not into list '.$conf->global->API_RESTRICT_ON_IP);
  149. print 'APIs are not allowed from the IP '.$ipremote;
  150. header('HTTP/1.1 503 API not allowed from your IP '.$ipremote);
  151. //session_destroy();
  152. exit(0);
  153. }
  154. }
  155. // Call Explorer file for all APIs definitions (this part is slow)
  156. 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')) {
  157. // Scan all API files to load them
  158. $listofapis = array();
  159. $modulesdir = dolGetModulesDirs();
  160. foreach ($modulesdir as $dir) {
  161. // Search available module
  162. dol_syslog("Scan directory ".$dir." for module descriptor files, then search for API files");
  163. $handle = @opendir(dol_osencode($dir));
  164. if (is_resource($handle)) {
  165. while (($file = readdir($handle)) !== false) {
  166. $regmod = array();
  167. if (is_readable($dir.$file) && preg_match("/^mod(.*)\.class\.php$/i", $file, $regmod)) {
  168. $module = strtolower($regmod[1]);
  169. $moduledirforclass = getModuleDirForApiClass($module);
  170. $modulenameforenabled = $module;
  171. if ($module == 'propale') {
  172. $modulenameforenabled = 'propal';
  173. }
  174. if ($module == 'supplierproposal') {
  175. $modulenameforenabled = 'supplier_proposal';
  176. }
  177. if ($module == 'ficheinter') {
  178. $modulenameforenabled = 'ficheinter';
  179. }
  180. dol_syslog("Found module file ".$file." - module=".$module." - modulenameforenabled=".$modulenameforenabled." - moduledirforclass=".$moduledirforclass);
  181. // Defined if module is enabled
  182. $enabled = true;
  183. if (empty($conf->$modulenameforenabled->enabled)) {
  184. $enabled = false;
  185. }
  186. if ($enabled) {
  187. // If exists, load the API class for enable module
  188. // Search files named api_<object>.class.php into /htdocs/<module>/class directory
  189. // @todo : use getElementProperties() function ?
  190. $dir_part = dol_buildpath('/'.$moduledirforclass.'/class/');
  191. $handle_part = @opendir(dol_osencode($dir_part));
  192. if (is_resource($handle_part)) {
  193. while (($file_searched = readdir($handle_part)) !== false) {
  194. if ($file_searched == 'api_access.class.php') {
  195. continue;
  196. }
  197. //$conf->global->MAIN_MODULE_API_LOGIN_DISABLED = 1;
  198. if ($file_searched == 'api_login.class.php' && !empty($conf->global->MAIN_MODULE_API_LOGIN_DISABLED)) {
  199. continue;
  200. }
  201. $regapi = array();
  202. if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i", $file_searched, $regapi)) {
  203. $classname = ucwords($regapi[1]);
  204. $classname = str_replace('_', '', $classname);
  205. require_once $dir_part.$file_searched;
  206. if (class_exists($classname.'Api')) {
  207. //dol_syslog("Found API by index.php: classname=".$classname."Api for module ".$dir." into ".$dir_part.$file_searched);
  208. $listofapis[strtolower($classname.'Api')] = $classname.'Api';
  209. } elseif (class_exists($classname)) {
  210. //dol_syslog("Found API by index.php: classname=".$classname." for module ".$dir." into ".$dir_part.$file_searched);
  211. $listofapis[strtolower($classname)] = $classname;
  212. } else {
  213. dol_syslog("We found an api_xxx file (".$file_searched.") but class ".$classname." does not exists after loading file", LOG_WARNING);
  214. }
  215. }
  216. }
  217. }
  218. }
  219. }
  220. }
  221. }
  222. }
  223. // Sort the classes before adding them to Restler.
  224. // The Restler API Explorer shows the classes in the order they are added and it's a mess if they are not sorted.
  225. asort($listofapis);
  226. foreach ($listofapis as $apiname => $classname) {
  227. $api->r->addAPIClass($classname, $apiname);
  228. }
  229. //var_dump($api->r);
  230. }
  231. // Call one APIs or one definition of an API
  232. $regbis = array();
  233. 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'))) {
  234. $moduleobject = $reg[1];
  235. if ($moduleobject == 'explorer') { // If we call page to explore details of a service
  236. $moduleobject = $regbis[2];
  237. }
  238. $moduleobject = strtolower($moduleobject);
  239. $moduledirforclass = getModuleDirForApiClass($moduleobject);
  240. // Load a dedicated API file
  241. dol_syslog("Load a dedicated API file moduleobject=".$moduleobject." moduledirforclass=".$moduledirforclass);
  242. $tmpmodule = $moduleobject;
  243. if ($tmpmodule != 'api') {
  244. $tmpmodule = preg_replace('/api$/i', '', $tmpmodule);
  245. }
  246. $classfile = str_replace('_', '', $tmpmodule);
  247. // Special cases that does not match name rules conventions
  248. if ($moduleobject == 'supplierproposals') {
  249. $classfile = 'supplier_proposals';
  250. }
  251. if ($moduleobject == 'supplierorders') {
  252. $classfile = 'supplier_orders';
  253. }
  254. if ($moduleobject == 'supplierinvoices') {
  255. $classfile = 'supplier_invoices';
  256. }
  257. if ($moduleobject == 'ficheinter') {
  258. $classfile = 'interventions';
  259. }
  260. if ($moduleobject == 'interventions') {
  261. $classfile = 'interventions';
  262. }
  263. $dir_part_file = dol_buildpath('/'.$moduledirforclass.'/class/api_'.$classfile.'.class.php', 0, 2);
  264. $classname = ucwords($moduleobject);
  265. // Test rules on endpoints. For example:
  266. // $conf->global->API_ENDPOINT_RULES = 'endpoint1:1,endpoint2:1,...'
  267. if (!empty($conf->global->API_ENDPOINT_RULES)) {
  268. $listofendpoints = explode(',', $conf->global->API_ENDPOINT_RULES);
  269. $endpointisallowed = false;
  270. foreach ($listofendpoints as $endpointrule) {
  271. $tmparray = explode(':', $endpointrule);
  272. if (($classfile == $tmparray[0] || $classfile.'api' == $tmparray[0]) && $tmparray[1] == 1) {
  273. $endpointisallowed = true;
  274. break;
  275. }
  276. }
  277. if (! $endpointisallowed) {
  278. dol_syslog('The API with endpoint /'.$classfile.' is forbidden by config API_ENDPOINT_RULES', LOG_WARNING);
  279. print 'The API with endpoint /'.$classfile.' is forbidden by config API_ENDPOINT_RULES';
  280. header('HTTP/1.1 501 API is forbidden by API_ENDPOINT_RULES');
  281. //session_destroy();
  282. exit(0);
  283. }
  284. }
  285. dol_syslog('Search api file /'.$moduledirforclass.'/class/api_'.$classfile.'.class.php => dir_part_file='.$dir_part_file.' classname='.$classname);
  286. $res = false;
  287. if ($dir_part_file) {
  288. $res = include_once $dir_part_file;
  289. }
  290. if (!$res) {
  291. dol_syslog('Failed to make include_once '.$dir_part_file, LOG_WARNING);
  292. print 'API not found (failed to include API file)';
  293. header('HTTP/1.1 501 API not found (failed to include API file)');
  294. //session_destroy();
  295. exit(0);
  296. }
  297. if (class_exists($classname)) {
  298. $api->r->addAPIClass($classname);
  299. }
  300. }
  301. //var_dump($api->r->apiVersionMap);
  302. //exit;
  303. // 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.
  304. // If API_DISABLE_COMPRESSION is set, returnResponse is false => It use default handling so output result directly.
  305. $usecompression = (empty($conf->global->API_DISABLE_COMPRESSION) && !empty($_SERVER['HTTP_ACCEPT_ENCODING']));
  306. $foundonealgorithm = 0;
  307. if ($usecompression) {
  308. if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'br') !== false && is_callable('brotli_compress')) {
  309. $foundonealgorithm++;
  310. }
  311. if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'bz') !== false && is_callable('bzcompress')) {
  312. $foundonealgorithm++;
  313. }
  314. if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false && is_callable('gzencode')) {
  315. $foundonealgorithm++;
  316. }
  317. if (!$foundonealgorithm) {
  318. $usecompression = false;
  319. }
  320. }
  321. //dol_syslog('We found some compression algoithm: '.$foundonealgorithm.' -> usecompression='.$usecompression, LOG_DEBUG);
  322. Luracast\Restler\Defaults::$returnResponse = $usecompression;
  323. // Call API (we suppose we found it).
  324. // 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.
  325. $result = $api->r->handle();
  326. if (Luracast\Restler\Defaults::$returnResponse) {
  327. // We try to compress the data received data
  328. if (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'br') !== false && is_callable('brotli_compress')) {
  329. header('Content-Encoding: br');
  330. $result = brotli_compress($result, 11, BROTLI_TEXT);
  331. } elseif (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'bz') !== false && is_callable('bzcompress')) {
  332. header('Content-Encoding: bz');
  333. $result = bzcompress($result, 9);
  334. } elseif (strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== false && is_callable('gzencode')) {
  335. header('Content-Encoding: gzip');
  336. $result = gzencode($result, 9);
  337. } else {
  338. header('Content-Encoding: text/html');
  339. print "No compression method found. Try to disable compression by adding API_DISABLE_COMPRESSION=1";
  340. exit(0);
  341. }
  342. // Restler did not output data yet, we return it now
  343. echo $result;
  344. }
  345. //session_destroy();