PageRenderTime 63ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/wp-db.php

https://bitbucket.org/mpmont/marcomonteiro.net
PHP | 1594 lines | 600 code | 155 blank | 839 comment | 134 complexity | 1057e00d4228a4dadc157e5e8cc70e98 MD5 | raw file
Possible License(s): AGPL-1.0, LGPL-3.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 2.5.0
  21. */
  22. define( 'OBJECT_K', 'OBJECT_K' );
  23. /**
  24. * @since 0.71
  25. */
  26. define( 'ARRAY_A', 'ARRAY_A' );
  27. /**
  28. * @since 0.71
  29. */
  30. define( 'ARRAY_N', 'ARRAY_N' );
  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 2.5
  61. * @var bool
  62. */
  63. var $suppress_errors = false;
  64. /**
  65. * The last error during query.
  66. *
  67. * @see get_last_error()
  68. * @since 2.5
  69. * @access private
  70. * @var string
  71. */
  72. var $last_error = '';
  73. /**
  74. * Amount of queries made
  75. *
  76. * @since 1.2.0
  77. * @access private
  78. * @var int
  79. */
  80. var $num_queries = 0;
  81. /**
  82. * Count of rows returned by previous query
  83. *
  84. * @since 1.2
  85. * @access private
  86. * @var int
  87. */
  88. var $num_rows = 0;
  89. /**
  90. * Count of affected rows by previous query
  91. *
  92. * @since 0.71
  93. * @access private
  94. * @var int
  95. */
  96. var $rows_affected = 0;
  97. /**
  98. * The ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
  99. *
  100. * @since 0.71
  101. * @access public
  102. * @var int
  103. */
  104. var $insert_id = 0;
  105. /**
  106. * Saved result of the last query made
  107. *
  108. * @since 1.2.0
  109. * @access private
  110. * @var array
  111. */
  112. var $last_query;
  113. /**
  114. * Results of the last query made
  115. *
  116. * @since 1.0.0
  117. * @access private
  118. * @var array|null
  119. */
  120. var $last_result;
  121. /**
  122. * Saved info on the table column
  123. *
  124. * @since 1.2.0
  125. * @access private
  126. * @var array
  127. */
  128. var $col_info;
  129. /**
  130. * Saved queries that were executed
  131. *
  132. * @since 1.5.0
  133. * @access private
  134. * @var array
  135. */
  136. var $queries;
  137. /**
  138. * WordPress table prefix
  139. *
  140. * You can set this to have multiple WordPress installations
  141. * in a single database. The second reason is for possible
  142. * security precautions.
  143. *
  144. * @since 0.71
  145. * @access private
  146. * @var string
  147. */
  148. var $prefix = '';
  149. /**
  150. * Whether the database queries are ready to start executing.
  151. *
  152. * @since 2.5.0
  153. * @access private
  154. * @var bool
  155. */
  156. var $ready = false;
  157. /**
  158. * {@internal Missing Description}}
  159. *
  160. * @since 3.0.0
  161. * @access public
  162. * @var int
  163. */
  164. var $blogid = 0;
  165. /**
  166. * {@internal Missing Description}}
  167. *
  168. * @since 3.0.0
  169. * @access public
  170. * @var int
  171. */
  172. var $siteid = 0;
  173. /**
  174. * List of WordPress per-blog tables
  175. *
  176. * @since 2.5.0
  177. * @access private
  178. * @see wpdb::tables()
  179. * @var array
  180. */
  181. var $tables = array( 'posts', 'comments', 'links', 'options', 'postmeta',
  182. 'terms', 'term_taxonomy', 'term_relationships', 'commentmeta' );
  183. /**
  184. * List of deprecated WordPress tables
  185. *
  186. * categories, post2cat, and link2cat were deprecated in 2.3.0, db version 5539
  187. *
  188. * @since 2.9.0
  189. * @access private
  190. * @see wpdb::tables()
  191. * @var array
  192. */
  193. var $old_tables = array( 'categories', 'post2cat', 'link2cat' );
  194. /**
  195. * List of WordPress global tables
  196. *
  197. * @since 3.0.0
  198. * @access private
  199. * @see wpdb::tables()
  200. * @var array
  201. */
  202. var $global_tables = array( 'users', 'usermeta' );
  203. /**
  204. * List of Multisite global tables
  205. *
  206. * @since 3.0.0
  207. * @access private
  208. * @see wpdb::tables()
  209. * @var array
  210. */
  211. var $ms_global_tables = array( 'blogs', 'signups', 'site', 'sitemeta',
  212. 'sitecategories', 'registration_log', 'blog_versions' );
  213. /**
  214. * WordPress Comments table
  215. *
  216. * @since 1.5.0
  217. * @access public
  218. * @var string
  219. */
  220. var $comments;
  221. /**
  222. * WordPress Comment Metadata table
  223. *
  224. * @since 2.9.0
  225. * @access public
  226. * @var string
  227. */
  228. var $commentmeta;
  229. /**
  230. * WordPress Links table
  231. *
  232. * @since 1.5.0
  233. * @access public
  234. * @var string
  235. */
  236. var $links;
  237. /**
  238. * WordPress Options table
  239. *
  240. * @since 1.5.0
  241. * @access public
  242. * @var string
  243. */
  244. var $options;
  245. /**
  246. * WordPress Post Metadata table
  247. *
  248. * @since 1.5.0
  249. * @access public
  250. * @var string
  251. */
  252. var $postmeta;
  253. /**
  254. * WordPress Posts table
  255. *
  256. * @since 1.5.0
  257. * @access public
  258. * @var string
  259. */
  260. var $posts;
  261. /**
  262. * WordPress Terms table
  263. *
  264. * @since 2.3.0
  265. * @access public
  266. * @var string
  267. */
  268. var $terms;
  269. /**
  270. * WordPress Term Relationships table
  271. *
  272. * @since 2.3.0
  273. * @access public
  274. * @var string
  275. */
  276. var $term_relationships;
  277. /**
  278. * WordPress Term Taxonomy table
  279. *
  280. * @since 2.3.0
  281. * @access public
  282. * @var string
  283. */
  284. var $term_taxonomy;
  285. /*
  286. * Global and Multisite tables
  287. */
  288. /**
  289. * WordPress User Metadata table
  290. *
  291. * @since 2.3.0
  292. * @access public
  293. * @var string
  294. */
  295. var $usermeta;
  296. /**
  297. * WordPress Users table
  298. *
  299. * @since 1.5.0
  300. * @access public
  301. * @var string
  302. */
  303. var $users;
  304. /**
  305. * Multisite Blogs table
  306. *
  307. * @since 3.0.0
  308. * @access public
  309. * @var string
  310. */
  311. var $blogs;
  312. /**
  313. * Multisite Blog Versions table
  314. *
  315. * @since 3.0.0
  316. * @access public
  317. * @var string
  318. */
  319. var $blog_versions;
  320. /**
  321. * Multisite Registration Log table
  322. *
  323. * @since 3.0.0
  324. * @access public
  325. * @var string
  326. */
  327. var $registration_log;
  328. /**
  329. * Multisite Signups table
  330. *
  331. * @since 3.0.0
  332. * @access public
  333. * @var string
  334. */
  335. var $signups;
  336. /**
  337. * Multisite Sites table
  338. *
  339. * @since 3.0.0
  340. * @access public
  341. * @var string
  342. */
  343. var $site;
  344. /**
  345. * Multisite Sitewide Terms table
  346. *
  347. * @since 3.0.0
  348. * @access public
  349. * @var string
  350. */
  351. var $sitecategories;
  352. /**
  353. * Multisite Site Metadata table
  354. *
  355. * @since 3.0.0
  356. * @access public
  357. * @var string
  358. */
  359. var $sitemeta;
  360. /**
  361. * Format specifiers for DB columns. Columns not listed here default to %s. Initialized during WP load.
  362. *
  363. * Keys are column names, values are format types: 'ID' => '%d'
  364. *
  365. * @since 2.8.0
  366. * @see wpdb:prepare()
  367. * @see wpdb:insert()
  368. * @see wpdb:update()
  369. * @see wp_set_wpdb_vars()
  370. * @access public
  371. * @var array
  372. */
  373. var $field_types = array();
  374. /**
  375. * Database table columns charset
  376. *
  377. * @since 2.2.0
  378. * @access public
  379. * @var string
  380. */
  381. var $charset;
  382. /**
  383. * Database table columns collate
  384. *
  385. * @since 2.2.0
  386. * @access public
  387. * @var string
  388. */
  389. var $collate;
  390. /**
  391. * Whether to use mysql_real_escape_string
  392. *
  393. * @since 2.8.0
  394. * @access public
  395. * @var bool
  396. */
  397. var $real_escape = false;
  398. /**
  399. * Database Username
  400. *
  401. * @since 2.9.0
  402. * @access private
  403. * @var string
  404. */
  405. var $dbuser;
  406. /**
  407. * A textual description of the last query/get_row/get_var call
  408. *
  409. * @since unknown
  410. * @access public
  411. * @var string
  412. */
  413. var $func_call;
  414. /**
  415. * Connects to the database server and selects a database
  416. *
  417. * PHP4 compatibility layer for calling the PHP5 constructor.
  418. *
  419. * @uses wpdb::__construct() Passes parameters and returns result
  420. * @since 0.71
  421. *
  422. * @param string $dbuser MySQL database user
  423. * @param string $dbpassword MySQL database password
  424. * @param string $dbname MySQL database name
  425. * @param string $dbhost MySQL database host
  426. */
  427. function wpdb( $dbuser, $dbpassword, $dbname, $dbhost ) {
  428. if( defined( 'WP_USE_MULTIPLE_DB' ) && WP_USE_MULTIPLE_DB )
  429. $this->db_connect();
  430. return $this->__construct( $dbuser, $dbpassword, $dbname, $dbhost );
  431. }
  432. /**
  433. * Connects to the database server and selects a database
  434. *
  435. * PHP5 style constructor for compatibility with PHP5. Does
  436. * the actual setting up of the class properties and connection
  437. * to the database.
  438. *
  439. * @link http://core.trac.wordpress.org/ticket/3354
  440. * @since 2.0.8
  441. *
  442. * @param string $dbuser MySQL database user
  443. * @param string $dbpassword MySQL database password
  444. * @param string $dbname MySQL database name
  445. * @param string $dbhost MySQL database host
  446. */
  447. function __construct( $dbuser, $dbpassword, $dbname, $dbhost ) {
  448. register_shutdown_function( array( &$this, '__destruct' ) );
  449. if ( WP_DEBUG )
  450. $this->show_errors();
  451. if ( is_multisite() ) {
  452. $this->charset = 'utf8';
  453. if ( defined( 'DB_COLLATE' ) && DB_COLLATE )
  454. $this->collate = DB_COLLATE;
  455. else
  456. $this->collate = 'utf8_general_ci';
  457. } elseif ( defined( 'DB_COLLATE' ) ) {
  458. $this->collate = DB_COLLATE;
  459. }
  460. if ( defined( 'DB_CHARSET' ) )
  461. $this->charset = DB_CHARSET;
  462. $this->dbuser = $dbuser;
  463. $this->dbh = @mysql_connect( $dbhost, $dbuser, $dbpassword, true );
  464. if ( !$this->dbh ) {
  465. $this->bail( sprintf( /*WP_I18N_DB_CONN_ERROR*/'
  466. <h1>Error de conexão à base de dados</h1>
  467. <p>Isto pode querer dizer que tanto o nome de utilizador como a password especificadas no ficheiro <code>wp-config.php</code> não estão correctas ou então que não é possível conectar ao servidor <code>%s</code>, que pode estar em baixo.</p>
  468. <ul>
  469. <li>Tem a certeza que o nome de utilizador e password estão correctos?</li>
  470. <li>Tem a certeza que o nome do servidor está correcto?</li>
  471. <li>Tem a certeza que o servidor está a funcionar?</li>
  472. </ul>
  473. <p>Se não tem a certeza do significado destes termos, deve entrar em contacto com o seu serviço de alojamento. Se mesmo assim precisar de ajuda, visite os <a href=\'http://wordpress.org/support/\'>Fóruns de Suporte do WordPress</a>.</p>
  474. '/*/WP_I18N_DB_CONN_ERROR*/, $dbhost ), 'db_connect_fail' );
  475. return;
  476. }
  477. $this->ready = true;
  478. if ( $this->has_cap( 'collation' ) && !empty( $this->charset ) ) {
  479. if ( function_exists( 'mysql_set_charset' ) ) {
  480. mysql_set_charset( $this->charset, $this->dbh );
  481. $this->real_escape = true;
  482. } else {
  483. $query = $this->prepare( 'SET NAMES %s', $this->charset );
  484. if ( ! empty( $this->collate ) )
  485. $query .= $this->prepare( ' COLLATE %s', $this->collate );
  486. $this->query( $query );
  487. }
  488. }
  489. $this->select( $dbname, $this->dbh );
  490. }
  491. /**
  492. * PHP5 style destructor and will run when database object is destroyed.
  493. *
  494. * @see wpdb::__construct()
  495. * @since 2.0.8
  496. * @return bool true
  497. */
  498. function __destruct() {
  499. return true;
  500. }
  501. /**
  502. * Sets the table prefix for the WordPress tables.
  503. *
  504. * @since 2.5.0
  505. *
  506. * @param string $prefix Alphanumeric name for the new prefix.
  507. * @return string|WP_Error Old prefix or WP_Error on error
  508. */
  509. function set_prefix( $prefix, $set_table_names = true ) {
  510. if ( preg_match( '|[^a-z0-9_]|i', $prefix ) )
  511. return new WP_Error('invalid_db_prefix', /*WP_I18N_DB_BAD_PREFIX*/'Prefixo de base de dados inválido'/*/WP_I18N_DB_BAD_PREFIX*/);
  512. $old_prefix = is_multisite() ? '' : $prefix;
  513. if ( isset( $this->base_prefix ) )
  514. $old_prefix = $this->base_prefix;
  515. $this->base_prefix = $prefix;
  516. if ( $set_table_names ) {
  517. foreach ( $this->tables( 'global' ) as $table => $prefixed_table )
  518. $this->$table = $prefixed_table;
  519. if ( is_multisite() && empty( $this->blogid ) )
  520. return $old_prefix;
  521. $this->prefix = $this->get_blog_prefix();
  522. foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
  523. $this->$table = $prefixed_table;
  524. foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
  525. $this->$table = $prefixed_table;
  526. }
  527. return $old_prefix;
  528. }
  529. /**
  530. * Sets blog id.
  531. *
  532. * @since 3.0.0
  533. * @access public
  534. * @param int $blog_id
  535. * @param int $site_id Optional.
  536. * @return string previous blog id
  537. */
  538. function set_blog_id( $blog_id, $site_id = 0 ) {
  539. if ( ! empty( $site_id ) )
  540. $this->siteid = $site_id;
  541. $old_blog_id = $this->blogid;
  542. $this->blogid = $blog_id;
  543. $this->prefix = $this->get_blog_prefix();
  544. foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
  545. $this->$table = $prefixed_table;
  546. foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
  547. $this->$table = $prefixed_table;
  548. return $old_blog_id;
  549. }
  550. /**
  551. * Gets blog prefix.
  552. *
  553. * @uses is_multisite()
  554. * @since 3.0.0
  555. * @param int $blog_id Optional.
  556. * @return string Blog prefix.
  557. */
  558. function get_blog_prefix( $blog_id = null ) {
  559. if ( is_multisite() ) {
  560. if ( null === $blog_id )
  561. $blog_id = $this->blogid;
  562. if ( defined( 'MULTISITE' ) && ( 0 == $blog_id || 1 == $blog_id ) )
  563. return $this->base_prefix;
  564. else
  565. return $this->base_prefix . $blog_id . '_';
  566. } else {
  567. return $this->base_prefix;
  568. }
  569. }
  570. /**
  571. * Returns an array of WordPress tables.
  572. *
  573. * Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to
  574. * override the WordPress users and usersmeta tables that would otherwise
  575. * be determined by the prefix.
  576. *
  577. * The scope argument can take one of the following:
  578. *
  579. * 'all' - returns 'all' and 'global' tables. No old tables are returned.
  580. * 'blog' - returns the blog-level tables for the queried blog.
  581. * 'global' - returns the global tables for the installation, returning multisite tables only if running multisite.
  582. * 'ms_global' - returns the multisite global tables, regardless if current installation is multisite.
  583. * 'old' - returns tables which are deprecated.
  584. *
  585. * @since 3.0.0
  586. * @uses wpdb::$tables
  587. * @uses wpdb::$old_tables
  588. * @uses wpdb::$global_tables
  589. * @uses wpdb::$ms_global_tables
  590. * @uses is_multisite()
  591. *
  592. * @param string $scope Optional. Can be all, global, ms_global, blog, or old tables. Defaults to all.
  593. * @param bool $prefix Optional. Whether to include table prefixes. Default true. If blog
  594. * prefix is requested, then the custom users and usermeta tables will be mapped.
  595. * @param int $blog_id Optional. The blog_id to prefix. Defaults to wpdb::$blogid. Used only when prefix is requested.
  596. * @return array Table names. When a prefix is requested, the key is the unprefixed table name.
  597. */
  598. function tables( $scope = 'all', $prefix = true, $blog_id = 0 ) {
  599. switch ( $scope ) {
  600. case 'all' :
  601. $tables = array_merge( $this->global_tables, $this->tables );
  602. if ( is_multisite() )
  603. $tables = array_merge( $tables, $this->ms_global_tables );
  604. break;
  605. case 'blog' :
  606. $tables = $this->tables;
  607. break;
  608. case 'global' :
  609. $tables = $this->global_tables;
  610. if ( is_multisite() )
  611. $tables = array_merge( $tables, $this->ms_global_tables );
  612. break;
  613. case 'ms_global' :
  614. $tables = $this->ms_global_tables;
  615. break;
  616. case 'old' :
  617. $tables = $this->old_tables;
  618. break;
  619. default :
  620. return array();
  621. break;
  622. }
  623. if ( $prefix ) {
  624. if ( ! $blog_id )
  625. $blog_id = $this->blogid;
  626. $blog_prefix = $this->get_blog_prefix( $blog_id );
  627. $base_prefix = $this->base_prefix;
  628. $global_tables = array_merge( $this->global_tables, $this->ms_global_tables );
  629. foreach ( $tables as $k => $table ) {
  630. if ( in_array( $table, $global_tables ) )
  631. $tables[ $table ] = $base_prefix . $table;
  632. else
  633. $tables[ $table ] = $blog_prefix . $table;
  634. unset( $tables[ $k ] );
  635. }
  636. if ( isset( $tables['users'] ) && defined( 'CUSTOM_USER_TABLE' ) )
  637. $tables['users'] = CUSTOM_USER_TABLE;
  638. if ( isset( $tables['usermeta'] ) && defined( 'CUSTOM_USER_META_TABLE' ) )
  639. $tables['usermeta'] = CUSTOM_USER_META_TABLE;
  640. }
  641. return $tables;
  642. }
  643. /**
  644. * Selects a database using the current database connection.
  645. *
  646. * The database name will be changed based on the current database
  647. * connection. On failure, the execution will bail and display an DB error.
  648. *
  649. * @since 0.71
  650. *
  651. * @param string $db MySQL database name
  652. * @param resource $dbh Optional link identifier.
  653. * @return null Always null.
  654. */
  655. function select( $db, $dbh = null) {
  656. if ( is_null($dbh) )
  657. $dbh = $this->dbh;
  658. if ( !@mysql_select_db( $db, $dbh ) ) {
  659. $this->ready = false;
  660. $this->bail( sprintf( /*WP_I18N_DB_SELECT_DB*/'
  661. <h1>Não foi possível seleccionar a base de dados</h1>
  662. <p>Foi possível conectar ao servidor de base de dados (o que quer dizer que o nome de utilizador e password estão correctos), mas não foi possível seleccionar a base de dados <code>%1$s</code>.</p>
  663. <ul>
  664. <li>Tem a certeza que existe?</li>
  665. <li>O utilizador <code>%2$s</code> tem permissões para usar a base de dados <code>%1$s</code>?</li>
  666. <li>Em alguns sistemas, o nome da base de dados tem o seu nome de utilizador como prefixo, por exemplo <code>username_%1$s</code>. Poderá ser esse o problema?</li>
  667. </ul>
  668. <p>Se não sabe configurar uma base de dados, deverá <strong>entrar em contacto com o seu serviço de alojamento</strong> . Se nada disto resultar poderá ainda encontrar ajuda no <a href="http://pt.forums.wordpress.org/">Fórum de Suporte do WordPress</a>.</p>'/*/WP_I18N_DB_SELECT_DB*/, $db, $this->dbuser ), 'db_select_fail' );
  669. return;
  670. }
  671. }
  672. /**
  673. * Weak escape, using addslashes()
  674. *
  675. * @see addslashes()
  676. * @since 2.8.0
  677. * @access private
  678. *
  679. * @param string $string
  680. * @return string
  681. */
  682. function _weak_escape( $string ) {
  683. return addslashes( $string );
  684. }
  685. /**
  686. * Real escape, using mysql_real_escape_string() or addslashes()
  687. *
  688. * @see mysql_real_escape_string()
  689. * @see addslashes()
  690. * @since 2.8
  691. * @access private
  692. *
  693. * @param string $string to escape
  694. * @return string escaped
  695. */
  696. function _real_escape( $string ) {
  697. if ( $this->dbh && $this->real_escape )
  698. return mysql_real_escape_string( $string, $this->dbh );
  699. else
  700. return addslashes( $string );
  701. }
  702. /**
  703. * Escape data. Works on arrays.
  704. *
  705. * @uses wpdb::_escape()
  706. * @uses wpdb::_real_escape()
  707. * @since 2.8
  708. * @access private
  709. *
  710. * @param string|array $data
  711. * @return string|array escaped
  712. */
  713. function _escape( $data ) {
  714. if ( is_array( $data ) ) {
  715. foreach ( (array) $data as $k => $v ) {
  716. if ( is_array($v) )
  717. $data[$k] = $this->_escape( $v );
  718. else
  719. $data[$k] = $this->_real_escape( $v );
  720. }
  721. } else {
  722. $data = $this->_real_escape( $data );
  723. }
  724. return $data;
  725. }
  726. /**
  727. * Escapes content for insertion into the database using addslashes(), for security.
  728. *
  729. * Works on arrays.
  730. *
  731. * @since 0.71
  732. * @param string|array $data to escape
  733. * @return string|array escaped as query safe string
  734. */
  735. function escape( $data ) {
  736. if ( is_array( $data ) ) {
  737. foreach ( (array) $data as $k => $v ) {
  738. if ( is_array( $v ) )
  739. $data[$k] = $this->escape( $v );
  740. else
  741. $data[$k] = $this->_weak_escape( $v );
  742. }
  743. } else {
  744. $data = $this->_weak_escape( $data );
  745. }
  746. return $data;
  747. }
  748. /**
  749. * Escapes content by reference for insertion into the database, for security
  750. *
  751. * @uses wpdb::_real_escape()
  752. * @since 2.3.0
  753. * @param string $string to escape
  754. * @return void
  755. */
  756. function escape_by_ref( &$string ) {
  757. $string = $this->_real_escape( $string );
  758. }
  759. /**
  760. * Prepares a SQL query for safe execution. Uses sprintf()-like syntax.
  761. *
  762. * The following directives can be used in the query format string:
  763. * %d (decimal number)
  764. * %s (string)
  765. * %% (literal percentage sign - no argument needed)
  766. *
  767. * Both %d and %s are to be left unquoted in the query string and they need an argument passed for them.
  768. * Literals (%) as parts of the query must be properly written as %%.
  769. *
  770. * This function only supports a small subset of the sprintf syntax; it only supports %d (decimal number), %s (string).
  771. * Does not support sign, padding, alignment, width or precision specifiers.
  772. * Does not support argument numbering/swapping.
  773. *
  774. * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}.
  775. *
  776. * Both %d and %s should be left unquoted in the query string.
  777. *
  778. * <code>
  779. * wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 )
  780. * wpdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
  781. * </code>
  782. *
  783. * @link http://php.net/sprintf Description of syntax.
  784. * @since 2.3.0
  785. *
  786. * @param string $query Query statement with sprintf()-like placeholders
  787. * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like
  788. * {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if
  789. * being called like {@link http://php.net/sprintf sprintf()}.
  790. * @param mixed $args,... further variables to substitute into the query's placeholders if being called like
  791. * {@link http://php.net/sprintf sprintf()}.
  792. * @return null|false|string Sanitized query string, null if there is no query, false if there is an error and string
  793. * if there was something to prepare
  794. */
  795. function prepare( $query = null ) { // ( $query, *$args )
  796. if ( is_null( $query ) )
  797. return;
  798. $args = func_get_args();
  799. array_shift( $args );
  800. // If args were passed as an array (as in vsprintf), move them up
  801. if ( isset( $args[0] ) && is_array($args[0]) )
  802. $args = $args[0];
  803. $query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it
  804. $query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
  805. $query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
  806. array_walk( $args, array( &$this, 'escape_by_ref' ) );
  807. return @vsprintf( $query, $args );
  808. }
  809. /**
  810. * Print SQL/DB error.
  811. *
  812. * @since 0.71
  813. * @global array $EZSQL_ERROR Stores error information of query and error string
  814. *
  815. * @param string $str The error to display
  816. * @return bool False if the showing of errors is disabled.
  817. */
  818. function print_error( $str = '' ) {
  819. global $EZSQL_ERROR;
  820. if ( !$str )
  821. $str = mysql_error( $this->dbh );
  822. $EZSQL_ERROR[] = array( 'query' => $this->last_query, 'error_str' => $str );
  823. if ( $this->suppress_errors )
  824. return false;
  825. if ( $caller = $this->get_caller() )
  826. $error_str = sprintf( /*WP_I18N_DB_QUERY_ERROR_FULL*/'Erro na base de dados do WordPress %1$s na query %2$s feita por %3$s'/*/WP_I18N_DB_QUERY_ERROR_FULL*/, $str, $this->last_query, $caller );
  827. else
  828. $error_str = sprintf( /*WP_I18N_DB_QUERY_ERROR*/'Erro na base de dados do WordPress %1$s na query %2$s'/*/WP_I18N_DB_QUERY_ERROR*/, $str, $this->last_query );
  829. if ( function_exists( 'error_log' )
  830. && ( $log_file = @ini_get( 'error_log' ) )
  831. && ( 'syslog' == $log_file || @is_writable( $log_file ) )
  832. )
  833. @error_log( $error_str );
  834. // Are we showing errors?
  835. if ( ! $this->show_errors )
  836. return false;
  837. // If there is an error then take note of it
  838. if ( is_multisite() ) {
  839. $msg = "WordPress database error: [$str]\n{$this->last_query}\n";
  840. if ( defined( 'ERRORLOGFILE' ) )
  841. error_log( $msg, 3, ERRORLOGFILE );
  842. if ( defined( 'DIEONDBERROR' ) )
  843. wp_die( $msg );
  844. } else {
  845. $str = htmlspecialchars( $str, ENT_QUOTES );
  846. $query = htmlspecialchars( $this->last_query, ENT_QUOTES );
  847. print "<div id='error'>
  848. <p class='wpdberror'><strong>WordPress database error:</strong> [$str]<br />
  849. <code>$query</code></p>
  850. </div>";
  851. }
  852. }
  853. /**
  854. * Enables showing of database errors.
  855. *
  856. * This function should be used only to enable showing of errors.
  857. * wpdb::hide_errors() should be used instead for hiding of errors. However,
  858. * this function can be used to enable and disable showing of database
  859. * errors.
  860. *
  861. * @since 0.71
  862. * @see wpdb::hide_errors()
  863. *
  864. * @param bool $show Whether to show or hide errors
  865. * @return bool Old value for showing errors.
  866. */
  867. function show_errors( $show = true ) {
  868. $errors = $this->show_errors;
  869. $this->show_errors = $show;
  870. return $errors;
  871. }
  872. /**
  873. * Disables showing of database errors.
  874. *
  875. * By default database errors are not shown.
  876. *
  877. * @since 0.71
  878. * @see wpdb::show_errors()
  879. *
  880. * @return bool Whether showing of errors was active
  881. */
  882. function hide_errors() {
  883. $show = $this->show_errors;
  884. $this->show_errors = false;
  885. return $show;
  886. }
  887. /**
  888. * Whether to suppress database errors.
  889. *
  890. * By default database errors are suppressed, with a simple
  891. * call to this function they can be enabled.
  892. *
  893. * @since 2.5
  894. * @see wpdb::hide_errors()
  895. * @param bool $suppress Optional. New value. Defaults to true.
  896. * @return bool Old value
  897. */
  898. function suppress_errors( $suppress = true ) {
  899. $errors = $this->suppress_errors;
  900. $this->suppress_errors = (bool) $suppress;
  901. return $errors;
  902. }
  903. /**
  904. * Kill cached query results.
  905. *
  906. * @since 0.71
  907. * @return void
  908. */
  909. function flush() {
  910. $this->last_result = array();
  911. $this->col_info = null;
  912. $this->last_query = null;
  913. }
  914. function db_connect( $query = "SELECT" ) {
  915. global $db_list, $global_db_list;
  916. if ( ! is_array( $db_list ) )
  917. return true;
  918. if ( $this->blogs != '' && preg_match("/(" . $this->blogs . "|" . $this->users . "|" . $this->usermeta . "|" . $this->site . "|" . $this->sitemeta . "|" . $this->sitecategories . ")/i",$query) ) {
  919. $action = 'global';
  920. $details = $global_db_list[ mt_rand( 0, count( $global_db_list ) -1 ) ];
  921. $this->db_global = $details;
  922. } elseif ( preg_match("/^\\s*(alter table|create|insert|delete|update|replace) /i",$query) ) {
  923. $action = 'write';
  924. $details = $db_list[ 'write' ][ mt_rand( 0, count( $db_list[ 'write' ] ) -1 ) ];
  925. $this->db_write = $details;
  926. } else {
  927. $action = '';
  928. $details = $db_list[ 'read' ][ mt_rand( 0, count( $db_list[ 'read' ] ) -1 ) ];
  929. $this->db_read = $details;
  930. }
  931. $dbhname = "dbh" . $action;
  932. $this->$dbhname = @mysql_connect( $details[ 'db_host' ], $details[ 'db_user' ], $details[ 'db_password' ] );
  933. if (!$this->$dbhname ) {
  934. $this->bail( sprintf( /*WP_I18N_DB_CONN_ERROR*/'
  935. <h1>Error de conexão à base de dados</h1>
  936. <p>Isto pode querer dizer que tanto o nome de utilizador como a password especificadas no ficheiro <code>wp-config.php</code> não estão correctas ou então que não é possível conectar ao servidor <code>%s</code>, que pode estar em baixo.</p>
  937. <ul>
  938. <li>Tem a certeza que o nome de utilizador e password estão correctos?</li>
  939. <li>Tem a certeza que o nome do servidor está correcto?</li>
  940. <li>Tem a certeza que o servidor está a funcionar?</li>
  941. </ul>
  942. <p>Se não tem a certeza do significado destes termos, deve entrar em contacto com o seu serviço de alojamento. Se mesmo assim precisar de ajuda, visite os <a href=\'http://wordpress.org/support/\'>Fóruns de Suporte do WordPress</a>.</p>
  943. '/*/WP_I18N_DB_CONN_ERROR*/, $details['db_host'] ), 'db_connect_fail' );
  944. }
  945. $this->select( $details[ 'db_name' ], $this->$dbhname );
  946. }
  947. /**
  948. * Perform a MySQL database query, using current database connection.
  949. *
  950. * More information can be found on the codex page.
  951. *
  952. * @since 0.71
  953. *
  954. * @param string $query Database query
  955. * @return int|false Number of rows affected/selected or false on error
  956. */
  957. function query( $query ) {
  958. if ( ! $this->ready )
  959. return false;
  960. // some queries are made before the plugins have been loaded, and thus cannot be filtered with this method
  961. if ( function_exists( 'apply_filters' ) )
  962. $query = apply_filters( 'query', $query );
  963. $return_val = 0;
  964. $this->flush();
  965. // Log how the function was called
  966. $this->func_call = "\$db->query(\"$query\")";
  967. // Keep track of the last query for debug..
  968. $this->last_query = $query;
  969. if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES )
  970. $this->timer_start();
  971. // use $this->dbh for read ops, and $this->dbhwrite for write ops
  972. // use $this->dbhglobal for gloal table ops
  973. unset( $dbh );
  974. if( defined( 'WP_USE_MULTIPLE_DB' ) && WP_USE_MULTIPLE_DB ) {
  975. if( $this->blogs != '' && preg_match("/(" . $this->blogs . "|" . $this->users . "|" . $this->usermeta . "|" . $this->site . "|" . $this->sitemeta . "|" . $this->sitecategories . ")/i",$query) ) {
  976. if( false == isset( $this->dbhglobal ) ) {
  977. $this->db_connect( $query );
  978. }
  979. $dbh =& $this->dbhglobal;
  980. $this->last_db_used = "global";
  981. } elseif ( preg_match("/^\\s*(alter table|create|insert|delete|update|replace) /i",$query) ) {
  982. if( false == isset( $this->dbhwrite ) ) {
  983. $this->db_connect( $query );
  984. }
  985. $dbh =& $this->dbhwrite;
  986. $this->last_db_used = "write";
  987. } else {
  988. $dbh =& $this->dbh;
  989. $this->last_db_used = "read";
  990. }
  991. } else {
  992. $dbh =& $this->dbh;
  993. $this->last_db_used = "other/read";
  994. }
  995. $this->result = @mysql_query( $query, $dbh );
  996. $this->num_queries++;
  997. if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES )
  998. $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
  999. // If there is an error then take note of it..
  1000. if ( $this->last_error = mysql_error( $dbh ) ) {
  1001. $this->print_error();
  1002. return false;
  1003. }
  1004. if ( preg_match( "/^\\s*(insert|delete|update|replace|alter) /i", $query ) ) {
  1005. $this->rows_affected = mysql_affected_rows( $dbh );
  1006. // Take note of the insert_id
  1007. if ( preg_match( "/^\\s*(insert|replace) /i", $query ) ) {
  1008. $this->insert_id = mysql_insert_id($dbh);
  1009. }
  1010. // Return number of rows affected
  1011. $return_val = $this->rows_affected;
  1012. } else {
  1013. $i = 0;
  1014. while ( $i < @mysql_num_fields( $this->result ) ) {
  1015. $this->col_info[$i] = @mysql_fetch_field( $this->result );
  1016. $i++;
  1017. }
  1018. $num_rows = 0;
  1019. while ( $row = @mysql_fetch_object( $this->result ) ) {
  1020. $this->last_result[$num_rows] = $row;
  1021. $num_rows++;
  1022. }
  1023. @mysql_free_result( $this->result );
  1024. // Log number of rows the query returned
  1025. // and return number of rows selected
  1026. $this->num_rows = $num_rows;
  1027. $return_val = $num_rows;
  1028. }
  1029. return $return_val;
  1030. }
  1031. /**
  1032. * Insert a row into a table.
  1033. *
  1034. * <code>
  1035. * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
  1036. * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
  1037. * </code>
  1038. *
  1039. * @since 2.5.0
  1040. * @see wpdb::prepare()
  1041. * @see wpdb::$field_types
  1042. * @see wp_set_wpdb_vars()
  1043. *
  1044. * @param string $table table name
  1045. * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  1046. * @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.
  1047. * A format is one of '%d', '%s' (decimal number, string). If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
  1048. * @return int|false The number of rows inserted, or false on error.
  1049. */
  1050. function insert( $table, $data, $format = null ) {
  1051. return $this->_insert_replace_helper( $table, $data, $format, 'INSERT' );
  1052. }
  1053. /**
  1054. * Replace a row into a table.
  1055. *
  1056. * <code>
  1057. * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
  1058. * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
  1059. * </code>
  1060. *
  1061. * @since 3.0.0
  1062. * @see wpdb::prepare()
  1063. * @see wpdb::$field_types
  1064. * @see wp_set_wpdb_vars()
  1065. *
  1066. * @param string $table table name
  1067. * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  1068. * @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.
  1069. * A format is one of '%d', '%s' (decimal number, string). If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
  1070. * @return int|false The number of rows affected, or false on error.
  1071. */
  1072. function replace( $table, $data, $format = null ) {
  1073. return $this->_insert_replace_helper( $table, $data, $format, 'REPLACE' );
  1074. }
  1075. /**
  1076. * Helper function for insert and replace.
  1077. *
  1078. * Runs an insert or replace query based on $type argument.
  1079. *
  1080. * @access private
  1081. * @since 3.0.0
  1082. * @see wpdb::prepare()
  1083. * @see wpdb::$field_types
  1084. * @see wp_set_wpdb_vars()
  1085. *
  1086. * @param string $table table name
  1087. * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  1088. * @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.
  1089. * A format is one of '%d', '%s' (decimal number, string). If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
  1090. * @return int|false The number of rows affected, or false on error.
  1091. */
  1092. function _insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' ) {
  1093. if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ) ) )
  1094. return false;
  1095. $formats = $format = (array) $format;
  1096. $fields = array_keys( $data );
  1097. $formatted_fields = array();
  1098. foreach ( $fields as $field ) {
  1099. if ( !empty( $format ) )
  1100. $form = ( $form = array_shift( $formats ) ) ? $form : $format[0];
  1101. elseif ( isset( $this->field_types[$field] ) )
  1102. $form = $this->field_types[$field];
  1103. else
  1104. $form = '%s';
  1105. $formatted_fields[] = $form;
  1106. }
  1107. $sql = "{$type} INTO `$table` (`" . implode( '`,`', $fields ) . "`) VALUES ('" . implode( "','", $formatted_fields ) . "')";
  1108. return $this->query( $this->prepare( $sql, $data ) );
  1109. }
  1110. /**
  1111. * Update a row in the table
  1112. *
  1113. * <code>
  1114. * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 'bar' ), array( 'ID' => 1 ) )
  1115. * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) )
  1116. * </code>
  1117. *
  1118. * @since 2.5.0
  1119. * @see wpdb::prepare()
  1120. * @see wpdb::$field_types
  1121. * @see wp_set_wpdb_vars()
  1122. *
  1123. * @param string $table table name
  1124. * @param array $data Data to update (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  1125. * @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".
  1126. * @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.
  1127. * A format is one of '%d', '%s' (decimal number, string). If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
  1128. * @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.
  1129. * @return int|false The number of rows updated, or false on error.
  1130. */
  1131. function update( $table, $data, $where, $format = null, $where_format = null ) {
  1132. if ( ! is_array( $data ) || ! is_array( $where ) )
  1133. return false;
  1134. $formats = $format = (array) $format;
  1135. $bits = $wheres = array();
  1136. foreach ( (array) array_keys( $data ) as $field ) {
  1137. if ( !empty( $format ) )
  1138. $form = ( $form = array_shift( $formats ) ) ? $form : $format[0];
  1139. elseif ( isset($this->field_types[$field]) )
  1140. $form = $this->field_types[$field];
  1141. else
  1142. $form = '%s';
  1143. $bits[] = "`$field` = {$form}";
  1144. }
  1145. $where_formats = $where_format = (array) $where_format;
  1146. foreach ( (array) array_keys( $where ) as $field ) {
  1147. if ( !empty( $where_format ) )
  1148. $form = ( $form = array_shift( $where_formats ) ) ? $form : $where_format[0];
  1149. elseif ( isset( $this->field_types[$field] ) )
  1150. $form = $this->field_types[$field];
  1151. else
  1152. $form = '%s';
  1153. $wheres[] = "`$field` = {$form}";
  1154. }
  1155. $sql = "UPDATE `$table` SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres );
  1156. return $this->query( $this->prepare( $sql, array_merge( array_values( $data ), array_values( $where ) ) ) );
  1157. }
  1158. /**
  1159. * Retrieve one variable from the database.
  1160. *
  1161. * Executes a SQL query and returns the value from the SQL result.
  1162. * 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.
  1163. * If $query is null, this function returns the value in the specified column and row from the previous SQL result.
  1164. *
  1165. * @since 0.71
  1166. *
  1167. * @param string|null $query Optional. SQL query. Defaults to null, use the result from the previous query.
  1168. * @param int $x Optional. Column of value to return. Indexed from 0.
  1169. * @param int $y Optional. Row of value to return. Indexed from 0.
  1170. * @return string|null Database query result (as string), or null on failure
  1171. */
  1172. function get_var( $query = null, $x = 0, $y = 0 ) {
  1173. $this->func_call = "\$db->get_var(\"$query\", $x, $y)";
  1174. if ( $query )
  1175. $this->query( $query );
  1176. // Extract var out of cached results based x,y vals
  1177. if ( !empty( $this->last_result[$y] ) ) {
  1178. $values = array_values( get_object_vars( $this->last_result[$y] ) );
  1179. }
  1180. // If there is a value return it else return null
  1181. return ( isset( $values[$x] ) && $values[$x] !== '' ) ? $values[$x] : null;
  1182. }
  1183. /**
  1184. * Retrieve one row from the database.
  1185. *
  1186. * Executes a SQL query and returns the row from the SQL result.
  1187. *
  1188. * @since 0.71
  1189. *
  1190. * @param string|null $query SQL query.
  1191. * @param string $output Optional. one of ARRAY_A | ARRAY_N | OBJECT constants. Return an associative array (column => value, ...),
  1192. * a numerically indexed array (0 => value, ...) or an object ( ->column = value ), respectively.
  1193. * @param int $y Optional. Row to return. Indexed from 0.
  1194. * @return mixed Database query result in format specifed by $output or null on failure
  1195. */
  1196. function get_row( $query = null, $output = OBJECT, $y = 0 ) {
  1197. $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
  1198. if ( $query )
  1199. $this->query( $query );
  1200. else
  1201. return null;
  1202. if ( !isset( $this->last_result[$y] ) )
  1203. return null;
  1204. if ( $output == OBJECT ) {
  1205. return $this->last_result[$y] ? $this->last_result[$y] : null;
  1206. } elseif ( $output == ARRAY_A ) {
  1207. return $this->last_result[$y] ? get_object_vars( $this->last_result[$y] ) : null;
  1208. } elseif ( $output == ARRAY_N ) {
  1209. return $this->last_result[$y] ? array_values( get_object_vars( $this->last_result[$y] ) ) : null;
  1210. } else {
  1211. $this->print_error(/*WP_I18N_DB_GETROW_ERROR*/' $db->get_row(string query, output type, int offset) -- O output tem que ser um de: OBJECT, ARRAY_A, ARRAY_N'/*/WP_I18N_DB_GETROW_ERROR*/);
  1212. }
  1213. }
  1214. /**
  1215. * Retrieve one column from the database.
  1216. *
  1217. * Executes a SQL query and returns the column from the SQL result.
  1218. * If the SQL result contains more than one column, this function returns the column specified.
  1219. * If $query is null, this function returns the specified column from the previous SQL result.
  1220. *
  1221. * @since 0.71
  1222. *
  1223. * @param string|null $query Optional. SQL query. Defaults to previous query.
  1224. * @param int $x Optional. Column to return. Indexed from 0.
  1225. * @return array Database query result. Array indexed from 0 by SQL result row number.
  1226. */
  1227. function get_col( $query = null , $x = 0 ) {
  1228. if ( $query )
  1229. $this->query( $query );
  1230. $new_array = array();
  1231. // Extract the column values
  1232. for ( $i = 0, $j = count( $this->last_result ); $i < $j; $i++ ) {
  1233. $new_array[$i] = $this->get_var( null, $x, $i );
  1234. }
  1235. return $new_array;
  1236. }
  1237. /**
  1238. * Retrieve an entire SQL result set from the database (i.e., many rows)
  1239. *
  1240. * Executes a SQL query and returns the entire SQL result.
  1241. *
  1242. * @since 0.71
  1243. *
  1244. * @param string $query SQL query.
  1245. * @param string $output Optional. Any 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.
  1246. * Each row is an associative array (column => value, ...), a numerically indexed array (0 => value, ...), or an object. ( ->column = value ), respectively.
  1247. * 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.
  1248. * @return mixed Database query results
  1249. */
  1250. function get_results( $query = null, $output = OBJECT ) {
  1251. $this->func_call = "\$db->get_results(\"$query\", $output)";
  1252. if ( $query )
  1253. $this->query( $query );
  1254. else
  1255. return null;
  1256. $new_array = array();
  1257. if ( $output == OBJECT ) {
  1258. // Return an integer-keyed array of row objects
  1259. return $this->last_result;
  1260. } elseif ( $output == OBJECT_K ) {
  1261. // Return an array of row objects with keys from column 1
  1262. // (Duplicates are discarded)
  1263. foreach ( $this->last_result as $row ) {
  1264. $key = array_shift( $var_by_ref = get_object_vars( $row ) );
  1265. if ( ! isset( $new_array[ $key ] ) )
  1266. $new_array[ $key ] = $row;
  1267. }
  1268. return $new_array;
  1269. } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
  1270. // Return an integer-keyed array of...
  1271. if ( $this->last_result ) {
  1272. foreach( (array) $this->last_result as $row ) {
  1273. if ( $output == ARRAY_N ) {
  1274. // ...integer-keyed row arrays
  1275. $new_array[] = array_values( get_object_vars( $row ) );
  1276. } else {
  1277. // ...column name-keyed row arrays
  1278. $new_array[] = get_object_vars( $row );
  1279. }
  1280. }
  1281. }
  1282. return $new_array;
  1283. }
  1284. return null;
  1285. }
  1286. /**
  1287. * Retrieve column metadata from the last query.
  1288. *
  1289. * @since 0.71
  1290. *
  1291. * @param string $info_type Optional. Type one of name, table, def, max_length, not_null, primary_key, multiple_key, unique_key, numeric, blob, type, unsigned, zerofill
  1292. * @param int $col_offset Optional. 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
  1293. * @return mixed Column Results
  1294. */
  1295. function get_col_info( $info_type = 'name', $col_offset = -1 ) {
  1296. if ( $this->col_info ) {
  1297. if ( $col_offset == -1 ) {
  1298. $i = 0;
  1299. $new_array = array();
  1300. foreach( (array) $this->col_info as $col ) {
  1301. $new_array[$i] = $col->{$info_type};
  1302. $i++;
  1303. }
  1304. return $new_array;
  1305. } else {
  1306. return $this->col_info[$col_offset]->{$info_type};
  1307. }
  1308. }
  1309. }
  1310. /**
  1311. * Starts the timer, for debugging purposes.
  1312. *
  1313. * @since 1.5.0
  1314. *
  1315. * @return true
  1316. */
  1317. function timer_start() {
  1318. $mtime = explode( ' ', microtime() );
  1319. $this->time_start = $mtime[1] + $mtime[0];
  1320. return true;
  1321. }
  1322. /**
  1323. * Stops the debugging timer.
  1324. *
  1325. * @since 1.5.0
  1326. *
  1327. * @return int Total time spent on the query, in milliseconds
  1328. */
  1329. function timer_stop() {
  1330. $mtime = explode( ' ', microtime() );
  1331. $time_end = $mtime[1] + $mtime[0];
  1332. $time_total = $time_end - $this->time_start;
  1333. return $time_total;
  1334. }
  1335. /**
  1336. * Wraps errors in a nice header and footer and dies.
  1337. *
  1338. * Will not die if wpdb::$show_errors is true
  1339. *
  1340. * @since 1.5.0
  1341. *
  1342. * @param string $message The Error message
  1343. * @param string $error_code Optional. A Computer readable string to identify the error.
  1344. * @return false|void
  1345. */
  1346. function bail( $message, $error_code = '500' ) {
  1347. if ( !$this->show_errors ) {
  1348. if ( class_exists( 'WP_Error' ) )
  1349. $this->error = new WP_Error($error_code, $message);
  1350. else
  1351. $this->error = $message;
  1352. return false;
  1353. }
  1354. wp_die($message);
  1355. }
  1356. /**
  1357. * Whether MySQL database is at least the required minimum version.
  1358. *
  1359. * @since 2.5.0
  1360. * @uses $wp_version
  1361. * @uses $required_mysql_version
  1362. *
  1363. * @return WP_Error
  1364. */
  1365. function check_database_version() {
  1366. global $wp_version, $required_mysql_version;
  1367. // Make sure the server has the required MySQL version
  1368. if ( version_compare($this->db_version(), $required_mysql_version, '<') )
  1369. return new WP_Error('database_version', sprintf( __( '<strong>ERROR</strong>: WordPress %1$s requires MySQL %2$s or higher' ), $wp_version, $required_mysql_version ));
  1370. }
  1371. /**
  1372. * Whether the database supports collation.
  1373. *
  1374. * Called when WordPress is generating the table scheme.
  1375. *
  1376. * @since 2.5.0
  1377. *
  1378. * @return bool True if collation is supported, false if version does not
  1379. */
  1380. function supports_collation() {
  1381. return $this->has_cap( 'collation' );
  1382. }
  1383. /**
  1384. * Determine if a database supports a particular feature
  1385. *
  1386. * @since 2.7
  1387. * @see wpdb::db_version()
  1388. *
  1389. * @param string $db_cap the feature
  1390. * @return bool
  1391. */
  1392. function has_cap( $db_cap ) {
  1393. $version = $this->db_version();
  1394. switch ( strtolower( $db_cap ) ) {
  1395. case 'collation' : // @since 2.5.0
  1396. case 'group_concat' : // @since 2.7
  1397. case 'subqueries' : // @since 2.7
  1398. return version_compare( $version, '4.1', '>=' );
  1399. };
  1400. return false;
  1401. }
  1402. /**
  1403. * Retrieve the name of the function that called wpdb.
  1404. *
  1405. * Searches up the list of functions until it reaches
  1406. * the one that would most logically had called this method.
  1407. *
  1408. * @since 2.5.0
  1409. *
  1410. * @return string The name of the calling function
  1411. */
  1412. function get_caller() {
  1413. $trace = array_reverse( debug_backtrace() );
  1414. $caller = array();
  1415. foreach ( $trace as $call ) {
  1416. if ( isset( $call['class'] ) && __CLASS__ == $call['class'] )
  1417. continue; // Filter out wpdb calls.
  1418. $caller[] = isset( $call['class'] ) ? "{$call['class']}->{$call['function']}" : $call['function'];
  1419. }
  1420. return join( ', ', $caller );
  1421. }
  1422. /**
  1423. * The database version number.
  1424. *
  1425. * @return false|string false on failure, version number on success
  1426. */
  1427. function db_version() {
  1428. return preg_replace( '/[^0-9.].*/', '', mysql_get_server_info( $this->dbh ) );
  1429. }
  1430. }
  1431. if ( ! isset( $wpdb ) ) {
  1432. /**
  1433. * WordPress Database Object, if it isn't set already in wp-content/db.php
  1434. * @global object $wpdb Creates a new wpdb object based on wp-config.php Constants for the database
  1435. * @since 0.71
  1436. */
  1437. $wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST );
  1438. }
  1439. ?>