index.php 17 KB

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