api de gestion de ticket, basé sur php-crud-api. Le but est de décorrélé les outils de gestion des données, afin
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

api.php 9.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. <?php
  2. class MySQL_CRUD_API {
  3. private $method;
  4. private $request;
  5. private $mysqli;
  6. private $database;
  7. private $whitelist;
  8. private $blacklist;
  9. private function connectDatabase($hostname,$username,$password,$database) {
  10. $mysqli = new mysqli($hostname,$username,$password,$database);
  11. if ($mysqli->connect_errno) {
  12. die('Connect failed: '.$mysqli->connect_error);
  13. }
  14. return $mysqli;
  15. }
  16. private function mapMethodToAction($method,$request) {
  17. switch ($method) {
  18. case 'GET': return count($request)>1?'read':'list';
  19. case 'PUT': return 'update';
  20. case 'POST': return 'create';
  21. case 'DELETE': return 'delete';
  22. default: $this->exitWith404();
  23. }
  24. }
  25. private function parseRequestParameter($request,$position,$characters,$default) {
  26. $value = isset($request[$position])?$request[$position]:$default;
  27. return $characters?preg_replace("/[^$characters]/",'',$value):$value;
  28. }
  29. private function parseGetParameter($name,$characters,$default) {
  30. $value = isset($_GET[$name])?$_GET[$name]:$default;
  31. return $characters?preg_replace("/[^$characters]/",'',$value):$value;
  32. }
  33. private function applyWhitelist($table,$action,$list) {
  34. if ($list===false) return $table;
  35. $list = array_filter($list, function($actions){
  36. return strpos($actions,$action[0])!==false;
  37. });
  38. return array_intersect($table, array_keys($list));
  39. }
  40. private function applyBlacklist($table,$action,$list) {
  41. if ($list===false) return $table;
  42. $list = array_filter($list, function($actions) use ($action) {
  43. return strpos($actions,$action[0])!==false;
  44. });
  45. return array_diff($table, array_keys($list));
  46. }
  47. private function applyWhitelistAndBlacklist($table, $action, $whitelist, $blacklist) {
  48. $table = $this->applyWhitelist($table, $action, $whitelist);
  49. $table = $this->applyBlacklist($table, $action, $blacklist);
  50. if (empty($table)) $this->exitWith404();
  51. return $table;
  52. }
  53. private function processTableParameter($table,$database,$mysqli) {
  54. $tablelist = explode(',',$table);
  55. $tables = array();
  56. foreach ($tablelist as $table) {
  57. $table = str_replace('*','%',$table);
  58. if ($result = $mysqli->query("SELECT `TABLE_NAME` FROM `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_NAME` LIKE '$table' AND `TABLE_SCHEMA` = '$database'")) {
  59. while ($row = $result->fetch_row()) $tables[] = $row[0];
  60. $result->close();
  61. }
  62. }
  63. return $tables;
  64. }
  65. private function findPrimaryKey($table,$database,$mysqli) {
  66. $keys = array();
  67. if ($result = $mysqli->query("SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `COLUMN_KEY` = 'PRI' AND `TABLE_NAME` = '$table[0]' AND `TABLE_SCHEMA` = '$database'")) {
  68. while ($row = $result->fetch_row()) $keys[] = $row[0];
  69. $result->close();
  70. }
  71. return count($keys)?$keys[0]:false;
  72. }
  73. private function exitWith404() {
  74. die(header("Content-Type:",true,404));
  75. }
  76. private function startOutput($callback) {
  77. if ($callback) {
  78. header("Content-Type: application/javascript");
  79. echo $callback.'(';
  80. } else {
  81. header("Content-Type: application/json");
  82. }
  83. }
  84. private function endOutput($callback) {
  85. if ($callback) {
  86. echo ');';
  87. }
  88. }
  89. private function processKeyParameter($key,$table,$database,$mysqli) {
  90. if ($key) {
  91. $key = array($key,$this->findPrimaryKey($table,$database,$mysqli));
  92. if ($key[1]===false) $this->exitWith404();
  93. }
  94. return $key;
  95. }
  96. private function processFilterParameter($filter,$match,$mysqli) {
  97. if ($filter) {
  98. $filter = explode(':',$filter,2);
  99. if (count($filter)==2) {
  100. $filter[0] = preg_replace('/[^a-zA-Z0-9\-_]/','',$filter[0]);
  101. if ($match=='in') {
  102. $filter[1] = implode("','",array_map(function($v){ return preg_replace('/[^a-zA-Z0-9\-]/','',$v); },explode(',',$filter[1])));
  103. } else {
  104. $filter[1] = $mysqli->real_escape_string($filter[1]);
  105. }
  106. $filter[2] = 'LIKE';
  107. if ($match=='any'||$match=='start') $filter[1] .= '%';
  108. if ($match=='any'||$match=='end') $filter[1] = '%'.$filter[1];
  109. if ($match=='exact') $filter[2] = '=';
  110. if ($match=='lower') $filter[2] = '<';
  111. if ($match=='upto') $filter[2] = '<=';
  112. if ($match=='from') $filter[2] = '>=';
  113. if ($match=='higher') $filter[2] = '>';
  114. if ($match=='in') $filter[2] = 'IN';
  115. $filter[1]="'$filter[1]'";
  116. if ($filter[2]=='IN') $filter[1]="($filter[1])";
  117. } else {
  118. $filter = false;
  119. }
  120. }
  121. return $filter;
  122. }
  123. private function processPageParameter($page) {
  124. if ($page) {
  125. $page = explode(',',$page,2);
  126. if (count($page)<2) $page[1]=20;
  127. $page[0] = ($page[0]-1)*$page[1];
  128. }
  129. return $page;
  130. }
  131. private function retrieveObject($key,$table,$mysqli) {
  132. if (!$key) return false;
  133. if ($result = $mysqli->query("SELECT * FROM `$table[0]` WHERE `$key[1]` = '$key[0]'")) {
  134. $object = $result->fetch_assoc();
  135. $result->close();
  136. }
  137. return $object;
  138. }
  139. private function createObject($input,$table,$mysqli) {
  140. if (!$input) return false;
  141. $keys = implode('`,`',array_map(function($v){ return preg_replace('/[^a-zA-Z0-9\-_]/','',$v); },array_keys((array)$input)));
  142. $values = implode("','",array_map(function($v) use ($mysqli){ return $mysqli->real_escape_string($v); },array_values((array)$input)));
  143. $mysqli->query("INSERT INTO `$table[0]` (`$keys`) VALUES ('$values')");
  144. return $mysqli->insert_id;
  145. }
  146. private function updateObject($key,$input,$table,$mysqli) {
  147. if (!$input) return false;
  148. $sql = "UPDATE `$table[0]` SET ";
  149. foreach (array_keys((array)$input) as $i=>$k) {
  150. if ($i) $sql .= ",";
  151. $v = $input->$k;
  152. $sql .= "`$k`='$v'";
  153. }
  154. $sql .= " WHERE `$key[1]`='$key[0]'";
  155. $mysqli->query($sql);
  156. return $mysqli->affected_rows;
  157. }
  158. private function deleteObject($key,$table,$mysqli) {
  159. $mysqli->query("DELETE FROM `$table[0]` WHERE `$key[1]`='$key[0]'");
  160. return $mysqli->affected_rows;
  161. }
  162. private function getParameters($method, $request, $database, $whitelist, $blacklist, $mysqli) {
  163. $action = $this->mapMethodToAction($method, $request);
  164. $table = $this->parseRequestParameter($request, 0, 'a-zA-Z0-9\-_*,', '*');
  165. $key = $this->parseRequestParameter($request, 1, 'a-zA-Z0-9\-,', false); // auto-increment or uuid
  166. $callback = $this->parseGetParameter('callback', 'a-zA-Z0-9\-_', false);
  167. $page = $this->parseGetParameter('page', '0-9,', false);
  168. $filter = $this->parseGetParameter('filter', false, 'start');
  169. $match = $this->parseGetParameter('match', 'a-z', false);
  170. $table = $this->processTableParameter($table,$database,$mysqli);
  171. $key = $this->processKeyParameter($key,$table,$database,$mysqli);
  172. $filter = $this->processFilterParameter($filter,$match,$mysqli);
  173. $page = $this->processPageParameter($page);
  174. $table = $this->applyWhitelistAndBlacklist($table,$action,$whitelist,$blacklist);
  175. $object = $this->retrieveObject($key,$table,$mysqli);
  176. $input = json_decode(file_get_contents('php://input'));
  177. return compact('action','table','key','callback','page','filter','match','mysqli','object','input');
  178. }
  179. private function listCommand($parameters) {
  180. extract($parameters);
  181. $this->startOutput($callback);
  182. echo '{';
  183. $tables = $table;
  184. foreach ($tables as $t=>$table) {
  185. $count = false;
  186. if ($t>0) echo ',';
  187. echo '"'.$table.'":{';
  188. if ($t==0 && is_array($page)) {
  189. $sql = "SELECT COUNT(*) FROM `$table`";
  190. if (is_array($filter)) $sql .= " WHERE `$filter[0]` $filter[2] $filter[1]";
  191. if ($result = $mysqli->query($sql)) {
  192. $pages = $result->fetch_row();
  193. $count = $pages[0];
  194. }
  195. }
  196. echo '"columns":';
  197. $sql = "SELECT * FROM `$table`";
  198. if ($t==0 && is_array($filter)) $sql .= " WHERE `$filter[0]` $filter[2] $filter[1]";
  199. if ($t==0 && is_array($page)) $sql .= " LIMIT $page[1] OFFSET $page[0]";
  200. if ($result = $mysqli->query($sql)) {
  201. $fields = array();
  202. foreach ($result->fetch_fields() as $field) $fields[] = $field->name;
  203. echo json_encode($fields);
  204. echo ',"records":[';
  205. $first_row = true;
  206. while ($row = $result->fetch_row()) {
  207. if ($first_row) $first_row = false;
  208. else echo ',';
  209. echo json_encode($row);
  210. }
  211. $result->close();
  212. }
  213. if ($count) echo ',"results":'.$count;
  214. echo ']}';
  215. }
  216. echo '}';
  217. $this->endOutput($callback);
  218. }
  219. private function readCommand($parameters) {
  220. extract($parameters);
  221. if (!$object) $this->exitWith404();
  222. $this->startOutput($callback);
  223. echo json_encode($object);
  224. $this->endOutput($callback);
  225. }
  226. private function createCommand($parameters) {
  227. extract($parameters);
  228. if (!$input) $this->exitWith404();
  229. $this->startOutput($callback);
  230. echo json_encode($this->createObject($input,$table,$mysqli));
  231. $this->endOutput($callback);
  232. }
  233. private function updateCommand($parameters) {
  234. extract($parameters);
  235. if (!$input) $this->exitWith404();
  236. $this->startOutput($callback);
  237. echo json_encode($this->updateObject($key,$input,$table,$mysqli));
  238. $this->endOutput($callback);
  239. }
  240. private function deleteCommand($parameters) {
  241. extract($parameters);
  242. $this->startOutput($callback);
  243. echo json_encode($this->deleteObject($key,$table,$mysqli));
  244. $this->endOutput($callback);
  245. }
  246. public function __construct($hostname,$username,$password,$database,$whitelist,$blacklist) {
  247. $this->method = $_SERVER['REQUEST_METHOD'];
  248. $this->request = explode("/", substr(@$_SERVER['PATH_INFO'], 1));
  249. $this->mysqli = $this->connectDatabase($hostname,$username,$password,$database);
  250. $this->database = $database;
  251. $this->whitelist = $whitelist;
  252. $this->blacklist = $blacklist;
  253. }
  254. public function executeCommand() {
  255. $parameters = $this->getParameters($this->method, $this->request, $this->database, $this->whitelist, $this->blacklist, $this->mysqli);
  256. switch($parameters['action']){
  257. case 'list': $this->listCommand($parameters); break;
  258. case 'read': $this->readCommand($parameters); break;
  259. case 'create': $this->readCommand($parameters); break;
  260. case 'update': $this->readCommand($parameters); break;
  261. case 'delete': $this->readCommand($parameters); break;
  262. }
  263. }
  264. }
  265. //$api = new MySQL_CRUD_API("localhost","user","pass","db",false,array("users"=>"crudl"));
  266. //$api->executeCommand();