PageRenderTime 52ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/web/lib/meekrodb.php

https://gitlab.com/JoelSanchez/lampadario
PHP | 956 lines | 745 code | 166 blank | 45 comment | 209 complexity | fd5d7080c9c5b2227135cfb1b42ca7e6 MD5 | raw file
  1. <?php
  2. /*
  3. Copyright (C) 2008-2012 Sergey Tsalkov (stsalkov@gmail.com)
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. class DB {
  16. // initial connection
  17. public static $dbName = '';
  18. public static $user = '';
  19. public static $password = '';
  20. public static $host = 'localhost';
  21. public static $port = null;
  22. public static $encoding = 'latin1';
  23. // configure workings
  24. public static $param_char = '%';
  25. public static $named_param_seperator = '_';
  26. public static $success_handler = false;
  27. public static $error_handler = true;
  28. public static $throw_exception_on_error = false;
  29. public static $nonsql_error_handler = null;
  30. public static $throw_exception_on_nonsql_error = false;
  31. public static $nested_transactions = false;
  32. public static $usenull = true;
  33. public static $ssl = array('key' => '', 'cert' => '', 'ca_cert' => '', 'ca_path' => '', 'cipher' => '');
  34. public static $connect_options = array(MYSQLI_OPT_CONNECT_TIMEOUT => 30);
  35. // internal
  36. protected static $mdb = null;
  37. public static function getMDB() {
  38. $mdb = DB::$mdb;
  39. if ($mdb === null) {
  40. $mdb = DB::$mdb = new MeekroDB();
  41. }
  42. static $variables_to_sync = array('param_char', 'named_param_seperator', 'success_handler', 'error_handler', 'throw_exception_on_error',
  43. 'nonsql_error_handler', 'throw_exception_on_nonsql_error', 'nested_transactions', 'usenull', 'ssl', 'connect_options');
  44. $db_class_vars = get_class_vars('DB'); // the DB::$$var syntax only works in 5.3+
  45. foreach ($variables_to_sync as $variable) {
  46. if ($mdb->$variable !== $db_class_vars[$variable]) {
  47. $mdb->$variable = $db_class_vars[$variable];
  48. }
  49. }
  50. return $mdb;
  51. }
  52. // yes, this is ugly. __callStatic() only works in 5.3+
  53. public static function get() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'get'), $args); }
  54. public static function disconnect() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'disconnect'), $args); }
  55. public static function query() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'query'), $args); }
  56. public static function queryFirstRow() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryFirstRow'), $args); }
  57. public static function queryOneRow() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryOneRow'), $args); }
  58. public static function queryAllLists() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryAllLists'), $args); }
  59. public static function queryFullColumns() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryFullColumns'), $args); }
  60. public static function queryFirstList() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryFirstList'), $args); }
  61. public static function queryOneList() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryOneList'), $args); }
  62. public static function queryFirstColumn() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryFirstColumn'), $args); }
  63. public static function queryOneColumn() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryOneColumn'), $args); }
  64. public static function queryFirstField() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryFirstField'), $args); }
  65. public static function queryOneField() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryOneField'), $args); }
  66. public static function queryRaw() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryRaw'), $args); }
  67. public static function queryRawUnbuf() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'queryRawUnbuf'), $args); }
  68. public static function insert() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'insert'), $args); }
  69. public static function insertIgnore() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'insertIgnore'), $args); }
  70. public static function insertUpdate() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'insertUpdate'), $args); }
  71. public static function replace() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'replace'), $args); }
  72. public static function update() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'update'), $args); }
  73. public static function delete() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'delete'), $args); }
  74. public static function insertId() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'insertId'), $args); }
  75. public static function count() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'count'), $args); }
  76. public static function affectedRows() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'affectedRows'), $args); }
  77. public static function useDB() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'useDB'), $args); }
  78. public static function startTransaction() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'startTransaction'), $args); }
  79. public static function commit() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'commit'), $args); }
  80. public static function rollback() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'rollback'), $args); }
  81. public static function tableList() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'tableList'), $args); }
  82. public static function columnList() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'columnList'), $args); }
  83. public static function sqlEval() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'sqlEval'), $args); }
  84. public static function nonSQLError() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'nonSQLError'), $args); }
  85. public static function serverVersion() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'serverVersion'), $args); }
  86. public static function transactionDepth() { $args = func_get_args(); return call_user_func_array(array(DB::getMDB(), 'transactionDepth'), $args); }
  87. public static function debugMode($handler = true) {
  88. DB::$success_handler = $handler;
  89. }
  90. }
  91. class MeekroDB {
  92. // initial connection
  93. public $dbName = '';
  94. public $user = '';
  95. public $password = '';
  96. public $host = 'localhost';
  97. public $port = null;
  98. public $encoding = 'latin1';
  99. // configure workings
  100. public $param_char = '%';
  101. public $named_param_seperator = '_';
  102. public $success_handler = false;
  103. public $error_handler = true;
  104. public $throw_exception_on_error = false;
  105. public $nonsql_error_handler = null;
  106. public $throw_exception_on_nonsql_error = false;
  107. public $nested_transactions = false;
  108. public $usenull = true;
  109. public $ssl = array('key' => '', 'cert' => '', 'ca_cert' => '', 'ca_path' => '', 'cipher' => '');
  110. public $connect_options = array(MYSQLI_OPT_CONNECT_TIMEOUT => 30);
  111. // internal
  112. public $internal_mysql = null;
  113. public $server_info = null;
  114. public $insert_id = 0;
  115. public $num_rows = 0;
  116. public $affected_rows = 0;
  117. public $current_db = null;
  118. public $nested_transactions_count = 0;
  119. public function __construct($host=null, $user=null, $password=null, $dbName=null, $port=null, $encoding=null) {
  120. if ($host === null) $host = DB::$host;
  121. if ($user === null) $user = DB::$user;
  122. if ($password === null) $password = DB::$password;
  123. if ($dbName === null) $dbName = DB::$dbName;
  124. if ($port === null) $port = DB::$port;
  125. if ($encoding === null) $encoding = DB::$encoding;
  126. $this->host = $host;
  127. $this->user = $user;
  128. $this->password = $password;
  129. $this->dbName = $dbName;
  130. $this->port = $port;
  131. $this->encoding = $encoding;
  132. }
  133. public function get() {
  134. $mysql = $this->internal_mysql;
  135. if (!($mysql instanceof MySQLi)) {
  136. if (! $this->port) $this->port = ini_get('mysqli.default_port');
  137. $this->current_db = $this->dbName;
  138. $mysql = new mysqli();
  139. $connect_flags = 0;
  140. if ($this->ssl['key']) {
  141. $mysql->ssl_set($this->ssl['key'], $this->ssl['cert'], $this->ssl['ca_cert'], $this->ssl['ca_path'], $this->ssl['cipher']);
  142. $connect_flags |= MYSQLI_CLIENT_SSL;
  143. }
  144. foreach ($this->connect_options as $key => $value) {
  145. $mysql->options($key, $value);
  146. }
  147. // suppress warnings, since we will check connect_error anyway
  148. @$mysql->real_connect($this->host, $this->user, $this->password, $this->dbName, $this->port, null, $connect_flags);
  149. if ($mysql->connect_error) {
  150. $this->nonSQLError('Unable to connect to MySQL server! Error: ' . $mysql->connect_error);
  151. }
  152. $mysql->set_charset($this->encoding);
  153. $this->internal_mysql = $mysql;
  154. $this->server_info = $mysql->server_info;
  155. }
  156. return $mysql;
  157. }
  158. public function disconnect() {
  159. $mysqli = $this->internal_mysql;
  160. if ($mysqli instanceof MySQLi) {
  161. if ($thread_id = $mysqli->thread_id) $mysqli->kill($thread_id);
  162. $mysqli->close();
  163. }
  164. $this->internal_mysql = null;
  165. }
  166. public function nonSQLError($message) {
  167. if ($this->throw_exception_on_nonsql_error) {
  168. $e = new MeekroDBException($message);
  169. throw $e;
  170. }
  171. $error_handler = is_callable($this->nonsql_error_handler) ? $this->nonsql_error_handler : 'meekrodb_error_handler';
  172. call_user_func($error_handler, array(
  173. 'type' => 'nonsql',
  174. 'error' => $message
  175. ));
  176. }
  177. public function debugMode($handler = true) {
  178. $this->success_handler = $handler;
  179. }
  180. public function serverVersion() { $this->get(); return $this->server_info; }
  181. public function transactionDepth() { return $this->nested_transactions_count; }
  182. public function insertId() { return $this->insert_id; }
  183. public function affectedRows() { return $this->affected_rows; }
  184. public function count() { $args = func_get_args(); return call_user_func_array(array($this, 'numRows'), $args); }
  185. public function numRows() { return $this->num_rows; }
  186. public function useDB() { $args = func_get_args(); return call_user_func_array(array($this, 'setDB'), $args); }
  187. public function setDB($dbName) {
  188. $db = $this->get();
  189. if (! $db->select_db($dbName)) $this->nonSQLError("Unable to set database to $dbName");
  190. $this->current_db = $dbName;
  191. }
  192. public function startTransaction() {
  193. if ($this->nested_transactions && $this->serverVersion() < '5.5') {
  194. return $this->nonSQLError("Nested transactions are only available on MySQL 5.5 and greater. You are using MySQL " . $this->serverVersion());
  195. }
  196. if (!$this->nested_transactions || $this->nested_transactions_count == 0) {
  197. $this->query('START TRANSACTION');
  198. $this->nested_transactions_count = 1;
  199. } else {
  200. $this->query("SAVEPOINT LEVEL{$this->nested_transactions_count}");
  201. $this->nested_transactions_count++;
  202. }
  203. return $this->nested_transactions_count;
  204. }
  205. public function commit($all=false) {
  206. if ($this->nested_transactions && $this->serverVersion() < '5.5') {
  207. return $this->nonSQLError("Nested transactions are only available on MySQL 5.5 and greater. You are using MySQL " . $this->serverVersion());
  208. }
  209. if ($this->nested_transactions && $this->nested_transactions_count > 0)
  210. $this->nested_transactions_count--;
  211. if (!$this->nested_transactions || $all || $this->nested_transactions_count == 0) {
  212. $this->nested_transactions_count = 0;
  213. $this->query('COMMIT');
  214. } else {
  215. $this->query("RELEASE SAVEPOINT LEVEL{$this->nested_transactions_count}");
  216. }
  217. return $this->nested_transactions_count;
  218. }
  219. public function rollback($all=false) {
  220. if ($this->nested_transactions && $this->serverVersion() < '5.5') {
  221. return $this->nonSQLError("Nested transactions are only available on MySQL 5.5 and greater. You are using MySQL " . $this->serverVersion());
  222. }
  223. if ($this->nested_transactions && $this->nested_transactions_count > 0)
  224. $this->nested_transactions_count--;
  225. if (!$this->nested_transactions || $all || $this->nested_transactions_count == 0) {
  226. $this->nested_transactions_count = 0;
  227. $this->query('ROLLBACK');
  228. } else {
  229. $this->query("ROLLBACK TO SAVEPOINT LEVEL{$this->nested_transactions_count}");
  230. }
  231. return $this->nested_transactions_count;
  232. }
  233. protected function formatTableName($table) {
  234. $table = trim($table, '`');
  235. if (strpos($table, '.')) return implode('.', array_map(array($this, 'formatTableName'), explode('.', $table)));
  236. else return '`' . str_replace('`', '``', $table) . '`';
  237. }
  238. public function update() {
  239. $args = func_get_args();
  240. $table = array_shift($args);
  241. $params = array_shift($args);
  242. $where = array_shift($args);
  243. $query = str_replace('%', $this->param_char, "UPDATE %b SET %? WHERE ") . $where;
  244. array_unshift($args, $params);
  245. array_unshift($args, $table);
  246. array_unshift($args, $query);
  247. return call_user_func_array(array($this, 'query'), $args);
  248. }
  249. public function insertOrReplace($which, $table, $datas, $options=array()) {
  250. $datas = unserialize(serialize($datas)); // break references within array
  251. $keys = $values = array();
  252. if (isset($datas[0]) && is_array($datas[0])) {
  253. foreach ($datas as $datum) {
  254. ksort($datum);
  255. if (! $keys) $keys = array_keys($datum);
  256. $values[] = array_values($datum);
  257. }
  258. } else {
  259. $keys = array_keys($datas);
  260. $values = array_values($datas);
  261. }
  262. if (isset($options['ignore']) && $options['ignore']) $which = 'INSERT IGNORE';
  263. if (isset($options['update']) && is_array($options['update']) && $options['update'] && strtolower($which) == 'insert') {
  264. if (array_values($options['update']) !== $options['update']) {
  265. return $this->query(
  266. str_replace('%', $this->param_char, "INSERT INTO %b %lb VALUES %? ON DUPLICATE KEY UPDATE %?"),
  267. $table, $keys, $values, $options['update']);
  268. } else {
  269. $update_str = array_shift($options['update']);
  270. $query_param = array(
  271. str_replace('%', $this->param_char, "INSERT INTO %b %lb VALUES %? ON DUPLICATE KEY UPDATE ") . $update_str,
  272. $table, $keys, $values);
  273. $query_param = array_merge($query_param, $options['update']);
  274. return call_user_func_array(array($this, 'query'), $query_param);
  275. }
  276. }
  277. return $this->query(
  278. str_replace('%', $this->param_char, "%l INTO %b %lb VALUES %?"),
  279. $which, $table, $keys, $values);
  280. }
  281. public function insert($table, $data) { return $this->insertOrReplace('INSERT', $table, $data); }
  282. public function insertIgnore($table, $data) { return $this->insertOrReplace('INSERT', $table, $data, array('ignore' => true)); }
  283. public function replace($table, $data) { return $this->insertOrReplace('REPLACE', $table, $data); }
  284. public function insertUpdate() {
  285. $args = func_get_args();
  286. $table = array_shift($args);
  287. $data = array_shift($args);
  288. if (! isset($args[0])) { // update will have all the data of the insert
  289. if (isset($data[0]) && is_array($data[0])) { //multiple insert rows specified -- failing!
  290. $this->nonSQLError("Badly formatted insertUpdate() query -- you didn't specify the update component!");
  291. }
  292. $args[0] = $data;
  293. }
  294. if (is_array($args[0])) $update = $args[0];
  295. else $update = $args;
  296. return $this->insertOrReplace('INSERT', $table, $data, array('update' => $update));
  297. }
  298. public function delete() {
  299. $args = func_get_args();
  300. $table = $this->formatTableName(array_shift($args));
  301. $where = array_shift($args);
  302. $buildquery = "DELETE FROM $table WHERE $where";
  303. array_unshift($args, $buildquery);
  304. return call_user_func_array(array($this, 'query'), $args);
  305. }
  306. public function sqleval() {
  307. $args = func_get_args();
  308. $text = call_user_func_array(array($this, 'parseQueryParams'), $args);
  309. return new MeekroDBEval($text);
  310. }
  311. public function columnList($table) {
  312. return $this->queryOneColumn('Field', "SHOW COLUMNS FROM %b", $table);
  313. }
  314. public function tableList($db = null) {
  315. if ($db) {
  316. $olddb = $this->current_db;
  317. $this->useDB($db);
  318. }
  319. $result = $this->queryFirstColumn('SHOW TABLES');
  320. if (isset($olddb)) $this->useDB($olddb);
  321. return $result;
  322. }
  323. protected function preparseQueryParams() {
  324. $args = func_get_args();
  325. $sql = trim(strval(array_shift($args)));
  326. $args_all = $args;
  327. if (count($args_all) == 0) return array($sql);
  328. $param_char_length = strlen($this->param_char);
  329. $named_seperator_length = strlen($this->named_param_seperator);
  330. $types = array(
  331. $this->param_char . 'll', // list of literals
  332. $this->param_char . 'ls', // list of strings
  333. $this->param_char . 'l', // literal
  334. $this->param_char . 'li', // list of integers
  335. $this->param_char . 'ld', // list of decimals
  336. $this->param_char . 'lb', // list of backticks
  337. $this->param_char . 'lt', // list of timestamps
  338. $this->param_char . 's', // string
  339. $this->param_char . 'i', // integer
  340. $this->param_char . 'd', // double / decimal
  341. $this->param_char . 'b', // backtick
  342. $this->param_char . 't', // timestamp
  343. $this->param_char . '?', // infer type
  344. $this->param_char . 'ss' // search string (like string, surrounded with %'s)
  345. );
  346. // generate list of all MeekroDB variables in our query, and their position
  347. // in the form "offset => variable", sorted by offsets
  348. $posList = array();
  349. foreach ($types as $type) {
  350. $lastPos = 0;
  351. while (($pos = strpos($sql, $type, $lastPos)) !== false) {
  352. $lastPos = $pos + 1;
  353. if (isset($posList[$pos]) && strlen($posList[$pos]) > strlen($type)) continue;
  354. $posList[$pos] = $type;
  355. }
  356. }
  357. ksort($posList);
  358. // for each MeekroDB variable, substitute it with array(type: i, value: 53) or whatever
  359. $chunkyQuery = array(); // preparsed query
  360. $pos_adj = 0; // how much we've added or removed from the original sql string
  361. foreach ($posList as $pos => $type) {
  362. $type = substr($type, $param_char_length); // variable, without % in front of it
  363. $length_type = strlen($type) + $param_char_length; // length of variable w/o %
  364. $new_pos = $pos + $pos_adj; // position of start of variable
  365. $new_pos_back = $new_pos + $length_type; // position of end of variable
  366. $arg_number_length = 0; // length of any named or numbered parameter addition
  367. // handle numbered parameters
  368. if ($arg_number_length = strspn($sql, '0123456789', $new_pos_back)) {
  369. $arg_number = substr($sql, $new_pos_back, $arg_number_length);
  370. if (! array_key_exists($arg_number, $args_all)) $this->nonSQLError("Non existent argument reference (arg $arg_number): $sql");
  371. $arg = $args_all[$arg_number];
  372. // handle named parameters
  373. } else if (substr($sql, $new_pos_back, $named_seperator_length) == $this->named_param_seperator) {
  374. $arg_number_length = strspn($sql, 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_',
  375. $new_pos_back + $named_seperator_length) + $named_seperator_length;
  376. $arg_number = substr($sql, $new_pos_back + $named_seperator_length, $arg_number_length - $named_seperator_length);
  377. if (count($args_all) != 1 || !is_array($args_all[0])) $this->nonSQLError("If you use named parameters, the second argument must be an array of parameters");
  378. if (! array_key_exists($arg_number, $args_all[0])) $this->nonSQLError("Non existent argument reference (arg $arg_number): $sql");
  379. $arg = $args_all[0][$arg_number];
  380. } else {
  381. $arg_number = 0;
  382. $arg = array_shift($args);
  383. }
  384. if ($new_pos > 0) $chunkyQuery[] = substr($sql, 0, $new_pos);
  385. if (is_object($arg) && ($arg instanceof WhereClause)) {
  386. list($clause_sql, $clause_args) = $arg->textAndArgs();
  387. array_unshift($clause_args, $clause_sql);
  388. $preparsed_sql = call_user_func_array(array($this, 'preparseQueryParams'), $clause_args);
  389. $chunkyQuery = array_merge($chunkyQuery, $preparsed_sql);
  390. } else {
  391. $chunkyQuery[] = array('type' => $type, 'value' => $arg);
  392. }
  393. $sql = substr($sql, $new_pos_back + $arg_number_length);
  394. $pos_adj -= $new_pos_back + $arg_number_length;
  395. }
  396. if (strlen($sql) > 0) $chunkyQuery[] = $sql;
  397. return $chunkyQuery;
  398. }
  399. protected function escape($str) { return "'" . $this->get()->real_escape_string(strval($str)) . "'"; }
  400. protected function sanitize($value) {
  401. if (is_object($value)) {
  402. if ($value instanceof MeekroDBEval) return $value->text;
  403. else if ($value instanceof DateTime) return $this->escape($value->format('Y-m-d H:i:s'));
  404. else return '';
  405. }
  406. if (is_null($value)) return $this->usenull ? 'NULL' : "''";
  407. else if (is_bool($value)) return ($value ? 1 : 0);
  408. else if (is_int($value)) return $value;
  409. else if (is_float($value)) return $value;
  410. else if (is_array($value)) {
  411. // non-assoc array?
  412. if (array_values($value) === $value) {
  413. if (is_array($value[0])) return implode(', ', array_map(array($this, 'sanitize'), $value));
  414. else return '(' . implode(', ', array_map(array($this, 'sanitize'), $value)) . ')';
  415. }
  416. $pairs = array();
  417. foreach ($value as $k => $v) {
  418. $pairs[] = $this->formatTableName($k) . '=' . $this->sanitize($v);
  419. }
  420. return implode(', ', $pairs);
  421. }
  422. else return $this->escape($value);
  423. }
  424. protected function parseTS($ts) {
  425. if (is_string($ts)) return date('Y-m-d H:i:s', strtotime($ts));
  426. else if (is_object($ts) && ($ts instanceof DateTime)) return $ts->format('Y-m-d H:i:s');
  427. }
  428. protected function intval($var) {
  429. if (PHP_INT_SIZE == 8) return intval($var);
  430. return floor(doubleval($var));
  431. }
  432. protected function parseQueryParams() {
  433. $args = func_get_args();
  434. $chunkyQuery = call_user_func_array(array($this, 'preparseQueryParams'), $args);
  435. $query = '';
  436. $array_types = array('ls', 'li', 'ld', 'lb', 'll', 'lt');
  437. foreach ($chunkyQuery as $chunk) {
  438. if (is_string($chunk)) {
  439. $query .= $chunk;
  440. continue;
  441. }
  442. $type = $chunk['type'];
  443. $arg = $chunk['value'];
  444. $result = '';
  445. if ($type != '?') {
  446. $is_array_type = in_array($type, $array_types, true);
  447. if ($is_array_type && !is_array($arg)) $this->nonSQLError("Badly formatted SQL query: Expected array, got scalar instead!");
  448. else if (!$is_array_type && is_array($arg)) $this->nonSQLError("Badly formatted SQL query: Expected scalar, got array instead!");
  449. }
  450. if ($type == 's') $result = $this->escape($arg);
  451. else if ($type == 'i') $result = $this->intval($arg);
  452. else if ($type == 'd') $result = doubleval($arg);
  453. else if ($type == 'b') $result = $this->formatTableName($arg);
  454. else if ($type == 'l') $result = $arg;
  455. else if ($type == 'ss') $result = $this->escape("%" . str_replace(array('%', '_'), array('\%', '\_'), $arg) . "%");
  456. else if ($type == 't') $result = $this->escape($this->parseTS($arg));
  457. else if ($type == 'ls') $result = array_map(array($this, 'escape'), $arg);
  458. else if ($type == 'li') $result = array_map(array($this, 'intval'), $arg);
  459. else if ($type == 'ld') $result = array_map('doubleval', $arg);
  460. else if ($type == 'lb') $result = array_map(array($this, 'formatTableName'), $arg);
  461. else if ($type == 'll') $result = $arg;
  462. else if ($type == 'lt') $result = array_map(array($this, 'escape'), array_map(array($this, 'parseTS'), $arg));
  463. else if ($type == '?') $result = $this->sanitize($arg);
  464. else $this->nonSQLError("Badly formatted SQL query: Invalid MeekroDB param $type");
  465. if (is_array($result)) $result = '(' . implode(',', $result) . ')';
  466. $query .= $result;
  467. }
  468. return $query;
  469. }
  470. protected function prependCall($function, $args, $prepend) { array_unshift($args, $prepend); return call_user_func_array($function, $args); }
  471. public function query() { $args = func_get_args(); return $this->prependCall(array($this, 'queryHelper'), $args, 'assoc'); }
  472. public function queryAllLists() { $args = func_get_args(); return $this->prependCall(array($this, 'queryHelper'), $args, 'list'); }
  473. public function queryFullColumns() { $args = func_get_args(); return $this->prependCall(array($this, 'queryHelper'), $args, 'full'); }
  474. public function queryRaw() { $args = func_get_args(); return $this->prependCall(array($this, 'queryHelper'), $args, 'raw_buf'); }
  475. public function queryRawUnbuf() { $args = func_get_args(); return $this->prependCall(array($this, 'queryHelper'), $args, 'raw_unbuf'); }
  476. protected function queryHelper() {
  477. $args = func_get_args();
  478. $type = array_shift($args);
  479. $db = $this->get();
  480. $is_buffered = true;
  481. $row_type = 'assoc'; // assoc, list, raw
  482. $full_names = false;
  483. switch ($type) {
  484. case 'assoc':
  485. break;
  486. case 'list':
  487. $row_type = 'list';
  488. break;
  489. case 'full':
  490. $row_type = 'list';
  491. $full_names = true;
  492. break;
  493. case 'raw_buf':
  494. $row_type = 'raw';
  495. break;
  496. case 'raw_unbuf':
  497. $is_buffered = false;
  498. $row_type = 'raw';
  499. break;
  500. default:
  501. $this->nonSQLError('Error -- invalid argument to queryHelper!');
  502. }
  503. $sql = call_user_func_array(array($this, 'parseQueryParams'), $args);
  504. if ($this->success_handler) $starttime = microtime(true);
  505. $result = $db->query($sql, $is_buffered ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT);
  506. if ($this->success_handler) $runtime = microtime(true) - $starttime;
  507. else $runtime = 0;
  508. // ----- BEGIN ERROR HANDLING
  509. if (!$sql || $db->error) {
  510. if ($this->error_handler) {
  511. $error_handler = is_callable($this->error_handler) ? $this->error_handler : 'meekrodb_error_handler';
  512. call_user_func($error_handler, array(
  513. 'type' => 'sql',
  514. 'query' => $sql,
  515. 'error' => $db->error,
  516. 'code' => $db->errno
  517. ));
  518. }
  519. if ($this->throw_exception_on_error) {
  520. $e = new MeekroDBException($db->error, $sql, $db->errno);
  521. throw $e;
  522. }
  523. } else if ($this->success_handler) {
  524. $runtime = sprintf('%f', $runtime * 1000);
  525. $success_handler = is_callable($this->success_handler) ? $this->success_handler : 'meekrodb_debugmode_handler';
  526. call_user_func($success_handler, array(
  527. 'query' => $sql,
  528. 'runtime' => $runtime,
  529. 'affected' => $db->affected_rows
  530. ));
  531. }
  532. // ----- END ERROR HANDLING
  533. $this->insert_id = $db->insert_id;
  534. $this->affected_rows = $db->affected_rows;
  535. // mysqli_result->num_rows won't initially show correct results for unbuffered data
  536. if ($is_buffered && ($result instanceof MySQLi_Result)) $this->num_rows = $result->num_rows;
  537. else $this->num_rows = null;
  538. if ($row_type == 'raw' || !($result instanceof MySQLi_Result)) return $result;
  539. $return = array();
  540. if ($full_names) {
  541. $infos = array();
  542. foreach ($result->fetch_fields() as $info) {
  543. if (strlen($info->table)) $infos[] = $info->table . '.' . $info->name;
  544. else $infos[] = $info->name;
  545. }
  546. }
  547. while ($row = ($row_type == 'assoc' ? $result->fetch_assoc() : $result->fetch_row())) {
  548. if ($full_names) $row = array_combine($infos, $row);
  549. $return[] = $row;
  550. }
  551. // free results
  552. $result->free();
  553. while ($db->more_results()) {
  554. $db->next_result();
  555. if ($result = $db->use_result()) $result->free();
  556. }
  557. return $return;
  558. }
  559. public function queryOneRow() { $args = func_get_args(); return call_user_func_array(array($this, 'queryFirstRow'), $args); }
  560. public function queryFirstRow() {
  561. $args = func_get_args();
  562. $result = call_user_func_array(array($this, 'query'), $args);
  563. if (!$result || !is_array($result)) return null;
  564. return reset($result);
  565. }
  566. public function queryOneList() { $args = func_get_args(); return call_user_func_array(array($this, 'queryFirstList'), $args); }
  567. public function queryFirstList() {
  568. $args = func_get_args();
  569. $result = call_user_func_array(array($this, 'queryAllLists'), $args);
  570. if (!$result || !is_array($result)) return null;
  571. return reset($result);
  572. }
  573. public function queryFirstColumn() {
  574. $args = func_get_args();
  575. $results = call_user_func_array(array($this, 'queryAllLists'), $args);
  576. $ret = array();
  577. if (!count($results) || !count($results[0])) return $ret;
  578. foreach ($results as $row) {
  579. $ret[] = $row[0];
  580. }
  581. return $ret;
  582. }
  583. public function queryOneColumn() {
  584. $args = func_get_args();
  585. $column = array_shift($args);
  586. $results = call_user_func_array(array($this, 'query'), $args);
  587. $ret = array();
  588. if (!count($results) || !count($results[0])) return $ret;
  589. if ($column === null) {
  590. $keys = array_keys($results[0]);
  591. $column = $keys[0];
  592. }
  593. foreach ($results as $row) {
  594. $ret[] = $row[$column];
  595. }
  596. return $ret;
  597. }
  598. public function queryFirstField() {
  599. $args = func_get_args();
  600. $row = call_user_func_array(array($this, 'queryFirstList'), $args);
  601. if ($row == null) return null;
  602. return $row[0];
  603. }
  604. public function queryOneField() {
  605. $args = func_get_args();
  606. $column = array_shift($args);
  607. $row = call_user_func_array(array($this, 'queryOneRow'), $args);
  608. if ($row == null) {
  609. return null;
  610. } else if ($column === null) {
  611. $keys = array_keys($row);
  612. $column = $keys[0];
  613. }
  614. return $row[$column];
  615. }
  616. }
  617. class WhereClause {
  618. public $type = 'and'; //AND or OR
  619. public $negate = false;
  620. public $clauses = array();
  621. function __construct($type) {
  622. $type = strtolower($type);
  623. if ($type !== 'or' && $type !== 'and') DB::nonSQLError('you must use either WhereClause(and) or WhereClause(or)');
  624. $this->type = $type;
  625. }
  626. function add() {
  627. $args = func_get_args();
  628. $sql = array_shift($args);
  629. if ($sql instanceof WhereClause) {
  630. $this->clauses[] = $sql;
  631. } else {
  632. $this->clauses[] = array('sql' => $sql, 'args' => $args);
  633. }
  634. }
  635. function negateLast() {
  636. $i = count($this->clauses) - 1;
  637. if (!isset($this->clauses[$i])) return;
  638. if ($this->clauses[$i] instanceof WhereClause) {
  639. $this->clauses[$i]->negate();
  640. } else {
  641. $this->clauses[$i]['sql'] = 'NOT (' . $this->clauses[$i]['sql'] . ')';
  642. }
  643. }
  644. function negate() {
  645. $this->negate = ! $this->negate;
  646. }
  647. function addClause($type) {
  648. $r = new WhereClause($type);
  649. $this->add($r);
  650. return $r;
  651. }
  652. function count() {
  653. return count($this->clauses);
  654. }
  655. function textAndArgs() {
  656. $sql = array();
  657. $args = array();
  658. if (count($this->clauses) == 0) return array('(1)', $args);
  659. foreach ($this->clauses as $clause) {
  660. if ($clause instanceof WhereClause) {
  661. list($clause_sql, $clause_args) = $clause->textAndArgs();
  662. } else {
  663. $clause_sql = $clause['sql'];
  664. $clause_args = $clause['args'];
  665. }
  666. $sql[] = "($clause_sql)";
  667. $args = array_merge($args, $clause_args);
  668. }
  669. if ($this->type == 'and') $sql = implode(' AND ', $sql);
  670. else $sql = implode(' OR ', $sql);
  671. if ($this->negate) $sql = '(NOT ' . $sql . ')';
  672. return array($sql, $args);
  673. }
  674. // backwards compatability
  675. // we now return full WhereClause object here and evaluate it in preparseQueryParams
  676. function text() { return $this; }
  677. }
  678. class DBTransaction {
  679. private $committed = false;
  680. function __construct() {
  681. DB::startTransaction();
  682. }
  683. function __destruct() {
  684. if (! $this->committed) DB::rollback();
  685. }
  686. function commit() {
  687. DB::commit();
  688. $this->committed = true;
  689. }
  690. }
  691. class MeekroDBException extends Exception {
  692. protected $query = '';
  693. function __construct($message='', $query='', $code = 0) {
  694. parent::__construct($message);
  695. $this->query = $query;
  696. $this->code = $code;
  697. }
  698. public function getQuery() { return $this->query; }
  699. }
  700. class DBHelper {
  701. /*
  702. verticalSlice
  703. 1. For an array of assoc rays, return an array of values for a particular key
  704. 2. if $keyfield is given, same as above but use that hash key as the key in new array
  705. */
  706. public static function verticalSlice($array, $field, $keyfield = null) {
  707. $array = (array) $array;
  708. $R = array();
  709. foreach ($array as $obj) {
  710. if (! array_key_exists($field, $obj)) die("verticalSlice: array doesn't have requested field\n");
  711. if ($keyfield) {
  712. if (! array_key_exists($keyfield, $obj)) die("verticalSlice: array doesn't have requested field\n");
  713. $R[$obj[$keyfield]] = $obj[$field];
  714. } else {
  715. $R[] = $obj[$field];
  716. }
  717. }
  718. return $R;
  719. }
  720. /*
  721. reIndex
  722. For an array of assoc rays, return a new array of assoc rays using a certain field for keys
  723. */
  724. public static function reIndex() {
  725. $fields = func_get_args();
  726. $array = array_shift($fields);
  727. $array = (array) $array;
  728. $R = array();
  729. foreach ($array as $obj) {
  730. $target =& $R;
  731. foreach ($fields as $field) {
  732. if (! array_key_exists($field, $obj)) die("reIndex: array doesn't have requested field\n");
  733. $nextkey = $obj[$field];
  734. $target =& $target[$nextkey];
  735. }
  736. $target = $obj;
  737. }
  738. return $R;
  739. }
  740. }
  741. function meekrodb_error_handler($params) {
  742. if (isset($params['query'])) $out[] = "QUERY: " . $params['query'];
  743. if (isset($params['error'])) $out[] = "ERROR: " . $params['error'];
  744. $out[] = "";
  745. if (php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR'])) {
  746. echo implode("\n", $out);
  747. } else {
  748. echo implode("<br>\n", $out);
  749. }
  750. die;
  751. }
  752. function meekrodb_debugmode_handler($params) {
  753. echo "QUERY: " . $params['query'] . " [" . $params['runtime'] . " ms]";
  754. if (php_sapi_name() == 'cli' && empty($_SERVER['REMOTE_ADDR'])) {
  755. echo "\n";
  756. } else {
  757. echo "<br>\n";
  758. }
  759. }
  760. class MeekroDBEval {
  761. public $text = '';
  762. function __construct($text) {
  763. $this->text = $text;
  764. }
  765. }
  766. ?>