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.

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