index.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. /**
  20. * \defgroup api Module DolibarrApi
  21. * \brief API loader
  22. * Search files htdocs/<module>/class/api_<module>.class.php
  23. * \file htdocs/api/index.php
  24. */
  25. if (! defined('NOCSRFCHECK')) define('NOCSRFCHECK','1'); // Do not check anti CSRF attack test
  26. if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Do not check anti POST attack test
  27. if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU','1'); // If there is no need to load and show top and left menu
  28. if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML','1'); // If we don't need to load the html.form.class.php
  29. if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX','1'); // Do not load ajax.lib.php library
  30. if (! defined("NOLOGIN")) define("NOLOGIN",'1'); // If this page is public (can be called outside logged session)
  31. // Force entity if a value is provided into HTTP header. Otherwise, will use the entity of user of token used.
  32. if (! empty($_SERVER['HTTP_DOLAPIENTITY'])) define("DOLENTITY", (int) $_SERVER['HTTP_DOLAPIENTITY']);
  33. $res=0;
  34. if (! $res && file_exists("../main.inc.php")) $res=include '../main.inc.php';
  35. if (! $res) die("Include of main fails");
  36. require_once DOL_DOCUMENT_ROOT.'/includes/restler/framework/Luracast/Restler/AutoLoader.php';
  37. call_user_func(function () {
  38. $loader = Luracast\Restler\AutoLoader::instance();
  39. spl_autoload_register($loader);
  40. return $loader;
  41. });
  42. require_once DOL_DOCUMENT_ROOT.'/api/class/api.class.php';
  43. require_once DOL_DOCUMENT_ROOT.'/api/class/api_access.class.php';
  44. require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
  45. // Enable and test if module Api is enabled
  46. if (empty($conf->global->MAIN_MODULE_API))
  47. {
  48. $langs->load("admin");
  49. dol_syslog("Call Dolibarr API interfaces with module REST disabled");
  50. print $langs->trans("WarningModuleNotActive",'Api').'.<br><br>';
  51. print $langs->trans("ToActivateModule");
  52. exit;
  53. }
  54. // Test if explorer is not disabled
  55. if (preg_match('/api\/index\.php\/explorer/', $_SERVER["PHP_SELF"]) && ! empty($conf->global->API_EXPLORER_DISABLED))
  56. {
  57. $langs->load("admin");
  58. dol_syslog("Call Dolibarr API interfaces with module REST disabled");
  59. print $langs->trans("WarningAPIExplorerDisabled").'.<br><br>';
  60. exit;
  61. }
  62. // This 2 lines are usefull only if we want to exclude some Urls from the explorer
  63. //use Luracast\Restler\Explorer;
  64. //Explorer::$excludedPaths = array('/categories');
  65. // Analyze URLs
  66. // index.php/explorer do a redirect to index.php/explorer/
  67. // index.php/explorer/ called by swagger to build explorer page
  68. // index.php/explorer/.../....png|.css|.js called by swagger for resources to build explorer page
  69. // index.php/explorer/resources.json called by swagger to get list of all services
  70. // index.php/explorer/resources.json/xxx called by swagger to get detail of services xxx
  71. // index.php/xxx called by any REST client to run API
  72. preg_match('/index\.php\/([^\/]+)(.*)$/', $_SERVER["PHP_SELF"], $reg);
  73. // .../index.php/categories?sortfield=t.rowid&sortorder=ASC
  74. // Set the flag to say to refresh (when we reload the explorer, production must be for API call only)
  75. $refreshcache=false;
  76. 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'))
  77. {
  78. $refreshcache=true;
  79. }
  80. $api = new DolibarrApi($db, '', $refreshcache);
  81. //var_dump($api->r->apiVersionMap);
  82. // Enable the Restler API Explorer.
  83. // See https://github.com/Luracast/Restler-API-Explorer for more info.
  84. $api->r->addAPIClass('Luracast\\Restler\\Explorer');
  85. $api->r->setSupportedFormats('JsonFormat', 'XmlFormat', 'UploadFormat'); // 'YamlFormat'
  86. $api->r->addAuthenticationClass('DolibarrApiAccess','');
  87. // Define accepted mime types
  88. UploadFormat::$allowedMimeTypes = array('image/jpeg', 'image/png', 'text/plain', 'application/octet-stream');
  89. // Call Explorer file for all APIs definitions
  90. 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'))
  91. {
  92. // Scan all API files to load them
  93. $listofapis = array();
  94. $modulesdir = dolGetModulesDirs();
  95. foreach ($modulesdir as $dir)
  96. {
  97. // Search available module
  98. dol_syslog("Scan directory ".$dir." for module descriptor files, then search for API files");
  99. $handle=@opendir(dol_osencode($dir));
  100. if (is_resource($handle))
  101. {
  102. while (($file = readdir($handle))!==false)
  103. {
  104. if (is_readable($dir.$file) && preg_match("/^mod(.*)\.class\.php$/i",$file,$regmod))
  105. {
  106. $module = strtolower($regmod[1]);
  107. $moduledirforclass = getModuleDirForApiClass($module);
  108. $modulenameforenabled = $module;
  109. if ($module == 'propale') { $modulenameforenabled='propal'; }
  110. if ($module == 'supplierproposal') { $modulenameforenabled='supplier_proposal'; }
  111. if ($module == 'ficheinter') { $modulenameforenabled='ficheinter'; }
  112. dol_syslog("Found module file ".$file." - module=".$module." - modulenameforenabled=".$modulenameforenabled." - moduledirforclass=".$moduledirforclass);
  113. // Defined if module is enabled
  114. $enabled=true;
  115. if (empty($conf->$modulenameforenabled->enabled)) $enabled=false;
  116. if ($enabled)
  117. {
  118. // If exists, load the API class for enable module
  119. // Search files named api_<object>.class.php into /htdocs/<module>/class directory
  120. // @todo : use getElementProperties() function ?
  121. $dir_part = dol_buildpath('/'.$moduledirforclass.'/class/');
  122. $handle_part=@opendir(dol_osencode($dir_part));
  123. if (is_resource($handle_part))
  124. {
  125. while (($file_searched = readdir($handle_part))!==false)
  126. {
  127. if ($file_searched == 'api_access.class.php') continue;
  128. if (is_readable($dir_part.$file_searched) && preg_match("/^api_(.*)\.class\.php$/i",$file_searched,$regapi))
  129. {
  130. $classname = ucwords($regapi[1]);
  131. $classname = str_replace('_', '', $classname);
  132. require_once $dir_part.$file_searched;
  133. if (class_exists($classname.'Api'))
  134. {
  135. //dol_syslog("Found API by index.php: classname=".$classname."Api for module ".$dir." into ".$dir_part.$file_searched);
  136. $listofapis[strtolower($classname.'Api')] = $classname.'Api';
  137. }
  138. elseif (class_exists($classname))
  139. {
  140. //dol_syslog("Found API by index.php: classname=".$classname." for module ".$dir." into ".$dir_part.$file_searched);
  141. $listofapis[strtolower($classname)] = $classname;
  142. }
  143. else
  144. {
  145. dol_syslog("We found an api_xxx file (".$file_searched.") but class ".$classname." does not exists after loading file", LOG_WARNING);
  146. }
  147. }
  148. }
  149. }
  150. }
  151. }
  152. }
  153. }
  154. }
  155. // Sort the classes before adding them to Restler.
  156. // The Restler API Explorer shows the classes in the order they are added and it's a mess if they are not sorted.
  157. asort($listofapis);
  158. foreach ($listofapis as $apiname => $classname)
  159. {
  160. $api->r->addAPIClass($classname, $apiname);
  161. }
  162. //var_dump($api->r);
  163. }
  164. // Call one APIs or one definition of an API
  165. 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')))
  166. {
  167. $module = $reg[1];
  168. if ($module == 'explorer') // If we call page to explore details of a service
  169. {
  170. $module = $regbis[2];
  171. }
  172. $module=strtolower($module);
  173. $moduledirforclass = getModuleDirForApiClass($module);
  174. // Load a dedicated API file
  175. dol_syslog("Load a dedicated API file module=".$module." moduledirforclass=".$moduledirforclass);
  176. $tmpmodule = $module;
  177. if ($tmpmodule != 'api')
  178. $tmpmodule = preg_replace('/api$/i', '', $tmpmodule);
  179. $classfile = str_replace('_', '', $tmpmodule);
  180. if ($module == 'supplierproposals')
  181. $classfile = 'supplier_proposals';
  182. if ($module == 'supplierorders')
  183. $classfile = 'supplier_orders';
  184. if ($module == 'supplierinvoices')
  185. $classfile = 'supplier_invoices';
  186. if ($module == 'ficheinter')
  187. $classfile = 'interventions';
  188. if ($module == 'interventions')
  189. $classfile = 'interventions';
  190. $dir_part_file = dol_buildpath('/' . $moduledirforclass . '/class/api_' . $classfile . '.class.php', 0, 2);
  191. $classname = ucwords($module);
  192. dol_syslog('Search /' . $moduledirforclass . '/class/api_' . $classfile . '.class.php => dir_part_file=' . $dir_part_file . ' classname=' . $classname);
  193. $res = false;
  194. if ($dir_part_file)
  195. $res = include_once $dir_part_file;
  196. if (! $res) {
  197. print 'API not found (failed to include API file)';
  198. header('HTTP/1.1 501 API not found (failed to include API file)');
  199. exit(0);
  200. }
  201. if (class_exists($classname))
  202. $api->r->addAPIClass($classname);
  203. }
  204. // TODO If not found, redirect to explorer
  205. //var_dump($api->r->apiVersionMap);
  206. //exit;
  207. // Call API (we suppose we found it)
  208. $api->r->handle();