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

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