PageRenderTime 26ms CodeModel.GetById 38ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/coresql.class.php

https://github.com/antonrodin/Simple-Framework
PHP | 550 lines | 328 code | 116 blank | 106 comment | 43 complexity | ead535074673ba3619567b60abf2a1a3 MD5 | raw file
  1. <?php
  2. /**
  3. * @author: Based on ezSQL on Justin Vincent (jv@vip.ie)
  4. * @author: Slightly modified by Anton Zekeriev Rodin (www.azrodin.com)
  5. * @link: http://www.justinvincent.com
  6. * @name: Coresql
  7. * @desc: SQL core module - database abstraction library to make
  8. * it very easy to deal with databases. Core sql can not be used by
  9. * itself (it is designed for use by database specific modules).
  10. */
  11. /**********************************************************************
  12. * Coresql constants
  13. */
  14. define('EZSQL_VERSION','2.08');
  15. define('OBJECT','OBJECT',true);
  16. define('ARRAY_A','ARRAY_A',true);
  17. define('ARRAY_N','ARRAY_N',true);
  18. /**********************************************************************
  19. * Core class containg common functions to manipulate query result
  20. * sets once returned
  21. */
  22. class Coresql
  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. var $timers = array();
  40. var $total_query_time = 0;
  41. var $db_connect_time = 0;
  42. var $trace_log = array();
  43. var $use_trace_log = false;
  44. var $sql_log_file = false;
  45. var $do_profile = false;
  46. var $profile_times = array();
  47. // == TJH == default now needed for echo of debug function
  48. var $debug_echo_is_on = true;
  49. /**
  50. * Constructor, don't do nothing;
  51. */
  52. function __construct() {
  53. }
  54. /**********************************************************************
  55. * Print SQL/DB error - over-ridden by specific DB class
  56. */
  57. function register_error($err_str)
  58. {
  59. // Keep track of last error
  60. $this->last_error = $err_str;
  61. // Capture all errors to an error array no matter what happens
  62. $this->captured_errors[] = array
  63. (
  64. 'error_str' => $err_str,
  65. 'query' => $this->last_query
  66. );
  67. }
  68. /**********************************************************************
  69. * Turn error handling on or off..
  70. */
  71. function show_errors()
  72. {
  73. $this->show_errors = true;
  74. }
  75. function hide_errors()
  76. {
  77. $this->show_errors = false;
  78. }
  79. /**********************************************************************
  80. * Kill cached query results
  81. */
  82. function flush()
  83. {
  84. // Get rid of these
  85. $this->last_result = null;
  86. $this->col_info = null;
  87. $this->last_query = null;
  88. $this->from_disk_cache = false;
  89. }
  90. /**********************************************************************
  91. * Get one variable from the DB - see docs for more detail
  92. */
  93. function get_var($query=null,$x=0,$y=0)
  94. {
  95. // Log how the function was called
  96. $this->func_call = "\$db->get_var(\"$query\",$x,$y)";
  97. // If there is a query then perform it if not then use cached results..
  98. if ( $query )
  99. {
  100. $this->query($query);
  101. }
  102. // Extract var out of cached results based x,y vals
  103. if ( $this->last_result[$y] )
  104. {
  105. $values = array_values(get_object_vars($this->last_result[$y]));
  106. }
  107. // If there is a value return it else return null
  108. return (isset($values[$x]) && $values[$x]!=='')?$values[$x]:null;
  109. }
  110. /**********************************************************************
  111. * Get one row from the DB - see docs for more detail
  112. */
  113. function get_row($query=null,$output=OBJECT,$y=0)
  114. {
  115. // Log how the function was called
  116. $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
  117. // If there is a query then perform it if not then use cached results..
  118. if ( $query )
  119. {
  120. $this->query($query);
  121. }
  122. // If the output is an object then return object using the row offset..
  123. if ( $output == OBJECT )
  124. {
  125. return $this->last_result[$y]?$this->last_result[$y]:null;
  126. }
  127. // If the output is an associative array then return row as such..
  128. elseif ( $output == ARRAY_A )
  129. {
  130. return $this->last_result[$y]?get_object_vars($this->last_result[$y]):null;
  131. }
  132. // If the output is an numerical array then return row as such..
  133. elseif ( $output == ARRAY_N )
  134. {
  135. return $this->last_result[$y]?array_values(get_object_vars($this->last_result[$y])):null;
  136. }
  137. // If invalid output type was specified..
  138. else
  139. {
  140. $this->print_error(" \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N");
  141. }
  142. }
  143. /**********************************************************************
  144. * Function to get 1 column from the cached result set based in X index
  145. * see docs for usage and info
  146. */
  147. function get_col($query=null,$x=0)
  148. {
  149. $new_array = array();
  150. // If there is a query then perform it if not then use cached results..
  151. if ( $query )
  152. {
  153. $this->query($query);
  154. }
  155. // Extract the column values
  156. for ( $i=0; $i < count($this->last_result); $i++ )
  157. {
  158. $new_array[$i] = $this->get_var(null,$x,$i);
  159. }
  160. return $new_array;
  161. }
  162. /**********************************************************************
  163. * Return the the query as a result set - see docs for more details
  164. */
  165. function get_results($query=null, $output = OBJECT)
  166. {
  167. // Log how the function was called
  168. $this->func_call = "\$db->get_results(\"$query\", $output)";
  169. // If there is a query then perform it if not then use cached results..
  170. if ( $query )
  171. {
  172. $this->query($query);
  173. }
  174. // Send back array of objects. Each row is an object
  175. if ( $output == OBJECT )
  176. {
  177. return $this->last_result;
  178. }
  179. elseif ( $output == ARRAY_A || $output == ARRAY_N )
  180. {
  181. if ( $this->last_result )
  182. {
  183. $i=0;
  184. foreach( $this->last_result as $row )
  185. {
  186. $new_array[$i] = get_object_vars($row);
  187. if ( $output == ARRAY_N )
  188. {
  189. $new_array[$i] = array_values($new_array[$i]);
  190. }
  191. $i++;
  192. }
  193. return $new_array;
  194. }
  195. else
  196. {
  197. return null;
  198. }
  199. }
  200. }
  201. /**********************************************************************
  202. * Function to get column meta data info pertaining to the last query
  203. * see docs for more info and usage
  204. */
  205. function get_col_info($info_type="name",$col_offset=-1)
  206. {
  207. if ( $this->col_info )
  208. {
  209. if ( $col_offset == -1 )
  210. {
  211. $i=0;
  212. foreach($this->col_info as $col )
  213. {
  214. $new_array[$i] = $col->{$info_type};
  215. $i++;
  216. }
  217. return $new_array;
  218. }
  219. else
  220. {
  221. return $this->col_info[$col_offset]->{$info_type};
  222. }
  223. }
  224. }
  225. /**********************************************************************
  226. * store_cache
  227. */
  228. function store_cache($query,$is_insert)
  229. {
  230. // The would be cache file for this query
  231. $cache_file = $this->cache_dir.'/'.md5($query);
  232. // disk caching of queries
  233. if ( $this->use_disk_cache && ( $this->cache_queries && ! $is_insert ) || ( $this->cache_inserts && $is_insert ))
  234. {
  235. if ( ! is_dir($this->cache_dir) )
  236. {
  237. $this->register_error("Could not open cache dir: $this->cache_dir");
  238. $this->show_errors ? trigger_error("Could not open cache dir: $this->cache_dir",E_USER_WARNING) : null;
  239. }
  240. else
  241. {
  242. // Cache all result values
  243. $result_cache = array
  244. (
  245. 'col_info' => $this->col_info,
  246. 'last_result' => $this->last_result,
  247. 'num_rows' => $this->num_rows,
  248. 'return_value' => $this->num_rows,
  249. );
  250. error_log ( serialize($result_cache), 3, $cache_file);
  251. }
  252. }
  253. }
  254. /**********************************************************************
  255. * get_cache
  256. */
  257. function get_cache($query)
  258. {
  259. // The would be cache file for this query
  260. $cache_file = $this->cache_dir.'/'.md5($query);
  261. // Try to get previously cached version
  262. if ( $this->use_disk_cache && file_exists($cache_file) )
  263. {
  264. // Only use this cache file if less than 'cache_timeout' (hours)
  265. if ( (time() - filemtime($cache_file)) > ($this->cache_timeout*3600) )
  266. {
  267. unlink($cache_file);
  268. }
  269. else
  270. {
  271. $result_cache = unserialize(file_get_contents($cache_file));
  272. $this->col_info = $result_cache['col_info'];
  273. $this->last_result = $result_cache['last_result'];
  274. $this->num_rows = $result_cache['num_rows'];
  275. $this->from_disk_cache = true;
  276. // If debug ALL queries
  277. $this->trace || $this->debug_all ? $this->debug() : null ;
  278. return $result_cache['return_value'];
  279. }
  280. }
  281. }
  282. /**********************************************************************
  283. * Dumps the contents of any input variable to screen in a nicely
  284. * formatted and easy to understand way - any type: Object, Var or Array
  285. */
  286. function vardump($mixed='')
  287. {
  288. // Start outup buffering
  289. ob_start();
  290. echo "<p><table><tr><td bgcolor=ffffff><blockquote><font color=000090>";
  291. echo "<pre><font face=arial>";
  292. if ( ! $this->vardump_called )
  293. {
  294. echo "<font color=800080><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Variable Dump..</b></font>\n\n";
  295. }
  296. $var_type = gettype ($mixed);
  297. print_r(($mixed?$mixed:"<font color=red>No Value / False</font>"));
  298. echo "\n\n<b>Type:</b> " . ucfirst($var_type) . "\n";
  299. echo "<b>Last Query</b> [$this->num_queries]<b>:</b> ".($this->last_query?$this->last_query:"NULL")."\n";
  300. echo "<b>Last Function Call:</b> " . ($this->func_call?$this->func_call:"None")."\n";
  301. echo "<b>Last Rows Returned:</b> ".count($this->last_result)."\n";
  302. echo "</font></pre></font></blockquote></td></tr></table>".$this->donation();
  303. echo "\n<hr size=1 noshade color=dddddd>";
  304. // Stop output buffering and capture debug HTML
  305. $html = ob_get_contents();
  306. ob_end_clean();
  307. // Only echo output if it is turned on
  308. if ( $this->debug_echo_is_on )
  309. {
  310. echo $html;
  311. }
  312. $this->vardump_called = true;
  313. return $html;
  314. }
  315. /**********************************************************************
  316. * Alias for the above function
  317. */
  318. function dumpvar($mixed)
  319. {
  320. $this->vardump($mixed);
  321. }
  322. /**********************************************************************
  323. * Displays the last query string that was sent to the database & a
  324. * table listing results (if there were any).
  325. * (abstracted into a seperate file to save server overhead).
  326. */
  327. function debug($print_to_screen=true)
  328. {
  329. // Start outup buffering
  330. ob_start();
  331. echo "<blockquote>";
  332. // Only show ezSQL credits once..
  333. if ( ! $this->debug_called )
  334. {
  335. echo "<font color=800080 face=arial size=2><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Debug..</b></font><p>\n";
  336. }
  337. if ( $this->last_error )
  338. {
  339. echo "<font face=arial size=2 color=000099><b>Last Error --</b> [<font color=000000><b>$this->last_error</b></font>]<p>";
  340. }
  341. if ( $this->from_disk_cache )
  342. {
  343. echo "<font face=arial size=2 color=000099><b>Results retrieved from disk cache</b></font><p>";
  344. }
  345. echo "<font face=arial size=2 color=000099><b>Query</b> [$this->num_queries] <b>--</b> ";
  346. echo "[<font color=000000><b>$this->last_query</b></font>]</font><p>";
  347. echo "<font face=arial size=2 color=000099><b>Query Result..</b></font>";
  348. echo "<blockquote>";
  349. if ( $this->col_info )
  350. {
  351. // =====================================================
  352. // Results top rows
  353. echo "<table cellpadding=5 cellspacing=1 bgcolor=555555>";
  354. echo "<tr bgcolor=eeeeee><td nowrap valign=bottom><font color=555599 face=arial size=2><b>(row)</b></font></td>";
  355. for ( $i=0; $i < count($this->col_info); $i++ )
  356. {
  357. 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>";
  358. }
  359. echo "</tr>";
  360. // ======================================================
  361. // print main results
  362. if ( $this->last_result )
  363. {
  364. $i=0;
  365. foreach ( $this->get_results(null,ARRAY_N) as $one_row )
  366. {
  367. $i++;
  368. echo "<tr bgcolor=ffffff><td bgcolor=eeeeee nowrap align=middle><font size=2 color=555599 face=arial>$i</font></td>";
  369. foreach ( $one_row as $item )
  370. {
  371. echo "<td nowrap><font face=arial size=2>$item</font></td>";
  372. }
  373. echo "</tr>";
  374. }
  375. } // if last result
  376. else
  377. {
  378. echo "<tr bgcolor=ffffff><td colspan=".(count($this->col_info)+1)."><font face=arial size=2>No Results</font></td></tr>";
  379. }
  380. echo "</table>";
  381. } // if col_info
  382. else
  383. {
  384. echo "<font face=arial size=2>No Results</font>";
  385. }
  386. echo "</blockquote></blockquote>".$this->donation()."<hr noshade color=dddddd size=1>";
  387. // Stop output buffering and capture debug HTML
  388. $html = ob_get_contents();
  389. ob_end_clean();
  390. // Only echo output if it is turned on
  391. if ( $this->debug_echo_is_on && $print_to_screen)
  392. {
  393. echo $html;
  394. }
  395. $this->debug_called = true;
  396. return $html;
  397. }
  398. /**********************************************************************
  399. * Naughty little function to ask for some remuniration!
  400. */
  401. function donation()
  402. {
  403. 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>";
  404. }
  405. /**********************************************************************
  406. * Timer related functions
  407. */
  408. function timer_get_cur()
  409. {
  410. list($usec, $sec) = explode(" ",microtime());
  411. return ((float)$usec + (float)$sec);
  412. }
  413. function timer_start($timer_name)
  414. {
  415. $this->timers[$timer_name] = $this->timer_get_cur();
  416. }
  417. function timer_elapsed($timer_name)
  418. {
  419. return round($this->timer_get_cur() - $this->timers[$timer_name],2);
  420. }
  421. function timer_update_global($timer_name)
  422. {
  423. if ( $this->do_profile )
  424. {
  425. $this->profile_times[] = array
  426. (
  427. 'query' => $this->last_query,
  428. 'time' => $this->timer_elapsed($timer_name)
  429. );
  430. }
  431. $this->total_query_time += $this->timer_elapsed($timer_name);
  432. }
  433. }
  434. ?>