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 61KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953
  1. <?php
  2. //var_dump($_SERVER['REQUEST_METHOD'],$_SERVER['PATH_INFO']); die();
  3. interface DatabaseInterface {
  4. public function getSql($name);
  5. public function connect($hostname,$username,$password,$database,$port,$socket,$charset);
  6. public function query($sql,$params);
  7. public function fetchAssoc($result);
  8. public function fetchRow($result);
  9. public function insertId($result);
  10. public function affectedRows($result);
  11. public function close($result);
  12. public function fetchFields($table);
  13. public function addLimitToSql($sql,$limit,$offset);
  14. public function likeEscape($string);
  15. public function isBinaryType($field);
  16. public function base64Encode($string);
  17. public function getDefaultCharset();
  18. }
  19. class MySQL implements DatabaseInterface {
  20. protected $db;
  21. protected $queries;
  22. public function __construct() {
  23. $this->queries = array(
  24. 'list_tables'=>'SELECT
  25. "TABLE_NAME","TABLE_COMMENT"
  26. FROM
  27. "INFORMATION_SCHEMA"."TABLES"
  28. WHERE
  29. "TABLE_SCHEMA" = ?',
  30. 'reflect_table'=>'SELECT
  31. "TABLE_NAME"
  32. FROM
  33. "INFORMATION_SCHEMA"."TABLES"
  34. WHERE
  35. "TABLE_NAME" COLLATE \'utf8_bin\' = ? AND
  36. "TABLE_SCHEMA" = ?',
  37. 'reflect_pk'=>'SELECT
  38. "COLUMN_NAME"
  39. FROM
  40. "INFORMATION_SCHEMA"."COLUMNS"
  41. WHERE
  42. "COLUMN_KEY" = \'PRI\' AND
  43. "TABLE_NAME" = ? AND
  44. "TABLE_SCHEMA" = ?',
  45. 'reflect_belongs_to'=>'SELECT
  46. "TABLE_NAME","COLUMN_NAME",
  47. "REFERENCED_TABLE_NAME","REFERENCED_COLUMN_NAME"
  48. FROM
  49. "INFORMATION_SCHEMA"."KEY_COLUMN_USAGE"
  50. WHERE
  51. "TABLE_NAME" COLLATE \'utf8_bin\' = ? AND
  52. "REFERENCED_TABLE_NAME" COLLATE \'utf8_bin\' IN ? AND
  53. "TABLE_SCHEMA" = ? AND
  54. "REFERENCED_TABLE_SCHEMA" = ?',
  55. 'reflect_has_many'=>'SELECT
  56. "TABLE_NAME","COLUMN_NAME",
  57. "REFERENCED_TABLE_NAME","REFERENCED_COLUMN_NAME"
  58. FROM
  59. "INFORMATION_SCHEMA"."KEY_COLUMN_USAGE"
  60. WHERE
  61. "TABLE_NAME" COLLATE \'utf8_bin\' IN ? AND
  62. "REFERENCED_TABLE_NAME" COLLATE \'utf8_bin\' = ? AND
  63. "TABLE_SCHEMA" = ? AND
  64. "REFERENCED_TABLE_SCHEMA" = ?',
  65. 'reflect_habtm'=>'SELECT
  66. k1."TABLE_NAME", k1."COLUMN_NAME",
  67. k1."REFERENCED_TABLE_NAME", k1."REFERENCED_COLUMN_NAME",
  68. k2."TABLE_NAME", k2."COLUMN_NAME",
  69. k2."REFERENCED_TABLE_NAME", k2."REFERENCED_COLUMN_NAME"
  70. FROM
  71. "INFORMATION_SCHEMA"."KEY_COLUMN_USAGE" k1,
  72. "INFORMATION_SCHEMA"."KEY_COLUMN_USAGE" k2
  73. WHERE
  74. k1."TABLE_SCHEMA" = ? AND
  75. k2."TABLE_SCHEMA" = ? AND
  76. k1."REFERENCED_TABLE_SCHEMA" = ? AND
  77. k2."REFERENCED_TABLE_SCHEMA" = ? AND
  78. k1."TABLE_NAME" COLLATE \'utf8_bin\' = k2."TABLE_NAME" COLLATE \'utf8_bin\' AND
  79. k1."REFERENCED_TABLE_NAME" COLLATE \'utf8_bin\' = ? AND
  80. k2."REFERENCED_TABLE_NAME" COLLATE \'utf8_bin\' IN ?'
  81. );
  82. }
  83. public function getSql($name) {
  84. return isset($this->queries[$name])?$this->queries[$name]:false;
  85. }
  86. public function connect($hostname,$username,$password,$database,$port,$socket,$charset) {
  87. $db = mysqli_connect($hostname,$username,$password,$database,$port,$socket);
  88. if (mysqli_connect_errno()) {
  89. throw new \Exception('Connect failed. '.mysqli_connect_error());
  90. }
  91. if (!mysqli_set_charset($db,$charset)) {
  92. throw new \Exception('Error setting charset. '.mysqli_error($db));
  93. }
  94. if (!mysqli_query($db,'SET SESSION sql_mode = \'ANSI_QUOTES\';')) {
  95. throw new \Exception('Error setting ANSI quotes. '.mysqli_error($db));
  96. }
  97. $this->db = $db;
  98. }
  99. public function query($sql,$params) {
  100. $db = $this->db;
  101. $sql = preg_replace_callback('/\!|\?/', function ($matches) use (&$db,&$params) {
  102. $param = array_shift($params);
  103. if ($matches[0]=='!') return preg_replace('/[^a-zA-Z0-9\-_=<> ]/','',$param);
  104. if (is_array($param)) return '('.implode(',',array_map(function($v) use (&$db) {
  105. return "'".mysqli_real_escape_string($db,$v)."'";
  106. },$param)).')';
  107. if (is_object($param) && $param->type=='base64') {
  108. return "x'".bin2hex(base64_decode($param->data))."'";
  109. }
  110. if ($param===null) return 'NULL';
  111. return "'".mysqli_real_escape_string($db,$param)."'";
  112. }, $sql);
  113. //if (!strpos($sql,'INFORMATION_SCHEMA')) echo "\n$sql\n";
  114. return mysqli_query($db,$sql);
  115. }
  116. public function fetchAssoc($result) {
  117. return mysqli_fetch_assoc($result);
  118. }
  119. public function fetchRow($result) {
  120. return mysqli_fetch_row($result);
  121. }
  122. public function insertId($result) {
  123. return mysqli_insert_id($this->db);
  124. }
  125. public function affectedRows($result) {
  126. return mysqli_affected_rows($this->db);
  127. }
  128. public function close($result) {
  129. return mysqli_free_result($result);
  130. }
  131. public function fetchFields($table) {
  132. $result = $this->query('SELECT * FROM "!" WHERE 1=2;',array($table));
  133. return mysqli_fetch_fields($result);
  134. }
  135. public function addLimitToSql($sql,$limit,$offset) {
  136. return "$sql LIMIT $limit OFFSET $offset";
  137. }
  138. public function likeEscape($string) {
  139. return addcslashes($string,'%_');
  140. }
  141. public function isBinaryType($field) {
  142. //echo "$field->name: $field->type ($field->flags)\n";
  143. return (($field->flags & 128) && ($field->type>=249) && ($field->type<=252));
  144. }
  145. public function base64Encode($string) {
  146. return base64_encode($string);
  147. }
  148. public function getDefaultCharset() {
  149. return 'utf8';
  150. }
  151. }
  152. class PostgreSQL implements DatabaseInterface {
  153. protected $db;
  154. protected $queries;
  155. public function __construct() {
  156. $this->queries = array(
  157. 'list_tables'=>'select
  158. "table_name","table_comment"
  159. from
  160. "information_schema"."tables"
  161. where
  162. "table_catalog" = ?',
  163. 'reflect_table'=>'select
  164. "table_name"
  165. from
  166. "information_schema"."tables"
  167. where
  168. "table_name" like ? and
  169. "table_catalog" = ?',
  170. 'reflect_pk'=>'select
  171. "column_name"
  172. from
  173. "information_schema"."table_constraints" tc,
  174. "information_schema"."key_column_usage" ku
  175. where
  176. tc."constraint_type" = \'PRIMARY KEY\' and
  177. tc."constraint_name" = ku."constraint_name" and
  178. ku."table_name" = ? and
  179. ku."table_catalog" = ?',
  180. 'reflect_belongs_to'=>'select
  181. cu1."table_name",cu1."column_name",
  182. cu2."table_name",cu2."column_name"
  183. from
  184. "information_schema".referential_constraints rc,
  185. "information_schema".key_column_usage cu1,
  186. "information_schema".key_column_usage cu2
  187. where
  188. cu1."constraint_name" = rc."constraint_name" and
  189. cu2."constraint_name" = rc."unique_constraint_name" and
  190. cu1."table_name" = ? and
  191. cu2."table_name" in ? and
  192. cu1."table_catalog" = ? and
  193. cu2."table_catalog" = ?',
  194. 'reflect_has_many'=>'select
  195. cu1."table_name",cu1."column_name",
  196. cu2."table_name",cu2."column_name"
  197. from
  198. "information_schema".referential_constraints rc,
  199. "information_schema".key_column_usage cu1,
  200. "information_schema".key_column_usage cu2
  201. where
  202. cu1."constraint_name" = rc."constraint_name" and
  203. cu2."constraint_name" = rc."unique_constraint_name" and
  204. cu1."table_name" in ? and
  205. cu2."table_name" = ? and
  206. cu1."table_catalog" = ? and
  207. cu2."table_catalog" = ?',
  208. 'reflect_habtm'=>'select
  209. cua1."table_name",cua1."column_name",
  210. cua2."table_name",cua2."column_name",
  211. cub1."table_name",cub1."column_name",
  212. cub2."table_name",cub2."column_name"
  213. from
  214. "information_schema".referential_constraints rca,
  215. "information_schema".referential_constraints rcb,
  216. "information_schema".key_column_usage cua1,
  217. "information_schema".key_column_usage cua2,
  218. "information_schema".key_column_usage cub1,
  219. "information_schema".key_column_usage cub2
  220. where
  221. cua1."constraint_name" = rca."constraint_name" and
  222. cua2."constraint_name" = rca."unique_constraint_name" and
  223. cub1."constraint_name" = rcb."constraint_name" and
  224. cub2."constraint_name" = rcb."unique_constraint_name" and
  225. cua1."table_catalog" = ? and
  226. cub1."table_catalog" = ? and
  227. cua2."table_catalog" = ? and
  228. cub2."table_catalog" = ? and
  229. cua1."table_name" = cub1."table_name" and
  230. cua2."table_name" = ? and
  231. cub2."table_name" in ?'
  232. );
  233. }
  234. public function getSql($name) {
  235. return isset($this->queries[$name])?$this->queries[$name]:false;
  236. }
  237. public function connect($hostname,$username,$password,$database,$port,$socket,$charset) {
  238. $e = function ($v) { return str_replace(array('\'','\\'),array('\\\'','\\\\'),$v); };
  239. $conn_string = '';
  240. if ($hostname || $socket) {
  241. if ($socket) $hostname = $e($socket);
  242. else $hostname = $e($hostname);
  243. $conn_string.= " host='$hostname'";
  244. }
  245. if ($port) {
  246. $port = ($port+0);
  247. $conn_string.= " port='$port'";
  248. }
  249. if ($database) {
  250. $database = $e($database);
  251. $conn_string.= " dbname='$database'";
  252. }
  253. if ($username) {
  254. $username = $e($username);
  255. $conn_string.= " user='$username'";
  256. }
  257. if ($password) {
  258. $password = $e($password);
  259. $conn_string.= " password='$password'";
  260. }
  261. if ($charset) {
  262. $charset = $e($charset);
  263. $conn_string.= " options='--client_encoding=$charset'";
  264. }
  265. $db = pg_connect($conn_string);
  266. $this->db = $db;
  267. }
  268. public function query($sql,$params) {
  269. $db = $this->db;
  270. $sql = preg_replace_callback('/\!|\?/', function ($matches) use (&$db,&$params) {
  271. $param = array_shift($params);
  272. if ($matches[0]=='!') return preg_replace('/[^a-zA-Z0-9\-_=<> ]/','',$param);
  273. if (is_array($param)) return '('.implode(',',array_map(function($v) use (&$db) {
  274. return "'".pg_escape_string($db,$v)."'";
  275. },$param)).')';
  276. if (is_object($param) && $param->type=='base64') {
  277. return "'\x".bin2hex(base64_decode($param->data))."'";
  278. }
  279. if ($param===null) return 'NULL';
  280. return "'".pg_escape_string($db,$param)."'";
  281. }, $sql);
  282. if (strtoupper(substr($sql,0,6))=='INSERT') {
  283. $sql .= ' RETURNING id;';
  284. }
  285. //echo "\n$sql\n";
  286. return @pg_query($db,$sql);
  287. }
  288. public function fetchAssoc($result) {
  289. return pg_fetch_assoc($result);
  290. }
  291. public function fetchRow($result) {
  292. return pg_fetch_row($result);
  293. }
  294. public function insertId($result) {
  295. list($id) = pg_fetch_row($result);
  296. return (int)$id;
  297. }
  298. public function affectedRows($result) {
  299. return pg_affected_rows($result);
  300. }
  301. public function close($result) {
  302. return pg_free_result($result);
  303. }
  304. public function fetchFields($table) {
  305. $result = $this->query('SELECT * FROM "!" WHERE 1=2;',array($table));
  306. $keys = array();
  307. for($i=0;$i<pg_num_fields($result);$i++) {
  308. $field = array();
  309. $field['name'] = pg_field_name($result,$i);
  310. $field['type'] = pg_field_type($result,$i);
  311. $keys[$i] = (object)$field;
  312. }
  313. return $keys;
  314. }
  315. public function addLimitToSql($sql,$limit,$offset) {
  316. return "$sql LIMIT $limit OFFSET $offset";
  317. }
  318. public function likeEscape($string) {
  319. return addcslashes($string,'%_');
  320. }
  321. public function isBinaryType($field) {
  322. return $field->type == 'bytea';
  323. }
  324. public function base64Encode($string) {
  325. return base64_encode(hex2bin(substr($string,2)));
  326. }
  327. public function getDefaultCharset() {
  328. return 'UTF8';
  329. }
  330. }
  331. class SQLServer implements DatabaseInterface {
  332. protected $db;
  333. protected $queries;
  334. public function __construct() {
  335. $this->queries = array(
  336. 'list_tables'=>'SELECT
  337. "TABLE_NAME",\'\' as "TABLE_COMMENT"
  338. FROM
  339. "INFORMATION_SCHEMA"."TABLES"
  340. WHERE
  341. "TABLE_CATALOG" = ?',
  342. 'reflect_table'=>'SELECT
  343. "TABLE_NAME"
  344. FROM
  345. "INFORMATION_SCHEMA"."TABLES"
  346. WHERE
  347. "TABLE_NAME" LIKE ? AND
  348. "TABLE_CATALOG" = ?',
  349. 'reflect_pk'=>'SELECT
  350. "COLUMN_NAME"
  351. FROM
  352. "INFORMATION_SCHEMA"."TABLE_CONSTRAINTS" tc,
  353. "INFORMATION_SCHEMA"."KEY_COLUMN_USAGE" ku
  354. WHERE
  355. tc."CONSTRAINT_TYPE" = \'PRIMARY KEY\' AND
  356. tc."CONSTRAINT_NAME" = ku."CONSTRAINT_NAME" AND
  357. ku."TABLE_NAME" = ? AND
  358. ku."TABLE_CATALOG" = ?',
  359. 'reflect_belongs_to'=>'SELECT
  360. cu1."TABLE_NAME",cu1."COLUMN_NAME",
  361. cu2."TABLE_NAME",cu2."COLUMN_NAME"
  362. FROM
  363. "INFORMATION_SCHEMA".REFERENTIAL_CONSTRAINTS rc,
  364. "INFORMATION_SCHEMA".CONSTRAINT_COLUMN_USAGE cu1,
  365. "INFORMATION_SCHEMA".CONSTRAINT_COLUMN_USAGE cu2
  366. WHERE
  367. cu1."CONSTRAINT_NAME" = rc."CONSTRAINT_NAME" AND
  368. cu2."CONSTRAINT_NAME" = rc."UNIQUE_CONSTRAINT_NAME" AND
  369. cu1."TABLE_NAME" = ? AND
  370. cu2."TABLE_NAME" IN ? AND
  371. cu1."TABLE_CATALOG" = ? AND
  372. cu2."TABLE_CATALOG" = ?',
  373. 'reflect_has_many'=>'SELECT
  374. cu1."TABLE_NAME",cu1."COLUMN_NAME",
  375. cu2."TABLE_NAME",cu2."COLUMN_NAME"
  376. FROM
  377. "INFORMATION_SCHEMA".REFERENTIAL_CONSTRAINTS rc,
  378. "INFORMATION_SCHEMA".CONSTRAINT_COLUMN_USAGE cu1,
  379. "INFORMATION_SCHEMA".CONSTRAINT_COLUMN_USAGE cu2
  380. WHERE
  381. cu1."CONSTRAINT_NAME" = rc."CONSTRAINT_NAME" AND
  382. cu2."CONSTRAINT_NAME" = rc."UNIQUE_CONSTRAINT_NAME" AND
  383. cu1."TABLE_NAME" IN ? AND
  384. cu2."TABLE_NAME" = ? AND
  385. cu1."TABLE_CATALOG" = ? AND
  386. cu2."TABLE_CATALOG" = ?',
  387. 'reflect_habtm'=>'SELECT
  388. cua1."TABLE_NAME",cua1."COLUMN_NAME",
  389. cua2."TABLE_NAME",cua2."COLUMN_NAME",
  390. cub1."TABLE_NAME",cub1."COLUMN_NAME",
  391. cub2."TABLE_NAME",cub2."COLUMN_NAME"
  392. FROM
  393. "INFORMATION_SCHEMA".REFERENTIAL_CONSTRAINTS rca,
  394. "INFORMATION_SCHEMA".REFERENTIAL_CONSTRAINTS rcb,
  395. "INFORMATION_SCHEMA".CONSTRAINT_COLUMN_USAGE cua1,
  396. "INFORMATION_SCHEMA".CONSTRAINT_COLUMN_USAGE cua2,
  397. "INFORMATION_SCHEMA".CONSTRAINT_COLUMN_USAGE cub1,
  398. "INFORMATION_SCHEMA".CONSTRAINT_COLUMN_USAGE cub2
  399. WHERE
  400. cua1."CONSTRAINT_NAME" = rca."CONSTRAINT_NAME" AND
  401. cua2."CONSTRAINT_NAME" = rca."UNIQUE_CONSTRAINT_NAME" AND
  402. cub1."CONSTRAINT_NAME" = rcb."CONSTRAINT_NAME" AND
  403. cub2."CONSTRAINT_NAME" = rcb."UNIQUE_CONSTRAINT_NAME" AND
  404. cua1."TABLE_CATALOG" = ? AND
  405. cub1."TABLE_CATALOG" = ? AND
  406. cua2."TABLE_CATALOG" = ? AND
  407. cub2."TABLE_CATALOG" = ? AND
  408. cua1."TABLE_NAME" = cub1."TABLE_NAME" AND
  409. cua2."TABLE_NAME" = ? AND
  410. cub2."TABLE_NAME" IN ?'
  411. );
  412. }
  413. public function getSql($name) {
  414. return isset($this->queries[$name])?$this->queries[$name]:false;
  415. }
  416. public function connect($hostname,$username,$password,$database,$port,$socket,$charset) {
  417. $connectionInfo = array();
  418. if ($port) $hostname.=','.$port;
  419. if ($username) $connectionInfo['UID']=$username;
  420. if ($password) $connectionInfo['PWD']=$password;
  421. if ($database) $connectionInfo['Database']=$database;
  422. if ($charset) $connectionInfo['CharacterSet']=$charset;
  423. $connectionInfo['QuotedId']=1;
  424. $connectionInfo['ReturnDatesAsStrings']=1;
  425. $db = sqlsrv_connect($hostname, $connectionInfo);
  426. if (!$db) {
  427. throw new \Exception('Connect failed. '.print_r( sqlsrv_errors(), true));
  428. }
  429. if ($socket) {
  430. throw new \Exception('Socket connection is not supported.');
  431. }
  432. $this->db = $db;
  433. }
  434. public function query($sql,$params) {
  435. $args = array();
  436. $db = $this->db;
  437. $sql = preg_replace_callback('/\!|\?/', function ($matches) use (&$db,&$params,&$args) {
  438. static $i=-1;
  439. $i++;
  440. $param = $params[$i];
  441. if ($matches[0]=='!') {
  442. return preg_replace('/[^a-zA-Z0-9\-_=<> ]/','',$param);
  443. }
  444. // This is workaround because SQLSRV cannot accept NULL in a param
  445. if ($matches[0]=='?' && is_null($param)) {
  446. return 'NULL';
  447. }
  448. if (is_array($param)) {
  449. $args = array_merge($args,$param);
  450. return '('.implode(',',str_split(str_repeat('?',count($param)))).')';
  451. }
  452. if (is_object($param)) {
  453. switch($param->type) {
  454. case 'base64':
  455. $args[] = bin2hex(base64_decode($param->data));
  456. return 'CONVERT(VARBINARY(MAX),?,2)';
  457. }
  458. }
  459. $args[] = $param;
  460. return '?';
  461. }, $sql);
  462. //var_dump($params);
  463. //echo "\n$sql\n";
  464. //var_dump($args);
  465. //file_put_contents('sql.txt',"\n$sql\n".var_export($args,true)."\n",FILE_APPEND);
  466. if (strtoupper(substr($sql,0,6))=='INSERT') {
  467. $sql .= ';SELECT SCOPE_IDENTITY()';
  468. }
  469. return sqlsrv_query($db,$sql,$args)?:null;
  470. }
  471. public function fetchAssoc($result) {
  472. $values = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC);
  473. if ($values) $values = array_map(function($v){ return is_null($v)?null:(string)$v; },$values);
  474. return $values;
  475. }
  476. public function fetchRow($result) {
  477. $values = sqlsrv_fetch_array($result, SQLSRV_FETCH_NUMERIC);
  478. if ($values) $values = array_map(function($v){ return is_null($v)?null:(string)$v; },$values);
  479. return $values;
  480. }
  481. public function insertId($result) {
  482. sqlsrv_next_result($result);
  483. sqlsrv_fetch($result);
  484. return (int)sqlsrv_get_field($result, 0);
  485. }
  486. public function affectedRows($result) {
  487. return sqlsrv_rows_affected($result);
  488. }
  489. public function close($result) {
  490. return sqlsrv_free_stmt($result);
  491. }
  492. public function fetchFields($table) {
  493. $result = $this->query('SELECT * FROM "!" WHERE 1=2;',array($table));
  494. //var_dump(sqlsrv_field_metadata($result));
  495. return array_map(function($a){
  496. $p = array();
  497. foreach ($a as $k=>$v) {
  498. $p[strtolower($k)] = $v;
  499. }
  500. return (object)$p;
  501. },sqlsrv_field_metadata($result));
  502. }
  503. public function addLimitToSql($sql,$limit,$offset) {
  504. return "$sql OFFSET $offset ROWS FETCH NEXT $limit ROWS ONLY";
  505. }
  506. public function likeEscape($string) {
  507. return str_replace(array('%','_'),array('[%]','[_]'),$string);
  508. }
  509. public function isBinaryType($field) {
  510. return ($field->type>=-4 && $field->type<=-2);
  511. }
  512. public function base64Encode($string) {
  513. return base64_encode($string);
  514. }
  515. public function getDefaultCharset() {
  516. return 'UTF-8';
  517. }
  518. }
  519. class SQLite implements DatabaseInterface {
  520. protected $db;
  521. protected $queries;
  522. public function __construct() {
  523. $this->queries = array(
  524. 'list_tables'=>'SELECT
  525. "name", ""
  526. FROM
  527. "sys/tables"',
  528. 'reflect_table'=>'SELECT
  529. "name"
  530. FROM
  531. "sys/tables"
  532. WHERE
  533. "name"=?',
  534. 'reflect_pk'=>'SELECT
  535. "name"
  536. FROM
  537. "sys/columns"
  538. WHERE
  539. "pk"=1 AND
  540. "self"=?',
  541. 'reflect_belongs_to'=>'SELECT
  542. "self", "from",
  543. "table", "to"
  544. FROM
  545. "sys/foreign_keys"
  546. WHERE
  547. "self" = ? AND
  548. "table" IN ? AND
  549. ? like "%" AND
  550. ? like "%"',
  551. 'reflect_has_many'=>'SELECT
  552. "self", "from",
  553. "table", "to"
  554. FROM
  555. "sys/foreign_keys"
  556. WHERE
  557. "self" IN ? AND
  558. "table" = ? AND
  559. ? like "%" AND
  560. ? like "%"',
  561. 'reflect_habtm'=>'SELECT
  562. k1."self", k1."from",
  563. k1."table", k1."to",
  564. k2."self", k2."from",
  565. k2."table", k2."to"
  566. FROM
  567. "sys/foreign_keys" k1,
  568. "sys/foreign_keys" k2
  569. WHERE
  570. ? like "%" AND
  571. ? like "%" AND
  572. ? like "%" AND
  573. ? like "%" AND
  574. k1."self" = k2."self" AND
  575. k1."table" = ? AND
  576. k2."table" IN ?'
  577. );
  578. }
  579. public function getSql($name) {
  580. return isset($this->queries[$name])?$this->queries[$name]:false;
  581. }
  582. public function connect($hostname,$username,$password,$database,$port,$socket,$charset) {
  583. $this->db = new SQLite3($database);
  584. // optimizations
  585. $this->db->querySingle('PRAGMA synchronous = NORMAL');
  586. $this->db->querySingle('PRAGMA foreign_keys = on');
  587. $reflection = $this->db->querySingle('SELECT name FROM sqlite_master WHERE type = "table" and name like "sys/%"');
  588. if (!$reflection) {
  589. //create reflection tables
  590. $this->query('CREATE table "sys/version" ("version" integer)');
  591. $this->query('CREATE table "sys/tables" ("name" text)');
  592. $this->query('CREATE table "sys/columns" ("self" text,"cid" integer,"name" text,"type" integer,"notnull" integer,"dflt_value" integer,"pk" integer)');
  593. $this->query('CREATE table "sys/foreign_keys" ("self" text,"id" integer,"seq" integer,"table" text,"from" text,"to" text,"on_update" text,"on_delete" text,"match" text)');
  594. }
  595. $version = $this->db->querySingle('pragma schema_version');
  596. if ($version != $this->db->querySingle('SELECT "version" from "sys/version"')) {
  597. // update version data
  598. $this->query('DELETE FROM "sys/version"');
  599. $this->query('INSERT into "sys/version" ("version") VALUES (?)',array($version));
  600. // update tables data
  601. $this->query('DELETE FROM "sys/tables"');
  602. $result = $this->query('SELECT * FROM sqlite_master WHERE type = "table" and name not like "sys/%" and name<>"sqlite_sequence"');
  603. $tables = array();
  604. while ($row = $this->fetchAssoc($result)) {
  605. $tables[] = $row['name'];
  606. $this->query('INSERT into "sys/tables" ("name") VALUES (?)',array($row['name']));
  607. }
  608. // update columns and foreign_keys data
  609. $this->query('DELETE FROM "sys/columns"');
  610. $this->query('DELETE FROM "sys/foreign_keys"');
  611. foreach ($tables as $table) {
  612. $result = $this->query('pragma table_info(!)',array($table));
  613. while ($row = $this->fetchRow($result)) {
  614. array_unshift($row, $table);
  615. $this->query('INSERT into "sys/columns" ("self","cid","name","type","notnull","dflt_value","pk") VALUES (?,?,?,?,?,?,?)',$row);
  616. }
  617. $result = $this->query('pragma foreign_key_list(!)',array($table));
  618. while ($row = $this->fetchRow($result)) {
  619. array_unshift($row, $table);
  620. $this->query('INSERT into "sys/foreign_keys" ("self","id","seq","table","from","to","on_update","on_delete","match") VALUES (?,?,?,?,?,?,?,?,?)',$row);
  621. }
  622. }
  623. }
  624. }
  625. public function query($sql,$params=array()) {
  626. $db = $this->db;
  627. $sql = preg_replace_callback('/\!|\?/', function ($matches) use (&$db,&$params) {
  628. $param = array_shift($params);
  629. if ($matches[0]=='!') return preg_replace('/[^a-zA-Z0-9\-_=<> ]/','',$param);
  630. if (is_array($param)) return '('.implode(',',array_map(function($v) use (&$db) {
  631. return "'".$db->escapeString($v)."'";
  632. },$param)).')';
  633. if (is_object($param) && $param->type=='base64') {
  634. return "x'".bin2hex(base64_decode($param->data))."'";
  635. }
  636. if ($param===null) return 'NULL';
  637. return "'".$db->escapeString($param)."'";
  638. }, $sql);
  639. //echo "\n$sql\n";
  640. try { $result=$db->query($sql); } catch(\Exception $e) { $result=null; }
  641. return $result;
  642. }
  643. public function fetchAssoc($result) {
  644. $values = $result->fetchArray(SQLITE3_ASSOC);
  645. if ($values) $values = array_map(function($v){ return is_null($v)?null:(string)$v; },$values);
  646. return $values;
  647. }
  648. public function fetchRow($result) {
  649. $values = $result->fetchArray(SQLITE3_NUM);
  650. if ($values) $values = array_map(function($v){ return is_null($v)?null:(string)$v; },$values);
  651. return $values;
  652. }
  653. public function insertId($result) {
  654. return $this->db->lastInsertRowID();
  655. }
  656. public function affectedRows($result) {
  657. return $this->db->changes();
  658. }
  659. public function close($result) {
  660. return $result->finalize();
  661. }
  662. public function fetchFields($table) {
  663. $result = $this->query('SELECT * FROM "sys/columns" WHERE "self"=?;',array($table));
  664. $fields = array();
  665. while ($row = $this->fetchAssoc($result)){
  666. $fields[strtolower($row['name'])] = (object)$row;
  667. }
  668. return $fields;
  669. }
  670. public function addLimitToSql($sql,$limit,$offset) {
  671. return "$sql LIMIT $limit OFFSET $offset";
  672. }
  673. public function likeEscape($string) {
  674. return addcslashes($string,'%_');
  675. }
  676. public function isBinaryType($field) {
  677. return (substr($field->type,0,4)=='blob');
  678. }
  679. public function base64Encode($string) {
  680. return base64_encode($string);
  681. }
  682. public function getDefaultCharset() {
  683. return 'utf8';
  684. }
  685. }
  686. class PHP_CRUD_API {
  687. protected $db;
  688. protected $settings;
  689. protected function mapMethodToAction($method,$key) {
  690. switch ($method) {
  691. case 'OPTIONS': return 'headers';
  692. case 'GET': return $key?'read':'list';
  693. case 'PUT': return 'update';
  694. case 'POST': return 'create';
  695. case 'DELETE': return 'delete';
  696. default: $this->exitWith404('method');
  697. }
  698. return false;
  699. }
  700. protected function parseRequestParameter(&$request,$characters) {
  701. if (!$request) return false;
  702. $pos = strpos($request,'/');
  703. $value = $pos?substr($request,0,$pos):$request;
  704. $request = $pos?substr($request,$pos+1):'';
  705. if (!$characters) return $value;
  706. return preg_replace("/[^$characters]/",'',$value);
  707. }
  708. protected function parseGetParameter($get,$name,$characters) {
  709. $value = isset($get[$name])?$get[$name]:false;
  710. return $characters?preg_replace("/[^$characters]/",'',$value):$value;
  711. }
  712. protected function parseGetParameterArray($get,$name,$characters) {
  713. $values = isset($get[$name])?$get[$name]:false;
  714. if (!is_array($values)) $values = array($values);
  715. if ($characters) {
  716. foreach ($values as &$value) {
  717. $value = preg_replace("/[^$characters]/",'',$value);
  718. }
  719. }
  720. return $values;
  721. }
  722. protected function applyTableAuthorizer($callback,$action,$database,&$tables) {
  723. if (is_callable($callback,true)) foreach ($tables as $i=>$table) {
  724. if (!$callback($action,$database,$table)) {
  725. unset($tables[$i]);
  726. }
  727. }
  728. }
  729. protected function applyRecordFilter($callback,$action,$database,$tables,&$filters) {
  730. if (is_callable($callback,true)) foreach ($tables as $i=>$table) {
  731. $f = $this->convertFilters($callback($action,$database,$table));
  732. if ($f) {
  733. if (!isset($filters[$table])) $filters[$table] = array();
  734. if (!isset($filters[$table]['and'])) $filters[$table]['and'] = array();
  735. $filters[$table]['and'] = array_merge($filters[$table]['and'],$f);
  736. }
  737. }
  738. }
  739. protected function applyTenancyFunction($callback,$action,$database,$fields,&$filters) {
  740. if (is_callable($callback,true)) foreach ($fields as $table=>$keys) {
  741. foreach ($keys as $field) {
  742. $v = $callback($action,$database,$table,$field->name);
  743. if ($v!==null) {
  744. if (!isset($filters[$table])) $filters[$table] = array();
  745. if (!isset($filters[$table]['and'])) $filters[$table]['and'] = array();
  746. $filters[$table]['and'][] = array($field->name,is_array($v)?'IN':'=',$v);
  747. }
  748. }
  749. }
  750. }
  751. protected function applyColumnAuthorizer($callback,$action,$database,&$fields) {
  752. if (is_callable($callback,true)) foreach ($fields as $table=>$keys) {
  753. foreach ($keys as $field) {
  754. if (!$callback($action,$database,$table,$field->name)) {
  755. unset($fields[$table][$field->name]);
  756. }
  757. }
  758. }
  759. }
  760. protected function applyInputTenancy($callback,$action,$database,$table,&$input,$keys) {
  761. if (is_callable($callback,true)) foreach ($keys as $key=>$field) {
  762. $v = $callback($action,$database,$table,$key);
  763. if ($v!==null) {
  764. if (is_array($v)) {
  765. if (!count($v)) {
  766. $input->$key = null;
  767. } elseif (!isset($input->$key)) {
  768. $input->$key = $v[0];
  769. } elseif (!in_array($input->$key,$v)) {
  770. $input->$key = null;
  771. }
  772. } else {
  773. $input->$key = $v;
  774. }
  775. }
  776. }
  777. }
  778. protected function applyInputSanitizer($callback,$action,$database,$table,&$input,$keys) {
  779. if (is_callable($callback,true)) foreach ((array)$input as $key=>$value) {
  780. if (isset($keys[$key])) {
  781. $input->$key = $callback($action,$database,$table,$key,$keys[$key]->type,$value);
  782. }
  783. }
  784. }
  785. protected function applyInputValidator($callback,$action,$database,$table,$input,$keys,$context) {
  786. $errors = array();
  787. if (is_callable($callback,true)) foreach ((array)$input as $key=>$value) {
  788. if (isset($keys[$key])) {
  789. $error = $callback($action,$database,$table,$key,$keys[$key]->type,$value,$context);
  790. if ($error!==true && $error!==null) $errors[$key] = $error;
  791. }
  792. }
  793. if (!empty($errors)) $this->exitWith422($errors);
  794. }
  795. protected function processTableAndIncludeParameters($database,$table,$include,$action) {
  796. $blacklist = array('information_schema','mysql','sys','pg_catalog');
  797. if (in_array(strtolower($database), $blacklist)) return array();
  798. $table_list = array();
  799. if ($result = $this->db->query($this->db->getSql('reflect_table'),array($table,$database))) {
  800. while ($row = $this->db->fetchRow($result)) $table_list[] = $row[0];
  801. $this->db->close($result);
  802. }
  803. if (empty($table_list)) $this->exitWith404('entity');
  804. if ($action=='list') {
  805. foreach (explode(',',$include) as $table) {
  806. if ($result = $this->db->query($this->db->getSql('reflect_table'),array($table,$database))) {
  807. while ($row = $this->db->fetchRow($result)) $table_list[] = $row[0];
  808. $this->db->close($result);
  809. }
  810. }
  811. }
  812. return $table_list;
  813. }
  814. protected function exitWith404($type) {
  815. if (isset($_SERVER['REQUEST_METHOD'])) {
  816. header('Content-Type:',true,404);
  817. die("Not found ($type)");
  818. } else {
  819. throw new \Exception("Not found ($type)");
  820. }
  821. }
  822. protected function exitWith422($object) {
  823. if (isset($_SERVER['REQUEST_METHOD'])) {
  824. header('Content-Type:',true,422);
  825. die(json_encode($object));
  826. } else {
  827. throw new \Exception(json_encode($object));
  828. }
  829. }
  830. protected function headersCommand($parameters) {
  831. $headers = array();
  832. $headers[]='Access-Control-Allow-Headers: Content-Type';
  833. $headers[]='Access-Control-Allow-Methods: OPTIONS, GET, PUT, POST, DELETE';
  834. $headers[]='Access-Control-Allow-Credentials: true';
  835. $headers[]='Access-Control-Max-Age: 1728000';
  836. if (isset($_SERVER['REQUEST_METHOD'])) {
  837. foreach ($headers as $header) header($header);
  838. } else {
  839. echo json_encode($headers);
  840. }
  841. }
  842. protected function startOutput($callback) {
  843. if ($callback) {
  844. if (isset($_SERVER['REQUEST_METHOD'])) {
  845. header('Content-Type: application/javascript; charset=utf-8');
  846. }
  847. echo $callback.'(';
  848. } else {
  849. if (isset($_SERVER['REQUEST_METHOD'])) {
  850. header('Content-Type: application/json; charset=utf-8');
  851. }
  852. }
  853. }
  854. protected function endOutput($callback) {
  855. if ($callback) {
  856. echo ');';
  857. }
  858. }
  859. protected function findPrimaryKeys($table,$database) {
  860. $fields = array();
  861. if ($result = $this->db->query($this->db->getSql('reflect_pk'),array($table,$database))) {
  862. while ($row = $this->db->fetchRow($result)) {
  863. $fields[] = $row[0];
  864. }
  865. $this->db->close($result);
  866. }
  867. return $fields;
  868. }
  869. protected function processKeyParameter($key,$tables,$database) {
  870. if (!$key) return false;
  871. $fields = $this->findPrimaryKeys($tables[0],$database);
  872. if (count($fields)!=1) $this->exitWith404('1pk');
  873. return array($key,$fields[0]);
  874. }
  875. protected function processOrderParameter($order) {
  876. if (!$order) return false;
  877. $order = explode(',',$order,2);
  878. if (count($order)<2) $order[1]='ASC';
  879. if (!strlen($order[0])) return false;
  880. $order[1] = strtoupper($order[1])=='DESC'?'DESC':'ASC';
  881. return $order;
  882. }
  883. protected function convertFilter($field, $comparator, $value) {
  884. switch (strtolower($comparator)) {
  885. case 'cs': $comparator = 'LIKE'; $value = '%'.$this->db->likeEscape($value).'%'; break;
  886. case 'sw': $comparator = 'LIKE'; $value = $this->db->likeEscape($value).'%'; break;
  887. case 'ew': $comparator = 'LIKE'; $value = '%'.$this->db->likeEscape($value); break;
  888. case 'eq': $comparator = '='; break;
  889. case 'ne': $comparator = '<>'; break;
  890. case 'lt': $comparator = '<'; break;
  891. case 'le': $comparator = '<='; break;
  892. case 'ge': $comparator = '>='; break;
  893. case 'gt': $comparator = '>'; break;
  894. case 'in': $comparator = 'IN'; $value = explode(',',$value); break;
  895. case 'ni': $comparator = 'NOT IN'; $value = explode(',',$value); break;
  896. case 'is': $comparator = 'IS'; $value = null; break;
  897. case 'no': $comparator = 'IS NOT'; $value = null; break;
  898. }
  899. return array($field, $comparator, $value);
  900. }
  901. protected function convertFilters($filters) {
  902. $result = array();
  903. if ($filters) {
  904. for ($i=0;$i<count($filters);$i++) {
  905. $filter = explode(',',$filters[$i],3);
  906. if (count($filter)==3) {
  907. $result[] = $this->convertFilter($filter[0],$filter[1],$filter[2]);
  908. } elseif (count($filter)==2) {
  909. $result[] = $this->convertFilter($filter[0],$filter[1],null);
  910. }
  911. }
  912. }
  913. return $result;
  914. }
  915. protected function processFiltersParameter($tables,$satisfy,$filters) {
  916. $result = $this->convertFilters($filters);
  917. if (!$result) return array();
  918. $and = ($satisfy && strtolower($satisfy)=='any')?'or':'and';
  919. return array($tables[0]=>array($and=>$result));
  920. }
  921. protected function processPageParameter($page) {
  922. if (!$page) return false;
  923. $page = explode(',',$page,2);
  924. if (count($page)<2) $page[1]=20;
  925. $page[0] = ($page[0]-1)*$page[1];
  926. return $page;
  927. }
  928. protected function retrieveObject($key,$fields,$filters,$tables) {
  929. if (!$key) return false;
  930. $table = $tables[0];
  931. $sql = 'SELECT ';
  932. $sql .= '"'.implode('","',array_keys($fields[$table])).'"';
  933. $sql .= ' FROM "!"';
  934. $params = array($table);
  935. if (!isset($filters[$table])) $filters[$table] = array();
  936. if (!isset($filters[$table]['or'])) $filters[$table]['or'] = array();
  937. $filters[$table]['or'][] = array($key[1],'=',$key[0]);
  938. $this->addWhereFromFilters($filters[$table],$sql,$params);
  939. $object = null;
  940. if ($result = $this->db->query($sql,$params)) {
  941. $object = $this->db->fetchAssoc($result);
  942. foreach ($fields[$table] as $field) {
  943. if ($this->db->isBinaryType($field) && $object[$field->name]) {
  944. $object[$field->name] = $this->db->base64Encode($object[$field->name]);
  945. }
  946. }
  947. $this->db->close($result);
  948. }
  949. return $object;
  950. }
  951. protected function createObject($input,$tables) {
  952. if (!$input) return false;
  953. $input = (array)$input;
  954. $keys = implode('","',str_split(str_repeat('!', count($input))));
  955. $values = implode(',',str_split(str_repeat('?', count($input))));
  956. $params = array_merge(array_keys($input),array_values($input));
  957. array_unshift($params, $tables[0]);
  958. $result = $this->db->query('INSERT INTO "!" ("'.$keys.'") VALUES ('.$values.')',$params);
  959. if (!$result) return null;
  960. return $this->db->insertId($result);
  961. }
  962. protected function updateObject($key,$input,$filters,$tables) {
  963. if (!$input) return false;
  964. $input = (array)$input;
  965. $table = $tables[0];
  966. $sql = 'UPDATE "!" SET ';
  967. $params = array($table);
  968. foreach (array_keys($input) as $i=>$k) {
  969. if ($i) $sql .= ',';
  970. $v = $input[$k];
  971. $sql .= '"!"=?';
  972. $params[] = $k;
  973. $params[] = $v;
  974. }
  975. if (!isset($filters[$table])) $filters[$table] = array();
  976. if (!isset($filters[$table]['or'])) $filters[$table]['or'] = array();
  977. $filters[$table]['or'][] = array($key[1],'=',$key[0]);
  978. $this->addWhereFromFilters($filters[$table],$sql,$params);
  979. $result = $this->db->query($sql,$params);
  980. if (!$result) return null;
  981. return $this->db->affectedRows($result);
  982. }
  983. protected function deleteObject($key,$filters,$tables) {
  984. $table = $tables[0];
  985. $sql = 'DELETE FROM "!"';
  986. $params = array($table);
  987. if (!isset($filters[$table])) $filters[$table] = array();
  988. if (!isset($filters[$table]['or'])) $filters[$table]['or'] = array();
  989. $filters[$table]['or'][] = array($key[1],'=',$key[0]);
  990. $this->addWhereFromFilters($filters[$table],$sql,$params);
  991. $result = $this->db->query($sql,$params);
  992. if (!$result) return null;
  993. return $this->db->affectedRows($result);
  994. }
  995. protected function findRelations($tables,$database) {
  996. $tableset = array();
  997. $collect = array();
  998. $select = array();
  999. while (count($tables)>1) {
  1000. $table0 = array_shift($tables);
  1001. $tableset[] = $table0;
  1002. $result = $this->db->query($this->db->getSql('reflect_belongs_to'),array($table0,$tables,$database,$database));
  1003. while ($row = $this->db->fetchRow($result)) {
  1004. $collect[$row[0]][$row[1]]=array();
  1005. $select[$row[2]][$row[3]]=array($row[0],$row[1]);
  1006. if (!in_array($row[0],$tableset)) $tableset[] = $row[0];
  1007. }
  1008. $result = $this->db->query($this->db->getSql('reflect_has_many'),array($tables,$table0,$database,$database));
  1009. while ($row = $this->db->fetchRow($result)) {
  1010. $collect[$row[2]][$row[3]]=array();
  1011. $select[$row[0]][$row[1]]=array($row[2],$row[3]);
  1012. if (!in_array($row[2],$tableset)) $tableset[] = $row[2];
  1013. }
  1014. $result = $this->db->query($this->db->getSql('reflect_habtm'),array($database,$database,$database,$database,$table0,$tables));
  1015. while ($row = $this->db->fetchRow($result)) {
  1016. $collect[$row[2]][$row[3]]=array();
  1017. $select[$row[0]][$row[1]]=array($row[2],$row[3]);
  1018. $collect[$row[4]][$row[5]]=array();
  1019. $select[$row[6]][$row[7]]=array($row[4],$row[5]);
  1020. if (!in_array($row[2],$tableset)) $tableset[] = $row[2];
  1021. if (!in_array($row[4],$tableset)) $tableset[] = $row[4];
  1022. }
  1023. }
  1024. $tableset[] = array_shift($tables);
  1025. $tableset = array_unique($tableset);
  1026. return array($tableset,$collect,$select);
  1027. }
  1028. protected function retrieveInput($post) {
  1029. $input = (object)array();
  1030. $data = trim(file_get_contents($post));
  1031. if (strlen($data)>0) {
  1032. if ($data[0]=='{') {
  1033. $input = json_decode($data);
  1034. } else {
  1035. parse_str($data, $input);
  1036. foreach ($input as $key => $value) {
  1037. if (substr($key,-9)=='__is_null') {
  1038. $input[substr($key,0,-9)] = null;
  1039. unset($input[$key]);
  1040. }
  1041. }
  1042. $input = (object)$input;
  1043. }
  1044. }
  1045. return $input;
  1046. }
  1047. protected function addRelationColumns($columns,$select) {
  1048. if ($columns) {
  1049. foreach ($select as $table=>$keys) {
  1050. foreach ($keys as $key=>$other) {
  1051. $columns.=",$table.$key,".implode('.',$other);
  1052. }
  1053. }
  1054. }
  1055. return $columns;
  1056. }
  1057. protected function findFields($tables,$columns,$database) {
  1058. $fields = array();
  1059. foreach ($tables as $i=>$table) {
  1060. $fields[$table] = $this->findTableFields($table,$database);
  1061. $fields[$table] = $this->filterFieldsByColumns($fields[$table],$columns,$i==0,$table);
  1062. }
  1063. return $fields;
  1064. }
  1065. protected function filterFieldsByColumns($fields,$columns,$first,$table) {
  1066. if ($columns) {
  1067. $columns = explode(',',$columns);
  1068. foreach (array_keys($fields) as $key) {
  1069. $delete = true;
  1070. foreach ($columns as $column) {
  1071. if (strpos($column,'.')) {
  1072. if ($column=="$table.$key" || $column=="$table.*") {
  1073. $delete = false;
  1074. }
  1075. } elseif ($first) {
  1076. if ($column==$key || $column=="*") {
  1077. $delete = false;
  1078. }
  1079. }
  1080. }
  1081. if ($delete) unset($fields[$key]);
  1082. }
  1083. }
  1084. return $fields;
  1085. }
  1086. protected function findTableFields($table,$database) {
  1087. $fields = array();
  1088. foreach ($this->db->fetchFields($table) as $field) {
  1089. $fields[$field->name] = $field;
  1090. }
  1091. return $fields;
  1092. }
  1093. protected function filterInputByFields($input,$fields) {
  1094. if ($fields) foreach (array_keys((array)$input) as $key) {
  1095. if (!isset($fields[$key])) {
  1096. unset($input->$key);
  1097. }
  1098. }
  1099. return $input;
  1100. }
  1101. protected function convertBinary(&$input,$keys) {
  1102. foreach ($keys as $key=>$field) {
  1103. if (isset($input->$key) && $input->$key && $this->db->isBinaryType($field)) {
  1104. $data = $input->$key;
  1105. $data = str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT);
  1106. $input->$key = (object)array('type'=>'base64','data'=>$data);
  1107. }
  1108. }
  1109. }
  1110. protected function getParameters($settings) {
  1111. extract($settings);
  1112. $table = $this->parseRequestParameter($request, 'a-zA-Z0-9\-_');
  1113. $key = $this->parseRequestParameter($request, 'a-zA-Z0-9\-_'); // auto-increment or uuid
  1114. $action = $this->mapMethodToAction($method,$key);
  1115. $include = $this->parseGetParameter($get, 'include', 'a-zA-Z0-9\-_,');
  1116. $callback = $this->parseGetParameter($get, 'callback', 'a-zA-Z0-9\-_');
  1117. $page = $this->parseGetParameter($get, 'page', '0-9,');
  1118. $filters = $this->parseGetParameterArray($get, 'filter', false);
  1119. $satisfy = $this->parseGetParameter($get, 'satisfy', 'a-zA-Z');
  1120. $columns = $this->parseGetParameter($get, 'columns', 'a-zA-Z0-9\-_,.*');
  1121. $order = $this->parseGetParameter($get, 'order', 'a-zA-Z0-9\-_,');
  1122. $transform = $this->parseGetParameter($get, 'transform', 't1');
  1123. $tables = $this->processTableAndIncludeParameters($database,$table,$include,$action);
  1124. $key = $this->processKeyParameter($key,$tables,$database);
  1125. $filters = $this->processFiltersParameter($tables,$satisfy,$filters);
  1126. $page = $this->processPageParameter($page);
  1127. $order = $this->processOrderParameter($order);
  1128. // reflection
  1129. list($tables,$collect,$select) = $this->findRelations($tables,$database);
  1130. $columns = $this->addRelationColumns($columns,$select);
  1131. $fields = $this->findFields($tables,$columns,$database);
  1132. // permissions
  1133. if ($table_authorizer) $this->applyTableAuthorizer($table_authorizer,$action,$database,$tables);
  1134. if (!isset($tables[0])) $this->exitWith404('entity');
  1135. if ($record_filter) $this->applyRecordFilter($record_filter,$action,$database,$tables,$filters);
  1136. if ($tenancy_function) $this->applyTenancyFunction($tenancy_function,$action,$database,$fields,$filters);
  1137. if ($column_authorizer) $this->applyColumnAuthorizer($column_authorizer,$action,$database,$fields);
  1138. if ($post) {
  1139. // input
  1140. $context = $this->retrieveInput($post);
  1141. $input = $this->filterInputByFields($context,$fields[$tables[0]]);
  1142. if ($tenancy_function) $this->applyInputTenancy($tenancy_function,$action,$database,$tables[0],$input,$fields[$tables[0]]);
  1143. if ($input_sanitizer) $this->applyInputSanitizer($input_sanitizer,$action,$database,$tables[0],$input,$fields[$tables[0]]);
  1144. if ($input_validator) $this->applyInputValidator($input_validator,$action,$database,$tables[0],$input,$fields[$tables[0]],$context);
  1145. $this->convertBinary($input,$fields[$tables[0]]);
  1146. }
  1147. return compact('action','database','tables','key','callback','page','filters','fields','order','transform','input','collect','select');
  1148. }
  1149. protected function addWhereFromFilters($filters,&$sql,&$params) {
  1150. $first = true;
  1151. if (isset($filters['or'])) {
  1152. $first = false;
  1153. $sql .= ' WHERE (';
  1154. foreach ($filters['or'] as $i=>$filter) {
  1155. $sql .= $i==0?'':' OR ';
  1156. $sql .= '"!" ! ?';
  1157. $params[] = $filter[0];
  1158. $params[] = $filter[1];
  1159. $params[] = $filter[2];
  1160. }
  1161. $sql .= ')';
  1162. }
  1163. if (isset($filters['and'])) {
  1164. foreach ($filters['and'] as $i=>$filter) {
  1165. $sql .= $first?' WHERE ':' AND ';
  1166. $sql .= '"!" ! ?';
  1167. $params[] = $filter[0];
  1168. $params[] = $filter[1];
  1169. $params[] = $filter[2];
  1170. $first = false;
  1171. }
  1172. }
  1173. }
  1174. protected function listCommandInternal($parameters) {
  1175. extract($parameters);
  1176. echo '{';
  1177. $table = array_shift($tables);
  1178. // first table
  1179. $count = false;
  1180. echo '"'.$table.'":{';
  1181. if (is_array($order) && is_array($page)) {
  1182. $params = array();
  1183. $sql = 'SELECT COUNT(*) FROM "!"';
  1184. $params[] = $table;
  1185. if (isset($filters[$table])) {
  1186. $this->addWhereFromFilters($filters[$table],$sql,$params);
  1187. }
  1188. if ($result = $this->db->query($sql,$params)) {
  1189. while ($pages = $this->db->fetchRow($result)) {
  1190. $count = $pages[0];
  1191. }
  1192. }
  1193. }
  1194. $params = array();
  1195. $sql = 'SELECT ';
  1196. $sql .= '"'.implode('","',array_keys($fields[$table])).'"';
  1197. $sql .= ' FROM "!"';
  1198. $params[] = $table;
  1199. if (isset($filters[$table])) {
  1200. $this->addWhereFromFilters($filters[$table],$sql,$params);
  1201. }
  1202. if (is_array($order)) {
  1203. $sql .= ' ORDER BY "!" !';
  1204. $params[] = $order[0];
  1205. $params[] = $order[1];
  1206. }
  1207. if (is_array($order) && is_array($page)) {
  1208. $sql = $this->db->addLimitToSql($sql,$page[1],$page[0]);
  1209. }
  1210. if ($result = $this->db->query($sql,$params)) {
  1211. echo '"columns":';
  1212. $keys = array();
  1213. $base64 = array();
  1214. foreach ($fields[$table] as $field) {
  1215. $base64[] = $this->db->isBinaryType($field);
  1216. $keys[] = $field->name;
  1217. }
  1218. echo json_encode($keys);
  1219. $keys = array_flip($keys);
  1220. echo ',"records":[';
  1221. $first_row = true;
  1222. while ($row = $this->db->fetchRow($result)) {
  1223. if ($first_row) $first_row = false;
  1224. else echo ',';
  1225. if (isset($collect[$table])) {
  1226. foreach (array_keys($collect[$table]) as $field) {
  1227. $collect[$table][$field][] = $row[$keys[$field]];
  1228. }
  1229. }
  1230. foreach ($base64 as $k=>$v) {
  1231. if ($v && $row[$k]) {
  1232. $row[$k] = $this->db->base64Encode($row[$k]);
  1233. }
  1234. }
  1235. echo json_encode($row);
  1236. }
  1237. $this->db->close($result);
  1238. echo ']';
  1239. if ($count) echo ',';
  1240. }
  1241. if ($count) echo '"results":'.$count;
  1242. echo '}';
  1243. // other tables
  1244. foreach ($tables as $t=>$table) {
  1245. echo ',';
  1246. echo '"'.$table.'":{';
  1247. $params = array();
  1248. $sql = 'SELECT ';
  1249. $sql .= '"'.implode('","',array_keys($fields[$table])).'"';
  1250. $sql .= ' FROM "!"';
  1251. $params[] = $table;
  1252. if (isset($select[$table])) {
  1253. echo '"relations":{';
  1254. $first_row = true;
  1255. foreach ($select[$table] as $field => $path) {
  1256. $values = $collect[$path[0]][$path[1]];
  1257. if (!isset($filters[$table])) $filters[$table] = array();
  1258. if (!isset($filters[$table]['or'])) $filters[$table]['or'] = array();
  1259. $filters[$table]['or'][] = array($field,'IN',$values);
  1260. if ($first_row) $first_row = false;
  1261. else echo ',';
  1262. echo '"'.$field.'":"'.implode('.',$path).'"';
  1263. }
  1264. echo '}';
  1265. $this->addWhereFromFilters($filters[$table],$sql,$params);
  1266. }
  1267. if ($result = $this->db->query($sql,$params)) {
  1268. if (isset($select[$table])) echo ',';
  1269. echo '"columns":';
  1270. $keys = array();
  1271. $base64 = array();
  1272. foreach ($fields[$table] as $field) {
  1273. $base64[] = $this->db->isBinaryType($field);
  1274. $keys[] = $field->name;
  1275. }
  1276. echo json_encode($keys);
  1277. $keys = array_flip($keys);
  1278. echo ',"records":[';
  1279. $first_row = true;
  1280. while ($row = $this->db->fetchRow($result)) {
  1281. if ($first_row) $first_row = false;
  1282. else echo ',';
  1283. if (isset($collect[$table])) {
  1284. foreach (array_keys($collect[$table]) as $field) {
  1285. $collect[$table][$field][]=$row[$keys[$field]];
  1286. }
  1287. }
  1288. foreach ($base64 as $k=>$v) {
  1289. if ($v && $row[$k]) {
  1290. $row[$k] = $this->db->base64Encode($row[$k]);
  1291. }
  1292. }
  1293. echo json_encode($row);
  1294. }
  1295. $this->db->close($result);
  1296. echo ']';
  1297. }
  1298. echo '}';
  1299. }
  1300. echo '}';
  1301. }
  1302. protected function readCommand($parameters) {
  1303. extract($parameters);
  1304. $object = $this->retrieveObject($key,$fields,$filters,$tables);
  1305. if (!$object) $this->exitWith404('object');
  1306. $this->startOutput($callback);
  1307. echo json_encode($object);
  1308. $this->endOutput($callback);
  1309. }
  1310. protected function createCommand($parameters) {
  1311. extract($parameters);
  1312. if (!$input) $this->exitWith404('input');
  1313. $this->startOutput($callback);
  1314. echo json_encode($this->createObject($input,$tables));
  1315. $this->endOutput($callback);
  1316. }
  1317. protected function updateCommand($parameters) {
  1318. extract($parameters);
  1319. if (!$input) $this->exitWith404('subject');
  1320. $this->startOutput($callback);
  1321. echo json_encode($this->updateObject($key,$input,$filters,$tables));
  1322. $this->endOutput($callback);
  1323. }
  1324. protected function deleteCommand($parameters) {
  1325. extract($parameters);
  1326. $this->startOutput($callback);
  1327. echo json_encode($this->deleteObject($key,$filters,$tables));
  1328. $this->endOutput($callback);
  1329. }
  1330. protected function listCommand($parameters) {
  1331. extract($parameters);
  1332. $this->startOutput($callback);
  1333. if ($transform) {
  1334. ob_start();
  1335. }
  1336. $this->listCommandInternal($parameters);
  1337. if ($transform) {
  1338. $content = ob_get_contents();
  1339. ob_end_clean();
  1340. $data = json_decode($content,true);
  1341. echo json_encode(self::php_crud_api_transform($data));
  1342. }
  1343. $this->endOutput($callback);
  1344. }
  1345. public function __construct($config) {
  1346. extract($config);
  1347. // initialize
  1348. $dbengine = isset($dbengine)?$dbengine:null;
  1349. $hostname = isset($hostname)?$hostname:null;
  1350. $username = isset($username)?$username:null;
  1351. $password = isset($password)?$password:null;
  1352. $database = isset($database)?$database:null;
  1353. $port = isset($port)?$port:null;
  1354. $socket = isset($socket)?$socket:null;
  1355. $charset = isset($charset)?$charset:null;
  1356. $table_authorizer = isset($table_authorizer)?$table_authorizer:null;
  1357. $record_filter = isset($record_filter)?$record_filter:null;
  1358. $column_authorizer = isset($column_authorizer)?$column_authorizer:null;
  1359. $tenancy_function = isset($tenancy_function)?$tenancy_function:null;
  1360. $input_sanitizer = isset($input_sanitizer)?$input_sanitizer:null;
  1361. $input_validator = isset($input_validator)?$input_validator:null;
  1362. $no_extensions = isset($no_extensions)?$no_extensions:null;
  1363. $db = isset($db)?$db:null;
  1364. $method = isset($method)?$method:null;
  1365. $request = isset($request)?$request:null;
  1366. $get = isset($get)?$get:null;
  1367. $post = isset($post)?$post:null;
  1368. // defaults
  1369. if (!$dbengine) {
  1370. $dbengine = 'MySQL';
  1371. }
  1372. if (!$method) {
  1373. $method = $_SERVER['REQUEST_METHOD'];
  1374. }
  1375. if (!$request) {
  1376. $request = isset($_SERVER['PATH_INFO'])?$_SERVER['PATH_INFO']:'';
  1377. if (!$request) {
  1378. $request = isset($_SERVER['ORIG_PATH_INFO'])?$_SERVER['ORIG_PATH_INFO']:'';
  1379. }
  1380. }
  1381. if (!$get) {
  1382. $get = $_GET;
  1383. }
  1384. if (!$post) {
  1385. $post = 'php://input';
  1386. }
  1387. // connect
  1388. $request = trim($request,'/');
  1389. if (!$database) {
  1390. $database = $this->parseRequestParameter($request, 'a-zA-Z0-9\-_');
  1391. }
  1392. if (!$db) {
  1393. $db = new $dbengine();
  1394. if (!$charset) {
  1395. $charset = $db->getDefaultCharset();
  1396. }
  1397. $db->connect($hostname,$username,$password,$database,$port,$socket,$charset);
  1398. }
  1399. $this->db = $db;
  1400. $this->settings = compact('method', 'request', 'get', 'post', 'database', 'table_authorizer', 'record_filter', 'column_authorizer', 'tenancy_function', 'input_sanitizer', 'input_validator', 'no_extensions');
  1401. }
  1402. public static function php_crud_api_transform(&$tables) {
  1403. $get_objects = function (&$tables,$table_name,$where_index=false,$match_value=false) use (&$get_objects) {
  1404. $objects = array();
  1405. if (isset($tables[$table_name]['records'])) {
  1406. foreach ($tables[$table_name]['records'] as $record) {
  1407. if ($where_index===false || $record[$where_index]==$match_value) {
  1408. $object = array();
  1409. foreach ($tables[$table_name]['columns'] as $index=>$column) {
  1410. $object[$column] = $record[$index];
  1411. foreach ($tables as $relation=>$reltable) {
  1412. if (isset($reltable['relations'])) {
  1413. foreach ($reltable['relations'] as $key=>$target) {
  1414. if ($target == "$table_name.$column") {
  1415. $column_indices = array_flip($reltable['columns']);
  1416. $object[$relation] = $get_objects($tables,$relation,$column_indices[$key],$record[$index]);
  1417. }
  1418. }
  1419. }
  1420. }
  1421. }
  1422. $objects[] = $object;
  1423. }
  1424. }
  1425. }
  1426. return $objects;
  1427. };
  1428. $tree = array();
  1429. foreach ($tables as $name=>$table) {
  1430. if (!isset($table['relations'])) {
  1431. $tree[$name] = $get_objects($tables,$name);
  1432. if (isset($table['results'])) {
  1433. $tree['_results'] = $table['results'];
  1434. }
  1435. }
  1436. }
  1437. return $tree;
  1438. }
  1439. protected function swagger($settings) {
  1440. extract($settings);
  1441. $tables = array();
  1442. if ($result = $this->db->query($this->db->getSql('list_tables'),array($database))) {
  1443. while ($row = $this->db->fetchRow($result)) {
  1444. $table = array(
  1445. 'name'=>$row[0],
  1446. 'comments'=>$row[1],
  1447. 'root_actions'=>array(
  1448. array('name'=>'list','method'=>'get'),
  1449. array('name'=>'create','method'=>'post'),
  1450. ),
  1451. 'id_actions'=>array(
  1452. array('name'=>'read','method'=>'get'),
  1453. array('name'=>'update','method'=>'put'),
  1454. array('name'=>'delete','method'=>'delete'),
  1455. ),
  1456. );
  1457. $tables[] = $table;
  1458. }
  1459. $this->db->close($result);
  1460. }
  1461. foreach ($tables as $t=>$table) {
  1462. $table_list = array($table['name']);
  1463. $table_fields = $this->findFields($table_list,false,$database);
  1464. $table_names = array_map(function($v){ return $v['name'];},$tables);
  1465. if (!$no_extensions) {
  1466. $result = $this->db->query($this->db->getSql('reflect_belongs_to'),array($table_list[0],$table_names,$database,$database));
  1467. while ($row = $this->db->fetchRow($result)) {
  1468. $table_fields[$table['name']][$row[1]]->references=array($row[2],$row[3]);
  1469. }
  1470. $result = $this->db->query($this->db->getSql('reflect_has_many'),array($table_names,$table_list[0],$database,$database));
  1471. while ($row = $this->db->fetchRow($result)) {
  1472. $table_fields[$table['name']][$row[3]]->referenced[]=array($row[0],$row[1]);
  1473. }
  1474. $primaryKeys = $this->findPrimaryKeys($table_list[0],$database);
  1475. foreach ($primaryKeys as $primaryKey) {
  1476. $table_fields[$table['name']][$primaryKey]->primaryKey = true;
  1477. }
  1478. }
  1479. foreach (array('root_actions','id_actions') as $path) {
  1480. foreach ($table[$path] as $i=>$action) {
  1481. $table_list = array($table['name']);
  1482. $fields = $table_fields;
  1483. if ($table_authorizer) $this->applyTableAuthorizer($table_authorizer,$action['name'],$database,$table_list);
  1484. if ($column_authorizer) $this->applyColumnAuthorizer($column_authorizer,$action['name'],$database,$fields);
  1485. if (!$table_list || !$fields[$table['name']]) $tables[$t][$path][$i] = false;
  1486. else $tables[$t][$path][$i]['fields'] = $fields[$table['name']];
  1487. }
  1488. // remove unauthorized tables and tables without fields
  1489. $tables[$t][$path] = array_values(array_filter($tables[$t][$path]));
  1490. }
  1491. if (!$tables[$t]['root_actions']&&!$tables[$t]['id_actions']) $tables[$t] = false;
  1492. }
  1493. $tables = array_merge(array_filter($tables));
  1494. //var_dump($tables);die();
  1495. header('Content-Type: application/json; charset=utf-8');
  1496. echo '{"swagger":"2.0",';
  1497. echo '"info":{';
  1498. echo '"title":"'.$database.'",';
  1499. echo '"description":"API generated with [PHP-CRUD-API](https://github.com/mevdschee/php-crud-api)",';
  1500. echo '"version":"1.0.0"';
  1501. echo '},';
  1502. echo '"host":"'.$_SERVER['HTTP_HOST'].'",';
  1503. echo '"basePath":"'.$_SERVER['SCRIPT_NAME'].'",';
  1504. echo '"schemes":["http'.((!empty($_SERVER['HTTPS'])&&$_SERVER['HTTPS']!=='off')?'s':'').'"],';
  1505. echo '"consumes":["application/json"],';
  1506. echo '"produces":["application/json"],';
  1507. echo '"tags":[';
  1508. foreach ($tables as $i=>$table) {
  1509. if ($i>0) echo ',';
  1510. echo '{';
  1511. echo '"name":"'.$table['name'].'",';
  1512. echo '"description":"'.$table['comments'].'"';
  1513. echo '}';
  1514. }
  1515. echo '],';
  1516. echo '"paths":{';
  1517. foreach ($tables as $i=>$table) {
  1518. if ($table['root_actions']) {
  1519. if ($i>0) echo ',';
  1520. echo '"/'.$table['name'].'":{';
  1521. foreach ($table['root_actions'] as $j=>$action) {
  1522. if ($j>0) echo ',';
  1523. echo '"'.$action['method'].'":{';
  1524. echo '"tags":["'.$table['name'].'"],';
  1525. echo '"summary":"'.ucfirst($action['name']).'",';
  1526. if ($action['name']=='list') {
  1527. echo '"parameters":[';
  1528. echo '{';
  1529. echo '"name":"include",';
  1530. echo '"in":"query",';
  1531. echo '"description":"One or more related entities (comma separated).",';
  1532. echo '"required":false,';
  1533. echo '"type":"string"';
  1534. echo '},';
  1535. echo '{';
  1536. echo '"name":"order",';
  1537. echo '"in":"query",';
  1538. echo '"description":"Column you want to sort on and the sort direction (comma separated). Example: id,desc",';
  1539. echo '"required":false,';
  1540. echo '"type":"string"';
  1541. echo '},';
  1542. echo '{';
  1543. echo '"name":"page",';
  1544. echo '"in":"query",';
  1545. echo '"description":"Page number and page size (comma separated). NB: You cannot use \"page\" without \"order\"! Example: 1,10",';
  1546. echo '"required":false,';
  1547. echo '"type":"string"';
  1548. echo '},';
  1549. echo '{';
  1550. echo '"name":"transform",';
  1551. echo '"in":"query",';
  1552. echo '"description":"Transform the records to object format. NB: This can also be done client-side in JavaScript!",';
  1553. echo '"required":false,';
  1554. echo '"type":"boolean"';
  1555. echo '},';
  1556. echo '{';
  1557. echo '"name":"columns",';
  1558. echo '"in":"query",';
  1559. echo '"description":"The table columns you want to retrieve (comma separated). Example: posts.*,categories.name",';
  1560. echo '"required":false,';
  1561. echo '"type":"string"';
  1562. echo '},';
  1563. echo '{';
  1564. echo '"name":"filter[]",';
  1565. echo '"in":"query",';
  1566. echo '"description":"Filters to be applied. Each filter consists of a column, an operator and a value (comma separated). Example: id,eq,1",';
  1567. echo '"required":false,';
  1568. echo '"type":"array",';
  1569. echo '"collectionFormat":"multi",';
  1570. echo '"items":{"type":"string"}';
  1571. echo '},';
  1572. echo '{';
  1573. echo '"name":"satisfy",';
  1574. echo '"in":"query",';
  1575. echo '"description":"Should all filters match (default)? Or any?",';
  1576. echo '"required":false,';
  1577. echo '"type":"string",';
  1578. echo '"enum":["any"]';
  1579. echo '},';
  1580. echo '{';
  1581. echo '"name":"callback",';
  1582. echo '"in":"query",';
  1583. echo '"description":"JSONP callback function name",';
  1584. echo '"required":false,';
  1585. echo '"type":"string"';
  1586. echo '}';
  1587. echo '],';
  1588. echo '"responses":{';
  1589. echo '"200":{';
  1590. echo '"description":"An array of '.$table['name'].'",';
  1591. echo '"schema":{';
  1592. echo '"type":"array",';
  1593. echo '"items":{';
  1594. echo '"type": "object",';
  1595. echo '"properties": {';
  1596. foreach (array_keys($action['fields']) as $k=>$field) {
  1597. if ($k>0) echo ',';
  1598. echo '"'.$field.'": {';
  1599. echo '"type": "string"';
  1600. if (isset($action['fields'][$field]->referenced)) {
  1601. echo ',"x-referenced": '.json_encode($action['fields'][$field]->referenced);
  1602. }
  1603. if (isset($action['fields'][$field]->references)) {
  1604. echo ',"x-references": '.json_encode($action['fields'][$field]->references);
  1605. }
  1606. if (isset($action['fields'][$field]->primaryKey)) {
  1607. echo ',"x-primary-key": true';
  1608. }
  1609. echo '}';
  1610. }
  1611. echo '}'; //properties
  1612. echo '}'; //items
  1613. echo '}'; //schema
  1614. echo '}'; //200
  1615. echo '}'; //responses
  1616. }
  1617. if ($action['name']=='create') {
  1618. echo '"parameters":[{';
  1619. echo '"name":"item",';
  1620. echo '"in":"body",';
  1621. echo '"description":"Item to create.",';
  1622. echo '"required":false,';
  1623. echo '"schema":{';
  1624. echo '"type": "object",';
  1625. echo '"properties": {';
  1626. foreach (array_keys($action['fields']) as $k=>$field) {
  1627. if ($k>0) echo ',';
  1628. echo '"'.$field.'": {';
  1629. echo '"type": "string"';
  1630. if (isset($action['fields'][$field]->referenced)) {
  1631. echo ',"x-referenced": '.json_encode($action['fields'][$field]->referenced);
  1632. }
  1633. if (isset($action['fields'][$field]->references)) {
  1634. echo ',"x-references": '.json_encode($action['fields'][$field]->references);
  1635. }
  1636. if (isset($action['fields'][$field]->primaryKey)) {
  1637. echo ',"x-primary-key": true';
  1638. }
  1639. echo '}';
  1640. }
  1641. echo '}'; //properties
  1642. echo '}'; //schema
  1643. echo '}],';
  1644. echo '"responses":{';
  1645. echo '"200":{';
  1646. echo '"description":"Identifier of created item.",';
  1647. echo '"schema":{';
  1648. echo '"type":"integer"';
  1649. echo '}';//schema
  1650. echo '}';//200
  1651. echo '}';//responses
  1652. }
  1653. echo '}';//method
  1654. }
  1655. echo '}';
  1656. }
  1657. if ($table['id_actions']) {
  1658. if ($i>0 || $table['root_actions']) echo ',';
  1659. echo '"/'.$table['name'].'/{id}":{';
  1660. foreach ($table['id_actions'] as $j=>$action) {
  1661. if ($j>0) echo ',';
  1662. echo '"'.$action['method'].'":{';
  1663. echo '"tags":["'.$table['name'].'"],';
  1664. echo '"summary":"'.ucfirst($action['name']).'",';
  1665. echo '"parameters":[';
  1666. echo '{';
  1667. echo '"name":"id",';
  1668. echo '"in":"path",';
  1669. echo '"description":"Identifier for item.",';
  1670. echo '"required":true,';
  1671. echo '"type":"string"';
  1672. echo '}';
  1673. if ($action['name']=='update') {
  1674. echo ',{';
  1675. echo '"name":"item",';
  1676. echo '"in":"body",';
  1677. echo '"description":"Properties of item to update.",';
  1678. echo '"required":false,';
  1679. echo '"schema":{';
  1680. echo '"type": "object",';
  1681. echo '"properties": {';
  1682. foreach (array_keys($action['fields']) as $k=>$field) {
  1683. if ($k>0) echo ',';
  1684. echo '"'.$field.'": {';
  1685. echo '"type": "string"';
  1686. if (isset($action['fields'][$field]->referenced)) {
  1687. echo ',"x-referenced": '.json_encode($action['fields'][$field]->referenced);
  1688. }
  1689. if (isset($action['fields'][$field]->references)) {
  1690. echo ',"x-references": '.json_encode($action['fields'][$field]->references);
  1691. }
  1692. if (isset($action['fields'][$field]->primaryKey)) {
  1693. echo ',"x-primary-key": true';
  1694. }
  1695. echo '}';
  1696. }
  1697. echo '}'; //properties
  1698. echo '}'; //schema
  1699. echo '}';
  1700. }
  1701. echo '],';
  1702. if ($action['name']=='read') {
  1703. echo '"responses":{';
  1704. echo '"200":{';
  1705. echo '"description":"The requested item.",';
  1706. echo '"schema":{';
  1707. echo '"type": "object",';
  1708. echo '"properties": {';
  1709. foreach (array_keys($action['fields']) as $k=>$field) {
  1710. if ($k>0) echo ',';
  1711. echo '"'.$field.'": {';
  1712. echo '"type": "string"';
  1713. if (isset($action['fields'][$field]->referenced)) {
  1714. echo ',"x-referenced": '.json_encode($action['fields'][$field]->referenced);
  1715. }
  1716. if (isset($action['fields'][$field]->references)) {
  1717. echo ',"x-references": '.json_encode($action['fields'][$field]->references);
  1718. }
  1719. if (isset($action['fields'][$field]->primaryKey)) {
  1720. echo ',"x-primary-key": true';
  1721. }
  1722. echo '}';
  1723. }
  1724. echo '}'; //properties
  1725. echo '}'; //schema
  1726. echo '}';
  1727. echo '}';
  1728. } else {
  1729. echo '"responses":{';
  1730. echo '"200":{';
  1731. echo '"description":"Number of affected rows.",';
  1732. echo '"schema":{';
  1733. echo '"type":"integer"';
  1734. echo '}';
  1735. echo '}';
  1736. echo '}';
  1737. }
  1738. echo '}';
  1739. }
  1740. echo '}';
  1741. }
  1742. }
  1743. echo '}';
  1744. echo '}';
  1745. }
  1746. public function executeCommand() {
  1747. if (isset($_SERVER['REQUEST_METHOD'])) {
  1748. header('Access-Control-Allow-Origin: *');
  1749. }
  1750. if (!$this->settings['request']) {
  1751. $this->swagger($this->settings);
  1752. } else {
  1753. $parameters = $this->getParameters($this->settings);
  1754. switch($parameters['action']){
  1755. case 'list': $this->listCommand($parameters); break;
  1756. case 'read': $this->readCommand($parameters); break;
  1757. case 'create': $this->createCommand($parameters); break;
  1758. case 'update': $this->updateCommand($parameters); break;
  1759. case 'delete': $this->deleteCommand($parameters); break;
  1760. case 'headers': $this->headersCommand($parameters); break;
  1761. }
  1762. }
  1763. }
  1764. }
  1765. // uncomment the lines below when running in stand-alone mode:
  1766. // $api = new PHP_CRUD_API(array(
  1767. // 'dbengine'=>'MySQL',
  1768. // 'hostname'=>'localhost',
  1769. // 'username'=>'xxx',
  1770. // 'password'=>'xxx',
  1771. // 'database'=>'xxx',
  1772. // 'charset'=>'utf8'
  1773. // ));
  1774. // $api->executeCommand();
  1775. // For Microsoft SQL Server 2012 use:
  1776. // $api = new PHP_CRUD_API(array(
  1777. // 'dbengine'=>'SQLServer',
  1778. // 'hostname'=>'(local)',
  1779. // 'username'=>'',
  1780. // 'password'=>'',
  1781. // 'database'=>'xxx',
  1782. // 'charset'=>'UTF-8'
  1783. // ));
  1784. // $api->executeCommand();
  1785. // For PostgreSQL 9 use:
  1786. // $api = new PHP_CRUD_API(array(
  1787. // 'dbengine'=>'PostgreSQL',
  1788. // 'hostname'=>'localhost',
  1789. // 'username'=>'xxx',
  1790. // 'password'=>'xxx',
  1791. // 'database'=>'xxx',
  1792. // 'charset'=>'UTF8'
  1793. // ));
  1794. // $api->executeCommand();
  1795. // For SQLite 3 use:
  1796. // $api = new PHP_CRUD_API(array(
  1797. // 'dbengine'=>'SQLite',
  1798. // 'database'=>'data/blog.db',
  1799. // ));
  1800. // $api->executeCommand();