PageRenderTime 76ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/wp-db.php

https://github.com/Mercedes/ratonesytortillas
PHP | 576 lines | 355 code | 85 blank | 136 comment | 73 complexity | 10b88b7fb8a4a058c7956769a3f9fb11 MD5 | raw file
  1. <?php
  2. // WordPress DB Class
  3. // ORIGINAL CODE FROM:
  4. // Justin Vincent (justin@visunet.ie)
  5. // http://php.justinvincent.com
  6. define('EZSQL_VERSION', 'WP1.25');
  7. define('OBJECT', 'OBJECT', true);
  8. define('OBJECT_K', 'OBJECT_K', false);
  9. define('ARRAY_A', 'ARRAY_A', false);
  10. define('ARRAY_N', 'ARRAY_N', false);
  11. if (!defined('SAVEQUERIES'))
  12. define('SAVEQUERIES', false);
  13. class wpdb {
  14. var $show_errors = false;
  15. var $suppress_errors = false;
  16. var $last_error = '';
  17. var $num_queries = 0;
  18. var $last_query;
  19. var $col_info;
  20. var $queries;
  21. var $prefix = '';
  22. var $ready = false;
  23. // Our tables
  24. var $posts;
  25. var $users;
  26. var $categories;
  27. var $post2cat;
  28. var $comments;
  29. var $links;
  30. var $options;
  31. var $postmeta;
  32. var $usermeta;
  33. var $terms;
  34. var $term_taxonomy;
  35. var $term_relationships;
  36. var $tables = array('users', 'usermeta', 'posts', 'categories', 'post2cat', 'comments', 'links', 'link2cat', 'options',
  37. 'postmeta', 'terms', 'term_taxonomy', 'term_relationships');
  38. var $charset;
  39. var $collate;
  40. /**
  41. * Connects to the database server and selects a database
  42. * @param string $dbuser
  43. * @param string $dbpassword
  44. * @param string $dbname
  45. * @param string $dbhost
  46. */
  47. function wpdb($dbuser, $dbpassword, $dbname, $dbhost) {
  48. return $this->__construct($dbuser, $dbpassword, $dbname, $dbhost);
  49. }
  50. function __construct($dbuser, $dbpassword, $dbname, $dbhost) {
  51. register_shutdown_function(array(&$this, "__destruct"));
  52. if ( defined('WP_DEBUG') and WP_DEBUG == true )
  53. $this->show_errors();
  54. if ( defined('DB_CHARSET') )
  55. $this->charset = DB_CHARSET;
  56. if ( defined('DB_COLLATE') )
  57. $this->collate = DB_COLLATE;
  58. $this->dbh = @mysql_connect($dbhost, $dbuser, $dbpassword, true);
  59. if (!$this->dbh) {
  60. $this->bail("
  61. <h1>Error establishing a database connection</h1>
  62. <p>This either means that the username and password information in your <code>wp-config.php</code> file is incorrect or we can't contact the database server at <code>$dbhost</code>. This could mean your host's database server is down.</p>
  63. <ul>
  64. <li>Are you sure you have the correct username and password?</li>
  65. <li>Are you sure that you have typed the correct hostname?</li>
  66. <li>Are you sure that the database server is running?</li>
  67. </ul>
  68. <p>If you're unsure what these terms mean you should probably contact your host. If you still need help you can always visit the <a href='http://wordpress.org/support/'>WordPress Support Forums</a>.</p>
  69. ");
  70. return;
  71. }
  72. $this->ready = true;
  73. if ( !empty($this->charset) && version_compare(mysql_get_server_info($this->dbh), '4.1.0', '>=') )
  74. $this->query("SET NAMES '$this->charset'");
  75. $this->select($dbname);
  76. }
  77. function __destruct() {
  78. return true;
  79. }
  80. function set_prefix($prefix) {
  81. if ( preg_match('|[^a-z0-9_]|i', $prefix) )
  82. return new WP_Error('invalid_db_prefix', 'Invalid database prefix'); // No gettext here
  83. $old_prefix = $this->prefix;
  84. $this->prefix = $prefix;
  85. foreach ( $this->tables as $table )
  86. $this->$table = $this->prefix . $table;
  87. if ( defined('CUSTOM_USER_TABLE') )
  88. $this->users = CUSTOM_USER_TABLE;
  89. if ( defined('CUSTOM_USER_META_TABLE') )
  90. $this->usermeta = CUSTOM_USER_META_TABLE;
  91. return $old_prefix;
  92. }
  93. /**
  94. * Selects a database using the current class's $this->dbh
  95. * @param string $db name
  96. */
  97. function select($db) {
  98. if (!@mysql_select_db($db, $this->dbh)) {
  99. $this->ready = false;
  100. $this->bail("
  101. <h1>Can&#8217;t select database</h1>
  102. <p>We were able to connect to the database server (which means your username and password is okay) but not able to select the <code>$db</code> database.</p>
  103. <ul>
  104. <li>Are you sure it exists?</li>
  105. <li>Does the user <code>".DB_USER."</code> have permission to use the <code>$db</code> database?</li>
  106. <li>On some systems the name of your database is prefixed with your username, so it would be like username_wordpress. Could that be the problem?</li>
  107. </ul>
  108. <p>If you don't know how to setup a database you should <strong>contact your host</strong>. If all else fails you may find help at the <a href='http://wordpress.org/support/'>WordPress Support Forums</a>.</p>");
  109. return;
  110. }
  111. }
  112. /**
  113. * Escapes content for insertion into the database, for security
  114. *
  115. * @param string $string
  116. * @return string query safe string
  117. */
  118. function escape($string) {
  119. return addslashes( $string );
  120. // Disable rest for now, causing problems
  121. /*
  122. if( !$this->dbh || version_compare( phpversion(), '4.3.0' ) == '-1' )
  123. return mysql_escape_string( $string );
  124. else
  125. return mysql_real_escape_string( $string, $this->dbh );
  126. */
  127. }
  128. /**
  129. * Escapes content by reference for insertion into the database, for security
  130. * @param string $s
  131. */
  132. function escape_by_ref(&$s) {
  133. $s = $this->escape($s);
  134. }
  135. /**
  136. * Prepares a SQL query for safe use, using sprintf() syntax
  137. */
  138. function prepare($args=NULL) {
  139. if ( NULL === $args )
  140. return;
  141. $args = func_get_args();
  142. $query = array_shift($args);
  143. $query = str_replace("'%s'", '%s', $query); // in case someone mistakenly already singlequoted it
  144. $query = str_replace('"%s"', '%s', $query); // doublequote unquoting
  145. $query = str_replace('%s', "'%s'", $query); // quote the strings
  146. array_walk($args, array(&$this, 'escape_by_ref'));
  147. return @vsprintf($query, $args);
  148. }
  149. // ==================================================================
  150. // Print SQL/DB error.
  151. function print_error($str = '') {
  152. global $EZSQL_ERROR;
  153. if (!$str) $str = mysql_error($this->dbh);
  154. $EZSQL_ERROR[] =
  155. array ('query' => $this->last_query, 'error_str' => $str);
  156. if ( $this->suppress_errors )
  157. return false;
  158. $error_str = "WordPress database error $str for query $this->last_query";
  159. if ( $caller = $this->get_caller() )
  160. $error_str .= " made by $caller";
  161. $log_error = true;
  162. if ( ! function_exists('error_log') )
  163. $log_error = false;
  164. $log_file = @ini_get('error_log');
  165. if ( !empty($log_file) && ('syslog' != $log_file) && !is_writable($log_file) )
  166. $log_error = false;
  167. if ( $log_error )
  168. @error_log($error_str, 0);
  169. // Is error output turned on or not..
  170. if ( !$this->show_errors )
  171. return false;
  172. $str = htmlspecialchars($str, ENT_QUOTES);
  173. $query = htmlspecialchars($this->last_query, ENT_QUOTES);
  174. // If there is an error then take note of it
  175. print "<div id='error'>
  176. <p class='wpdberror'><strong>WordPress database error:</strong> [$str]<br />
  177. <code>$query</code></p>
  178. </div>";
  179. }
  180. // ==================================================================
  181. // Turn error handling on or off..
  182. function show_errors( $show = true ) {
  183. $errors = $this->show_errors;
  184. $this->show_errors = $show;
  185. return $errors;
  186. }
  187. function hide_errors() {
  188. $show = $this->show_errors;
  189. $this->show_errors = false;
  190. return $show;
  191. }
  192. function suppress_errors( $suppress = true ) {
  193. $errors = $this->suppress_errors;
  194. $this->suppress_errors = $suppress;
  195. return $errors;
  196. }
  197. // ==================================================================
  198. // Kill cached query results
  199. function flush() {
  200. $this->last_result = array();
  201. $this->col_info = null;
  202. $this->last_query = null;
  203. }
  204. // ==================================================================
  205. // Basic Query - see docs for more detail
  206. function query($query) {
  207. if ( ! $this->ready )
  208. return false;
  209. // filter the query, if filters are available
  210. // NOTE: some queries are made before the plugins have been loaded, and thus cannot be filtered with this method
  211. if ( function_exists('apply_filters') )
  212. $query = apply_filters('query', $query);
  213. // initialise return
  214. $return_val = 0;
  215. $this->flush();
  216. // Log how the function was called
  217. $this->func_call = "\$db->query(\"$query\")";
  218. // Keep track of the last query for debug..
  219. $this->last_query = $query;
  220. // Perform the query via std mysql_query function..
  221. if (SAVEQUERIES)
  222. $this->timer_start();
  223. $this->result = @mysql_query($query, $this->dbh);
  224. ++$this->num_queries;
  225. if (SAVEQUERIES)
  226. $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
  227. // If there is an error then take note of it..
  228. if ( $this->last_error = mysql_error($this->dbh) ) {
  229. $this->print_error();
  230. return false;
  231. }
  232. if ( preg_match("/^\\s*(insert|delete|update|replace) /i",$query) ) {
  233. $this->rows_affected = mysql_affected_rows($this->dbh);
  234. // Take note of the insert_id
  235. if ( preg_match("/^\\s*(insert|replace) /i",$query) ) {
  236. $this->insert_id = mysql_insert_id($this->dbh);
  237. }
  238. // Return number of rows affected
  239. $return_val = $this->rows_affected;
  240. } else {
  241. $i = 0;
  242. while ($i < @mysql_num_fields($this->result)) {
  243. $this->col_info[$i] = @mysql_fetch_field($this->result);
  244. $i++;
  245. }
  246. $num_rows = 0;
  247. while ( $row = @mysql_fetch_object($this->result) ) {
  248. $this->last_result[$num_rows] = $row;
  249. $num_rows++;
  250. }
  251. @mysql_free_result($this->result);
  252. // Log number of rows the query returned
  253. $this->num_rows = $num_rows;
  254. // Return number of rows selected
  255. $return_val = $this->num_rows;
  256. }
  257. return $return_val;
  258. }
  259. /**
  260. * Insert an array of data into a table
  261. * @param string $table WARNING: not sanitized!
  262. * @param array $data should not already be SQL-escaped
  263. * @return mixed results of $this->query()
  264. */
  265. function insert($table, $data) {
  266. $data = add_magic_quotes($data);
  267. $fields = array_keys($data);
  268. return $this->query("INSERT INTO $table (`" . implode('`,`',$fields) . "`) VALUES ('".implode("','",$data)."')");
  269. }
  270. /**
  271. * Update a row in the table with an array of data
  272. * @param string $table WARNING: not sanitized!
  273. * @param array $data should not already be SQL-escaped
  274. * @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!
  275. * @return mixed results of $this->query()
  276. */
  277. function update($table, $data, $where){
  278. $data = add_magic_quotes($data);
  279. $bits = $wheres = array();
  280. foreach ( array_keys($data) as $k )
  281. $bits[] = "`$k` = '$data[$k]'";
  282. if ( is_array( $where ) )
  283. foreach ( $where as $c => $v )
  284. $wheres[] = "$c = '" . $this->escape( $v ) . "'";
  285. else
  286. return false;
  287. return $this->query( "UPDATE $table SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres ) . ' LIMIT 1' );
  288. }
  289. /**
  290. * Get one variable from the database
  291. * @param string $query (can be null as well, for caching, see codex)
  292. * @param int $x = 0 row num to return
  293. * @param int $y = 0 col num to return
  294. * @return mixed results
  295. */
  296. function get_var($query=null, $x = 0, $y = 0) {
  297. $this->func_call = "\$db->get_var(\"$query\",$x,$y)";
  298. if ( $query )
  299. $this->query($query);
  300. // Extract var out of cached results based x,y vals
  301. if ( !empty( $this->last_result[$y] ) ) {
  302. $values = array_values(get_object_vars($this->last_result[$y]));
  303. }
  304. // If there is a value return it else return null
  305. return (isset($values[$x]) && $values[$x]!=='') ? $values[$x] : null;
  306. }
  307. /**
  308. * Get one row from the database
  309. * @param string $query
  310. * @param string $output ARRAY_A | ARRAY_N | OBJECT
  311. * @param int $y row num to return
  312. * @return mixed results
  313. */
  314. function get_row($query = null, $output = OBJECT, $y = 0) {
  315. $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
  316. if ( $query )
  317. $this->query($query);
  318. else
  319. return null;
  320. if ( !isset($this->last_result[$y]) )
  321. return null;
  322. if ( $output == OBJECT ) {
  323. return $this->last_result[$y] ? $this->last_result[$y] : null;
  324. } elseif ( $output == ARRAY_A ) {
  325. return $this->last_result[$y] ? get_object_vars($this->last_result[$y]) : null;
  326. } elseif ( $output == ARRAY_N ) {
  327. return $this->last_result[$y] ? array_values(get_object_vars($this->last_result[$y])) : null;
  328. } else {
  329. $this->print_error(" \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N");
  330. }
  331. }
  332. /**
  333. * Gets one column from the database
  334. * @param string $query (can be null as well, for caching, see codex)
  335. * @param int $x col num to return
  336. * @return array results
  337. */
  338. function get_col($query = null , $x = 0) {
  339. if ( $query )
  340. $this->query($query);
  341. $new_array = array();
  342. // Extract the column values
  343. for ( $i=0; $i < count($this->last_result); $i++ ) {
  344. $new_array[$i] = $this->get_var(null, $x, $i);
  345. }
  346. return $new_array;
  347. }
  348. /**
  349. * Return an entire result set from the database
  350. * @param string $query (can also be null to pull from the cache)
  351. * @param string $output ARRAY_A | ARRAY_N | OBJECT_K | OBJECT
  352. * @return mixed results
  353. */
  354. function get_results($query = null, $output = OBJECT) {
  355. $this->func_call = "\$db->get_results(\"$query\", $output)";
  356. if ( $query )
  357. $this->query($query);
  358. else
  359. return null;
  360. if ( $output == OBJECT ) {
  361. // Return an integer-keyed array of row objects
  362. return $this->last_result;
  363. } elseif ( $output == OBJECT_K ) {
  364. // Return an array of row objects with keys from column 1
  365. // (Duplicates are discarded)
  366. foreach ( $this->last_result as $row ) {
  367. $key = array_shift( get_object_vars( $row ) );
  368. if ( !isset( $new_array[ $key ] ) )
  369. $new_array[ $key ] = $row;
  370. }
  371. return $new_array;
  372. } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
  373. // Return an integer-keyed array of...
  374. if ( $this->last_result ) {
  375. $i = 0;
  376. foreach( $this->last_result as $row ) {
  377. if ( $output == ARRAY_N ) {
  378. // ...integer-keyed row arrays
  379. $new_array[$i] = array_values( get_object_vars( $row ) );
  380. } else {
  381. // ...column name-keyed row arrays
  382. $new_array[$i] = get_object_vars( $row );
  383. }
  384. ++$i;
  385. }
  386. return $new_array;
  387. }
  388. }
  389. }
  390. /**
  391. * Grabs column metadata from the last query
  392. * @param string $info_type one of name, table, def, max_length, not_null, primary_key, multiple_key, unique_key, numeric, blob, type, unsigned, zerofill
  393. * @param int $col_offset 0: col name. 1: which table the col's in. 2: col's max length. 3: if the col is numeric. 4: col's type
  394. * @return mixed results
  395. */
  396. function get_col_info($info_type = 'name', $col_offset = -1) {
  397. if ( $this->col_info ) {
  398. if ( $col_offset == -1 ) {
  399. $i = 0;
  400. foreach($this->col_info as $col ) {
  401. $new_array[$i] = $col->{$info_type};
  402. $i++;
  403. }
  404. return $new_array;
  405. } else {
  406. return $this->col_info[$col_offset]->{$info_type};
  407. }
  408. }
  409. }
  410. /**
  411. * Starts the timer, for debugging purposes
  412. */
  413. function timer_start() {
  414. $mtime = microtime();
  415. $mtime = explode(' ', $mtime);
  416. $this->time_start = $mtime[1] + $mtime[0];
  417. return true;
  418. }
  419. /**
  420. * Stops the debugging timer
  421. * @return int total time spent on the query, in milliseconds
  422. */
  423. function timer_stop() {
  424. $mtime = microtime();
  425. $mtime = explode(' ', $mtime);
  426. $time_end = $mtime[1] + $mtime[0];
  427. $time_total = $time_end - $this->time_start;
  428. return $time_total;
  429. }
  430. /**
  431. * Wraps fatal errors in a nice header and footer and dies.
  432. * @param string $message
  433. */
  434. function bail($message) { // Just wraps errors in a nice header and footer
  435. if ( !$this->show_errors ) {
  436. if ( class_exists('WP_Error') )
  437. $this->error = new WP_Error('500', $message);
  438. else
  439. $this->error = $message;
  440. return false;
  441. }
  442. wp_die($message);
  443. }
  444. /**
  445. * Checks wether of not the database version is high enough to support the features WordPress uses
  446. * @global $wp_version
  447. */
  448. function check_database_version()
  449. {
  450. global $wp_version;
  451. // Make sure the server has MySQL 4.0
  452. $mysql_version = preg_replace('|[^0-9\.]|', '', @mysql_get_server_info($this->dbh));
  453. if ( version_compare($mysql_version, '4.0.0', '<') )
  454. return new WP_Error('database_version',sprintf(__('<strong>ERROR</strong>: WordPress %s requires MySQL 4.0.0 or higher'), $wp_version));
  455. }
  456. /**
  457. * This function is called when WordPress is generating the table schema to determine wether or not the current database
  458. * supports or needs the collation statements.
  459. */
  460. function supports_collation()
  461. {
  462. return ( version_compare(mysql_get_server_info($this->dbh), '4.1.0', '>=') );
  463. }
  464. /**
  465. * Get the name of the function that called wpdb.
  466. * @return string the name of the calling function
  467. */
  468. function get_caller() {
  469. // requires PHP 4.3+
  470. if ( !is_callable('debug_backtrace') )
  471. return '';
  472. $bt = debug_backtrace();
  473. $caller = '';
  474. foreach ( $bt as $trace ) {
  475. if ( @$trace['class'] == __CLASS__ )
  476. continue;
  477. elseif ( strtolower(@$trace['function']) == 'call_user_func_array' )
  478. continue;
  479. elseif ( strtolower(@$trace['function']) == 'apply_filters' )
  480. continue;
  481. elseif ( strtolower(@$trace['function']) == 'do_action' )
  482. continue;
  483. $caller = $trace['function'];
  484. break;
  485. }
  486. return $caller;
  487. }
  488. }
  489. if ( ! isset($wpdb) )
  490. $wpdb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
  491. ?>