Api.class.php 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. <?php
  2. /**
  3. * Classe de gestion des API (REST).
  4. * @author Valentin CARRUESCO
  5. * @category Plugin
  6. * @license copyright
  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. public static function run(){
  26. global $_,$myUser;
  27. $response = array();
  28. try{
  29. /*set_error_handler(function( $errno , $errstr , $errfile , $errline){
  30. throw new Exception("Error ".$errno." Processing Request ".$errfile.$errstr, 500);
  31. });
  32. register_shutdown_function(function( $errno , $errstr , $errfile , $errline){
  33. $error = error_get_last();
  34. throw new Exception("Error ".E_CORE_ERROR." Processing Request ".$error['file'], 500);
  35. });*/
  36. $command = explode('/',$_['command']);
  37. if(count($command)<1) throw new Exception("Unspecified API");
  38. $headers = apache_request_headers();
  39. //basic auth
  40. if(isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])){
  41. $user = User::check($_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW']);
  42. if(!$user) throw new Exception('Le compte spécifié est inexistant');
  43. $myUser = $user;
  44. }
  45. $request = array(
  46. 'version' =>array_shift($command),
  47. 'module' =>array_shift($command),
  48. 'route' =>array_shift($command),
  49. 'body' =>file_get_contents("php://input"),
  50. 'method' => strtoupper($_SERVER['REQUEST_METHOD']),
  51. 'parameters' => $_,
  52. 'pathes' => array_filter($command)
  53. );
  54. $code = 200;
  55. $headers = array(
  56. 'Content-Type: application/json'
  57. );
  58. $apis = array();
  59. Plugin::callHook('api',array(&$apis));
  60. //format de l'url : /api/v{version}/
  61. 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);
  62. if($request['module'] == 'schema'){
  63. foreach ($apis as $api) {
  64. $routes= array();
  65. foreach($api->route as $route){
  66. foreach($route as $method=>$infos){
  67. if(!isset($routes[$infos->slug])) $routes[$infos->slug] = array() ;
  68. $routes[$infos->slug][] = $infos->method.' '.$api->slug .'/'.$infos->pattern .': '. $infos->description ;
  69. }
  70. }
  71. $response[] = array( $api->slug => $api->description,'routes'=> $routes);
  72. }
  73. }else{
  74. if(!isset($apis[$request['module']])) throw new Exception("Api '".$request['module']."' is missing, see ".ROOT_URL."/api/schema for available calls", 404);
  75. $api = $apis[$request['module']];
  76. 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);
  77. $route = $api->route[$request['route']];
  78. if(!isset($route[$request['method']])) throw new Exception("Method ".$request['method']." '".$api->slug.'/'.$route->slug."' is not allowed", 405);
  79. $method = $route[$request['method']];
  80. $callback = $method->callback;
  81. $callback($request,$response);
  82. if(isset($response['code'])) $code = $response['code'];
  83. if(isset($response['headers'])) $headers = array_merge($headers,$response['headers']);
  84. unset($response['code']);
  85. unset($response['headers']);
  86. }
  87. }catch(Exception $e){
  88. $response['error'] = $e->getMessage();
  89. $code = $e->getCode();
  90. if(empty($code) || $code==0) $code = 666;
  91. }
  92. $codes = array(
  93. 200 => 'HTTP/1.1 200 Ok',
  94. 201 => 'HTTP/1.1 201 Created',
  95. 204 => 'HTTP/1.1 204 No Content',
  96. 207 => 'HTTP/1.1 207 Multi-Status',
  97. 400 => 'HTTP/1.0 400 Bad Request',
  98. 401 => 'HTTP/1.0 401 Unauthorized',
  99. 403 => 'HTTP/1.1 403 Forbidden',
  100. 404 => 'HTTP/1.1 404 Not Found',
  101. 404 => 'HTTP/1.1 405 Method Not Allowed',
  102. 406 => 'HTTP/1.1 406 Not acceptable',
  103. 409 => 'HTTP/1.1 409 Conflict',
  104. 415 => 'HTTP/1.1 415 Unsupported Media Type',
  105. 423 => 'HTTP/1.1 423 Locked',
  106. 500 => 'HTTP/1.1 500 Internal Server Error',
  107. 501 => 'HTTP/1.1 501 Not implemented',
  108. 666 => 'HTTP/1.1 666 Welcome to Hell mate!',
  109. );
  110. if (ob_get_length()) ob_end_clean();
  111. header(isset($codes[$code]) ? $codes[$code] : $codes[666]);
  112. foreach ($headers as $header) {
  113. header($header);
  114. }
  115. if(isset($_['pretty'])){
  116. echo json_encode($response,JSON_PRETTY_PRINT);
  117. }else{
  118. echo json_encode($response);
  119. }
  120. exit();
  121. }
  122. }
  123. class ApiRoute{
  124. public $slug,$description,$callback,$method,$pathes,$parameters,$pattern;
  125. function __construct($slug='default',$description='No description',$method='GET',$callback){
  126. $this->pattern = $slug;
  127. $infos = explode('?',$slug);
  128. if(isset($infos[1])) $this->parameters = $infos[1];
  129. $infos = explode('/',$infos[0]);
  130. $this->slug = array_shift($infos);
  131. $this->pathes = $infos;
  132. $this->description = $description;
  133. $this->method = $method;
  134. $this->callback = $callback;
  135. }
  136. }
  137. ?>