PageRenderTime 42ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/libs/ez_sql_core.php

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