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
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

api.php 58KB

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