PageRenderTime 63ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/blog/wp-includes/wp-db.php

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