Api.class.php 7.1 KB

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