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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894
  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 processKeyParameter($key,$tables,$database) {
  860. if (!$key) return false;
  861. $count = 0;
  862. $field = false;
  863. if ($result = $this->db->query($this->db->getSql('reflect_pk'),array($tables[0],$database))) {
  864. while ($row = $this->db->fetchRow($result)) {
  865. $count++;
  866. $field = $row[0];
  867. }
  868. $this->db->close($result);
  869. }
  870. if ($count!=1 || $field==false) $this->exitWith404('1pk');
  871. return array($key,$field);
  872. }
  873. protected function processOrderParameter($order) {
  874. if (!$order) return false;
  875. $order = explode(',',$order,2);
  876. if (count($order)<2) $order[1]='ASC';
  877. if (!strlen($order[0])) return false;
  878. $order[1] = strtoupper($order[1])=='DESC'?'DESC':'ASC';
  879. return $order;
  880. }
  881. protected function convertFilter($field, $comparator, $value) {
  882. switch (strtolower($comparator)) {
  883. case 'cs': $comparator = 'LIKE'; $value = '%'.$this->db->likeEscape($value).'%'; break;
  884. case 'sw': $comparator = 'LIKE'; $value = $this->db->likeEscape($value).'%'; break;
  885. case 'ew': $comparator = 'LIKE'; $value = '%'.$this->db->likeEscape($value); break;
  886. case 'eq': $comparator = '='; break;
  887. case 'ne': $comparator = '<>'; break;
  888. case 'lt': $comparator = '<'; break;
  889. case 'le': $comparator = '<='; break;
  890. case 'ge': $comparator = '>='; break;
  891. case 'gt': $comparator = '>'; break;
  892. case 'in': $comparator = 'IN'; $value = explode(',',$value); break;
  893. case 'ni': $comparator = 'NOT IN'; $value = explode(',',$value); break;
  894. case 'is': $comparator = 'IS'; $value = null; break;
  895. case 'no': $comparator = 'IS NOT'; $value = null; break;
  896. }
  897. return array($field, $comparator, $value);
  898. }
  899. protected function convertFilters($filters) {
  900. $result = array();
  901. if ($filters) {
  902. for ($i=0;$i<count($filters);$i++) {
  903. $filter = explode(',',$filters[$i],3);
  904. if (count($filter)==3) {
  905. $result[] = $this->convertFilter($filter[0],$filter[1],$filter[2]);
  906. } elseif (count($filter)==2) {
  907. $result[] = $this->convertFilter($filter[0],$filter[1],null);
  908. }
  909. }
  910. }
  911. return $result;
  912. }
  913. protected function processFiltersParameter($tables,$satisfy,$filters) {
  914. $result = $this->convertFilters($filters);
  915. if (!$result) return array();
  916. $and = ($satisfy && strtolower($satisfy)=='any')?'or':'and';
  917. return array($tables[0]=>array($and=>$result));
  918. }
  919. protected function processPageParameter($page) {
  920. if (!$page) return false;
  921. $page = explode(',',$page,2);
  922. if (count($page)<2) $page[1]=20;
  923. $page[0] = ($page[0]-1)*$page[1];
  924. return $page;
  925. }
  926. protected function retrieveObject($key,$fields,$filters,$tables) {
  927. if (!$key) return false;
  928. $table = $tables[0];
  929. $sql = 'SELECT ';
  930. $sql .= '"'.implode('","',array_keys($fields[$table])).'"';
  931. $sql .= ' FROM "!"';
  932. $params = array($table);
  933. if (!isset($filters[$table])) $filters[$table] = array();
  934. if (!isset($filters[$table]['or'])) $filters[$table]['or'] = array();
  935. $filters[$table]['or'][] = array($key[1],'=',$key[0]);
  936. $this->addWhereFromFilters($filters[$table],$sql,$params);
  937. $object = null;
  938. if ($result = $this->db->query($sql,$params)) {
  939. $object = $this->db->fetchAssoc($result);
  940. foreach ($fields[$table] as $field) {
  941. if ($this->db->isBinaryType($field) && $object[$field->name]) {
  942. $object[$field->name] = $this->db->base64Encode($object[$field->name]);
  943. }
  944. }
  945. $this->db->close($result);
  946. }
  947. return $object;
  948. }
  949. protected function createObject($input,$tables) {
  950. if (!$input) return false;
  951. $input = (array)$input;
  952. $keys = implode('","',str_split(str_repeat('!', count($input))));
  953. $values = implode(',',str_split(str_repeat('?', count($input))));
  954. $params = array_merge(array_keys($input),array_values($input));
  955. array_unshift($params, $tables[0]);
  956. $result = $this->db->query('INSERT INTO "!" ("'.$keys.'") VALUES ('.$values.')',$params);
  957. if (!$result) return null;
  958. return $this->db->insertId($result);
  959. }
  960. protected function updateObject($key,$input,$filters,$tables) {
  961. if (!$input) return false;
  962. $input = (array)$input;
  963. $table = $tables[0];
  964. $sql = 'UPDATE "!" SET ';
  965. $params = array($table);
  966. foreach (array_keys($input) as $i=>$k) {
  967. if ($i) $sql .= ',';
  968. $v = $input[$k];
  969. $sql .= '"!"=?';
  970. $params[] = $k;
  971. $params[] = $v;
  972. }
  973. if (!isset($filters[$table])) $filters[$table] = array();
  974. if (!isset($filters[$table]['or'])) $filters[$table]['or'] = array();
  975. $filters[$table]['or'][] = array($key[1],'=',$key[0]);
  976. $this->addWhereFromFilters($filters[$table],$sql,$params);
  977. $result = $this->db->query($sql,$params);
  978. if (!$result) return null;
  979. return $this->db->affectedRows($result);
  980. }
  981. protected function deleteObject($key,$filters,$tables) {
  982. $table = $tables[0];
  983. $sql = 'DELETE FROM "!"';
  984. $params = array($table);
  985. if (!isset($filters[$table])) $filters[$table] = array();
  986. if (!isset($filters[$table]['or'])) $filters[$table]['or'] = array();
  987. $filters[$table]['or'][] = array($key[1],'=',$key[0]);
  988. $this->addWhereFromFilters($filters[$table],$sql,$params);
  989. $result = $this->db->query($sql,$params);
  990. if (!$result) return null;
  991. return $this->db->affectedRows($result);
  992. }
  993. protected function findRelations($tables,$database) {
  994. $tableset = array();
  995. $collect = array();
  996. $select = array();
  997. while (count($tables)>1) {
  998. $table0 = array_shift($tables);
  999. $tableset[] = $table0;
  1000. $result = $this->db->query($this->db->getSql('reflect_belongs_to'),array($table0,$tables,$database,$database));
  1001. while ($row = $this->db->fetchRow($result)) {
  1002. $collect[$row[0]][$row[1]]=array();
  1003. $select[$row[2]][$row[3]]=array($row[0],$row[1]);
  1004. if (!in_array($row[0],$tableset)) $tableset[] = $row[0];
  1005. }
  1006. $result = $this->db->query($this->db->getSql('reflect_has_many'),array($tables,$table0,$database,$database));
  1007. while ($row = $this->db->fetchRow($result)) {
  1008. $collect[$row[2]][$row[3]]=array();
  1009. $select[$row[0]][$row[1]]=array($row[2],$row[3]);
  1010. if (!in_array($row[2],$tableset)) $tableset[] = $row[2];
  1011. }
  1012. $result = $this->db->query($this->db->getSql('reflect_habtm'),array($database,$database,$database,$database,$table0,$tables));
  1013. while ($row = $this->db->fetchRow($result)) {
  1014. $collect[$row[2]][$row[3]]=array();
  1015. $select[$row[0]][$row[1]]=array($row[2],$row[3]);
  1016. $collect[$row[4]][$row[5]]=array();
  1017. $select[$row[6]][$row[7]]=array($row[4],$row[5]);
  1018. if (!in_array($row[2],$tableset)) $tableset[] = $row[2];
  1019. if (!in_array($row[4],$tableset)) $tableset[] = $row[4];
  1020. }
  1021. }
  1022. $tableset[] = array_shift($tables);
  1023. $tableset = array_unique($tableset);
  1024. return array($tableset,$collect,$select);
  1025. }
  1026. protected function retrieveInput($post) {
  1027. $input = (object)array();
  1028. $data = trim(file_get_contents($post));
  1029. if (strlen($data)>0) {
  1030. if ($data[0]=='{') {
  1031. $input = json_decode($data);
  1032. } else {
  1033. parse_str($data, $input);
  1034. foreach ($input as $key => $value) {
  1035. if (substr($key,-9)=='__is_null') {
  1036. $input[substr($key,0,-9)] = null;
  1037. unset($input[$key]);
  1038. }
  1039. }
  1040. $input = (object)$input;
  1041. }
  1042. }
  1043. return $input;
  1044. }
  1045. protected function addRelationColumns($columns,$select) {
  1046. if ($columns) {
  1047. foreach ($select as $table=>$keys) {
  1048. foreach ($keys as $key=>$other) {
  1049. $columns.=",$table.$key,".implode('.',$other);
  1050. }
  1051. }
  1052. }
  1053. return $columns;
  1054. }
  1055. protected function findFields($tables,$columns,$database) {
  1056. $fields = array();
  1057. foreach ($tables as $i=>$table) {
  1058. $fields[$table] = $this->findTableFields($table,$database);
  1059. $fields[$table] = $this->filterFieldsByColumns($fields[$table],$columns,$i==0,$table);
  1060. }
  1061. return $fields;
  1062. }
  1063. protected function filterFieldsByColumns($fields,$columns,$first,$table) {
  1064. if ($columns) {
  1065. $columns = explode(',',$columns);
  1066. foreach (array_keys($fields) as $key) {
  1067. $delete = true;
  1068. foreach ($columns as $column) {
  1069. if (strpos($column,'.')) {
  1070. if ($column=="$table.$key" || $column=="$table.*") {
  1071. $delete = false;
  1072. }
  1073. } elseif ($first) {
  1074. if ($column==$key || $column=="*") {
  1075. $delete = false;
  1076. }
  1077. }
  1078. }
  1079. if ($delete) unset($fields[$key]);
  1080. }
  1081. }
  1082. return $fields;
  1083. }
  1084. protected function findTableFields($table,$database) {
  1085. $fields = array();
  1086. foreach ($this->db->fetchFields($table) as $field) {
  1087. $fields[$field->name] = $field;
  1088. }
  1089. return $fields;
  1090. }
  1091. protected function filterInputByFields($input,$fields) {
  1092. if ($fields) foreach (array_keys((array)$input) as $key) {
  1093. if (!isset($fields[$key])) {
  1094. unset($input->$key);
  1095. }
  1096. }
  1097. return $input;
  1098. }
  1099. protected function convertBinary(&$input,$keys) {
  1100. foreach ($keys as $key=>$field) {
  1101. if (isset($input->$key) && $input->$key && $this->db->isBinaryType($field)) {
  1102. $data = $input->$key;
  1103. $data = str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT);
  1104. $input->$key = (object)array('type'=>'base64','data'=>$data);
  1105. }
  1106. }
  1107. }
  1108. protected function getParameters($settings) {
  1109. extract($settings);
  1110. $table = $this->parseRequestParameter($request, 'a-zA-Z0-9\-_');
  1111. $key = $this->parseRequestParameter($request, 'a-zA-Z0-9\-_'); // auto-increment or uuid
  1112. $action = $this->mapMethodToAction($method,$key);
  1113. $include = $this->parseGetParameter($get, 'include', 'a-zA-Z0-9\-_,');
  1114. $callback = $this->parseGetParameter($get, 'callback', 'a-zA-Z0-9\-_');
  1115. $page = $this->parseGetParameter($get, 'page', '0-9,');
  1116. $filters = $this->parseGetParameterArray($get, 'filter', false);
  1117. $satisfy = $this->parseGetParameter($get, 'satisfy', 'a-zA-Z');
  1118. $columns = $this->parseGetParameter($get, 'columns', 'a-zA-Z0-9\-_,.*');
  1119. $order = $this->parseGetParameter($get, 'order', 'a-zA-Z0-9\-_,');
  1120. $transform = $this->parseGetParameter($get, 'transform', 't1');
  1121. $tables = $this->processTableAndIncludeParameters($database,$table,$include,$action);
  1122. $key = $this->processKeyParameter($key,$tables,$database);
  1123. $filters = $this->processFiltersParameter($tables,$satisfy,$filters);
  1124. $page = $this->processPageParameter($page);
  1125. $order = $this->processOrderParameter($order);
  1126. // reflection
  1127. list($tables,$collect,$select) = $this->findRelations($tables,$database);
  1128. $columns = $this->addRelationColumns($columns,$select);
  1129. $fields = $this->findFields($tables,$columns,$database);
  1130. // permissions
  1131. if ($table_authorizer) $this->applyTableAuthorizer($table_authorizer,$action,$database,$tables);
  1132. if (!isset($tables[0])) $this->exitWith404('entity');
  1133. if ($record_filter) $this->applyRecordFilter($record_filter,$action,$database,$tables,$filters);
  1134. if ($tenancy_function) $this->applyTenancyFunction($tenancy_function,$action,$database,$fields,$filters);
  1135. if ($column_authorizer) $this->applyColumnAuthorizer($column_authorizer,$action,$database,$fields);
  1136. if ($post) {
  1137. // input
  1138. $context = $this->retrieveInput($post);
  1139. $input = $this->filterInputByFields($context,$fields[$tables[0]]);
  1140. if ($tenancy_function) $this->applyInputTenancy($tenancy_function,$action,$database,$tables[0],$input,$fields[$tables[0]]);
  1141. if ($input_sanitizer) $this->applyInputSanitizer($input_sanitizer,$action,$database,$tables[0],$input,$fields[$tables[0]]);
  1142. if ($input_validator) $this->applyInputValidator($input_validator,$action,$database,$tables[0],$input,$fields[$tables[0]],$context);
  1143. $this->convertBinary($input,$fields[$tables[0]]);
  1144. }
  1145. return compact('action','database','tables','key','callback','page','filters','fields','order','transform','input','collect','select');
  1146. }
  1147. protected function addWhereFromFilters($filters,&$sql,&$params) {
  1148. $first = true;
  1149. if (isset($filters['or'])) {
  1150. $first = false;
  1151. $sql .= ' WHERE (';
  1152. foreach ($filters['or'] as $i=>$filter) {
  1153. $sql .= $i==0?'':' OR ';
  1154. $sql .= '"!" ! ?';
  1155. $params[] = $filter[0];
  1156. $params[] = $filter[1];
  1157. $params[] = $filter[2];
  1158. }
  1159. $sql .= ')';
  1160. }
  1161. if (isset($filters['and'])) {
  1162. foreach ($filters['and'] as $i=>$filter) {
  1163. $sql .= $first?' WHERE ':' AND ';
  1164. $sql .= '"!" ! ?';
  1165. $params[] = $filter[0];
  1166. $params[] = $filter[1];
  1167. $params[] = $filter[2];
  1168. $first = false;
  1169. }
  1170. }
  1171. }
  1172. protected function listCommandInternal($parameters) {
  1173. extract($parameters);
  1174. echo '{';
  1175. $table = array_shift($tables);
  1176. // first table
  1177. $count = false;
  1178. echo '"'.$table.'":{';
  1179. if (is_array($order) && is_array($page)) {
  1180. $params = array();
  1181. $sql = 'SELECT COUNT(*) FROM "!"';
  1182. $params[] = $table;
  1183. if (isset($filters[$table])) {
  1184. $this->addWhereFromFilters($filters[$table],$sql,$params);
  1185. }
  1186. if ($result = $this->db->query($sql,$params)) {
  1187. while ($pages = $this->db->fetchRow($result)) {
  1188. $count = $pages[0];
  1189. }
  1190. }
  1191. }
  1192. $params = array();
  1193. $sql = 'SELECT ';
  1194. $sql .= '"'.implode('","',array_keys($fields[$table])).'"';
  1195. $sql .= ' FROM "!"';
  1196. $params[] = $table;
  1197. if (isset($filters[$table])) {
  1198. $this->addWhereFromFilters($filters[$table],$sql,$params);
  1199. }
  1200. if (is_array($order)) {
  1201. $sql .= ' ORDER BY "!" !';
  1202. $params[] = $order[0];
  1203. $params[] = $order[1];
  1204. }
  1205. if (is_array($order) && is_array($page)) {
  1206. $sql = $this->db->addLimitToSql($sql,$page[1],$page[0]);
  1207. }
  1208. if ($result = $this->db->query($sql,$params)) {
  1209. echo '"columns":';
  1210. $keys = array();
  1211. $base64 = array();
  1212. foreach ($fields[$table] as $field) {
  1213. $base64[] = $this->db->isBinaryType($field);
  1214. $keys[] = $field->name;
  1215. }
  1216. echo json_encode($keys);
  1217. $keys = array_flip($keys);
  1218. echo ',"records":[';
  1219. $first_row = true;
  1220. while ($row = $this->db->fetchRow($result)) {
  1221. if ($first_row) $first_row = false;
  1222. else echo ',';
  1223. if (isset($collect[$table])) {
  1224. foreach (array_keys($collect[$table]) as $field) {
  1225. $collect[$table][$field][] = $row[$keys[$field]];
  1226. }
  1227. }
  1228. foreach ($base64 as $k=>$v) {
  1229. if ($v && $row[$k]) {
  1230. $row[$k] = $this->db->base64Encode($row[$k]);
  1231. }
  1232. }
  1233. echo json_encode($row);
  1234. }
  1235. $this->db->close($result);
  1236. echo ']';
  1237. if ($count) echo ',';
  1238. }
  1239. if ($count) echo '"results":'.$count;
  1240. echo '}';
  1241. // other tables
  1242. foreach ($tables as $t=>$table) {
  1243. echo ',';
  1244. echo '"'.$table.'":{';
  1245. $params = array();
  1246. $sql = 'SELECT ';
  1247. $sql .= '"'.implode('","',array_keys($fields[$table])).'"';
  1248. $sql .= ' FROM "!"';
  1249. $params[] = $table;
  1250. if (isset($select[$table])) {
  1251. echo '"relations":{';
  1252. $first_row = true;
  1253. foreach ($select[$table] as $field => $path) {
  1254. $values = $collect[$path[0]][$path[1]];
  1255. if (!isset($filters[$table])) $filters[$table] = array();
  1256. if (!isset($filters[$table]['or'])) $filters[$table]['or'] = array();
  1257. $filters[$table]['or'][] = array($field,'IN',$values);
  1258. if ($first_row) $first_row = false;
  1259. else echo ',';
  1260. echo '"'.$field.'":"'.implode('.',$path).'"';
  1261. }
  1262. echo '}';
  1263. $this->addWhereFromFilters($filters[$table],$sql,$params);
  1264. }
  1265. if ($result = $this->db->query($sql,$params)) {
  1266. if (isset($select[$table])) echo ',';
  1267. echo '"columns":';
  1268. $keys = array();
  1269. $base64 = array();
  1270. foreach ($fields[$table] as $field) {
  1271. $base64[] = $this->db->isBinaryType($field);
  1272. $keys[] = $field->name;
  1273. }
  1274. echo json_encode($keys);
  1275. $keys = array_flip($keys);
  1276. echo ',"records":[';
  1277. $first_row = true;
  1278. while ($row = $this->db->fetchRow($result)) {
  1279. if ($first_row) $first_row = false;
  1280. else echo ',';
  1281. if (isset($collect[$table])) {
  1282. foreach (array_keys($collect[$table]) as $field) {
  1283. $collect[$table][$field][]=$row[$keys[$field]];
  1284. }
  1285. }
  1286. foreach ($base64 as $k=>$v) {
  1287. if ($v && $row[$k]) {
  1288. $row[$k] = $this->db->base64Encode($row[$k]);
  1289. }
  1290. }
  1291. echo json_encode($row);
  1292. }
  1293. $this->db->close($result);
  1294. echo ']';
  1295. }
  1296. echo '}';
  1297. }
  1298. echo '}';
  1299. }
  1300. protected function readCommand($parameters) {
  1301. extract($parameters);
  1302. $object = $this->retrieveObject($key,$fields,$filters,$tables);
  1303. if (!$object) $this->exitWith404('object');
  1304. $this->startOutput($callback);
  1305. echo json_encode($object);
  1306. $this->endOutput($callback);
  1307. }
  1308. protected function createCommand($parameters) {
  1309. extract($parameters);
  1310. if (!$input) $this->exitWith404('input');
  1311. $this->startOutput($callback);
  1312. echo json_encode($this->createObject($input,$tables));
  1313. $this->endOutput($callback);
  1314. }
  1315. protected function updateCommand($parameters) {
  1316. extract($parameters);
  1317. if (!$input) $this->exitWith404('subject');
  1318. $this->startOutput($callback);
  1319. echo json_encode($this->updateObject($key,$input,$filters,$tables));
  1320. $this->endOutput($callback);
  1321. }
  1322. protected function deleteCommand($parameters) {
  1323. extract($parameters);
  1324. $this->startOutput($callback);
  1325. echo json_encode($this->deleteObject($key,$filters,$tables));
  1326. $this->endOutput($callback);
  1327. }
  1328. protected function listCommand($parameters) {
  1329. extract($parameters);
  1330. $this->startOutput($callback);
  1331. if ($transform) {
  1332. ob_start();
  1333. }
  1334. $this->listCommandInternal($parameters);
  1335. if ($transform) {
  1336. $content = ob_get_contents();
  1337. ob_end_clean();
  1338. $data = json_decode($content,true);
  1339. echo json_encode(self::php_crud_api_transform($data));
  1340. }
  1341. $this->endOutput($callback);
  1342. }
  1343. public function __construct($config) {
  1344. extract($config);
  1345. // initialize
  1346. $dbengine = isset($dbengine)?$dbengine:null;
  1347. $hostname = isset($hostname)?$hostname:null;
  1348. $username = isset($username)?$username:null;
  1349. $password = isset($password)?$password:null;
  1350. $database = isset($database)?$database:null;
  1351. $port = isset($port)?$port:null;
  1352. $socket = isset($socket)?$socket:null;
  1353. $charset = isset($charset)?$charset:null;
  1354. $table_authorizer = isset($table_authorizer)?$table_authorizer:null;
  1355. $record_filter = isset($record_filter)?$record_filter:null;
  1356. $column_authorizer = isset($column_authorizer)?$column_authorizer:null;
  1357. $tenancy_function = isset($tenancy_function)?$tenancy_function:null;
  1358. $input_sanitizer = isset($input_sanitizer)?$input_sanitizer:null;
  1359. $input_validator = isset($input_validator)?$input_validator:null;
  1360. $db = isset($db)?$db:null;
  1361. $method = isset($method)?$method:null;
  1362. $request = isset($request)?$request:null;
  1363. $get = isset($get)?$get:null;
  1364. $post = isset($post)?$post:null;
  1365. // defaults
  1366. if (!$dbengine) {
  1367. $dbengine = 'MySQL';
  1368. }
  1369. if (!$method) {
  1370. $method = $_SERVER['REQUEST_METHOD'];
  1371. }
  1372. if (!$request) {
  1373. $request = isset($_SERVER['PATH_INFO'])?$_SERVER['PATH_INFO']:'';
  1374. if (!$request) {
  1375. $request = isset($_SERVER['ORIG_PATH_INFO'])?$_SERVER['ORIG_PATH_INFO']:'';
  1376. }
  1377. }
  1378. if (!$get) {
  1379. $get = $_GET;
  1380. }
  1381. if (!$post) {
  1382. $post = 'php://input';
  1383. }
  1384. // connect
  1385. $request = trim($request,'/');
  1386. if (!$database) {
  1387. $database = $this->parseRequestParameter($request, 'a-zA-Z0-9\-_');
  1388. }
  1389. if (!$db) {
  1390. $db = new $dbengine();
  1391. if (!$charset) {
  1392. $charset = $db->getDefaultCharset();
  1393. }
  1394. $db->connect($hostname,$username,$password,$database,$port,$socket,$charset);
  1395. }
  1396. $this->db = $db;
  1397. $this->settings = compact('method', 'request', 'get', 'post', 'database', 'table_authorizer', 'record_filter', 'column_authorizer', 'tenancy_function', 'input_sanitizer', 'input_validator');
  1398. }
  1399. public static function php_crud_api_transform(&$tables) {
  1400. $get_objects = function (&$tables,$table_name,$where_index=false,$match_value=false) use (&$get_objects) {
  1401. $objects = array();
  1402. if (isset($tables[$table_name]['records'])) {
  1403. foreach ($tables[$table_name]['records'] as $record) {
  1404. if ($where_index===false || $record[$where_index]==$match_value) {
  1405. $object = array();
  1406. foreach ($tables[$table_name]['columns'] as $index=>$column) {
  1407. $object[$column] = $record[$index];
  1408. foreach ($tables as $relation=>$reltable) {
  1409. if (isset($reltable['relations'])) {
  1410. foreach ($reltable['relations'] as $key=>$target) {
  1411. if ($target == "$table_name.$column") {
  1412. $column_indices = array_flip($reltable['columns']);
  1413. $object[$relation] = $get_objects($tables,$relation,$column_indices[$key],$record[$index]);
  1414. }
  1415. }
  1416. }
  1417. }
  1418. }
  1419. $objects[] = $object;
  1420. }
  1421. }
  1422. }
  1423. return $objects;
  1424. };
  1425. $tree = array();
  1426. foreach ($tables as $name=>$table) {
  1427. if (!isset($table['relations'])) {
  1428. $tree[$name] = $get_objects($tables,$name);
  1429. if (isset($table['results'])) {
  1430. $tree['_results'] = $table['results'];
  1431. }
  1432. }
  1433. }
  1434. return $tree;
  1435. }
  1436. protected function swagger($settings) {
  1437. extract($settings);
  1438. $tables = array();
  1439. if ($result = $this->db->query($this->db->getSql('list_tables'),array($database))) {
  1440. while ($row = $this->db->fetchRow($result)) {
  1441. $table = array(
  1442. 'name'=>$row[0],
  1443. 'comments'=>$row[1],
  1444. 'root_actions'=>array(
  1445. array('name'=>'list','method'=>'get'),
  1446. array('name'=>'create','method'=>'post'),
  1447. ),
  1448. 'id_actions'=>array(
  1449. array('name'=>'read','method'=>'get'),
  1450. array('name'=>'update','method'=>'put'),
  1451. array('name'=>'delete','method'=>'delete'),
  1452. ),
  1453. );
  1454. $tables[] = $table;
  1455. }
  1456. $this->db->close($result);
  1457. }
  1458. foreach ($tables as $t=>$table) {
  1459. foreach (array('root_actions','id_actions') as $path) {
  1460. foreach ($table[$path] as $i=>$action) {
  1461. $table_list = array($table['name']);
  1462. $fields = $this->findFields($table_list,false,$database);
  1463. if ($table_authorizer) $this->applyTableAuthorizer($table_authorizer,$action['name'],$database,$table_list);
  1464. if ($column_authorizer) $this->applyColumnAuthorizer($column_authorizer,$action['name'],$database,$fields);
  1465. if (!$table_list || !$fields[$table['name']]) $tables[$t][$path][$i] = false;
  1466. else $tables[$t][$path][$i]['fields'] = $fields[$table['name']];
  1467. }
  1468. // remove unauthorized tables and tables without fields
  1469. $tables[$t][$path] = array_values(array_filter($tables[$t][$path]));
  1470. }
  1471. if (!$tables[$t]['root_actions']&&!$tables[$t]['id_actions']) $tables[$t] = false;
  1472. }
  1473. $tables = array_merge(array_filter($tables));
  1474. //var_dump($tables);die();
  1475. header('Content-Type: application/json; charset=utf-8');
  1476. echo '{"swagger":"2.0",';
  1477. echo '"info":{';
  1478. echo '"title":"'.$database.'",';
  1479. echo '"description":"API generated with [PHP_CRUD_API](https://github.com/mevdschee/php-crud-api)",';
  1480. echo '"version":"1.0.0"';
  1481. echo '},';
  1482. echo '"host":"'.$_SERVER['HTTP_HOST'].'",';
  1483. echo '"basePath":"'.$_SERVER['SCRIPT_NAME'].'",';
  1484. echo '"schemes":["http'.((!empty($_SERVER['HTTPS'])&&$_SERVER['HTTPS']!=='off')?'s':'').'"],';
  1485. echo '"consumes":["application/json"],';
  1486. echo '"produces":["application/json"],';
  1487. echo '"tags":[';
  1488. foreach ($tables as $i=>$table) {
  1489. if ($i>0) echo ',';
  1490. echo '{';
  1491. echo '"name":"'.$table['name'].'",';
  1492. echo '"description":"'.$table['comments'].'"';
  1493. echo '}';
  1494. }
  1495. echo '],';
  1496. echo '"paths":{';
  1497. foreach ($tables as $i=>$table) {
  1498. if ($table['root_actions']) {
  1499. if ($i>0) echo ',';
  1500. echo '"/'.$table['name'].'":{';
  1501. foreach ($table['root_actions'] as $j=>$action) {
  1502. if ($j>0) echo ',';
  1503. echo '"'.$action['method'].'":{';
  1504. echo '"tags":["'.$table['name'].'"],';
  1505. echo '"summary":"'.ucfirst($action['name']).'",';
  1506. if ($action['name']=='list') {
  1507. echo '"parameters":[';
  1508. echo '{';
  1509. echo '"name":"include",';
  1510. echo '"in":"query",';
  1511. echo '"description":"One or more related entities (comma separated).",';
  1512. echo '"required":false,';
  1513. echo '"type":"string"';
  1514. echo '},';
  1515. echo '{';
  1516. echo '"name":"order",';
  1517. echo '"in":"query",';
  1518. echo '"description":"Column you want to sort on and the sort direction (comma separated). Example: id,desc",';
  1519. echo '"required":false,';
  1520. echo '"type":"string"';
  1521. echo '},';
  1522. echo '{';
  1523. echo '"name":"page",';
  1524. echo '"in":"query",';
  1525. echo '"description":"Page number and page size (comma separated). NB: You cannot use \"page\" without \"order\"! Example: 1,10",';
  1526. echo '"required":false,';
  1527. echo '"type":"string"';
  1528. echo '},';
  1529. echo '{';
  1530. echo '"name":"transform",';
  1531. echo '"in":"query",';
  1532. echo '"description":"Transform the records to object format. NB: This can also be done client-side in JavaScript!",';
  1533. echo '"required":false,';
  1534. echo '"type":"boolean"';
  1535. echo '},';
  1536. echo '{';
  1537. echo '"name":"columns",';
  1538. echo '"in":"query",';
  1539. echo '"description":"The table columns you want to retrieve (comma separated). Example: posts.*,categories.name",';
  1540. echo '"required":false,';
  1541. echo '"type":"string"';
  1542. echo '},';
  1543. echo '{';
  1544. echo '"name":"filter[]",';
  1545. echo '"in":"query",';
  1546. echo '"description":"Filters to be applied. Each filter consists of a column, an operator and a value (comma separated). Example: id,eq,1",';
  1547. echo '"required":false,';
  1548. echo '"type":"array",';
  1549. echo '"collectionFormat":"multi",';
  1550. echo '"items":{"type":"string"}';
  1551. echo '},';
  1552. echo '{';
  1553. echo '"name":"satisfy",';
  1554. echo '"in":"query",';
  1555. echo '"description":"Should all filters match (default)? Or any?",';
  1556. echo '"required":false,';
  1557. echo '"type":"string",';
  1558. echo '"enum":["any"]';
  1559. echo '},';
  1560. echo '{';
  1561. echo '"name":"callback",';
  1562. echo '"in":"query",';
  1563. echo '"description":"JSONP callback function name",';
  1564. echo '"required":false,';
  1565. echo '"type":"string"';
  1566. echo '}';
  1567. echo '],';
  1568. echo '"responses":{';
  1569. echo '"200":{';
  1570. echo '"description":"An array of '.$table['name'].'",';
  1571. echo '"schema":{';
  1572. echo '"type":"array",';
  1573. echo '"items":{';
  1574. echo '"type": "object",';
  1575. echo '"properties": {';
  1576. foreach (array_keys($action['fields']) as $k=>$field) {
  1577. if ($k>0) echo ',';
  1578. echo '"'.$field.'": {';
  1579. echo '"type": "string"';
  1580. echo '}';
  1581. }
  1582. echo '}'; //properties
  1583. echo '}'; //items
  1584. echo '}'; //schema
  1585. echo '}'; //200
  1586. echo '}'; //responses
  1587. }
  1588. if ($action['name']=='create') {
  1589. echo '"parameters":[{';
  1590. echo '"name":"item",';
  1591. echo '"in":"body",';
  1592. echo '"description":"Item to create.",';
  1593. echo '"required":false,';
  1594. echo '"schema":{';
  1595. echo '"type": "object",';
  1596. echo '"properties": {';
  1597. foreach (array_keys($action['fields']) as $k=>$field) {
  1598. if ($k>0) echo ',';
  1599. echo '"'.$field.'": {';
  1600. echo '"type": "string"';
  1601. echo '}';
  1602. }
  1603. echo '}'; //properties
  1604. echo '}'; //schema
  1605. echo '}],';
  1606. echo '"responses":{';
  1607. echo '"200":{';
  1608. echo '"description":"Identifier of created item.",';
  1609. echo '"schema":{';
  1610. echo '"type":"integer"';
  1611. echo '}';//schema
  1612. echo '}';//200
  1613. echo '}';//responses
  1614. }
  1615. echo '}';//method
  1616. }
  1617. echo '}';
  1618. }
  1619. if ($table['id_actions']) {
  1620. if ($i>0 || $table['root_actions']) echo ',';
  1621. echo '"/'.$table['name'].'/{id}":{';
  1622. foreach ($table['id_actions'] as $j=>$action) {
  1623. if ($j>0) echo ',';
  1624. echo '"'.$action['method'].'":{';
  1625. echo '"tags":["'.$table['name'].'"],';
  1626. echo '"summary":"'.ucfirst($action['name']).'",';
  1627. echo '"parameters":[';
  1628. echo '{';
  1629. echo '"name":"id",';
  1630. echo '"in":"path",';
  1631. echo '"description":"Identifier for item.",';
  1632. echo '"required":true,';
  1633. echo '"type":"string"';
  1634. echo '}';
  1635. if ($action['name']=='update') {
  1636. echo ',{';
  1637. echo '"name":"item",';
  1638. echo '"in":"body",';
  1639. echo '"description":"Properties of item to update.",';
  1640. echo '"required":false,';
  1641. echo '"schema":{';
  1642. echo '"type": "object",';
  1643. echo '"properties": {';
  1644. foreach (array_keys($action['fields']) as $k=>$field) {
  1645. if ($k>0) echo ',';
  1646. echo '"'.$field.'": {';
  1647. echo '"type": "string"';
  1648. echo '}';
  1649. }
  1650. echo '}'; //properties
  1651. echo '}'; //schema
  1652. echo '}';
  1653. }
  1654. echo '],';
  1655. if ($action['name']=='read') {
  1656. echo '"responses":{';
  1657. echo '"200":{';
  1658. echo '"description":"The requested item.",';
  1659. echo '"schema":{';
  1660. echo '"type": "object",';
  1661. echo '"properties": {';
  1662. foreach (array_keys($action['fields']) as $k=>$field) {
  1663. if ($k>0) echo ',';
  1664. echo '"'.$field.'": {';
  1665. echo '"type": "string"';
  1666. echo '}';
  1667. }
  1668. echo '}'; //properties
  1669. echo '}'; //schema
  1670. echo '}';
  1671. echo '}';
  1672. } else {
  1673. echo '"responses":{';
  1674. echo '"200":{';
  1675. echo '"description":"Number of affected rows.",';
  1676. echo '"schema":{';
  1677. echo '"type":"integer"';
  1678. echo '}';
  1679. echo '}';
  1680. echo '}';
  1681. }
  1682. echo '}';
  1683. }
  1684. echo '}';
  1685. }
  1686. }
  1687. echo '}';
  1688. echo '}';
  1689. }
  1690. public function executeCommand() {
  1691. if (isset($_SERVER['REQUEST_METHOD'])) {
  1692. header('Access-Control-Allow-Origin: *');
  1693. }
  1694. if (!$this->settings['request']) {
  1695. $this->swagger($this->settings);
  1696. } else {
  1697. $parameters = $this->getParameters($this->settings);
  1698. switch($parameters['action']){
  1699. case 'list': $this->listCommand($parameters); break;
  1700. case 'read': $this->readCommand($parameters); break;
  1701. case 'create': $this->createCommand($parameters); break;
  1702. case 'update': $this->updateCommand($parameters); break;
  1703. case 'delete': $this->deleteCommand($parameters); break;
  1704. case 'headers': $this->headersCommand($parameters); break;
  1705. }
  1706. }
  1707. }
  1708. }
  1709. // uncomment the lines below when running in stand-alone mode:
  1710. // $api = new PHP_CRUD_API(array(
  1711. // 'dbengine'=>'MySQL',
  1712. // 'hostname'=>'localhost',
  1713. // 'username'=>'xxx',
  1714. // 'password'=>'xxx',
  1715. // 'database'=>'xxx',
  1716. // 'charset'=>'utf8'
  1717. // ));
  1718. // $api->executeCommand();
  1719. // For Microsoft SQL Server 2012 use:
  1720. // $api = new PHP_CRUD_API(array(
  1721. // 'dbengine'=>'SQLServer',
  1722. // 'hostname'=>'(local)',
  1723. // 'username'=>'',
  1724. // 'password'=>'',
  1725. // 'database'=>'xxx',
  1726. // 'charset'=>'UTF-8'
  1727. // ));
  1728. // $api->executeCommand();
  1729. // For PostgreSQL 9 use:
  1730. // $api = new PHP_CRUD_API(array(
  1731. // 'dbengine'=>'PostgreSQL',
  1732. // 'hostname'=>'localhost',
  1733. // 'username'=>'xxx',
  1734. // 'password'=>'xxx',
  1735. // 'database'=>'xxx',
  1736. // 'charset'=>'UTF8'
  1737. // ));
  1738. // $api->executeCommand();
  1739. // For SQLite 3 use:
  1740. // $api = new PHP_CRUD_API(array(
  1741. // 'dbengine'=>'SQLite',
  1742. // 'database'=>'data/blog.db',
  1743. // ));
  1744. // $api->executeCommand();