PageRenderTime 59ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/libs/extensions/ezSQL/ez_sql_core.php

https://github.com/shibuya246/Hotaru-Plugins
PHP | 604 lines | 339 code | 133 blank | 132 comment | 46 complexity | 95ba9a710ed55008e242bd8743384021 MD5 | raw file
  1. <?php
  2. /**********************************************************************
  3. * Author: Justin Vincent (justin@visunet.ie)
  4. * Web...: http://php.justinvincent.com
  5. * Name..: ezSQL
  6. * Desc..: ezSQL Core module - database abstraction library to make
  7. * it very easy to deal with databases.
  8. *
  9. */
  10. /**********************************************************************
  11. * ezSQL Constants
  12. */
  13. define('EZSQL_VERSION','2.03');
  14. define('OBJECT','OBJECT',true);
  15. define('ARRAY_A','ARRAY_A',true);
  16. define('ARRAY_N','ARRAY_N',true);
  17. define('EZSQL_CORE_ERROR','ezSQLcore can not be used by itself (it is designed for use by database specific modules).');
  18. /**********************************************************************
  19. * Core class containg common functions to manipulate query result
  20. * sets once returned
  21. */
  22. class ezSQLcore
  23. {
  24. var $trace = false; // same as $debug_all
  25. var $debug_all = false; // same as $trace
  26. var $debug_called = false;
  27. var $vardump_called = false;
  28. var $show_errors = true;
  29. var $num_queries = 0;
  30. var $last_query = null;
  31. var $last_error = null;
  32. var $col_info = null;
  33. var $captured_errors = array();
  34. var $cache_dir = false;
  35. var $cache_queries = false;
  36. var $cache_inserts = false;
  37. var $use_disk_cache = false;
  38. var $cache_timeout = 24; // hours
  39. // == TJH == default now needed for echo of debug function
  40. var $debug_echo_is_on = true;
  41. /**********************************************************************
  42. * Constructor
  43. */
  44. function ezSQLcore()
  45. {
  46. }
  47. /**********************************************************************
  48. * Connect to DB - over-ridden by specific DB class
  49. */
  50. function connect()
  51. {
  52. die(EZSQL_CORE_ERROR);
  53. }
  54. /**********************************************************************
  55. * Select DB - over-ridden by specific DB class
  56. */
  57. function selectDB()
  58. {
  59. die(EZSQL_CORE_ERROR);
  60. }
  61. /**********************************************************************
  62. * Basic Query - over-ridden by specific DB class
  63. */
  64. function query($query = '')
  65. {
  66. die(EZSQL_CORE_ERROR);
  67. }
  68. /**********************************************************************
  69. * Format a string correctly for safe insert - over-ridden by specific
  70. * DB class
  71. */
  72. function escape($str = '')
  73. {
  74. die(EZSQL_CORE_ERROR);
  75. }
  76. /**********************************************************************
  77. * Return database specific system date syntax
  78. * i.e. Oracle: SYSDATE Mysql: NOW()
  79. */
  80. function sysdate()
  81. {
  82. die(EZSQL_CORE_ERROR);
  83. }
  84. /**********************************************************************
  85. * Print SQL/DB error - over-ridden by specific DB class
  86. */
  87. function register_error($err_str)
  88. {
  89. // Keep track of last error
  90. $this->last_error = $err_str;
  91. // Capture all errors to an error array no matter what happens
  92. $this->captured_errors[] = array
  93. (
  94. 'error_str' => $err_str,
  95. 'query' => $this->last_query
  96. );
  97. }
  98. /**********************************************************************
  99. * Turn error handling on or off..
  100. */
  101. function show_errors()
  102. {
  103. $this->show_errors = true;
  104. }
  105. function hide_errors()
  106. {
  107. $this->show_errors = false;
  108. }
  109. /**********************************************************************
  110. * Kill cached query results
  111. */
  112. function flush()
  113. {
  114. // Get rid of these
  115. $this->last_result = null;
  116. $this->col_info = null;
  117. $this->last_query = null;
  118. $this->from_disk_cache = false;
  119. }
  120. /**********************************************************************
  121. * Get one variable from the DB - see docs for more detail
  122. */
  123. function get_var($query=null,$x=0,$y=0)
  124. {
  125. // Log how the function was called
  126. $this->func_call = "\$db->get_var(\"$query\",$x,$y)";
  127. // If there is a query then perform it if not then use cached results..
  128. if ( $query )
  129. {
  130. $this->query($query);
  131. }
  132. // Extract var out of cached results based x,y vals
  133. if ( $this->last_result[$y] )
  134. {
  135. $values = array_values(get_object_vars($this->last_result[$y]));
  136. }
  137. // If there is a value return it else return null
  138. return (isset($values[$x]) && $values[$x]!=='')?$values[$x]:null;
  139. }
  140. /**********************************************************************
  141. * Get one row from the DB - see docs for more detail
  142. */
  143. function get_row($query=null,$output=OBJECT,$y=0)
  144. {
  145. // Log how the function was called
  146. $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
  147. // If there is a query then perform it if not then use cached results..
  148. if ( $query )
  149. {
  150. $this->query($query);
  151. }
  152. // If the output is an object then return object using the row offset..
  153. if ( $output == OBJECT )
  154. {
  155. return $this->last_result[$y]?$this->last_result[$y]:null;
  156. }
  157. // If the output is an associative array then return row as such..
  158. elseif ( $output == ARRAY_A )
  159. {
  160. return $this->last_result[$y]?get_object_vars($this->last_result[$y]):null;
  161. }
  162. // If the output is an numerical array then return row as such..
  163. elseif ( $output == ARRAY_N )
  164. {
  165. return $this->last_result[$y]?array_values(get_object_vars($this->last_result[$y])):null;
  166. }
  167. // If invalid output type was specified..
  168. else
  169. {
  170. $this->print_error(" \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N");
  171. }
  172. }
  173. /**********************************************************************
  174. * Function to get 1 column from the cached result set based in X index
  175. * see docs for usage and info
  176. */
  177. function get_col($query=null,$x=0)
  178. {
  179. $new_array = array();
  180. // If there is a query then perform it if not then use cached results..
  181. if ( $query )
  182. {
  183. $this->query($query);
  184. }
  185. // Extract the column values
  186. for ( $i=0; $i < count($this->last_result); $i++ )
  187. {
  188. $new_array[$i] = $this->get_var(null,$x,$i);
  189. }
  190. return $new_array;
  191. }
  192. /**********************************************************************
  193. * Return the the query as a result set - see docs for more details
  194. */
  195. function get_results($query=null, $output = OBJECT)
  196. {
  197. // Log how the function was called
  198. $this->func_call = "\$db->get_results(\"$query\", $output)";
  199. // If there is a query then perform it if not then use cached results..
  200. if ( $query )
  201. {
  202. $this->query($query);
  203. }
  204. // Send back array of objects. Each row is an object
  205. if ( $output == OBJECT )
  206. {
  207. return $this->last_result;
  208. }
  209. elseif ( $output == ARRAY_A || $output == ARRAY_N )
  210. {
  211. if ( $this->last_result )
  212. {
  213. $i=0;
  214. foreach( $this->last_result as $row )
  215. {
  216. $new_array[$i] = get_object_vars($row);
  217. if ( $output == ARRAY_N )
  218. {
  219. $new_array[$i] = array_values($new_array[$i]);
  220. }
  221. $i++;
  222. }
  223. return $new_array;
  224. }
  225. else
  226. {
  227. return null;
  228. }
  229. }
  230. }
  231. /**********************************************************************
  232. * Function to get column meta data info pertaining to the last query
  233. * see docs for more info and usage
  234. */
  235. function get_col_info($info_type="name",$col_offset=-1)
  236. {
  237. if ( $this->col_info )
  238. {
  239. if ( $col_offset == -1 )
  240. {
  241. $i=0;
  242. foreach($this->col_info as $col )
  243. {
  244. $new_array[$i] = $col->{$info_type};
  245. $i++;
  246. }
  247. return $new_array;
  248. }
  249. else
  250. {
  251. return $this->col_info[$col_offset]->{$info_type};
  252. }
  253. }
  254. }
  255. /**********************************************************************
  256. * store_cache
  257. */
  258. function store_cache($query,$is_insert)
  259. {
  260. // The would be cache file for this query
  261. $cache_file = $this->cache_dir.'/'.md5($query).'.php';
  262. // disk caching of queries
  263. if ( $this->use_disk_cache && ( $this->cache_queries && ! $is_insert ) || ( $this->cache_inserts && $is_insert ))
  264. {
  265. if ( ! is_dir($this->cache_dir) )
  266. {
  267. $this->register_error("Could not open cache dir: $this->cache_dir");
  268. $this->show_errors ? trigger_error("Could not open cache dir: $this->cache_dir",E_USER_WARNING) : null;
  269. }
  270. else
  271. {
  272. if($this->num_rows == 0) {
  273. $return = "empty";
  274. } else {
  275. $return = $this->num_rows;
  276. }
  277. // Cache all result values
  278. $result_cache = array
  279. (
  280. 'col_info' => $this->col_info,
  281. 'last_result' => $this->last_result,
  282. 'num_rows' => $this->num_rows,
  283. //'return_value' => $this->num_rows,
  284. 'return_value' => $return, // "empty" or number of rows
  285. );
  286. $prevent_access = "<?php die(); ?>";
  287. $serialized_results = serialize($result_cache);
  288. error_log ($prevent_access . $serialized_results, 3, $cache_file);
  289. }
  290. }
  291. }
  292. /**********************************************************************
  293. * get_cache
  294. */
  295. function get_cache($query)
  296. {
  297. // The would be cache file for this query
  298. $cache_file = $this->cache_dir.'/'.md5($query).'.php';
  299. // Try to get previously cached version
  300. if ( $this->use_disk_cache && file_exists($cache_file) )
  301. {
  302. // Only use this cache file if less than 'cache_timeout' (hours)
  303. if ( (time() - filemtime($cache_file)) > ($this->cache_timeout*3600) )
  304. {
  305. unlink($cache_file);
  306. }
  307. else
  308. {
  309. // skip the opening die() statement
  310. $result_cache = unserialize(file_get_contents($cache_file, NULL, NULL, 15));
  311. $this->col_info = $result_cache['col_info'];
  312. $this->last_result = $result_cache['last_result'];
  313. $this->num_rows = $result_cache['num_rows'];
  314. $this->from_disk_cache = true;
  315. // If debug ALL queries
  316. $this->trace || $this->debug_all ? $this->debug() : null ;
  317. return $result_cache['return_value'];
  318. }
  319. }
  320. }
  321. /**********************************************************************
  322. * Dumps the contents of any input variable to screen in a nicely
  323. * formatted and easy to understand way - any type: Object, Var or Array
  324. */
  325. function vardump($mixed='')
  326. {
  327. // Start outup buffering
  328. ob_start();
  329. echo "<p><table><tr><td bgcolor=ffffff><blockquote><font color=000090>";
  330. echo "<pre><font face=arial>";
  331. if ( ! $this->vardump_called )
  332. {
  333. echo "<font color=800080><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Variable Dump..</b></font>\n\n";
  334. }
  335. $var_type = gettype ($mixed);
  336. print_r(($mixed?$mixed:"<font color=red>No Value / False</font>"));
  337. echo "\n\n<b>Type:</b> " . ucfirst($var_type) . "\n";
  338. echo "<b>Last Query</b> [$this->num_queries]<b>:</b> ".($this->last_query?$this->last_query:"NULL")."\n";
  339. echo "<b>Last Function Call:</b> " . ($this->func_call?$this->func_call:"None")."\n";
  340. echo "<b>Last Rows Returned:</b> ".count($this->last_result)."\n";
  341. echo "</font></pre></font></blockquote></td></tr></table>".$this->donation();
  342. echo "\n<hr size=1 noshade color=dddddd>";
  343. // Stop output buffering and capture debug HTML
  344. $html = ob_get_contents();
  345. ob_end_clean();
  346. // Only echo output if it is turned on
  347. if ( $this->debug_echo_is_on )
  348. {
  349. echo $html;
  350. }
  351. $this->vardump_called = true;
  352. return $html;
  353. }
  354. /**********************************************************************
  355. * Alias for the above function
  356. */
  357. function dumpvar($mixed)
  358. {
  359. $this->vardump($mixed);
  360. }
  361. /**********************************************************************
  362. * Displays the last query string that was sent to the database & a
  363. * table listing results (if there were any).
  364. * (abstracted into a seperate file to save server overhead).
  365. */
  366. function debug()
  367. {
  368. // Start outup buffering
  369. ob_start();
  370. echo "<blockquote>";
  371. // Only show ezSQL credits once..
  372. if ( ! $this->debug_called )
  373. {
  374. echo "<font color=800080 face=arial size=2><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Debug..</b></font><p>\n";
  375. }
  376. if ( $this->last_error )
  377. {
  378. echo "<font face=arial size=2 color=000099><b>Last Error --</b> [<font color=000000><b>$this->last_error</b></font>]<p>";
  379. }
  380. if ( $this->from_disk_cache )
  381. {
  382. echo "<font face=arial size=2 color=000099><b>Results retrieved from disk cache</b></font><p>";
  383. }
  384. echo "<font face=arial size=2 color=000099><b>Query</b> [$this->num_queries] <b>--</b> ";
  385. echo "[<font color=000000><b>$this->last_query</b></font>]</font><p>";
  386. echo "<font face=arial size=2 color=000099><b>Query Result..</b></font>";
  387. echo "<blockquote>";
  388. if ( $this->col_info )
  389. {
  390. // =====================================================
  391. // Results top rows
  392. echo "<table cellpadding=5 cellspacing=1 bgcolor=555555>";
  393. echo "<tr bgcolor=eeeeee><td nowrap valign=bottom><font color=555599 face=arial size=2><b>(row)</b></font></td>";
  394. for ( $i=0; $i < count($this->col_info); $i++ )
  395. {
  396. echo "<td nowrap align=left valign=top><font size=1 color=555599 face=arial>{$this->col_info[$i]->type} {$this->col_info[$i]->max_length}</font><br><span style='font-family: arial; font-size: 10pt; font-weight: bold;'>{$this->col_info[$i]->name}</span></td>";
  397. }
  398. echo "</tr>";
  399. // ======================================================
  400. // print main results
  401. if ( $this->last_result )
  402. {
  403. $i=0;
  404. foreach ( $this->get_results(null,ARRAY_N) as $one_row )
  405. {
  406. $i++;
  407. echo "<tr bgcolor=ffffff><td bgcolor=eeeeee nowrap align=middle><font size=2 color=555599 face=arial>$i</font></td>";
  408. foreach ( $one_row as $item )
  409. {
  410. echo "<td nowrap><font face=arial size=2>$item</font></td>";
  411. }
  412. echo "</tr>";
  413. }
  414. } // if last result
  415. else
  416. {
  417. echo "<tr bgcolor=ffffff><td colspan=".(count($this->col_info)+1)."><font face=arial size=2>No Results</font></td></tr>";
  418. }
  419. echo "</table>";
  420. } // if col_info
  421. else
  422. {
  423. echo "<font face=arial size=2>No Results</font>";
  424. }
  425. //echo "</blockquote></blockquote>".$this->donation()."<hr noshade color=dddddd size=1>";
  426. // Stop output buffering and capture debug HTML
  427. $html = ob_get_contents();
  428. ob_end_clean();
  429. // Only echo output if it is turned on
  430. if ( $this->debug_echo_is_on )
  431. {
  432. echo $html;
  433. }
  434. $this->debug_called = true;
  435. return $html;
  436. }
  437. /**********************************************************************
  438. * Prepares a SQL query for safe use, using sprintf() syntax.
  439. *
  440. * @link http://php.net/sprintf See for syntax to use for query string.
  441. * @since 2.3.0
  442. *
  443. * @param null|string $args If string, first parameter must be query statement
  444. * @param mixed $args, If additional parameters, they will be set inserted into the query.
  445. * @return null|string Sanitized query string
  446. */
  447. function escape_by_ref(&$s)
  448. {
  449. $s = $this->escape($s);
  450. }
  451. function prepare($args=null)
  452. {
  453. if (is_null( $args ))
  454. return;
  455. $args = func_get_args();
  456. // This is a Hotaru hack, enabling args to be built on the fly.
  457. if(is_array($args[0]))
  458. {
  459. // See Submit plugin: class.post.php get_posts() for an example.
  460. $args = $args[0];
  461. }
  462. $query = array_shift($args);
  463. // in case someone mistakenly already singlequoted it
  464. $query = str_replace("'%s'", '%s', $query);
  465. $query = str_replace('"%s"', '%s', $query); // doublequote unquoting
  466. $query = str_replace('%s', "'%s'", $query); // quote the strings
  467. array_walk($args, array(&$this, 'escape_by_ref'));
  468. return @vsprintf($query, $args);
  469. }
  470. }
  471. ?>