index.php 17 KB

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