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

/wp-content/plugins/w3-total-cache/db/mssql.php

https://github.com/digitalstrategyworks/Reese-WordPress
PHP | 1255 lines | 1022 code | 91 blank | 142 comment | 10 complexity | 646a0cfbdd1714b617bcb5df5bec8be6 MD5 | raw file
  1. <?php
  2. /*
  3. http://code.google.com/p/wordpress-mssql/
  4. Contributors: Aizu Ikmal Ahmad & Iwani Khalid
  5. Requires at least: 2.3.0
  6. Tested up to: 2.7.1
  7. Development Status: Alpha
  8. Database Abstraction Class: ezSQL by Justin Vincent (http://php.justinvincent.com)
  9. How to install MS-SQL support for Wordpress
  10. 1. Download Wordpress ( http://wordpress.org/wordpress-2.7.1-IIS-RC1.zip )
  11. 2. Then, upload it on your webhosting that supports MSSQL and IIS like how you would usually do it
  12. 3. Download our Magic Plugin at ( http://code.google.com/p/wordpress-mssql/ )
  13. 4. Then upload that db.php to your wp-contents folder
  14. 5. Edit the MSSQL database setting in db.php file according to your MSSQL settings 6. You're done :D
  15. At this moment, this workaround works for these functions, to where we have debugged and tested
  16. * Basic submit, edit, manage posts and pages
  17. * Comments system
  18. * Dynamic sidebar
  19. * Changing themes
  20. * Installing plugins
  21. * Long text retrieval
  22. What we didn't have time to debug
  23. * Pagination
  24. * Categories > Posts retrieval
  25. * Dates / Time of posts
  26. * Others which we look forward to debug later :D
  27. */
  28. // ==================================================================
  29. // Author: Justin Vincent (justin@visunet.ie)
  30. // Web: http://php.justinvincent.com
  31. // Name: ezSQL
  32. // Desc: Class to make it very easy to deal with MS SQL database connections.
  33. //
  34. // N.B. ezSQL was converted for use with MS SQL
  35. // by Tom De Bruyne (tom@challenge.be).
  36. //
  37. // !! IMPORTANT !!
  38. //
  39. // Please send me a mail telling me what you think of ezSQL
  40. // and what your using it for!! Cheers. [ justin@visunet.ie ]
  41. //
  42. // ==================================================================
  43. // User Settings -- CHANGE HERE
  44. ini_set ('mssql.textlimit','2147483647');
  45. ini_set ('mssql.textsize','2147483647');
  46. define("EZSQL_DB_USER", "tretinoin_wpuser"); // <-- MS SQL Server db user
  47. define("EZSQL_DB_PASSWORD", "83h93hdi."); // <-- MS SQL Server db password
  48. define("EZSQL_DB_NAME", "tretinoin_wordpress"); // <-- MS SQL Server db pname
  49. define("EZSQL_DB_HOST", "lamp2win"); // <-- MS SQL Server server host
  50. // ==================================================================
  51. // ezSQL Constants
  52. define("EZSQL_VERSION","1.26");
  53. define("OBJECT","OBJECT",true);
  54. define("ARRAY_A","ARRAY_A",true);
  55. define("ARRAY_N","ARRAY_N",true);
  56. // ==================================================================
  57. // The Main Class
  58. class W3_Db_Driver {
  59. var $debug_called;
  60. var $vardump_called;
  61. var $show_errors = false;
  62. var $num_queries = 0;
  63. var $debug_all = false;
  64. var $last_query;
  65. var $col_info;
  66. var $suppress_errors = false;
  67. var $last_error = '';
  68. var $queries;
  69. var $prefix = '';
  70. var $ready = false;
  71. var $posts;
  72. var $users;
  73. var $categories;
  74. var $post2cat;
  75. var $comments;
  76. var $links;
  77. var $options;
  78. var $postmeta;
  79. var $usermeta;
  80. var $terms;
  81. var $term_taxonomy;
  82. var $term_relationships;
  83. var $tables = array('users', 'usermeta', 'posts', 'categories', 'post2cat', 'comments', 'links', 'link2cat', 'options',
  84. 'postmeta', 'terms', 'term_taxonomy', 'term_relationships');
  85. var $charset;
  86. var $collate;
  87. // ==================================================================
  88. // DB Constructor - connects to the server and selects a database
  89. function W3_Db_Driver($dbuser, $dbpassword, $dbname, $dbhost)
  90. {
  91. $this->dbh = mssql_connect($dbhost, $dbuser, $dbpassword);
  92. if ( ! $this->dbh ) {
  93. $this->print_error("<ol><b>Error establishing a database connection!</b><li>Are you sure you have the correct user/password?<li>Are you sure that you have typed the correct hostname?<li>Are you sure that the database server is running?</ol>");
  94. }
  95. $this->select($dbname);
  96. }
  97. // ==================================================================
  98. // Select a DB (if another one needs to be selected)
  99. function select($db)
  100. {
  101. mssql_select_db ($db);
  102. }
  103. // ==================================================================
  104. // Basic Query - see docs for more detail
  105. function query($query)
  106. {
  107. $query = trim($query);
  108. $query = str_replace('`',"'",$query);
  109. $query = str_replace('\012',"\n",$query);
  110. $query = str_replace('\015',"\r",$query);
  111. //$query = str_replace("\n",'',$query);
  112. //$query = str_replace("\r",'',$query);
  113. //$query = $this->escape($query);
  114. //$query = str_replace('"','\"',$query);
  115. //$query = str_replace("'","\'",$query);
  116. if(substr($query,0,7) == 'SELECT '){
  117. dbug($query,'SELECT : ORIGINAL QUERY ::::::: ','orange');
  118. $query_arr = explode('LIMIT',$query);
  119. if($query_arr[0] AND $query_arr[1]){
  120. $query_one = str_replace('SELECT ','',$query_arr[0]);
  121. $top_arr = explode(' ',$query_arr[1]);
  122. if($top_arr[1] && $top_arr[2]){
  123. $query = 'SELECT TOP '.$top_arr[2].' '.$query_one;
  124. }else{
  125. $query = 'SELECT TOP '.$top_arr[1].' '.$query_one;
  126. }
  127. /*
  128. // TO BE DEVELOP
  129. //LIMIT 1, 3
  130. SELECT * FROM (
  131. SELECT TOP 3 * FROM
  132. (SELECT TOP (1+3) * FROM wp_posts WHERE 1=1 AND post_type = 'post' AND (post_status = 'publish' OR post_status = 'private') ORDER BY post_date DESC)
  133. AS table1 ORDER BY post_date ASC
  134. ) AS table2 ORDER BY post_date DESC
  135. */
  136. //pre($query_arr);
  137. //exit();
  138. }
  139. if(substr($query,0,23) == "SELECT TOP 1 comment_ID"){
  140. $query = str_replace(' = ',' = ',$query);
  141. }
  142. /* DUMP DIRTY SWEPT TEST */
  143. $query = str_replace('wp_posts.','',$query);
  144. /*
  145. hacks for query;
  146. - SELECT * FROM wp_posts WHERE (post_type = 'page' AND post_status = 'publish') ORDER BY menu_order, post_title ASC
  147. - SELECT * FROM wp_posts WHERE 1=1 AND post_type = 'page' AND (post_status = 'publish' OR post_status = 'future' OR post_status = 'draft' OR post_status = 'pending' OR post_status = 'private') ORDER BY menu_order,post_title asc
  148. notes;
  149. somehow Wordpress developer create this 'post_title' date-type as 'text' in database. the post_title should be varchar since the amount of character in title is generally less then 255 char.
  150. and in ms-sql, text cannot be sorted. so this is a big mistake. haihhh...
  151. */
  152. $pattern = '/post_title asc/is';
  153. $replacement = 'cast(post_title as varchar(500)) ASC';
  154. $query = preg_replace($pattern, $replacement, $query);
  155. /*
  156. hacks for query;
  157. - SELECT DISTINCT YEAR(post_date) AS yyear, MONTH(post_date) AS mmonth FROM wp_posts WHERE post_type = 'post' ORDER BY post_date DESC
  158. notes;
  159. this is one another hacks for SELECT DISTINCT call.
  160. The above query tries to sort by the column post_date. Because the keyword DISTINCT is also specified, column post_date must appear in the SELECT list
  161. expected return;
  162. - SELECT DISTINCT post_date, YEAR(post_date) AS yyear, MONTH(post_date) AS mmonth FROM wp_posts WHERE post_type = 'post' ORDER BY post_date DESC
  163. */
  164. if(substr($query,0,15) == "SELECT DISTINCT"){
  165. $string = $query;
  166. $pattern = '/SELECT DISTINCT (.*)? ORDER BY (.*)? (asc|desc)/i';
  167. $replacement = 'cast(post_title as varchar(500)) ASC';
  168. preg_match_all($pattern, $string, $result);
  169. $order_by_col = $result[2][0];
  170. $col_calls = $result[1][0];
  171. $order_by_prop = $result[3][0];
  172. $query = 'SELECT DISTINCT '.$order_by_col.', '.$col_calls.' ORDER BY '.$order_by_col.' '.$order_by_prop;
  173. }
  174. /*
  175. hacks for query;
  176. - SELECT user_id FROM wp_usermeta WHERE meta_key = 'wp_user_level' AND meta_value != '0'
  177. notes;
  178. replace != into NOT <col_name> LIKE
  179. expected return;
  180. - SELECT user_id FROM wp_usermeta WHERE meta_key = 'wp_user_level' AND NOT meta_value LIKE '0'
  181. */
  182. $pattern = "/ (?:[a-z][a-z0-9_]*)? \!\= /is";
  183. preg_match_all($pattern, $query, $result);
  184. $result_arr = $result[0];
  185. $query = str_replace('!=','',$query);
  186. foreach($result_arr as $result_item){
  187. $result_item = str_replace('!=','',$result_item);
  188. $result_item = trim($result_item);
  189. $query = str_replace($result_item,' NOT '.$result_item.' LIKE ',$query);
  190. }
  191. /*
  192. hacks for;
  193. - SQL have 'GROUP BY'
  194. - SELECT DISTINCT post_date, YEAR(post_date) AS year, MONTH(post_date) AS month, count(ID) as posts FROM wp_posts WHERE post_type = 'post' AND post_status = 'publish
  195. GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC
  196. */
  197. if (preg_match("/GROUP BY/i", $query)) {
  198. $pattern = '/SELECT (.*) GROUP BY (.*)? ORDER BY (.*)/i';
  199. preg_match($pattern, $string, $output);
  200. $query0 = 'SELECT '.$output[1].' ORDER BY '.$output[3];
  201. }
  202. $query = str_replace('SQL_CALC_FOUND_ROWS',' ',$query);
  203. if (preg_match("/SELECT FOUND_ROWS()/i", $query)) {
  204. $last_query = $this->last_query;
  205. $last_query_one_arr = explode('TOP',$last_query);
  206. $last_query_two = trim($last_query_one_arr[1]);
  207. $last_query_three_arr = explode(' ',$last_query_two);
  208. $last_query_four = str_replace($last_query_three_arr[0],'',$last_query_two);
  209. $query = 'SELECT '.$last_query_four;
  210. }
  211. dbug($query,'SELECT : MODDED QUERY :::::::: ','orange');
  212. }elseif(substr($query,0,7) == 'INSERT '){
  213. dbug($query,'INSERT : ORIGINAL QUERY ::::::::: ','purple');
  214. $pattern = '/INSERT INTO (.*)?\((.*)\).*?VALUES.*?\((.*)\)/is';
  215. preg_match_all($pattern, $query, $output);
  216. $insert_table = trim($output[1][0]);
  217. $insert_cols = trim($output[2][0]);
  218. $insert_values = trim($output[3][0]);
  219. /* STRIP QUOTE FROM COLS NAME */
  220. $insert_cols = str_replace("'",'',$insert_cols);
  221. $query = $this->prepare($query);
  222. /* PROCESS THE $insert_values. NEED TO REPLACE THE INNER QUOTES */
  223. preg_match_all("/([0-9]+|\'(.*?)\'[ ]*?),/is", $insert_values.',', $output);
  224. $insert_values_arr = array(); //PREPARE THE NEW FRESH VALUES
  225. foreach($output[0] as $insert_values_item){
  226. if(substr(trim($insert_values_item),0,1) == "'"){
  227. $insert_values_item = substr($insert_values_item,1); // TAKE OUT THE FIRST 1 CHAR, WHICH IS QUOTE
  228. }
  229. $insert_values_item = trim($insert_values_item); // TRIM THE WHITESPACE
  230. if(substr(trim($insert_values_item),-1) == ","){
  231. $insert_values_item = substr($insert_values_item,0,-1); // TAKE OUT THE LAST 1 CHAR, WHICH IS COMMA
  232. }
  233. if(substr(trim($insert_values_item),-1) == "'"){
  234. $insert_values_item = substr($insert_values_item,0,-1); // TAKE OUT THE LAST 1 CHAR, WHICH IS QUOTE
  235. }
  236. $insert_values_item = str_replace("'","''",$insert_values_item); // NOW WE PUT THE EXTRA QUOTE ON IT
  237. $insert_values_item = trim($insert_values_item); // TRIM THE WHITESPACE
  238. $insert_values_item = "'".$insert_values_item."'"; // WRAP THE VALUES WITH OUR SINGLE-QUOTE
  239. $insert_values_arr[] = $insert_values_item;
  240. }
  241. $insert_values = implode(',',$insert_values_arr);
  242. /* CONSTRUCT NEW INSERT CALL */
  243. $query = 'INSERT INTO '.$insert_table.' ('.$insert_cols.') VALUES ('.$insert_values.');';
  244. dbug($query,'INSERT : MODDED QUERY :::::::::: ','purple');
  245. }elseif(substr($query,0,7) == 'UPDATE '){
  246. dbug($query,'UPDATE : ORIGINAL QUERY ::::::::: ','blue');
  247. $pattern = '/UPDATE ([A-Za-z0-9_-]+) SET (.*)? WHERE (.*)?/is';
  248. preg_match_all($pattern, $query, $output);
  249. $update_table = trim($output[1][0]);
  250. $update_values = trim($output[2][0]);
  251. $update_where = trim($output[3][0]);
  252. preg_match_all("/(.*?)[ *]?=[ *]?(\'(.*?)\'|[0-9]+),/is", $update_values.',', $output_vals);
  253. $update_vals_colname = $output_vals[1];
  254. $update_vals_values = $output_vals[2];
  255. $update_vals_colname_mod = array();
  256. foreach($update_vals_colname as $update_vals_colname_item){
  257. $update_vals_colname_item = str_replace("'",'',$update_vals_colname_item); // GREEDY REPLACE ALL QUOTES. NO QUOTES ALLOWED IN COL NAME
  258. $update_vals_colname_item = trim($update_vals_colname_item); // TRIM THE WHITESPACE
  259. $update_vals_colname_mod[] = $update_vals_colname_item;
  260. }
  261. $update_vals_values_mod = array();
  262. foreach($update_vals_values as $update_vals_values_item){
  263. if(substr(trim($update_vals_values_item),0,1) == "'"){
  264. $update_vals_values_item = substr($update_vals_values_item,1); // TAKE OUT THE FIRST 1 CHAR, WHICH IS QUOTE
  265. }
  266. if(substr(trim($update_vals_values_item),-1) == "'"){
  267. $update_vals_values_item = substr($update_vals_values_item,0,-1); // TAKE OUT THE LAST 1 CHAR, WHICH IS QUOTE
  268. }
  269. $update_vals_values_item = trim($update_vals_values_item); // TRIM THE WHITESPACE
  270. $update_vals_values_item = str_replace("'","''",$update_vals_values_item); // ADD ADDITIONAL QUOTE TO ESCAPE IT IN MSSQL
  271. $update_vals_values_mod[] = $update_vals_values_item;
  272. }
  273. $update_values_modded = array_combine($update_vals_colname_mod,$update_vals_values_mod);
  274. $update_values = '';
  275. $update_values_prepare_arr = '';
  276. $update_values_item = '';
  277. foreach($update_values_modded as $update_values_item_colname => $update_values_item_value){
  278. $update_values_prepare_arr[] = $update_values_item_colname." = '".$update_values_item_value."'";
  279. }
  280. $update_values = implode(',',$update_values_prepare_arr);
  281. /* CONSTRUCT NEW UPDATE CALL */
  282. $query = 'UPDATE '.$update_table.' SET '.$update_values.' WHERE '.$update_where.';';
  283. dbug($query,'UPDATE : MODDED QUERY :::::::::: ','blue');
  284. }elseif(substr($query,0,7) == 'DELETE '){
  285. dbug($query,'DELETE','orange');
  286. }elseif(substr($query,0,7) == 'CREATE '){
  287. $query_two = str_replace('auto_increment','IDENTITY(1,1)',$query);
  288. $query_two = str_replace('tinytext','text',$query_two);
  289. $query_two = str_replace('longtext','text',$query_two);
  290. $query_two = str_replace('mediumtext','text',$query_two);
  291. $query_two = str_replace('unsigned ','',$query_two);
  292. $query_three = preg_replace('/bigint\(\d+\)/i','int',$query_two);
  293. $query_three = preg_replace('/int\(\d+\)/i','int',$query_three);
  294. $query_four_arr = explode('PRIMARY KEY',$query_three);
  295. $query_five = $query_four_arr[0].' ';
  296. $query_six = $query_four_arr[1];
  297. $query_seven_arr = explode('),',$query_six);
  298. $query_eight_arr = explode('(',$query);
  299. $query_nine = trim($query_eight_arr[0]);
  300. $query_ten = str_replace($query_nine,'',$query_five);
  301. $table_name = trim(str_replace('CREATE TABLE','',$query_nine));
  302. $create_table_header = "
  303. IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[tretinoin_wpuser].[".$table_name."]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
  304. DROP TABLE [tretinoin_wpuser].[".$table_name."]
  305. GO
  306. CREATE TABLE [tretinoin_wpuser].[".$table_name."]";
  307. $create_table_header_simple = "CREATE TABLE [tretinoin_wpuser].[".$table_name."]
  308. ";
  309. $query = $create_table_header_simple . $query_ten . ' PRIMARY KEY ' . $query_seven_arr[0] .'))';
  310. dbug($query,'CREATE','purple');
  311. }elseif(substr($query,0,5) == 'SHOW '){
  312. $query = str_replace('SHOW TABLES;','',$query);
  313. dbug($query,'SHOW','yellow');
  314. }else{
  315. dbug($query);
  316. }
  317. // For reg expressions
  318. $query = trim($query);
  319. // Flush cached values..
  320. $this->flush();
  321. // Log how the function was called
  322. $this->func_call = "\$db->query(\"$query\")";
  323. // Keep track of the last query for debug..
  324. $this->last_query = $query;
  325. // Perform the query via std mssql_query function..
  326. if(substr($query,0,7) == 'SELECT '){
  327. $this->result_check = @mssql_query($query, $this->dbh);
  328. }elseif(substr($query,0,7) == 'INSERT '){
  329. }elseif(substr($query,0,7) == 'UPDATE '){
  330. $this->result_check = @mssql_query($query, $this->dbh);
  331. }elseif(substr($query,0,7) == 'DELETE '){
  332. }elseif(substr($query,0,7) == 'CREATE '){
  333. }elseif(substr($query,0,5) == 'SHOW '){
  334. }
  335. // Unfortunately, PHP fuctions for MS SQL currently don't offer a decent way
  336. // to retrieve errors from MS SQL
  337. // Make sure not to run a query between the actual query and this one !
  338. $get_errorcode = "SELECT @@ERROR as errorcode";
  339. $error_res = @mssql_query($get_errorcode, $this->dbh);
  340. $errorcode = @mssql_result($error_res, 0, "errorcode");
  341. // ERROR LIST
  342. // 402 : The data types text and varchar are incompatible in the equal to operator.
  343. // 306 : The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator.
  344. if ($errorcode == '402') {
  345. $query_two = str_replace(' = ',' LIKE ',$query);
  346. /* NEED MORE IMPROVEMENT HERE */
  347. }else{
  348. $query_two = $query;
  349. }
  350. dbug($query,$errorcode,'green');
  351. $this->result = @mssql_query($query_two, $this->dbh);
  352. $this->num_queries++;
  353. // If there was an insert, delete or update see how many rows were affected
  354. // (Also, If there there was an insert take note of the last OID
  355. $query_type = array("insert","delete","update","replace");
  356. // loop through the above array
  357. foreach ( $query_type as $word )
  358. {
  359. // This is true if the query starts with insert, delete or update
  360. if ( preg_match("/^$word\s+/i",$query) )
  361. {
  362. $this->rows_affected = @mssql_rows_affected ($this->dbh);
  363. // This gets the insert ID
  364. if ( $word == "insert" || $word == "replace" )
  365. {
  366. $get_last_ident = "SELECT @@IDENTITY as id";
  367. $last_res = @mssql_query($get_last_ident, $this->dbh);
  368. $this->insert_id = @mssql_result($last_res, 0, "id");
  369. // If insert id then return it - true evaluation
  370. return $this->insert_id;
  371. }
  372. // Set to false if there was no insert id
  373. $this->result = false;
  374. }
  375. }
  376. if ($errorcode <> 0) {
  377. // there is an error
  378. $this->print_error();
  379. }
  380. else
  381. {
  382. // =======================================================
  383. // Take note of column info
  384. $i=0;
  385. while ($i < @mssql_num_fields($this->result))
  386. {
  387. $this->col_info[$i]->name = @mssql_field_name($this->result,$i);
  388. $this->col_info[$i]->type = @mssql_field_type($this->result,$i);
  389. $this->col_info[$i]->size = @mssql_field_length($this->result,$i);
  390. $i++;
  391. }
  392. // =======================================================
  393. // Store Query Results
  394. $i=0;
  395. while ( $row_arr = @mssql_fetch_array($this->result) )
  396. {
  397. $row = array_to_object($row_arr);
  398. $this->last_result[$i] = $row;
  399. // Store relults as an objects within main array
  400. $i++;
  401. }
  402. if($i == 0){
  403. $this->last_result = array();
  404. }
  405. //pre($this->last_result);
  406. // Log number of rows the query returned
  407. $this->num_rows = $i;
  408. //}
  409. @mssql_free_result($this->result);
  410. // If this was a select..
  411. if ( preg_match("/^(select|show|desc)\s+/i",$query) )
  412. {
  413. // If debug ALL queries
  414. $this->debug_all ? $this->debug() : null ;
  415. // If there were results then return true for $db->query
  416. if ( $i )
  417. {
  418. return true;
  419. }
  420. else
  421. {
  422. return false;
  423. }
  424. }
  425. else
  426. {
  427. // If debug ALL queries
  428. $this->debug_all ? $this->debug() : null ;
  429. // Update insert etc. was good..
  430. return true;
  431. }
  432. }
  433. }
  434. // ====================================================================
  435. // Format a string correctly for safe insert under all PHP conditions
  436. function escape($str)
  437. {
  438. // This deals with quote escaping
  439. //$str = str_replace("'","''",$str);
  440. //$str = str_replace("\'","'",$str);
  441. //$str = mysql_real_escape_string($str);
  442. //$str = str_replace("'", "''", $str);
  443. //$str = addslashes($str);
  444. //dbug($str,'ESCAPE RUN TWICE','red');
  445. // These values need to be escaped for ms sql
  446. $escape = array ( "\n"=>"\\\\012","\r"=>"\\\\015");
  447. // Firstly unescape
  448. /*
  449. foreach ( $escape as $match => $replace )
  450. {
  451. $str = str_replace($match,$replace,$str);
  452. }
  453. */
  454. return $str;
  455. }
  456. // ==================================================================
  457. // Print SQL/DB error.
  458. function print_error($str = "")
  459. {
  460. // All erros go to the global error array $EZSQL_ERROR..
  461. global $EZSQL_ERROR;
  462. // if no special error, take last mssql error
  463. if ( !$str ) $str = mssql_get_last_message();
  464. // Log this error to the global array..
  465. $EZSQL_ERROR[] = array
  466. (
  467. "query" => $this->last_query,
  468. "error_str" => $str
  469. );
  470. // Is error output turned on or not..
  471. if ( $this->show_errors )
  472. {
  473. // If there is an error then take note of it
  474. /*
  475. print "<blockquote><font face=arial size=2 color=ff0000>";
  476. print "<b>SQL/DB Error --</b> ";
  477. print "[<font color=000000>".$this->last_query."</font>]";
  478. print "[<font color=000077>$str</font>]";
  479. print "</font></blockquote>";
  480. */
  481. dbug($this->last_query.'<br />'.$str,'ERROR','red');
  482. return false;
  483. }
  484. else
  485. {
  486. return false;
  487. }
  488. }
  489. // ==================================================================
  490. // Turn error handling on or off..
  491. function show_errors()
  492. {
  493. $this->show_errors = true;
  494. }
  495. function hide_errors()
  496. {
  497. $this->show_errors = false;
  498. }
  499. // ==================================================================
  500. // Kill cached query results
  501. function flush()
  502. {
  503. // Get rid of these
  504. $this->last_result = null;
  505. $this->col_info = null;
  506. $this->last_query = null;
  507. }
  508. // ==================================================================
  509. // Get one variable from the DB - see docs for more detail
  510. function get_var($query=null,$x=0,$y=0)
  511. {
  512. // Log how the function was called
  513. $this->func_call = "\$db->get_var(\"$query\",$x,$y)";
  514. // If there is a query then perform it if not then use cached results..
  515. if ( $query )
  516. {
  517. $this->query($query);
  518. }
  519. // Extract var out of cached results based x,y vals
  520. if ( $this->last_result[$y] )
  521. {
  522. $values = array_values(get_object_vars($this->last_result[$y]));
  523. }
  524. // If there is a value return it else return null
  525. return (isset($values[$x]) && $values[$x]!=='')?$values[$x]:null;
  526. }
  527. // ==================================================================
  528. // Get one row from the DB - see docs for more detail
  529. function get_row($query=null,$output=OBJECT,$y=0)
  530. {
  531. // Log how the function was called
  532. $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
  533. // If there is a query then perform it if not then use cached results..
  534. if ( $query )
  535. {
  536. $this->query($query);
  537. }
  538. // If the output is an object then return object using the row offset..
  539. if ( $output == OBJECT )
  540. {
  541. return $this->last_result[$y]?$this->last_result[$y]:null;
  542. }
  543. // If the output is an associative array then return row as such..
  544. elseif ( $output == ARRAY_A )
  545. {
  546. return $this->last_result[$y]?get_object_vars($this->last_result[$y]):null;
  547. }
  548. // If the output is an numerical array then return row as such..
  549. elseif ( $output == ARRAY_N )
  550. {
  551. return $this->last_result[$y]?array_values(get_object_vars($this->last_result[$y])):null;
  552. }
  553. // If invalid output type was specified..
  554. else
  555. {
  556. $this->print_error(" \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N");
  557. }
  558. }
  559. // ==================================================================
  560. // Function to get 1 column from the cached result set based in X index
  561. // se docs for usage and info
  562. function get_col($query=null,$x=0)
  563. {
  564. // If there is a query then perform it if not then use cached results..
  565. if ( $query )
  566. {
  567. $this->query($query);
  568. }
  569. // Extract the column values
  570. for ( $i=0; $i < count($this->last_result); $i++ )
  571. {
  572. $new_array[$i] = $this->get_var(null,$x,$i);
  573. }
  574. if($i == 0){
  575. $new_array = array();
  576. }
  577. return $new_array;
  578. }
  579. // ==================================================================
  580. // Return the the query as a result set - see docs for more details
  581. function get_results($query=null, $output = OBJECT)
  582. {
  583. // Log how the function was called
  584. $this->func_call = "\$db->get_results(\"$query\", $output)";
  585. // If there is a query then perform it if not then use cached results..
  586. if ( $query )
  587. {
  588. $this->query($query);
  589. }
  590. // Send back array of objects. Each row is an object
  591. if ( $output == OBJECT )
  592. {
  593. $out = get_object_vars($this->last_result);
  594. return $this->last_result;
  595. }
  596. elseif ( $output == ARRAY_A || $output == ARRAY_N )
  597. {
  598. if ( $this->last_result )
  599. {
  600. $i=0;
  601. foreach( $this->last_result as $row )
  602. {
  603. $new_array[$i] = get_object_vars($row);
  604. if ( $output == ARRAY_N )
  605. {
  606. $new_array[$i] = array_values($new_array[$i]);
  607. }
  608. $i++;
  609. }
  610. return $new_array;
  611. }
  612. else
  613. {
  614. return null;
  615. }
  616. }
  617. }
  618. // ==================================================================
  619. // Function to get column meta data info pertaining to the last query
  620. // see docs for more info and usage
  621. function get_col_info($info_type="name",$col_offset=-1)
  622. {
  623. if ( $this->col_info )
  624. {
  625. if ( $col_offset == -1 )
  626. {
  627. $i=0;
  628. foreach($this->col_info as $col )
  629. {
  630. $new_array[$i] = $col->{$info_type};
  631. $i++;
  632. }
  633. return $new_array;
  634. }
  635. else
  636. {
  637. return $this->col_info[$col_offset]->{$info_type};
  638. }
  639. }
  640. }
  641. // ==================================================================
  642. // Dumps the contents of any input variable to screen in a nicely
  643. // formatted and easy to understand way - any type: Object, Var or Array
  644. function vardump($mixed='')
  645. {
  646. echo "<p><table><tr><td bgcolor=ffffff><blockquote><font color=000090>";
  647. echo "<pre><font face=arial>";
  648. if ( ! $this->vardump_called )
  649. {
  650. echo "<font color=800080><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Variable Dump..</b></font>\n\n";
  651. }
  652. $var_type = gettype ($mixed);
  653. print_r(($mixed?$mixed:"<font color=red>No Value / False</font>"));
  654. echo "\n\n<b>Type:</b> " . ucfirst($var_type) . "\n";
  655. echo "<b>Last Query</b> [$this->num_queries]<b>:</b> ".($this->last_query?$this->last_query:"NULL")."\n";
  656. echo "<b>Last Function Call:</b> " . ($this->func_call?$this->func_call:"None")."\n";
  657. echo "<b>Last Rows Returned:</b> ".count($this->last_result)."\n";
  658. echo "</font></pre></font></blockquote></td></tr></table>".$this->donation();
  659. echo "\n<hr size=1 noshade color=dddddd>";
  660. $this->vardump_called = true;
  661. }
  662. // Alias for the above function
  663. function dumpvar($mixed)
  664. {
  665. $this->vardump($mixed);
  666. }
  667. // ==================================================================
  668. // Displays the last query string that was sent to the database & a
  669. // table listing results (if there were any).
  670. // (abstracted into a seperate file to save server overhead).
  671. function debug()
  672. {
  673. echo "<blockquote>";
  674. // Only show ezSQL credits once..
  675. if ( ! $this->debug_called )
  676. {
  677. echo "<font color=800080 face=arial size=2><b>ezSQL</b> (v".EZSQL_VERSION.") <b>Debug..</b></font><p>\n";
  678. }
  679. echo "<font face=arial size=2 color=000099><b>Query</b> [$this->num_queries] <b>--</b> ";
  680. echo "[<font color=000000><b>$this->last_query</b></font>]</font><p>";
  681. echo "<font face=arial size=2 color=000099><b>Query Result..</b></font>";
  682. echo "<blockquote>";
  683. if ( $this->col_info )
  684. {
  685. // =====================================================
  686. // Results top rows
  687. echo "<table cellpadding=5 cellspacing=1 bgcolor=555555>";
  688. echo "<tr bgcolor=eeeeee><td nowrap valign=bottom><font color=555599 face=arial size=2><b>(row)</b></font></td>";
  689. for ( $i=0; $i < count($this->col_info); $i++ )
  690. {
  691. 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>";
  692. }
  693. echo "</tr>";
  694. // ======================================================
  695. // print main results
  696. if ( $this->last_result )
  697. {
  698. $i=0;
  699. foreach ( $this->get_results(null,ARRAY_N) as $one_row )
  700. {
  701. $i++;
  702. echo "<tr bgcolor=ffffff><td bgcolor=eeeeee nowrap align=middle><font size=2 color=555599 face=arial>$i</font></td>";
  703. foreach ( $one_row as $item )
  704. {
  705. echo "<td nowrap><font face=arial size=2>$item</font></td>";
  706. }
  707. echo "</tr>";
  708. }
  709. } // if last result
  710. else
  711. {
  712. echo "<tr bgcolor=ffffff><td colspan=".(count($this->col_info)+1)."><font face=arial size=2>No Results</font></td></tr>";
  713. }
  714. echo "</table>";
  715. } // if col_info
  716. else
  717. {
  718. echo "<font face=arial size=2>No Results</font>";
  719. }
  720. echo "</blockquote></blockquote>".$this->donation()."<hr noshade color=dddddd size=1>";
  721. $this->debug_called = true;
  722. }
  723. // =======================================================
  724. // Naughty little function to ask for some remuniration!
  725. function donation()
  726. {
  727. 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>";
  728. }
  729. /**
  730. * Sets the table prefix for the WordPress .
  731. *
  732. * Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to
  733. * override the WordPress users and usersmeta tables.
  734. *
  735. * @since 2.5.0
  736. *
  737. * @param string $prefix Alphanumeric name for the new prefix.
  738. * @return string Old prefix
  739. */
  740. function set_prefix($prefix) {
  741. if ( preg_match('|[^a-z0-9_]|i', $prefix) )
  742. return new WP_Error('invalid_db_prefix', /*WP_I18N_DB_BAD_PREFIX*/'Invalid database prefix'/*/WP_I18N_DB_BAD_PREFIX*/);
  743. $old_prefix = $this->prefix;
  744. $this->prefix = $prefix;
  745. foreach ( (array) $this->tables as $table )
  746. $this->$table = $this->prefix . $table;
  747. if ( defined('CUSTOM_USER_TABLE') )
  748. $this->users = CUSTOM_USER_TABLE;
  749. if ( defined('CUSTOM_USER_META_TABLE') )
  750. $this->usermeta = CUSTOM_USER_META_TABLE;
  751. return $old_prefix;
  752. }
  753. /**
  754. * Whether to suppress database errors.
  755. *
  756. * @param unknown_type $suppress
  757. * @return unknown
  758. */
  759. function suppress_errors( $suppress = true ) {
  760. $errors = $this->suppress_errors;
  761. $this->suppress_errors = $suppress;
  762. return $errors;
  763. }
  764. /**
  765. * Escapes content by reference for insertion into the database, for security
  766. *
  767. * @since 2.3.0
  768. *
  769. * @param string $s
  770. */
  771. function escape_by_ref(&$s) {
  772. $s = $this->escape($s);
  773. }
  774. /**
  775. * Generic function to determine if a database supports a particular feature
  776. * @param string $db_cap the feature
  777. * @param false|string|resource $dbh_or_table the databaese (the current database, the database housing the specified table, or the database of the mysql resource)
  778. * @return bool
  779. */
  780. function has_cap( $db_cap ) {
  781. return false;
  782. }
  783. /**
  784. * Insert an array of data into a table.
  785. *
  786. * @since 2.5.0
  787. *
  788. * @param string $table WARNING: not sanitized!
  789. * @param array $data Should not already be SQL-escaped
  790. * @return mixed Results of $this->query()
  791. */
  792. function insert($table, $data) {
  793. $data = add_magic_quotes($data);
  794. $fields = array_keys($data);
  795. return $this->query("INSERT INTO $table (`" . implode('`,`',$fields) . "`) VALUES ('".implode("','",$data)."')");
  796. }
  797. /**
  798. * Prepares a SQL query for safe use, using sprintf() syntax.
  799. *
  800. * @link http://php.net/sprintf See for syntax to use for query string.
  801. * @since 2.3.0
  802. *
  803. * @param null|string $args If string, first parameter must be query statement
  804. * @param mixed $args,... If additional parameters, they will be set inserted into the query.
  805. * @return null|string Sanitized query string
  806. */
  807. function prepare($args=null) {
  808. if ( is_null( $args ) )
  809. return;
  810. $args = func_get_args();
  811. $query = array_shift($args);
  812. $query = str_replace("'%s'", '%s', $query); // in case someone mistakenly already singlequoted it
  813. $query = str_replace('"%s"', '%s', $query); // doublequote unquoting
  814. $query = str_replace('%s', "'%s'", $query); // quote the strings
  815. array_walk($args, array(&$this, 'escape_by_ref'));
  816. return @vsprintf($query, $args);
  817. }
  818. /**
  819. * Update a row in the table with an array of data.
  820. *
  821. * @since 2.5.0
  822. *
  823. * @param string $table WARNING: not sanitized!
  824. * @param array $data Should not already be SQL-escaped
  825. * @param array $where A named array of WHERE column => value relationships. Multiple member pairs will be joined with ANDs. WARNING: the column names are not currently sanitized!
  826. * @return mixed Results of $this->query()
  827. */
  828. function update($table, $data, $where){
  829. $data = add_magic_quotes($data);
  830. $bits = $wheres = array();
  831. foreach ( (array) array_keys($data) as $k )
  832. $bits[] = "`$k` = '$data[$k]'";
  833. if ( is_array( $where ) )
  834. foreach ( $where as $c => $v ){
  835. $v = str_replace("'","'",$v);
  836. //$wheres[] = "$c = '" . $this->escape( $v ) . "'";
  837. $wheres[] = "$c = '" . $v . "'";
  838. }
  839. else
  840. return false;
  841. return $this->query( "UPDATE $table SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres ) );
  842. }
  843. /**
  844. * Whether or not MySQL database is minimal required version.
  845. *
  846. * @since 2.5.0
  847. * @uses $wp_version
  848. *
  849. * @return WP_Error
  850. */
  851. function check_database_version()
  852. {
  853. global $wp_version;
  854. // Make sure the server has MySQL 4.0
  855. /*
  856. if ( version_compare($this->db_version(), '4.0.0', '<') )
  857. return new WP_Error('database_version',sprintf(__('<strong>ERROR</strong>: WordPress %s requires MySQL 4.0.0 or higher'), $wp_version));
  858. */
  859. }
  860. }
  861. // automatically create a new $db object
  862. //$wpdb = new db(EZSQL_DB_USER, EZSQL_DB_PASSWORD, EZSQL_DB_NAME, EZSQL_DB_HOST);
  863. function array_to_object($array = array()) {
  864. if (!empty($array)) {
  865. $data = false;
  866. foreach ($array as $akey => $aval) {
  867. if(!is_numeric($akey)){
  868. $data -> {$akey} = trim($aval);
  869. }
  870. }
  871. return $data;
  872. }
  873. return false;
  874. }
  875. function pre($sting_to_pre = '',$ob=false){
  876. if($sting_to_pre){
  877. if($ob){
  878. ob_start();
  879. echo '<pre>';
  880. print_r($sting_to_pre);
  881. echo '</pre>';
  882. $the_return = ob_get_contents();
  883. ob_end_clean();
  884. return $the_return;
  885. }else{
  886. echo '<pre>';
  887. print_r($sting_to_pre);
  888. echo '</pre>';
  889. }
  890. }
  891. }
  892. function dbug($val,$prepend='',$prepend_color='red'){
  893. /*
  894. $fp = fopen('E:\wwwusr\vhosts\tretinoin.dev.lamp2win.com\httpdocs\debug\log.txt', 'a');
  895. fwrite($fp, '<span style="color:'.$prepend_color.';"><b>'.$prepend.'</b></span> '.$val."\n");
  896. fclose($fp);
  897. */
  898. }
  899. ?>