PageRenderTime 29ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/ezsql/ez_sql_core.php

https://bitbucket.org/ladasoukup/sb_eventlogmonitor
PHP | 558 lines | 317 code | 122 blank | 119 comment | 41 complexity | 869aa275e110ed86ef1854b4f9157154 MD5 | raw file
Possible License(s): Unlicense
  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 select()
  58. {
  59. die(EZSQL_CORE_ERROR);
  60. }
  61. /**********************************************************************
  62. * Basic Query - over-ridden by specific DB class
  63. */
  64. function 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()
  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 = null;
  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);
  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. // Cache all result values
  273. $result_cache = array
  274. (
  275. 'col_info' => $this->col_info,
  276. 'last_result' => $this->last_result,
  277. 'num_rows' => $this->num_rows,
  278. 'return_value' => $this->num_rows,
  279. );
  280. error_log ( serialize($result_cache), 3, $cache_file);
  281. }
  282. }
  283. }
  284. /**********************************************************************
  285. * get_cache
  286. */
  287. function get_cache($query)
  288. {
  289. // The would be cache file for this query
  290. $cache_file = $this->cache_dir.'/'.md5($query);
  291. // Try to get previously cached version
  292. if ( $this->use_disk_cache && file_exists($cache_file) )
  293. {
  294. // Only use this cache file if less than 'cache_timeout' (hours)
  295. if ( (time() - filemtime($cache_file)) > ($this->cache_timeout*3600) )
  296. {
  297. unlink($cache_file);
  298. }
  299. else
  300. {
  301. $result_cache = unserialize(file_get_contents($cache_file));
  302. $this->col_info = $result_cache['col_info'];
  303. $this->last_result = $result_cache['last_result'];
  304. $this->num_rows = $result_cache['num_rows'];
  305. $this->from_disk_cache = true;
  306. // If debug ALL queries
  307. $this->trace || $this->debug_all ? $this->debug() : null ;
  308. return $result_cache['return_value'];
  309. }
  310. }
  311. }
  312. /**********************************************************************
  313. * Dumps the contents of any input variable to screen in a nicely
  314. * formatted and easy to understand way - any type: Object, Var or Array
  315. */
  316. function vardump($mixed='')
  317. {
  318. // Start outup buffering
  319. ob_start();
  320. echo "<p><table><tr><td bgcolor=ffffff><blockquote><font color=000090>";
  321. echo "<pre><font face=arial>";
  322. if ( ! $this->vardump_called )
  323. {
  324. echo "<font color=800080><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Variable Dump..</b></font>\n\n";
  325. }
  326. $var_type = gettype ($mixed);
  327. print_r(($mixed?$mixed:"<font color=red>No Value / False</font>"));
  328. echo "\n\n<b>Type:</b> " . ucfirst($var_type) . "\n";
  329. echo "<b>Last Query</b> [$this->num_queries]<b>:</b> ".($this->last_query?$this->last_query:"NULL")."\n";
  330. echo "<b>Last Function Call:</b> " . ($this->func_call?$this->func_call:"None")."\n";
  331. echo "<b>Last Rows Returned:</b> ".count($this->last_result)."\n";
  332. echo "</font></pre></font></blockquote></td></tr></table>".$this->donation();
  333. echo "\n<hr size=1 noshade color=dddddd>";
  334. // Stop output buffering and capture debug HTML
  335. $html = ob_get_contents();
  336. ob_end_clean();
  337. // Only echo output if it is turned on
  338. if ( $this->debug_echo_is_on )
  339. {
  340. echo $html;
  341. }
  342. $this->vardump_called = true;
  343. return $html;
  344. }
  345. /**********************************************************************
  346. * Alias for the above function
  347. */
  348. function dumpvar($mixed)
  349. {
  350. $this->vardump($mixed);
  351. }
  352. /**********************************************************************
  353. * Displays the last query string that was sent to the database & a
  354. * table listing results (if there were any).
  355. * (abstracted into a seperate file to save server overhead).
  356. */
  357. function debug()
  358. {
  359. // Start outup buffering
  360. ob_start();
  361. echo "<blockquote>";
  362. // Only show ezSQL credits once..
  363. if ( ! $this->debug_called )
  364. {
  365. echo "<font color=800080 face=arial size=2><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Debug..</b></font><p>\n";
  366. }
  367. if ( $this->last_error )
  368. {
  369. echo "<font face=arial size=2 color=000099><b>Last Error --</b> [<font color=000000><b>$this->last_error</b></font>]<p>";
  370. }
  371. if ( $this->from_disk_cache )
  372. {
  373. echo "<font face=arial size=2 color=000099><b>Results retrieved from disk cache</b></font><p>";
  374. }
  375. echo "<font face=arial size=2 color=000099><b>Query</b> [$this->num_queries] <b>--</b> ";
  376. echo "[<font color=000000><b>$this->last_query</b></font>]</font><p>";
  377. echo "<font face=arial size=2 color=000099><b>Query Result..</b></font>";
  378. echo "<blockquote>";
  379. if ( $this->col_info )
  380. {
  381. // =====================================================
  382. // Results top rows
  383. echo "<table cellpadding=5 cellspacing=1 bgcolor=555555>";
  384. echo "<tr bgcolor=eeeeee><td nowrap valign=bottom><font color=555599 face=arial size=2><b>(row)</b></font></td>";
  385. for ( $i=0; $i < count($this->col_info); $i++ )
  386. {
  387. 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>";
  388. }
  389. echo "</tr>";
  390. // ======================================================
  391. // print main results
  392. if ( $this->last_result )
  393. {
  394. $i=0;
  395. foreach ( $this->get_results(null,ARRAY_N) as $one_row )
  396. {
  397. $i++;
  398. echo "<tr bgcolor=ffffff><td bgcolor=eeeeee nowrap align=middle><font size=2 color=555599 face=arial>$i</font></td>";
  399. foreach ( $one_row as $item )
  400. {
  401. echo "<td nowrap><font face=arial size=2>$item</font></td>";
  402. }
  403. echo "</tr>";
  404. }
  405. } // if last result
  406. else
  407. {
  408. echo "<tr bgcolor=ffffff><td colspan=".(count($this->col_info)+1)."><font face=arial size=2>No Results</font></td></tr>";
  409. }
  410. echo "</table>";
  411. } // if col_info
  412. else
  413. {
  414. echo "<font face=arial size=2>No Results</font>";
  415. }
  416. echo "</blockquote></blockquote>".$this->donation()."<hr noshade color=dddddd size=1>";
  417. // Stop output buffering and capture debug HTML
  418. $html = ob_get_contents();
  419. ob_end_clean();
  420. // Only echo output if it is turned on
  421. if ( $this->debug_echo_is_on )
  422. {
  423. echo $html;
  424. }
  425. $this->debug_called = true;
  426. return $html;
  427. }
  428. /**********************************************************************
  429. * Naughty little function to ask for some remuniration!
  430. */
  431. function donation()
  432. {
  433. return "<font size=1 face=arial color=000000>If ezSQL has helped <a href=\"https://www.paypal.com/xclick/business=justin%40justinvincent.com&item_name=ezSQL&no_note=1&tax=0\" style=\"color: 0000CC;\">make a donation!?</a> &nbsp;&nbsp;<!--[ go on! you know you want to! ]--></font>";
  434. }
  435. }
  436. ?>