PageRenderTime 50ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/code/apps/myop/api/lib/ez_sql_core.php

http://thinksns-2.googlecode.com/
PHP | 556 lines | 316 code | 121 blank | 119 comment | 41 complexity | f17222c1432e23b03e95867182f12ec1 MD5 | raw file
Possible License(s): LGPL-2.1
  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($str)
  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. // If there is a query then perform it if not then use cached results..
  180. if ( $query )
  181. {
  182. $this->query($query);
  183. }
  184. // Extract the column values
  185. for ( $i=0; $i < count($this->last_result); $i++ )
  186. {
  187. $new_array[$i] = $this->get_var(null,$x,$i);
  188. }
  189. return $new_array;
  190. }
  191. /**********************************************************************
  192. * Return the the query as a result set - see docs for more details
  193. */
  194. function get_results($query=null, $output = OBJECT)
  195. {
  196. // Log how the function was called
  197. $this->func_call = "\$db->get_results(\"$query\", $output)";
  198. // If there is a query then perform it if not then use cached results..
  199. if ( $query )
  200. {
  201. $this->query($query);
  202. }
  203. // Send back array of objects. Each row is an object
  204. if ( $output == OBJECT )
  205. {
  206. return $this->last_result;
  207. }
  208. elseif ( $output == ARRAY_A || $output == ARRAY_N )
  209. {
  210. if ( $this->last_result )
  211. {
  212. $i=0;
  213. foreach( $this->last_result as $row )
  214. {
  215. $new_array[$i] = get_object_vars($row);
  216. if ( $output == ARRAY_N )
  217. {
  218. $new_array[$i] = array_values($new_array[$i]);
  219. }
  220. $i++;
  221. }
  222. return $new_array;
  223. }
  224. else
  225. {
  226. return null;
  227. }
  228. }
  229. }
  230. /**********************************************************************
  231. * Function to get column meta data info pertaining to the last query
  232. * see docs for more info and usage
  233. */
  234. function get_col_info($info_type="name",$col_offset=-1)
  235. {
  236. if ( $this->col_info )
  237. {
  238. if ( $col_offset == -1 )
  239. {
  240. $i=0;
  241. foreach($this->col_info as $col )
  242. {
  243. $new_array[$i] = $col->{$info_type};
  244. $i++;
  245. }
  246. return $new_array;
  247. }
  248. else
  249. {
  250. return $this->col_info[$col_offset]->{$info_type};
  251. }
  252. }
  253. }
  254. /**********************************************************************
  255. * store_cache
  256. */
  257. function store_cache($query,$is_insert)
  258. {
  259. // The would be cache file for this query
  260. $cache_file = $this->cache_dir.'/'.md5($query);
  261. // disk caching of queries
  262. if ( $this->use_disk_cache && ( $this->cache_queries && ! $is_insert ) || ( $this->cache_inserts && $is_insert ))
  263. {
  264. if ( ! is_dir($this->cache_dir) )
  265. {
  266. $this->register_error("Could not open cache dir: $this->cache_dir");
  267. $this->show_errors ? trigger_error("Could not open cache dir: $this->cache_dir",E_USER_WARNING) : null;
  268. }
  269. else
  270. {
  271. // Cache all result values
  272. $result_cache = array
  273. (
  274. 'col_info' => $this->col_info,
  275. 'last_result' => $this->last_result,
  276. 'num_rows' => $this->num_rows,
  277. 'return_value' => $this->num_rows,
  278. );
  279. error_log ( serialize($result_cache), 3, $cache_file);
  280. }
  281. }
  282. }
  283. /**********************************************************************
  284. * get_cache
  285. */
  286. function get_cache($query)
  287. {
  288. // The would be cache file for this query
  289. $cache_file = $this->cache_dir.'/'.md5($query);
  290. // Try to get previously cached version
  291. if ( $this->use_disk_cache && file_exists($cache_file) )
  292. {
  293. // Only use this cache file if less than 'cache_timeout' (hours)
  294. if ( (time() - filemtime($cache_file)) > ($this->cache_timeout*3600) )
  295. {
  296. unlink($cache_file);
  297. }
  298. else
  299. {
  300. $result_cache = unserialize(file_get_contents($cache_file));
  301. $this->col_info = $result_cache['col_info'];
  302. $this->last_result = $result_cache['last_result'];
  303. $this->num_rows = $result_cache['num_rows'];
  304. $this->from_disk_cache = true;
  305. // If debug ALL queries
  306. $this->trace || $this->debug_all ? $this->debug() : null ;
  307. return $result_cache['return_value'];
  308. }
  309. }
  310. }
  311. /**********************************************************************
  312. * Dumps the contents of any input variable to screen in a nicely
  313. * formatted and easy to understand way - any type: Object, Var or Array
  314. */
  315. function vardump($mixed='')
  316. {
  317. // Start outup buffering
  318. ob_start();
  319. echo "<p><table><tr><td bgcolor=ffffff><blockquote><font color=000090>";
  320. echo "<pre><font face=arial>";
  321. if ( ! $this->vardump_called )
  322. {
  323. echo "<font color=800080><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Variable Dump..</b></font>\n\n";
  324. }
  325. $var_type = gettype ($mixed);
  326. print_r(($mixed?$mixed:"<font color=red>No Value / False</font>"));
  327. echo "\n\n<b>Type:</b> " . ucfirst($var_type) . "\n";
  328. echo "<b>Last Query</b> [$this->num_queries]<b>:</b> ".($this->last_query?$this->last_query:"NULL")."\n";
  329. echo "<b>Last Function Call:</b> " . ($this->func_call?$this->func_call:"None")."\n";
  330. echo "<b>Last Rows Returned:</b> ".count($this->last_result)."\n";
  331. echo "</font></pre></font></blockquote></td></tr></table>".$this->donation();
  332. echo "\n<hr size=1 noshade color=dddddd>";
  333. // Stop output buffering and capture debug HTML
  334. $html = ob_get_contents();
  335. ob_end_clean();
  336. // Only echo output if it is turned on
  337. if ( $this->debug_echo_is_on )
  338. {
  339. echo $html;
  340. }
  341. $this->vardump_called = true;
  342. return $html;
  343. }
  344. /**********************************************************************
  345. * Alias for the above function
  346. */
  347. function dumpvar($mixed)
  348. {
  349. $this->vardump($mixed);
  350. }
  351. /**********************************************************************
  352. * Displays the last query string that was sent to the database & a
  353. * table listing results (if there were any).
  354. * (abstracted into a seperate file to save server overhead).
  355. */
  356. function debug()
  357. {
  358. // Start outup buffering
  359. ob_start();
  360. echo "<blockquote>";
  361. // Only show ezSQL credits once..
  362. if ( ! $this->debug_called )
  363. {
  364. echo "<font color=800080 face=arial size=2><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Debug..</b></font><p>\n";
  365. }
  366. if ( $this->last_error )
  367. {
  368. echo "<font face=arial size=2 color=000099><b>Last Error --</b> [<font color=000000><b>$this->last_error</b></font>]<p>";
  369. }
  370. if ( $this->from_disk_cache )
  371. {
  372. echo "<font face=arial size=2 color=000099><b>Results retrieved from disk cache</b></font><p>";
  373. }
  374. echo "<font face=arial size=2 color=000099><b>Query</b> [$this->num_queries] <b>--</b> ";
  375. echo "[<font color=000000><b>$this->last_query</b></font>]</font><p>";
  376. echo "<font face=arial size=2 color=000099><b>Query Result..</b></font>";
  377. echo "<blockquote>";
  378. if ( $this->col_info )
  379. {
  380. // =====================================================
  381. // Results top rows
  382. echo "<table cellpadding=5 cellspacing=1 bgcolor=555555>";
  383. echo "<tr bgcolor=eeeeee><td nowrap valign=bottom><font color=555599 face=arial size=2><b>(row)</b></font></td>";
  384. for ( $i=0; $i < count($this->col_info); $i++ )
  385. {
  386. 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>";
  387. }
  388. echo "</tr>";
  389. // ======================================================
  390. // print main results
  391. if ( $this->last_result )
  392. {
  393. $i=0;
  394. foreach ( $this->get_results(null,ARRAY_N) as $one_row )
  395. {
  396. $i++;
  397. echo "<tr bgcolor=ffffff><td bgcolor=eeeeee nowrap align=middle><font size=2 color=555599 face=arial>$i</font></td>";
  398. foreach ( $one_row as $item )
  399. {
  400. echo "<td nowrap><font face=arial size=2>$item</font></td>";
  401. }
  402. echo "</tr>";
  403. }
  404. } // if last result
  405. else
  406. {
  407. echo "<tr bgcolor=ffffff><td colspan=".(count($this->col_info)+1)."><font face=arial size=2>No Results</font></td></tr>";
  408. }
  409. echo "</table>";
  410. } // if col_info
  411. else
  412. {
  413. echo "<font face=arial size=2>No Results</font>";
  414. }
  415. echo "</blockquote></blockquote>".$this->donation()."<hr noshade color=dddddd size=1>";
  416. // Stop output buffering and capture debug HTML
  417. $html = ob_get_contents();
  418. ob_end_clean();
  419. // Only echo output if it is turned on
  420. if ( $this->debug_echo_is_on )
  421. {
  422. echo $html;
  423. }
  424. $this->debug_called = true;
  425. return $html;
  426. }
  427. /**********************************************************************
  428. * Naughty little function to ask for some remuniration!
  429. */
  430. function donation()
  431. {
  432. 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>";
  433. }
  434. }
  435. ?>