Api.class.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. <?php
  2. /**
  3. * Classe de gestion des API (REST).
  4. * @author Valentin CARRUESCO
  5. * @category Plugin
  6. * @license MIT
  7. */
  8. class Api{
  9. public $slug,$description;
  10. function __construct($slug=null,$description=null){
  11. if(isset($slug)) $this->slug = $slug;
  12. if(isset($description)) $this->description = $description;
  13. $this->route = array();
  14. return $this;
  15. }
  16. function route($slug = null,$description = null,$method = null,$callback){
  17. $route = new ApiRoute($slug,$description,$method,$callback);
  18. $this->route[$route->slug][$method] = $route;
  19. }
  20. function register(){
  21. Plugin::addHook('api',function(&$apis){
  22. $apis[$this->slug] = $this;
  23. });
  24. }
  25. //retourne la liste des headers de la requete courante (clé normalisées)
  26. public static function headers(){
  27. $headers = array();
  28. foreach(getallheaders() as $key=>$value) $headers[mb_strtolower($key)] = $value;
  29. return $headers;
  30. }
  31. //définis si la requete courante est via api ou en http classique (ou autre)
  32. public static function requested(){
  33. return preg_match('/\/api\/v[0-9]*\//i', $_SERVER['REQUEST_URI']);
  34. }
  35. //SI un JWToken est fournis en header Authorization: Bearer <token>, on récupere la session associée
  36. //si la session a expirée on la relance
  37. public static function token_session(){
  38. if(php_sapi_name() == 'cli') return;
  39. if(!self::requested()) return;
  40. $headers = self::headers();
  41. if(!isset($headers['authorization'])) return;
  42. try{
  43. $authorization = explode(' ',$headers['authorization']);
  44. if(count($authorization)!=2 || strtolower($authorization[0])!='bearer') throw new Exception("Bad Authorization header (required Authorization: Bearer <JWToken>)",403);
  45. global $conf,$myUser;
  46. $token = JWToken::parse(trim($authorization[1]),$conf->get('jwtauth_secret'));
  47. //si une session est en cours
  48. if(session_status() == PHP_SESSION_ACTIVE){
  49. //si la session courant a le mauvais id (ex une session anonyme ou expirée) on la détruit et on la recréé avec le bon id
  50. if( session_id() !=$token['attributes']['session_id']){
  51. session_destroy();
  52. session_id($token['attributes']['session_id']);
  53. session_start();
  54. }
  55. }else{
  56. //si aucun session en cours, on la créé avec le bon id
  57. session_id($token['attributes']['session_id']);
  58. session_start();
  59. }
  60. if(!isset($_SESSION['currentUser'])) throw new Exception('Token session has expired',498);
  61. }catch(Exception $e){
  62. $response['error'] = $e->getMessage();
  63. $response['errorCode'] = $e->getCode();
  64. echo json_encode($response);
  65. exit;
  66. }
  67. }
  68. public static function run(){
  69. global $_,$myUser;
  70. $response = array();
  71. try{
  72. set_error_handler(function( $errno , $errstr , $errfile , $errline){
  73. throw new Exception("Error ".$errno." Processing Request : ".$errfile." => ".$errstr.' L'.$errline, 500);
  74. });
  75. // register_shutdown_function(function(){
  76. // $error = error_get_last();
  77. // throw new Exception("Error 0 Processing Request ".$error['file'], 500);
  78. // });
  79. $command = explode('/',$_['command']);
  80. if(count($command)<1) throw new Exception("Unspecified API");
  81. $headers = self::headers();
  82. //basic auth (deprecated, utiliser plutot JWToken et Authorization Bearer)
  83. if(isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])){
  84. $user = User::check($_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW']);
  85. if(!$user) throw new Exception('Le compte spécifié est inexistant');
  86. $myUser = $user;
  87. }
  88. $request = array(
  89. 'version' =>array_shift($command),
  90. 'module' =>array_shift($command),
  91. 'route' =>array_shift($command),
  92. 'body' =>file_get_contents("php://input"),
  93. 'headers' =>$headers,
  94. 'method' => strtoupper($_SERVER['REQUEST_METHOD']),
  95. 'parameters' => $_,
  96. 'pathes' => array_filter($command)
  97. );
  98. $code = 200;
  99. $headers = array(
  100. 'Content-Type: application/json'
  101. );
  102. $apis = array();
  103. Plugin::callHook('api',array(&$apis));
  104. //format de l'url : /api/v{version}/
  105. if(!isset($request['version']) || !is_numeric(substr($request['version'],1)) || substr($request['version'], 0,1)!='v') throw new Exception("Api version is missing or invalid, specify ".ROOT_URL."/api/{version} for valid requests", 404);
  106. if($request['module'] == 'schema'){
  107. if(!$myUser->connected()) throw new Exception("Credentials are missing",401);
  108. foreach ($apis as $api) {
  109. $routes= array();
  110. foreach($api->route as $route){
  111. foreach($route as $method=>$infos){
  112. if(!isset($routes[$infos->slug])) $routes[$infos->slug] = array() ;
  113. $routes[$infos->slug][] = $infos->method.' '.$api->slug .'/'.$infos->pattern .': '. $infos->description ;
  114. }
  115. }
  116. $response[] = array( $api->slug => $api->description,'routes'=> $routes);
  117. }
  118. }else{
  119. if(!isset($apis[$request['module']])) throw new Exception("Api '".$request['module']."' is missing, see ".ROOT_URL."/api/{version}/schema for available calls", 404);
  120. $api = $apis[$request['module']];
  121. if(!isset($api->route[$request['route']])) throw new Exception("Route '".$api->slug.'/'.$request['route']."' is missing, see ".ROOT_URL."/api/schema?pretty for available calls", 404);
  122. $route = $api->route[$request['route']];
  123. if(!isset($route[$request['method']])) throw new Exception("Method ".$request['method']." '".$api->slug.'/'.$route->slug."' is not allowed", 405);
  124. $method = $route[$request['method']];
  125. $callback = $method->callback;
  126. $callback($request,$response);
  127. if(isset($response['code'])) $code = $response['code'];
  128. if(isset($response['headers'])) $headers = array_merge($headers,$response['headers']);
  129. unset($response['code']);
  130. unset($response['headers']);
  131. }
  132. }catch(Exception $e){
  133. $response['error'] = $e->getMessage();
  134. $code = $e->getCode();
  135. if(empty($code)) $code = 0;
  136. $response['errorCode'] = $code;
  137. }
  138. $codes = array(
  139. 200 => 'HTTP/1.1 200 Ok',
  140. 201 => 'HTTP/1.1 201 Created',
  141. 204 => 'HTTP/1.1 204 No Content',
  142. 207 => 'HTTP/1.1 207 Multi-Status',
  143. 400 => 'HTTP/1.0 400 Bad Request',
  144. 401 => 'HTTP/1.0 401 Unauthorized',
  145. 403 => 'HTTP/1.1 403 Forbidden',
  146. 404 => 'HTTP/1.1 404 Not Found',
  147. 404 => 'HTTP/1.1 405 Method Not Allowed',
  148. 406 => 'HTTP/1.1 406 Not acceptable',
  149. 409 => 'HTTP/1.1 409 Conflict',
  150. 415 => 'HTTP/1.1 415 Unsupported Media Type',
  151. 423 => 'HTTP/1.1 423 Locked',
  152. 500 => 'HTTP/1.1 500 Internal Server Error',
  153. 501 => 'HTTP/1.1 501 Not implemented',
  154. 0 => 'HTTP/1.1 0 Unknown Error',
  155. );
  156. if (ob_get_length()) ob_end_clean();
  157. header(isset($codes[$code]) ? $codes[$code] : $codes[0]);
  158. foreach ($headers as $header) {
  159. header($header);
  160. }
  161. if(isset($_['pretty'])){
  162. echo json_encode($response,JSON_PRETTY_PRINT);
  163. }else{
  164. echo json_encode($response);
  165. }
  166. exit();
  167. }
  168. }
  169. class ApiRoute{
  170. public $slug,$description,$callback,$method,$pathes,$parameters,$pattern;
  171. function __construct($slug='default',$description='No description',$method='GET',$callback){
  172. $this->pattern = $slug;
  173. $infos = explode('?',$slug);
  174. if(isset($infos[1])) $this->parameters = $infos[1];
  175. $infos = explode('/',$infos[0]);
  176. $this->slug = array_shift($infos);
  177. $this->pathes = $infos;
  178. $this->description = $description;
  179. $this->method = $method;
  180. $this->callback = $callback;
  181. }
  182. }
  183. ?>