[ Root ] [ Search ] [ Index ]

PHP Cross Reference of WordPress MU 2.9.2

Provided by Yoast

title

Body

[close]

/wp-includes/ -> wp-db.php (source)

   1  <?php
   2  /**
   3   * WordPress DB Class
   4   *
   5   * Original code from {@link http://php.justinvincent.com Justin Vincent (justin@visunet.ie)}
   6   *
   7   * @package WordPress
   8   * @subpackage Database
   9   * @since 0.71
  10   */
  11  
  12  /**
  13   * @since 0.71
  14   */
  15  define('EZSQL_VERSION', 'WP1.25');
  16  
  17  /**
  18   * @since 0.71
  19   */
  20  define('OBJECT', 'OBJECT', true);
  21  
  22  /**
  23   * @since {@internal Version Unknown}}
  24   */
  25  define('OBJECT_K', 'OBJECT_K', false);
  26  
  27  /**
  28   * @since 0.71
  29   */
  30  define('ARRAY_A', 'ARRAY_A', false);
  31  
  32  /**
  33   * @since 0.71
  34   */
  35  define('ARRAY_N', 'ARRAY_N', false);
  36  
  37  /**
  38   * WordPress Database Access Abstraction Object
  39   *
  40   * It is possible to replace this class with your own
  41   * by setting the $wpdb global variable in wp-content/db.php
  42   * file with your class. You can name it wpdb also, since
  43   * this file will not be included, if the other file is
  44   * available.
  45   *
  46   * @link http://codex.wordpress.org/Function_Reference/wpdb_Class
  47   *
  48   * @package WordPress
  49   * @subpackage Database
  50   * @since 0.71
  51   * @final
  52   */
  53  class wpdb {
  54  
  55      /**
  56       * Whether to show SQL/DB errors
  57       *
  58       * @since 0.71
  59       * @access private
  60       * @var bool
  61       */
  62      var $show_errors = false;
  63  
  64      /**
  65       * Whether to suppress errors during the DB bootstrapping.
  66       *
  67       * @access private
  68       * @since {@internal Version Unknown}}
  69       * @var bool
  70       */
  71      var $suppress_errors = false;
  72  
  73      /**
  74       * The last error during query.
  75       *
  76       * @since {@internal Version Unknown}}
  77       * @var string
  78       */
  79      var $last_error = '';
  80  
  81      /**
  82       * Amount of queries made
  83       *
  84       * @since 1.2.0
  85       * @access private
  86       * @var int
  87       */
  88      var $num_queries = 0;
  89  
  90      /**
  91       * Saved result of the last query made
  92       *
  93       * @since 1.2.0
  94       * @access private
  95       * @var array
  96       */
  97      var $last_query;
  98  
  99      /**
 100       * Saved info on the table column
 101       *
 102       * @since 1.2.0
 103       * @access private
 104       * @var array
 105       */
 106      var $col_info;
 107  
 108      /**
 109       * Saved queries that were executed
 110       *
 111       * @since 1.5.0
 112       * @access private
 113       * @var array
 114       */
 115      var $queries;
 116  
 117      /**
 118       * WordPress table prefix
 119       *
 120       * You can set this to have multiple WordPress installations
 121       * in a single database. The second reason is for possible
 122       * security precautions.
 123       *
 124       * @since 0.71
 125       * @access private
 126       * @var string
 127       */
 128      var $prefix = '';
 129  
 130      /**
 131       * Whether the database queries are ready to start executing.
 132       *
 133       * @since 2.5.0
 134       * @access private
 135       * @var bool
 136       */
 137      var $ready = false;
 138      var $blogid = 0;
 139      var $siteid = 0;
 140      var $blogs;
 141      var $signups;
 142      var $site;
 143      var $sitemeta;
 144      var $sitecategories;
 145      var $global_tables = array('blogs', 'signups', 'site', 'sitemeta', 'users', 'usermeta', 'sitecategories', 'registration_log', 'blog_versions');
 146  
 147      /**
 148       * WordPress Posts table
 149       *
 150       * @since 1.5.0
 151       * @access public
 152       * @var string
 153       */
 154      var $posts;
 155  
 156      /**
 157       * WordPress Users table
 158       *
 159       * @since 1.5.0
 160       * @access public
 161       * @var string
 162       */
 163      var $users;
 164  
 165      /**
 166       * WordPress Categories table
 167       *
 168       * @since 1.5.0
 169       * @access public
 170       * @var string
 171       */
 172      var $categories;
 173  
 174      /**
 175       * WordPress Post to Category table
 176       *
 177       * @since 1.5.0
 178       * @access public
 179       * @var string
 180       */
 181      var $post2cat;
 182  
 183      /**
 184       * WordPress Comments table
 185       *
 186       * @since 1.5.0
 187       * @access public
 188       * @var string
 189       */
 190      var $comments;
 191  
 192      /**
 193       * WordPress Links table
 194       *
 195       * @since 1.5.0
 196       * @access public
 197       * @var string
 198       */
 199      var $links;
 200  
 201      /**
 202       * WordPress Options table
 203       *
 204       * @since 1.5.0
 205       * @access public
 206       * @var string
 207       */
 208      var $options;
 209  
 210      /**
 211       * WordPress Post Metadata table
 212       *
 213       * @since {@internal Version Unknown}}
 214       * @access public
 215       * @var string
 216       */
 217      var $postmeta;
 218  
 219      /**
 220       * WordPress Comment Metadata table
 221       *
 222       * @since 2.9
 223       * @access public
 224       * @var string
 225       */
 226      var $commentmeta;
 227  
 228      /**
 229       * WordPress User Metadata table
 230       *
 231       * @since 2.3.0
 232       * @access public
 233       * @var string
 234       */
 235      var $usermeta;
 236  
 237      /**
 238       * WordPress Terms table
 239       *
 240       * @since 2.3.0
 241       * @access public
 242       * @var string
 243       */
 244      var $terms;
 245  
 246      /**
 247       * WordPress Term Taxonomy table
 248       *
 249       * @since 2.3.0
 250       * @access public
 251       * @var string
 252       */
 253      var $term_taxonomy;
 254  
 255      /**
 256       * WordPress Term Relationships table
 257       *
 258       * @since 2.3.0
 259       * @access public
 260       * @var string
 261       */
 262      var $term_relationships;
 263  
 264      /**
 265       * List of WordPress tables
 266       *
 267       * @since {@internal Version Unknown}}
 268       * @access private
 269       * @var array
 270       */
 271      var $tables = array('posts', 'categories', 'post2cat', 'comments', 'links', 'link2cat', 'options',
 272              'postmeta', 'terms', 'term_taxonomy', 'term_relationships', 'commentmeta');
 273  
 274      /**
 275       * List of deprecated WordPress tables
 276       *
 277       * @since 2.9.0
 278       * @access private
 279       * @var array
 280       */
 281      var $old_tables = array('categories', 'post2cat', 'link2cat');
 282  
 283  
 284      /**
 285       * Format specifiers for DB columns. Columns not listed here default to %s.  Initialized in wp-settings.php.
 286       *
 287       * Keys are colmn names, values are format types: 'ID' => '%d'
 288       *
 289       * @since 2.8.0
 290       * @see wpdb:prepare()
 291       * @see wpdb:insert()
 292       * @see wpdb:update()
 293       * @access public
 294       * @war array
 295       */
 296      var $field_types = array();
 297  
 298      /**
 299       * Database table columns charset
 300       *
 301       * @since 2.2.0
 302       * @access public
 303       * @var string
 304       */
 305      var $charset;
 306  
 307      /**
 308       * Database table columns collate
 309       *
 310       * @since 2.2.0
 311       * @access public
 312       * @var string
 313       */
 314      var $collate;
 315  
 316      /**
 317       * Whether to use mysql_real_escape_string
 318       *
 319       * @since 2.8.0
 320       * @access public
 321       * @var bool
 322       */
 323      var $real_escape = false;
 324  
 325      /**
 326       * Database Username
 327       *
 328       * @since 2.9.0
 329       * @access private
 330       * @var string
 331       */
 332      var $dbuser;
 333  
 334      /**
 335       * Connects to the database server and selects a database
 336       *
 337       * PHP4 compatibility layer for calling the PHP5 constructor.
 338       *
 339       * @uses wpdb::__construct() Passes parameters and returns result
 340       * @since 0.71
 341       *
 342       * @param string $dbuser MySQL database user
 343       * @param string $dbpassword MySQL database password
 344       * @param string $dbname MySQL database name
 345       * @param string $dbhost MySQL database host
 346       */
 347  	function wpdb($dbuser, $dbpassword, $dbname, $dbhost) {
 348          if( defined( "WP_USE_MULTIPLE_DB" ) && CONSTANT( "WP_USE_MULTIPLE_DB" ) == true )
 349              $this->db_connect();
 350          return $this->__construct($dbuser, $dbpassword, $dbname, $dbhost);
 351      }
 352  
 353      /**
 354       * Connects to the database server and selects a database
 355       *
 356       * PHP5 style constructor for compatibility with PHP5. Does
 357       * the actual setting up of the class properties and connection
 358       * to the database.
 359       *
 360       * @since 2.0.8
 361       *
 362       * @param string $dbuser MySQL database user
 363       * @param string $dbpassword MySQL database password
 364       * @param string $dbname MySQL database name
 365       * @param string $dbhost MySQL database host
 366       */
 367  	function __construct($dbuser, $dbpassword, $dbname, $dbhost) {
 368          register_shutdown_function(array(&$this, "__destruct"));
 369  
 370          if ( defined('WP_DEBUG') and WP_DEBUG )
 371              $this->show_errors();
 372  
 373          $this->charset = 'utf8';
 374          if( defined( 'DB_COLLATE' ) && constant( 'DB_COLLATE' ) != '' ) {
 375              $this->collate = constant( 'DB_COLLATE' );
 376          } else {
 377              $this->collate = 'utf8_general_ci';
 378          }
 379  
 380          if ( defined('DB_CHARSET') )
 381              $this->charset = DB_CHARSET;
 382  
 383          if ( defined('DB_COLLATE') )
 384              $this->collate = DB_COLLATE;
 385  
 386          $this->dbuser = $dbuser;
 387  
 388          $this->dbh = @mysql_connect($dbhost, $dbuser, $dbpassword, true);
 389          if (!$this->dbh) {
 390              $this->bail(sprintf(/*WP_I18N_DB_CONN_ERROR*/"
 391  <h1>Error establishing a database connection</h1>
 392  <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>%s</code>. This could mean your host's database server is down.</p>
 393  <ul>
 394      <li>Are you sure you have the correct username and password?</li>
 395      <li>Are you sure that you have typed the correct hostname?</li>
 396      <li>Are you sure that the database server is running?</li>
 397  </ul>
 398  <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>
 399  "/*/WP_I18N_DB_CONN_ERROR*/, $dbhost), 'db_connect_fail');
 400              return;
 401          }
 402  
 403          $this->ready = true;
 404  
 405          if ( $this->has_cap( 'collation' ) && !empty($this->charset) ) {
 406              if ( function_exists('mysql_set_charset') ) {
 407                  mysql_set_charset($this->charset, $this->dbh);
 408                  $this->real_escape = true;
 409              } else {
 410                  $collation_query = "SET NAMES '{$this->charset}'";
 411                  if ( !empty($this->collate) )
 412                      $collation_query .= " COLLATE '{$this->collate}'";
 413                  $this->query($collation_query);
 414              }
 415          }
 416  
 417          $this->select($dbname, $this->dbh);
 418      }
 419  
 420      /**
 421       * PHP5 style destructor and will run when database object is destroyed.
 422       *
 423       * @since 2.0.8
 424       *
 425       * @return bool Always true
 426       */
 427  	function __destruct() {
 428          return true;
 429      }
 430  
 431      /**
 432       * Sets the table prefix for the WordPress tables.
 433       *
 434       * Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to
 435       * override the WordPress users and usersmeta tables that would otherwise be determined by the $prefix.
 436       *
 437       * @since 2.5.0
 438       *
 439       * @param string $prefix Alphanumeric name for the new prefix.
 440       * @return string|WP_Error Old prefix or WP_Error on error
 441       */
 442  	function set_prefix($prefix) {
 443  
 444          if ( preg_match('|[^a-z0-9_]|i', $prefix) )
 445              return new WP_Error('invalid_db_prefix', /*WP_I18N_DB_BAD_PREFIX*/'Invalid database prefix'/*/WP_I18N_DB_BAD_PREFIX*/);
 446  
 447          $old_prefix = '';
 448          if( isset( $this->base_prefix ) )
 449              $old_prefix = $this->base_prefix;
 450          $this->base_prefix = $prefix;
 451          foreach ( $this->global_tables as $table )
 452              $this->$table = $prefix . $table;
 453  
 454          if ( empty($this->blogid) )
 455              return $old_prefix;
 456  
 457          $this->prefix = $this->get_blog_prefix( $this->blogid );
 458  
 459          foreach ( (array) $this->tables as $table )
 460              $this->$table = $this->prefix . $table;
 461  
 462          if ( defined('CUSTOM_USER_TABLE') )
 463              $this->users = CUSTOM_USER_TABLE;
 464  
 465          if ( defined('CUSTOM_USER_META_TABLE') )
 466              $this->usermeta = CUSTOM_USER_META_TABLE;
 467  
 468          return $old_prefix;
 469      }
 470  
 471  	function set_blog_id($blog_id, $site_id = '') {
 472          if ( !empty($site_id) )
 473              $this->siteid = $site_id;
 474  
 475          $old_blog_id = $this->blogid;
 476          $this->blogid = $blog_id;
 477  
 478          $this->prefix = $this->get_blog_prefix( $this->blogid );
 479  
 480          foreach ( $this->tables as $table )
 481              $this->$table = $this->prefix . $table;
 482  
 483          return $old_blog_id;
 484      }
 485  
 486  	function get_blog_prefix( $blog_id = '' ) {
 487          if ( $blog_id ) {
 488              return $this->base_prefix . $blog_id . '_';
 489          } else {
 490              return $this->prefix;
 491          }
 492      }
 493  
 494      /**
 495       * Selects a database using the current database connection.
 496       *
 497       * The database name will be changed based on the current database
 498       * connection. On failure, the execution will bail and display an DB error.
 499       *
 500       * @since 0.71
 501       *
 502       * @param string $db MySQL database name
 503       * @return null Always null.
 504       */
 505  	function select($db, &$dbh) {
 506          if (!@mysql_select_db($db, $dbh)) {
 507              $this->ready = false;
 508              $this->bail(sprintf(/*WP_I18N_DB_SELECT_DB*/'
 509  <h1>Can&#8217;t select database</h1>
 510  <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>%1$s</code> database.</p>
 511  <ul>
 512  <li>Are you sure it exists?</li>
 513  <li>Does the user <code>%2$s</code> have permission to use the <code>%1$s</code> database?</li>
 514  <li>On some systems the name of your database is prefixed with your username, so it would be like <code>username_%1$s</code>. Could that be the problem?</li>
 515  </ul>
 516  <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>'/*/WP_I18N_DB_SELECT_DB*/, $db, $this->dbuser), 'db_select_fail');
 517              return;
 518          }
 519      }
 520  
 521  	function _weak_escape($string) {
 522          return addslashes($string);
 523      }
 524  
 525  	function _real_escape($string) {
 526          if ( $this->dbh && $this->real_escape )
 527              return mysql_real_escape_string( $string, $this->dbh );
 528          else
 529              return addslashes( $string );
 530      }
 531  
 532  	function _escape($data) {
 533          if ( is_array($data) ) {
 534              foreach ( (array) $data as $k => $v ) {
 535                  if ( is_array($v) )
 536                      $data[$k] = $this->_escape( $v );
 537                  else
 538                      $data[$k] = $this->_real_escape( $v );
 539              }
 540          } else {
 541              $data = $this->_real_escape( $data );
 542          }
 543  
 544          return $data;
 545      }
 546  
 547      /**
 548       * Escapes content for insertion into the database using addslashes(), for security
 549       *
 550       * @since 0.71
 551       *
 552       * @param string|array $data
 553       * @return string query safe string
 554       */
 555  	function escape($data) {
 556          if ( is_array($data) ) {
 557              foreach ( (array) $data as $k => $v ) {
 558                  if ( is_array($v) )
 559                      $data[$k] = $this->escape( $v );
 560                  else
 561                      $data[$k] = $this->_weak_escape( $v );
 562              }
 563          } else {
 564              $data = $this->_weak_escape( $data );
 565          }
 566  
 567          return $data;
 568      }
 569  
 570      /**
 571       * Escapes content by reference for insertion into the database, for security
 572       *
 573       * @since 2.3.0
 574       *
 575       * @param string $s
 576       */
 577  	function escape_by_ref(&$string) {
 578          $string = $this->_real_escape( $string );
 579      }
 580  
 581      /**
 582       * Prepares a SQL query for safe execution.  Uses sprintf()-like syntax.
 583       *
 584       * This function only supports a small subset of the sprintf syntax; it only supports %d (decimal number), %s (string).
 585       * Does not support sign, padding, alignment, width or precision specifiers.
 586       * Does not support argument numbering/swapping.
 587       *
 588       * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}.
 589       *
 590       * Both %d and %s should be left unquoted in the query string.
 591       *
 592       * <code>
 593       * wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", "foo", 1337 )
 594       * </code>
 595       *
 596       * @link http://php.net/sprintf Description of syntax.
 597       * @since 2.3.0
 598       *
 599       * @param string $query Query statement with sprintf()-like placeholders
 600       * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if being called like {@link http://php.net/sprintf sprintf()}.
 601       * @param mixed $args,... further variables to substitute into the query's placeholders if being called like {@link http://php.net/sprintf sprintf()}.
 602       * @return null|string Sanitized query string
 603       */
 604  	function prepare($query = null) { // ( $query, *$args )
 605          if ( is_null( $query ) )
 606              return;
 607          $args = func_get_args();
 608          array_shift($args);
 609          // If args were passed as an array (as in vsprintf), move them up
 610          if ( isset($args[0]) && is_array($args[0]) )
 611              $args = $args[0];
 612          $query = str_replace("'%s'", '%s', $query); // in case someone mistakenly already singlequoted it
 613          $query = str_replace('"%s"', '%s', $query); // doublequote unquoting
 614          $query = str_replace('%s', "'%s'", $query); // quote the strings
 615          array_walk($args, array(&$this, 'escape_by_ref'));
 616          return @vsprintf($query, $args);
 617      }
 618  
 619      /**
 620       * Print SQL/DB error.
 621       *
 622       * @since 0.71
 623       * @global array $EZSQL_ERROR Stores error information of query and error string
 624       *
 625       * @param string $str The error to display
 626       * @return bool False if the showing of errors is disabled.
 627       */
 628  	function print_error($str = '') {
 629          global $EZSQL_ERROR;
 630  
 631          if (!$str) $str = mysql_error($this->dbh);
 632          $EZSQL_ERROR[] = array ('query' => $this->last_query, 'error_str' => $str);
 633  
 634          if ( $this->suppress_errors )
 635              return false;
 636  
 637          if ( $caller = $this->get_caller() )
 638              $error_str = sprintf(/*WP_I18N_DB_QUERY_ERROR_FULL*/'WordPress database error %1$s for query %2$s made by %3$s'/*/WP_I18N_DB_QUERY_ERROR_FULL*/, $str, $this->last_query, $caller);
 639          else
 640              $error_str = sprintf(/*WP_I18N_DB_QUERY_ERROR*/'WordPress database error %1$s for query %2$s'/*/WP_I18N_DB_QUERY_ERROR*/, $str, $this->last_query);
 641  
 642          $log_error = true;
 643          if ( ! function_exists('error_log') )
 644              $log_error = false;
 645  
 646          $log_file = @ini_get('error_log');
 647          if ( !empty($log_file) && ('syslog' != $log_file) && !@is_writable($log_file) )
 648              $log_error = false;
 649  
 650          if ( $log_error )
 651              @error_log($error_str, 0);
 652  
 653          // Is error output turned on or not..
 654          if ( !$this->show_errors )
 655              return false;
 656  
 657          // If there is an error then take note of it
 658          $msg = "WordPress database error: [$str]\n{$this->query}\n";
 659          if( defined( 'ERRORLOGFILE' ) )
 660              error_log( $msg, 3, CONSTANT( 'ERRORLOGFILE' ) );
 661          if( defined( 'DIEONDBERROR' ) )
 662              die( $msg );
 663      }
 664  
 665      /**
 666       * Enables showing of database errors.
 667       *
 668       * This function should be used only to enable showing of errors.
 669       * wpdb::hide_errors() should be used instead for hiding of errors. However,
 670       * this function can be used to enable and disable showing of database
 671       * errors.
 672       *
 673       * @since 0.71
 674       *
 675       * @param bool $show Whether to show or hide errors
 676       * @return bool Old value for showing errors.
 677       */
 678  	function show_errors( $show = true ) {
 679          $errors = $this->show_errors;
 680          $this->show_errors = $show;
 681          return $errors;
 682      }
 683  
 684      /**
 685       * Disables showing of database errors.
 686       *
 687       * @since 0.71
 688       *
 689       * @return bool Whether showing of errors was active or not
 690       */
 691  	function hide_errors() {
 692          $show = $this->show_errors;
 693          $this->show_errors = false;
 694          return $show;
 695      }
 696  
 697      /**
 698       * Whether to suppress database errors.
 699       *
 700       * @param unknown_type $suppress
 701       * @return unknown
 702       */
 703  	function suppress_errors( $suppress = true ) {
 704          $errors = $this->suppress_errors;
 705          $this->suppress_errors = $suppress;
 706          return $errors;
 707      }
 708  
 709      /**
 710       * Kill cached query results.
 711       *
 712       * @since 0.71
 713       */
 714  	function flush() {
 715          $this->last_result = array();
 716          $this->col_info = null;
 717          $this->last_query = null;
 718      }
 719  
 720  	function db_connect( $query = "SELECT" ) {
 721          global $db_list, $global_db_list;
 722          if( is_array( $db_list ) == false )
 723              return true;
 724  
 725          if( $this->blogs != '' && preg_match("/(" . $this->blogs . "|" . $this->users . "|" . $this->usermeta . "|" . $this->site . "|" . $this->sitemeta . "|" . $this->sitecategories . ")/i",$query) ) {
 726              $action = 'global';
 727              $details = $global_db_list[ mt_rand( 0, count( $global_db_list ) -1 ) ];
 728              $this->db_global = $details;
 729          } elseif ( preg_match("/^\\s*(alter table|create|insert|delete|update|replace) /i",$query) ) {
 730              $action = 'write';
 731              $details = $db_list[ 'write' ][ mt_rand( 0, count( $db_list[ 'write' ] ) -1 ) ];
 732              $this->db_write = $details;
 733          } else {
 734              $action = '';
 735              $details = $db_list[ 'read' ][ mt_rand( 0, count( $db_list[ 'read' ] ) -1 ) ];
 736              $this->db_read = $details;
 737          }
 738  
 739          $dbhname = "dbh" . $action;
 740          $this->$dbhname = @mysql_connect( $details[ 'db_host' ], $details[ 'db_user' ], $details[ 'db_password' ] );
 741          if (!$this->$dbhname ) {
 742              $this->bail("
 743  <h1>Error establishing a database connection</h1>
 744  <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>
 745  <ul>
 746      <li>Are you sure you have the correct username and password?</li>
 747      <li>Are you sure that you have typed the correct hostname?</li>
 748      <li>Are you sure that the database server is running?</li>
 749  </ul>
 750  <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>
 751  ");
 752          }
 753          $this->select( $details[ 'db_name' ], $this->$dbhname );
 754      }
 755  
 756      /**
 757       * Perform a MySQL database query, using current database connection.
 758       *
 759       * More information can be found on the codex page.
 760       *
 761       * @since 0.71
 762       *
 763       * @param string $query
 764       * @return int|false Number of rows affected/selected or false on error
 765       */
 766  	function query($query) {
 767          if ( ! $this->ready )
 768              return false;
 769  
 770          // filter the query, if filters are available
 771          // NOTE: some queries are made before the plugins have been loaded, and thus cannot be filtered with this method
 772          if ( function_exists('apply_filters') )
 773              $query = apply_filters('query', $query);
 774  
 775          // initialise return
 776          $return_val = 0;
 777          $this->flush();
 778  
 779          // Log how the function was called
 780          $this->func_call = "\$db->query(\"$query\")";
 781  
 782          // Keep track of the last query for debug..
 783          $this->last_query = $query;
 784  
 785          // Perform the query via std mysql_query function..
 786          if ( defined('SAVEQUERIES') && SAVEQUERIES )
 787              $this->timer_start();
 788          
 789          // use $this->dbh for read ops, and $this->dbhwrite for write ops
 790          // use $this->dbhglobal for gloal table ops
 791          unset( $dbh );
 792          if( defined( "WP_USE_MULTIPLE_DB" ) && CONSTANT( "WP_USE_MULTIPLE_DB" ) == true ) {
 793              if( $this->blogs != '' && preg_match("/(" . $this->blogs . "|" . $this->users . "|" . $this->usermeta . "|" . $this->site . "|" . $this->sitemeta . "|" . $this->sitecategories . ")/i",$query) ) {
 794                  if( false == isset( $this->dbhglobal ) ) {
 795                      $this->db_connect( $query );
 796                  }
 797                  $dbh =& $this->dbhglobal;
 798                  $this->last_db_used = "global";
 799              } elseif ( preg_match("/^\\s*(alter table|create|insert|delete|update|replace) /i",$query) ) {
 800                  if( false == isset( $this->dbhwrite ) ) {
 801                      $this->db_connect( $query );
 802                  }
 803                  $dbh =& $this->dbhwrite;
 804                  $this->last_db_used = "write";
 805              } else {
 806                  $dbh =& $this->dbh;
 807                  $this->last_db_used = "read";
 808              }
 809          } else {
 810              $dbh =& $this->dbh;
 811              $this->last_db_used = "other/read";
 812          }
 813  
 814          $this->result = @mysql_query($query, $dbh);
 815          ++$this->num_queries;
 816  
 817          if ( defined('SAVEQUERIES') && SAVEQUERIES )
 818              $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
 819  
 820          // If there is an error then take note of it..
 821          if ( $this->last_error = mysql_error($dbh) ) {
 822              $this->print_error();
 823              return false;
 824          }
 825  
 826          if ( preg_match("/^\\s*(insert|delete|update|replace|alter) /i",$query) ) {
 827              $this->rows_affected = mysql_affected_rows($dbh);
 828              // Take note of the insert_id
 829              if ( preg_match("/^\\s*(insert|replace) /i",$query) ) {
 830                  $this->insert_id = mysql_insert_id($dbh);
 831              }
 832              // Return number of rows affected
 833              $return_val = $this->rows_affected;
 834          } else {
 835              $i = 0;
 836              while ($i < @mysql_num_fields($this->result)) {
 837                  $this->col_info[$i] = @mysql_fetch_field($this->result);
 838                  $i++;
 839              }
 840              $num_rows = 0;
 841              while ( $row = @mysql_fetch_object($this->result) ) {
 842                  $this->last_result[$num_rows] = $row;
 843                  $num_rows++;
 844              }
 845  
 846              @mysql_free_result($this->result);
 847  
 848              // Log number of rows the query returned
 849              $this->num_rows = $num_rows;
 850  
 851              // Return number of rows selected
 852              $return_val = $this->num_rows;
 853          }
 854  
 855          return $return_val;
 856      }
 857  
 858      /**
 859       * Insert a row into a table.
 860       *
 861       * <code>
 862       * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
 863       * </code>
 864       *
 865       * @since 2.5.0
 866       * @see wpdb::prepare()
 867       *
 868       * @param string $table table name
 869       * @param array $data Data to insert (in column => value pairs).  Both $data columns and $data values should be "raw" (neither should be SQL escaped).
 870       * @param array|string $format (optional) An array of formats to be mapped to each of the value in $data.  If string, that format will be used for all of the values in $data.  A format is one of '%d', '%s' (decimal number, string).  If omitted, all values in $data will be treated as strings.
 871       * @return int|false The number of rows inserted, or false on error.
 872       */
 873  	function insert($table, $data, $format = null) {
 874          $formats = $format = (array) $format;
 875          $fields = array_keys($data);
 876          $formatted_fields = array();
 877          foreach ( $fields as $field ) {
 878              if ( !empty($format) )
 879                  $form = ( $form = array_shift($formats) ) ? $form : $format[0];
 880              elseif ( isset($this->field_types[$field]) )
 881                  $form = $this->field_types[$field];
 882              else
 883                  $form = '%s';
 884              $formatted_fields[] = $form;
 885          }
 886          $sql = "INSERT INTO `$table` (`" . implode( '`,`', $fields ) . "`) VALUES ('" . implode( "','", $formatted_fields ) . "')";
 887          return $this->query( $this->prepare( $sql, $data) );
 888      }
 889  
 890  
 891      /**
 892       * Update a row in the table
 893       *
 894       * <code>
 895       * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) )
 896       * </code>
 897       *
 898       * @since 2.5.0
 899       * @see wpdb::prepare()
 900       *
 901       * @param string $table table name
 902       * @param array $data Data to update (in column => value pairs).  Both $data columns and $data values should be "raw" (neither should be SQL escaped).
 903       * @param array $where A named array of WHERE clauses (in column => value pairs).  Multiple clauses will be joined with ANDs.  Both $where columns and $where values should be "raw".
 904       * @param array|string $format (optional) An array of formats to be mapped to each of the values in $data.  If string, that format will be used for all of the values in $data.  A format is one of '%d', '%s' (decimal number, string).  If omitted, all values in $data will be treated as strings.
 905       * @param array|string $format_where (optional) An array of formats to be mapped to each of the values in $where.  If string, that format will be used for all of  the items in $where.  A format is one of '%d', '%s' (decimal number, string).  If omitted, all values in $where will be treated as strings.
 906       * @return int|false The number of rows updated, or false on error.
 907       */
 908  	function update($table, $data, $where, $format = null, $where_format = null) {
 909          if ( !is_array( $where ) )
 910              return false;
 911  
 912          $formats = $format = (array) $format;
 913          $bits = $wheres = array();
 914          foreach ( (array) array_keys($data) as $field ) {
 915              if ( !empty($format) )
 916                  $form = ( $form = array_shift($formats) ) ? $form : $format[0];
 917              elseif ( isset($this->field_types[$field]) )
 918                  $form = $this->field_types[$field];
 919              else
 920                  $form = '%s';
 921              $bits[] = "`$field` = {$form}";
 922          }
 923  
 924          $where_formats = $where_format = (array) $where_format;
 925          foreach ( (array) array_keys($where) as $field ) {
 926              if ( !empty($where_format) )
 927                  $form = ( $form = array_shift($where_formats) ) ? $form : $where_format[0];
 928              elseif ( isset($this->field_types[$field]) )
 929                  $form = $this->field_types[$field];
 930              else
 931                  $form = '%s';
 932              $wheres[] = "`$field` = {$form}";
 933          }
 934  
 935          $sql = "UPDATE `$table` SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres );
 936          return $this->query( $this->prepare( $sql, array_merge(array_values($data), array_values($where))) );
 937      }
 938  
 939      /**
 940       * Retrieve one variable from the database.
 941       *
 942       * Executes a SQL query and returns the value from the SQL result.
 943       * If the SQL result contains more than one column and/or more than one row, this function returns the value in the column and row specified.
 944       * If $query is null, this function returns the value in the specified column and row from the previous SQL result.
 945       *
 946       * @since 0.71
 947       *
 948       * @param string|null $query SQL query.  If null, use the result from the previous query.
 949       * @param int $x (optional) Column of value to return.  Indexed from 0.
 950       * @param int $y (optional) Row of value to return.  Indexed from 0.
 951       * @return string Database query result
 952       */
 953  	function get_var($query=null, $x = 0, $y = 0) {
 954          $this->func_call = "\$db->get_var(\"$query\",$x,$y)";
 955          if ( $query )
 956              $this->query($query);
 957  
 958          // Extract var out of cached results based x,y vals
 959          if ( !empty( $this->last_result[$y] ) ) {
 960              $values = array_values(get_object_vars($this->last_result[$y]));
 961          }
 962  
 963          // If there is a value return it else return null
 964          return (isset($values[$x]) && $values[$x]!=='') ? $values[$x] : null;
 965      }
 966  
 967      /**
 968       * Retrieve one row from the database.
 969       *
 970       * Executes a SQL query and returns the row from the SQL result.
 971       *
 972       * @since 0.71
 973       *
 974       * @param string|null $query SQL query.
 975       * @param string $output (optional) one of ARRAY_A | ARRAY_N | OBJECT constants.  Return an associative array (column => value, ...), a numerically indexed array (0 => value, ...) or an object ( ->column = value ), respectively.
 976       * @param int $y (optional) Row to return.  Indexed from 0.
 977       * @return mixed Database query result in format specifed by $output
 978       */
 979  	function get_row($query = null, $output = OBJECT, $y = 0) {
 980          $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
 981          if ( $query )
 982              $this->query($query);
 983          else
 984              return null;
 985  
 986          if ( !isset($this->last_result[$y]) )
 987              return null;
 988  
 989          if ( $output == OBJECT ) {
 990              return $this->last_result[$y] ? $this->last_result[$y] : null;
 991          } elseif ( $output == ARRAY_A ) {
 992              return $this->last_result[$y] ? get_object_vars($this->last_result[$y]) : null;
 993          } elseif ( $output == ARRAY_N ) {
 994              return $this->last_result[$y] ? array_values(get_object_vars($this->last_result[$y])) : null;
 995          } else {
 996              $this->print_error(/*WP_I18N_DB_GETROW_ERROR*/" \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N"/*/WP_I18N_DB_GETROW_ERROR*/);
 997          }
 998      }
 999  
1000      /**
1001       * Retrieve one column from the database.
1002       *
1003       * Executes a SQL query and returns the column from the SQL result.
1004       * If the SQL result contains more than one column, this function returns the column specified.
1005       * If $query is null, this function returns the specified column from the previous SQL result.
1006       *
1007       * @since 0.71
1008       *
1009       * @param string|null $query SQL query.  If null, use the result from the previous query.
1010       * @param int $x Column to return.  Indexed from 0.
1011       * @return array Database query result.  Array indexed from 0 by SQL result row number.
1012       */
1013  	function get_col($query = null , $x = 0) {
1014          if ( $query )
1015              $this->query($query);
1016  
1017          $new_array = array();
1018          // Extract the column values
1019          for ( $i=0; $i < count($this->last_result); $i++ ) {
1020              $new_array[$i] = $this->get_var(null, $x, $i);
1021          }
1022          return $new_array;
1023      }
1024  
1025      /**
1026       * Retrieve an entire SQL result set from the database (i.e., many rows)
1027       *
1028       * Executes a SQL query and returns the entire SQL result.
1029       *
1030       * @since 0.71
1031       *
1032       * @param string $query SQL query.
1033       * @param string $output (optional) ane of ARRAY_A | ARRAY_N | OBJECT | OBJECT_K constants.  With one of the first three, return an array of rows indexed from 0 by SQL result row number.  Each row is an associative array (column => value, ...), a numerically indexed array (0 => value, ...), or an object. ( ->column = value ), respectively.  With OBJECT_K, return an associative array of row objects keyed by the value of each row's first column's value.  Duplicate keys are discarded.
1034       * @return mixed Database query results
1035       */
1036  	function get_results($query = null, $output = OBJECT) {
1037          $this->func_call = "\$db->get_results(\"$query\", $output)";
1038  
1039          if ( $query )
1040              $this->query($query);
1041          else
1042              return null;
1043  
1044          if ( $output == OBJECT ) {
1045              // Return an integer-keyed array of row objects
1046              return $this->last_result;
1047          } elseif ( $output == OBJECT_K ) {
1048              // Return an array of row objects with keys from column 1
1049              // (Duplicates are discarded)
1050              foreach ( $this->last_result as $row ) {
1051                  $key = array_shift( get_object_vars( $row ) );
1052                  if ( !isset( $new_array[ $key ] ) )
1053                      $new_array[ $key ] = $row;
1054              }
1055              return $new_array;
1056          } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
1057              // Return an integer-keyed array of...
1058              if ( $this->last_result ) {
1059                  $i = 0;
1060                  foreach( (array) $this->last_result as $row ) {
1061                      if ( $output == ARRAY_N ) {
1062                          // ...integer-keyed row arrays
1063                          $new_array[$i] = array_values( get_object_vars( $row ) );
1064                      } else {
1065                          // ...column name-keyed row arrays
1066                          $new_array[$i] = get_object_vars( $row );
1067                      }
1068                      ++$i;
1069                  }
1070                  return $new_array;
1071              }
1072          }
1073      }
1074  
1075      /**
1076       * Retrieve column metadata from the last query.
1077       *
1078       * @since 0.71
1079       *
1080       * @param string $info_type one of name, table, def, max_length, not_null, primary_key, multiple_key, unique_key, numeric, blob, type, unsigned, zerofill
1081       * @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
1082       * @return mixed Column Results
1083       */
1084  	function get_col_info($info_type = 'name', $col_offset = -1) {
1085          if ( $this->col_info ) {
1086              if ( $col_offset == -1 ) {
1087                  $i = 0;
1088                  foreach( (array) $this->col_info as $col ) {
1089                      $new_array[$i] = $col->{$info_type};
1090                      $i++;
1091                  }
1092                  return $new_array;
1093              } else {
1094                  return $this->col_info[$col_offset]->{$info_type};
1095              }
1096          }
1097      }
1098  
1099      /**
1100       * Starts the timer, for debugging purposes.
1101       *
1102       * @since 1.5.0
1103       *
1104       * @return true
1105       */
1106  	function timer_start() {
1107          $mtime = microtime();
1108          $mtime = explode(' ', $mtime);
1109          $this->time_start = $mtime[1] + $mtime[0];
1110          return true;
1111      }
1112  
1113      /**
1114       * Stops the debugging timer.
1115       *
1116       * @since 1.5.0
1117       *
1118       * @return int Total time spent on the query, in milliseconds
1119       */
1120  	function timer_stop() {
1121          $mtime = microtime();
1122          $mtime = explode(' ', $mtime);
1123          $time_end = $mtime[1] + $mtime[0];
1124          $time_total = $time_end - $this->time_start;
1125          return $time_total;
1126      }
1127  
1128      /**
1129       * Wraps errors in a nice header and footer and dies.
1130       *
1131       * Will not die if wpdb::$show_errors is true
1132       *
1133       * @since 1.5.0
1134       *
1135       * @param string $message The Error message
1136       * @param string $error_code (optional) A Computer readable string to identify the error.
1137       * @return false|void
1138       */
1139  	function bail($message, $error_code = '500') {
1140          if ( !$this->show_errors ) {
1141              if ( class_exists('WP_Error') )
1142                  $this->error = new WP_Error($error_code, $message);
1143              else
1144                  $this->error = $message;
1145              return false;
1146          }
1147          if ( function_exists( 'wp_die' ) ) {
1148              wp_die($message);
1149          } else {
1150              die( $message );
1151          }
1152      }
1153  
1154      /**
1155       * Whether or not MySQL database is at least the required minimum version.
1156       *
1157       * @since 2.5.0
1158       * @uses $wp_version
1159       *
1160       * @return WP_Error
1161       */
1162  	function check_database_version()
1163      {
1164          global $wp_version;
1165          // Make sure the server has MySQL 4.1.2
1166          if ( version_compare($this->db_version(), '4.1.2', '<') )
1167              return new WP_Error('database_version',sprintf(__('<strong>ERROR</strong>: WordPress %s requires MySQL 4.1.2 or higher'), $wp_version));
1168      }
1169  
1170      /**
1171       * Whether of not the database supports collation.
1172       *
1173       * Called when WordPress is generating the table scheme.
1174       *
1175       * @since 2.5.0
1176       *
1177       * @return bool True if collation is supported, false if version does not
1178       */
1179  	function supports_collation() {
1180          return $this->has_cap( 'collation' );
1181      }
1182  
1183      /**
1184       * Generic function to determine if a database supports a particular feature
1185       * @param string $db_cap the feature
1186       * @param false|string|resource $dbh_or_table (not implemented) Which database to test.  False = the currently selected database, string = the database containing the specified table, resource = the database corresponding to the specified mysql resource.
1187       * @return bool
1188       */
1189  	function has_cap( $db_cap ) {
1190          $version = $this->db_version();
1191  
1192          switch ( strtolower( $db_cap ) ) :
1193          case 'collation' :    // @since 2.5.0
1194          case 'group_concat' : // @since 2.7
1195          case 'subqueries' :   // @since 2.7
1196              return version_compare($version, '4.1', '>=');
1197              break;
1198          endswitch;
1199  
1200          return false;
1201      }
1202  
1203      /**
1204       * Retrieve the name of the function that called wpdb.
1205       *
1206       * Requires PHP 4.3 and searches up the list of functions until it reaches
1207       * the one that would most logically had called this method.
1208       *
1209       * @since 2.5.0
1210       *
1211       * @return string The name of the calling function
1212       */
1213  	function get_caller() {
1214          // requires PHP 4.3+
1215          if ( !is_callable('debug_backtrace') )
1216              return '';
1217  
1218          $bt = debug_backtrace();
1219          $caller = array();
1220  
1221          $bt = array_reverse( $bt );
1222          foreach ( (array) $bt as $call ) {
1223              if ( @$call['class'] == __CLASS__ )
1224                  continue;
1225              $function = $call['function'];
1226              if ( isset( $call['class'] ) )
1227                  $function = $call['class'] . "->$function";
1228              $caller[] = $function;
1229          }
1230          $caller = join( ', ', $caller );
1231  
1232          return $caller;
1233      }
1234  
1235      /**
1236       * The database version number
1237       * @param false|string|resource $dbh_or_table (not implemented) Which database to test.  False = the currently selected database, string = the database containing the specified table, resource = the database corresponding to the specified mysql resource.
1238       * @return false|string false on failure, version number on success
1239       */
1240  	function db_version() {
1241          return preg_replace('/[^0-9.].*/', '', mysql_get_server_info( $this->dbh ));
1242      }
1243  }
1244  
1245  if ( ! isset($wpdb) ) {
1246      /**
1247       * WordPress Database Object, if it isn't set already in wp-content/db.php
1248       * @global object $wpdb Creates a new wpdb object based on wp-config.php Constants for the database
1249       * @since 0.71
1250       */
1251      $wpdb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
1252  }
1253  ?>


Generated: Mon May 3 12:25:32 2010 Cross-referenced by PHPXref 0.7