PageRenderTime 56ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/wp-db.php

https://bitbucket.org/bobaldo/ipc-progettino
PHP | 1140 lines | 439 code | 122 blank | 579 comment | 87 complexity | d136eb1d085a50531c951d26ae279a94 MD5 | raw file
Possible License(s): 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. /**
  124. * WordPress Posts table
  125. *
  126. * @since 1.5.0
  127. * @access public
  128. * @var string
  129. */
  130. var $posts;
  131. /**
  132. * WordPress Users table
  133. *
  134. * @since 1.5.0
  135. * @access public
  136. * @var string
  137. */
  138. var $users;
  139. /**
  140. * WordPress Categories table
  141. *
  142. * @since 1.5.0
  143. * @access public
  144. * @var string
  145. */
  146. var $categories;
  147. /**
  148. * WordPress Post to Category table
  149. *
  150. * @since 1.5.0
  151. * @access public
  152. * @var string
  153. */
  154. var $post2cat;
  155. /**
  156. * WordPress Comments table
  157. *
  158. * @since 1.5.0
  159. * @access public
  160. * @var string
  161. */
  162. var $comments;
  163. /**
  164. * WordPress Links table
  165. *
  166. * @since 1.5.0
  167. * @access public
  168. * @var string
  169. */
  170. var $links;
  171. /**
  172. * WordPress Options table
  173. *
  174. * @since 1.5.0
  175. * @access public
  176. * @var string
  177. */
  178. var $options;
  179. /**
  180. * WordPress Post Metadata table
  181. *
  182. * @since {@internal Version Unknown}}
  183. * @access public
  184. * @var string
  185. */
  186. var $postmeta;
  187. /**
  188. * WordPress Comment Metadata table
  189. *
  190. * @since 2.9
  191. * @access public
  192. * @var string
  193. */
  194. var $commentmeta;
  195. /**
  196. * WordPress User Metadata table
  197. *
  198. * @since 2.3.0
  199. * @access public
  200. * @var string
  201. */
  202. var $usermeta;
  203. /**
  204. * WordPress Terms table
  205. *
  206. * @since 2.3.0
  207. * @access public
  208. * @var string
  209. */
  210. var $terms;
  211. /**
  212. * WordPress Term Taxonomy table
  213. *
  214. * @since 2.3.0
  215. * @access public
  216. * @var string
  217. */
  218. var $term_taxonomy;
  219. /**
  220. * WordPress Term Relationships table
  221. *
  222. * @since 2.3.0
  223. * @access public
  224. * @var string
  225. */
  226. var $term_relationships;
  227. /**
  228. * List of WordPress tables
  229. *
  230. * @since {@internal Version Unknown}}
  231. * @access private
  232. * @var array
  233. */
  234. var $tables = array('users', 'usermeta', 'posts', 'categories', 'post2cat', 'comments', 'links', 'link2cat', 'options',
  235. 'postmeta', 'terms', 'term_taxonomy', 'term_relationships', 'commentmeta');
  236. /**
  237. * List of deprecated WordPress tables
  238. *
  239. * @since 2.9.0
  240. * @access private
  241. * @var array
  242. */
  243. var $old_tables = array('categories', 'post2cat', 'link2cat');
  244. /**
  245. * Format specifiers for DB columns. Columns not listed here default to %s. Initialized in wp-settings.php.
  246. *
  247. * Keys are colmn names, values are format types: 'ID' => '%d'
  248. *
  249. * @since 2.8.0
  250. * @see wpdb:prepare()
  251. * @see wpdb:insert()
  252. * @see wpdb:update()
  253. * @access public
  254. * @war array
  255. */
  256. var $field_types = array();
  257. /**
  258. * Database table columns charset
  259. *
  260. * @since 2.2.0
  261. * @access public
  262. * @var string
  263. */
  264. var $charset;
  265. /**
  266. * Database table columns collate
  267. *
  268. * @since 2.2.0
  269. * @access public
  270. * @var string
  271. */
  272. var $collate;
  273. /**
  274. * Whether to use mysql_real_escape_string
  275. *
  276. * @since 2.8.0
  277. * @access public
  278. * @var bool
  279. */
  280. var $real_escape = false;
  281. /**
  282. * Database Username
  283. *
  284. * @since 2.9.0
  285. * @access private
  286. * @var string
  287. */
  288. var $dbuser;
  289. /**
  290. * Connects to the database server and selects a database
  291. *
  292. * PHP4 compatibility layer for calling the PHP5 constructor.
  293. *
  294. * @uses wpdb::__construct() Passes parameters and returns result
  295. * @since 0.71
  296. *
  297. * @param string $dbuser MySQL database user
  298. * @param string $dbpassword MySQL database password
  299. * @param string $dbname MySQL database name
  300. * @param string $dbhost MySQL database host
  301. */
  302. function wpdb($dbuser, $dbpassword, $dbname, $dbhost) {
  303. return $this->__construct($dbuser, $dbpassword, $dbname, $dbhost);
  304. }
  305. /**
  306. * Connects to the database server and selects a database
  307. *
  308. * PHP5 style constructor for compatibility with PHP5. Does
  309. * the actual setting up of the class properties and connection
  310. * to the database.
  311. *
  312. * @since 2.0.8
  313. *
  314. * @param string $dbuser MySQL database user
  315. * @param string $dbpassword MySQL database password
  316. * @param string $dbname MySQL database name
  317. * @param string $dbhost MySQL database host
  318. */
  319. function __construct($dbuser, $dbpassword, $dbname, $dbhost) {
  320. register_shutdown_function(array(&$this, "__destruct"));
  321. if ( WP_DEBUG )
  322. $this->show_errors();
  323. if ( defined('DB_CHARSET') )
  324. $this->charset = DB_CHARSET;
  325. if ( defined('DB_COLLATE') )
  326. $this->collate = DB_COLLATE;
  327. $this->dbuser = $dbuser;
  328. $this->dbh = @mysql_connect($dbhost, $dbuser, $dbpassword, true);
  329. if (!$this->dbh) {
  330. $this->bail(sprintf(/*WP_I18N_DB_CONN_ERROR*/'
  331. <h1>Errore nello stabilire una connessione al database</h1>
  332. <p>Ciò significa che le informazioni sul nome utente o sulla password presenti nel file <code>wp-config.php</code> non sono corrette o che non è possibile contattare il server del database a <code>%s</code>. Il che potrebbe voler dire che il database server del fornitore di hosting non è attivo.</p>
  333. <ul>
  334. <li>Si è sicuri di disporre del nome utente e della password corretti?</li>
  335. <li>Si è sicuri di aver digitato correttamente il nome dell\'host?</li>
  336. <li>Si è sicuri che il server del database sia funzionante?</li>
  337. </ul>
  338. <p>Nel caso non si abbia certezza sul significato di questi termini è opportuno contattare il proprio host. Se si ha bisogno di ulteriore aiuto è sempre possibile visitare il <a href=\'http://www.wordpress-it.it/forumt/\'>Forum di supporto italiano su WordPress</a>.</p>
  339. '/*/WP_I18N_DB_CONN_ERROR*/, $dbhost), 'db_connect_fail');
  340. return;
  341. }
  342. $this->ready = true;
  343. if ( $this->has_cap( 'collation' ) && !empty($this->charset) ) {
  344. if ( function_exists('mysql_set_charset') ) {
  345. mysql_set_charset($this->charset, $this->dbh);
  346. $this->real_escape = true;
  347. } else {
  348. $collation_query = "SET NAMES '{$this->charset}'";
  349. if ( !empty($this->collate) )
  350. $collation_query .= " COLLATE '{$this->collate}'";
  351. $this->query($collation_query);
  352. }
  353. }
  354. $this->select($dbname);
  355. }
  356. /**
  357. * PHP5 style destructor and will run when database object is destroyed.
  358. *
  359. * @since 2.0.8
  360. *
  361. * @return bool Always true
  362. */
  363. function __destruct() {
  364. return true;
  365. }
  366. /**
  367. * Sets the table prefix for the WordPress tables.
  368. *
  369. * Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to
  370. * override the WordPress users and usersmeta tables that would otherwise be determined by the $prefix.
  371. *
  372. * @since 2.5.0
  373. *
  374. * @param string $prefix Alphanumeric name for the new prefix.
  375. * @return string|WP_Error Old prefix or WP_Error on error
  376. */
  377. function set_prefix($prefix) {
  378. if ( preg_match('|[^a-z0-9_]|i', $prefix) )
  379. return new WP_Error('invalid_db_prefix', /*WP_I18N_DB_BAD_PREFIX*/'Prefisso database non valido'/*/WP_I18N_DB_BAD_PREFIX*/);
  380. $old_prefix = $this->prefix;
  381. $this->prefix = $prefix;
  382. foreach ( (array) $this->tables as $table )
  383. $this->$table = $this->prefix . $table;
  384. if ( defined('CUSTOM_USER_TABLE') )
  385. $this->users = CUSTOM_USER_TABLE;
  386. if ( defined('CUSTOM_USER_META_TABLE') )
  387. $this->usermeta = CUSTOM_USER_META_TABLE;
  388. return $old_prefix;
  389. }
  390. /**
  391. * Selects a database using the current database connection.
  392. *
  393. * The database name will be changed based on the current database
  394. * connection. On failure, the execution will bail and display an DB error.
  395. *
  396. * @since 0.71
  397. *
  398. * @param string $db MySQL database name
  399. * @return null Always null.
  400. */
  401. function select($db) {
  402. if (!@mysql_select_db($db, $this->dbh)) {
  403. $this->ready = false;
  404. $this->bail(sprintf(/*WP_I18N_DB_SELECT_DB*/'
  405. <h1>Impossibile selezionare il database</h1>
  406. <p>&Egrave; stato possibile connettersi al server del database (il che significa che il nome utente e la password sono ok) ma non è stato possibile selezionare il database <code>%1$s</code>.</p>
  407. <ul>
  408. <li>Si è certi che esista?</li>
  409. <li>L\'utente <code>%2$s</code> ha i permessi di usare il database <code>%1$s</code>?</li>
  410. <li>Su alcuni sistemi il nome del database va fatto precedere dal nome utente, così da avere un formato simile a username_wordpress. Potrebbe essere questo il problema?</li>
  411. </ul>
  412. <p>Se non si sa come impostare un database sarebbe opportuno <strong>contattare il proprio host</strong>. Se tutto questo fallisce è possibile trovare aiuto sul <a href=\'http://www.wordpress-it.it/forumt/\'>Forum di supporto italiano su WordPress</a>.</p>'/*/WP_I18N_DB_SELECT_DB*/, $db, $this->dbuser), 'db_select_fail');
  413. return;
  414. }
  415. }
  416. function _weak_escape($string) {
  417. return addslashes($string);
  418. }
  419. function _real_escape($string) {
  420. if ( $this->dbh && $this->real_escape )
  421. return mysql_real_escape_string( $string, $this->dbh );
  422. else
  423. return addslashes( $string );
  424. }
  425. function _escape($data) {
  426. if ( is_array($data) ) {
  427. foreach ( (array) $data as $k => $v ) {
  428. if ( is_array($v) )
  429. $data[$k] = $this->_escape( $v );
  430. else
  431. $data[$k] = $this->_real_escape( $v );
  432. }
  433. } else {
  434. $data = $this->_real_escape( $data );
  435. }
  436. return $data;
  437. }
  438. /**
  439. * Escapes content for insertion into the database using addslashes(), for security
  440. *
  441. * @since 0.71
  442. *
  443. * @param string|array $data
  444. * @return string query safe string
  445. */
  446. function escape($data) {
  447. if ( is_array($data) ) {
  448. foreach ( (array) $data as $k => $v ) {
  449. if ( is_array($v) )
  450. $data[$k] = $this->escape( $v );
  451. else
  452. $data[$k] = $this->_weak_escape( $v );
  453. }
  454. } else {
  455. $data = $this->_weak_escape( $data );
  456. }
  457. return $data;
  458. }
  459. /**
  460. * Escapes content by reference for insertion into the database, for security
  461. *
  462. * @since 2.3.0
  463. *
  464. * @param string $s
  465. */
  466. function escape_by_ref(&$string) {
  467. $string = $this->_real_escape( $string );
  468. }
  469. /**
  470. * Prepares a SQL query for safe execution. Uses sprintf()-like syntax.
  471. *
  472. * This function only supports a small subset of the sprintf syntax; it only supports %d (decimal number), %s (string).
  473. * Does not support sign, padding, alignment, width or precision specifiers.
  474. * Does not support argument numbering/swapping.
  475. *
  476. * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}.
  477. *
  478. * Both %d and %s should be left unquoted in the query string.
  479. *
  480. * <code>
  481. * wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", "foo", 1337 )
  482. * </code>
  483. *
  484. * @link http://php.net/sprintf Description of syntax.
  485. * @since 2.3.0
  486. *
  487. * @param string $query Query statement with sprintf()-like placeholders
  488. * @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()}.
  489. * @param mixed $args,... further variables to substitute into the query's placeholders if being called like {@link http://php.net/sprintf sprintf()}.
  490. * @return null|string Sanitized query string
  491. */
  492. function prepare($query = null) { // ( $query, *$args )
  493. if ( is_null( $query ) )
  494. return;
  495. $args = func_get_args();
  496. array_shift($args);
  497. // If args were passed as an array (as in vsprintf), move them up
  498. if ( isset($args[0]) && is_array($args[0]) )
  499. $args = $args[0];
  500. $query = str_replace("'%s'", '%s', $query); // in case someone mistakenly already singlequoted it
  501. $query = str_replace('"%s"', '%s', $query); // doublequote unquoting
  502. $query = str_replace('%s', "'%s'", $query); // quote the strings
  503. array_walk($args, array(&$this, 'escape_by_ref'));
  504. return @vsprintf($query, $args);
  505. }
  506. /**
  507. * Print SQL/DB error.
  508. *
  509. * @since 0.71
  510. * @global array $EZSQL_ERROR Stores error information of query and error string
  511. *
  512. * @param string $str The error to display
  513. * @return bool False if the showing of errors is disabled.
  514. */
  515. function print_error($str = '') {
  516. global $EZSQL_ERROR;
  517. if (!$str) $str = mysql_error($this->dbh);
  518. $EZSQL_ERROR[] = array ('query' => $this->last_query, 'error_str' => $str);
  519. if ( $this->suppress_errors )
  520. return false;
  521. if ( $caller = $this->get_caller() )
  522. $error_str = sprintf(/*WP_I18N_DB_QUERY_ERROR_FULL*/'WordPress errore sul database %1$s per la query %2$s fatta da %3$s'/*/WP_I18N_DB_QUERY_ERROR_FULL*/, $str, $this->last_query, $caller);
  523. else
  524. $error_str = sprintf(/*WP_I18N_DB_QUERY_ERROR*/'WordPress errore database %1$s per la query %2$s'/*/WP_I18N_DB_QUERY_ERROR*/, $str, $this->last_query);
  525. $log_error = true;
  526. if ( ! function_exists('error_log') )
  527. $log_error = false;
  528. $log_file = @ini_get('error_log');
  529. if ( !empty($log_file) && ('syslog' != $log_file) && !@is_writable($log_file) )
  530. $log_error = false;
  531. if ( $log_error )
  532. @error_log($error_str, 0);
  533. // Is error output turned on or not..
  534. if ( !$this->show_errors )
  535. return false;
  536. $str = htmlspecialchars($str, ENT_QUOTES);
  537. $query = htmlspecialchars($this->last_query, ENT_QUOTES);
  538. // If there is an error then take note of it
  539. print "<div id='error'>
  540. <p class='wpdberror'><strong>WordPress database error:</strong> [$str]<br />
  541. <code>$query</code></p>
  542. </div>";
  543. }
  544. /**
  545. * Enables showing of database errors.
  546. *
  547. * This function should be used only to enable showing of errors.
  548. * wpdb::hide_errors() should be used instead for hiding of errors. However,
  549. * this function can be used to enable and disable showing of database
  550. * errors.
  551. *
  552. * @since 0.71
  553. *
  554. * @param bool $show Whether to show or hide errors
  555. * @return bool Old value for showing errors.
  556. */
  557. function show_errors( $show = true ) {
  558. $errors = $this->show_errors;
  559. $this->show_errors = $show;
  560. return $errors;
  561. }
  562. /**
  563. * Disables showing of database errors.
  564. *
  565. * @since 0.71
  566. *
  567. * @return bool Whether showing of errors was active or not
  568. */
  569. function hide_errors() {
  570. $show = $this->show_errors;
  571. $this->show_errors = false;
  572. return $show;
  573. }
  574. /**
  575. * Whether to suppress database errors.
  576. *
  577. * @param unknown_type $suppress
  578. * @return unknown
  579. */
  580. function suppress_errors( $suppress = true ) {
  581. $errors = $this->suppress_errors;
  582. $this->suppress_errors = $suppress;
  583. return $errors;
  584. }
  585. /**
  586. * Kill cached query results.
  587. *
  588. * @since 0.71
  589. */
  590. function flush() {
  591. $this->last_result = array();
  592. $this->col_info = null;
  593. $this->last_query = null;
  594. }
  595. /**
  596. * Perform a MySQL database query, using current database connection.
  597. *
  598. * More information can be found on the codex page.
  599. *
  600. * @since 0.71
  601. *
  602. * @param string $query
  603. * @return int|false Number of rows affected/selected or false on error
  604. */
  605. function query($query) {
  606. if ( ! $this->ready )
  607. return false;
  608. // filter the query, if filters are available
  609. // NOTE: some queries are made before the plugins have been loaded, and thus cannot be filtered with this method
  610. if ( function_exists('apply_filters') )
  611. $query = apply_filters('query', $query);
  612. // initialise return
  613. $return_val = 0;
  614. $this->flush();
  615. // Log how the function was called
  616. $this->func_call = "\$db->query(\"$query\")";
  617. // Keep track of the last query for debug..
  618. $this->last_query = $query;
  619. // Perform the query via std mysql_query function..
  620. if ( defined('SAVEQUERIES') && SAVEQUERIES )
  621. $this->timer_start();
  622. $this->result = @mysql_query($query, $this->dbh);
  623. ++$this->num_queries;
  624. if ( defined('SAVEQUERIES') && SAVEQUERIES )
  625. $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
  626. // If there is an error then take note of it..
  627. if ( $this->last_error = mysql_error($this->dbh) ) {
  628. $this->print_error();
  629. return false;
  630. }
  631. if ( preg_match("/^\\s*(insert|delete|update|replace|alter) /i",$query) ) {
  632. $this->rows_affected = mysql_affected_rows($this->dbh);
  633. // Take note of the insert_id
  634. if ( preg_match("/^\\s*(insert|replace) /i",$query) ) {
  635. $this->insert_id = mysql_insert_id($this->dbh);
  636. }
  637. // Return number of rows affected
  638. $return_val = $this->rows_affected;
  639. } else {
  640. $i = 0;
  641. while ($i < @mysql_num_fields($this->result)) {
  642. $this->col_info[$i] = @mysql_fetch_field($this->result);
  643. $i++;
  644. }
  645. $num_rows = 0;
  646. while ( $row = @mysql_fetch_object($this->result) ) {
  647. $this->last_result[$num_rows] = $row;
  648. $num_rows++;
  649. }
  650. @mysql_free_result($this->result);
  651. // Log number of rows the query returned
  652. $this->num_rows = $num_rows;
  653. // Return number of rows selected
  654. $return_val = $this->num_rows;
  655. }
  656. return $return_val;
  657. }
  658. /**
  659. * Insert a row into a table.
  660. *
  661. * <code>
  662. * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
  663. * </code>
  664. *
  665. * @since 2.5.0
  666. * @see wpdb::prepare()
  667. *
  668. * @param string $table table name
  669. * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  670. * @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.
  671. * @return int|false The number of rows inserted, or false on error.
  672. */
  673. function insert($table, $data, $format = null) {
  674. $formats = $format = (array) $format;
  675. $fields = array_keys($data);
  676. $formatted_fields = array();
  677. foreach ( $fields as $field ) {
  678. if ( !empty($format) )
  679. $form = ( $form = array_shift($formats) ) ? $form : $format[0];
  680. elseif ( isset($this->field_types[$field]) )
  681. $form = $this->field_types[$field];
  682. else
  683. $form = '%s';
  684. $formatted_fields[] = $form;
  685. }
  686. $sql = "INSERT INTO `$table` (`" . implode( '`,`', $fields ) . "`) VALUES ('" . implode( "','", $formatted_fields ) . "')";
  687. return $this->query( $this->prepare( $sql, $data) );
  688. }
  689. /**
  690. * Update a row in the table
  691. *
  692. * <code>
  693. * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) )
  694. * </code>
  695. *
  696. * @since 2.5.0
  697. * @see wpdb::prepare()
  698. *
  699. * @param string $table table name
  700. * @param array $data Data to update (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  701. * @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".
  702. * @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.
  703. * @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.
  704. * @return int|false The number of rows updated, or false on error.
  705. */
  706. function update($table, $data, $where, $format = null, $where_format = null) {
  707. if ( !is_array( $where ) )
  708. return false;
  709. $formats = $format = (array) $format;
  710. $bits = $wheres = array();
  711. foreach ( (array) array_keys($data) as $field ) {
  712. if ( !empty($format) )
  713. $form = ( $form = array_shift($formats) ) ? $form : $format[0];
  714. elseif ( isset($this->field_types[$field]) )
  715. $form = $this->field_types[$field];
  716. else
  717. $form = '%s';
  718. $bits[] = "`$field` = {$form}";
  719. }
  720. $where_formats = $where_format = (array) $where_format;
  721. foreach ( (array) array_keys($where) as $field ) {
  722. if ( !empty($where_format) )
  723. $form = ( $form = array_shift($where_formats) ) ? $form : $where_format[0];
  724. elseif ( isset($this->field_types[$field]) )
  725. $form = $this->field_types[$field];
  726. else
  727. $form = '%s';
  728. $wheres[] = "`$field` = {$form}";
  729. }
  730. $sql = "UPDATE `$table` SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres );
  731. return $this->query( $this->prepare( $sql, array_merge(array_values($data), array_values($where))) );
  732. }
  733. /**
  734. * Retrieve one variable from the database.
  735. *
  736. * Executes a SQL query and returns the value from the SQL result.
  737. * 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.
  738. * If $query is null, this function returns the value in the specified column and row from the previous SQL result.
  739. *
  740. * @since 0.71
  741. *
  742. * @param string|null $query SQL query. If null, use the result from the previous query.
  743. * @param int $x (optional) Column of value to return. Indexed from 0.
  744. * @param int $y (optional) Row of value to return. Indexed from 0.
  745. * @return string Database query result
  746. */
  747. function get_var($query=null, $x = 0, $y = 0) {
  748. $this->func_call = "\$db->get_var(\"$query\",$x,$y)";
  749. if ( $query )
  750. $this->query($query);
  751. // Extract var out of cached results based x,y vals
  752. if ( !empty( $this->last_result[$y] ) ) {
  753. $values = array_values(get_object_vars($this->last_result[$y]));
  754. }
  755. // If there is a value return it else return null
  756. return (isset($values[$x]) && $values[$x]!=='') ? $values[$x] : null;
  757. }
  758. /**
  759. * Retrieve one row from the database.
  760. *
  761. * Executes a SQL query and returns the row from the SQL result.
  762. *
  763. * @since 0.71
  764. *
  765. * @param string|null $query SQL query.
  766. * @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.
  767. * @param int $y (optional) Row to return. Indexed from 0.
  768. * @return mixed Database query result in format specifed by $output
  769. */
  770. function get_row($query = null, $output = OBJECT, $y = 0) {
  771. $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
  772. if ( $query )
  773. $this->query($query);
  774. else
  775. return null;
  776. if ( !isset($this->last_result[$y]) )
  777. return null;
  778. if ( $output == OBJECT ) {
  779. return $this->last_result[$y] ? $this->last_result[$y] : null;
  780. } elseif ( $output == ARRAY_A ) {
  781. return $this->last_result[$y] ? get_object_vars($this->last_result[$y]) : null;
  782. } elseif ( $output == ARRAY_N ) {
  783. return $this->last_result[$y] ? array_values(get_object_vars($this->last_result[$y])) : null;
  784. } else {
  785. $this->print_error(/*WP_I18N_DB_GETROW_ERROR*/' $db->get_row(string query, output type, int offset) -- Il risultato deve essere uno fra questi: OBJECT, ARRAY_A, ARRAY_N'/*/WP_I18N_DB_GETROW_ERROR*/);
  786. }
  787. }
  788. /**
  789. * Retrieve one column from the database.
  790. *
  791. * Executes a SQL query and returns the column from the SQL result.
  792. * If the SQL result contains more than one column, this function returns the column specified.
  793. * If $query is null, this function returns the specified column from the previous SQL result.
  794. *
  795. * @since 0.71
  796. *
  797. * @param string|null $query SQL query. If null, use the result from the previous query.
  798. * @param int $x Column to return. Indexed from 0.
  799. * @return array Database query result. Array indexed from 0 by SQL result row number.
  800. */
  801. function get_col($query = null , $x = 0) {
  802. if ( $query )
  803. $this->query($query);
  804. $new_array = array();
  805. // Extract the column values
  806. for ( $i=0; $i < count($this->last_result); $i++ ) {
  807. $new_array[$i] = $this->get_var(null, $x, $i);
  808. }
  809. return $new_array;
  810. }
  811. /**
  812. * Retrieve an entire SQL result set from the database (i.e., many rows)
  813. *
  814. * Executes a SQL query and returns the entire SQL result.
  815. *
  816. * @since 0.71
  817. *
  818. * @param string $query SQL query.
  819. * @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.
  820. * @return mixed Database query results
  821. */
  822. function get_results($query = null, $output = OBJECT) {
  823. $this->func_call = "\$db->get_results(\"$query\", $output)";
  824. if ( $query )
  825. $this->query($query);
  826. else
  827. return null;
  828. if ( $output == OBJECT ) {
  829. // Return an integer-keyed array of row objects
  830. return $this->last_result;
  831. } elseif ( $output == OBJECT_K ) {
  832. // Return an array of row objects with keys from column 1
  833. // (Duplicates are discarded)
  834. foreach ( $this->last_result as $row ) {
  835. $key = array_shift( get_object_vars( $row ) );
  836. if ( !isset( $new_array[ $key ] ) )
  837. $new_array[ $key ] = $row;
  838. }
  839. return $new_array;
  840. } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
  841. // Return an integer-keyed array of...
  842. if ( $this->last_result ) {
  843. $i = 0;
  844. foreach( (array) $this->last_result as $row ) {
  845. if ( $output == ARRAY_N ) {
  846. // ...integer-keyed row arrays
  847. $new_array[$i] = array_values( get_object_vars( $row ) );
  848. } else {
  849. // ...column name-keyed row arrays
  850. $new_array[$i] = get_object_vars( $row );
  851. }
  852. ++$i;
  853. }
  854. return $new_array;
  855. }
  856. }
  857. }
  858. /**
  859. * Retrieve column metadata from the last query.
  860. *
  861. * @since 0.71
  862. *
  863. * @param string $info_type one of name, table, def, max_length, not_null, primary_key, multiple_key, unique_key, numeric, blob, type, unsigned, zerofill
  864. * @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
  865. * @return mixed Column Results
  866. */
  867. function get_col_info($info_type = 'name', $col_offset = -1) {
  868. if ( $this->col_info ) {
  869. if ( $col_offset == -1 ) {
  870. $i = 0;
  871. foreach( (array) $this->col_info as $col ) {
  872. $new_array[$i] = $col->{$info_type};
  873. $i++;
  874. }
  875. return $new_array;
  876. } else {
  877. return $this->col_info[$col_offset]->{$info_type};
  878. }
  879. }
  880. }
  881. /**
  882. * Starts the timer, for debugging purposes.
  883. *
  884. * @since 1.5.0
  885. *
  886. * @return true
  887. */
  888. function timer_start() {
  889. $mtime = microtime();
  890. $mtime = explode(' ', $mtime);
  891. $this->time_start = $mtime[1] + $mtime[0];
  892. return true;
  893. }
  894. /**
  895. * Stops the debugging timer.
  896. *
  897. * @since 1.5.0
  898. *
  899. * @return int Total time spent on the query, in milliseconds
  900. */
  901. function timer_stop() {
  902. $mtime = microtime();
  903. $mtime = explode(' ', $mtime);
  904. $time_end = $mtime[1] + $mtime[0];
  905. $time_total = $time_end - $this->time_start;
  906. return $time_total;
  907. }
  908. /**
  909. * Wraps errors in a nice header and footer and dies.
  910. *
  911. * Will not die if wpdb::$show_errors is true
  912. *
  913. * @since 1.5.0
  914. *
  915. * @param string $message The Error message
  916. * @param string $error_code (optional) A Computer readable string to identify the error.
  917. * @return false|void
  918. */
  919. function bail($message, $error_code = '500') {
  920. if ( !$this->show_errors ) {
  921. if ( class_exists('WP_Error') )
  922. $this->error = new WP_Error($error_code, $message);
  923. else
  924. $this->error = $message;
  925. return false;
  926. }
  927. wp_die($message);
  928. }
  929. /**
  930. * Whether or not MySQL database is at least the required minimum version.
  931. *
  932. * @since 2.5.0
  933. * @uses $wp_version
  934. *
  935. * @return WP_Error
  936. */
  937. function check_database_version()
  938. {
  939. global $wp_version;
  940. // Make sure the server has MySQL 4.1.2
  941. if ( version_compare($this->db_version(), '4.1.2', '<') )
  942. return new WP_Error('database_version',sprintf(__('<strong>ERROR</strong>: WordPress %s requires MySQL 4.1.2 or higher'), $wp_version));
  943. }
  944. /**
  945. * Whether of not the database supports collation.
  946. *
  947. * Called when WordPress is generating the table scheme.
  948. *
  949. * @since 2.5.0
  950. *
  951. * @return bool True if collation is supported, false if version does not
  952. */
  953. function supports_collation() {
  954. return $this->has_cap( 'collation' );
  955. }
  956. /**
  957. * Generic function to determine if a database supports a particular feature
  958. * @param string $db_cap the feature
  959. * @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.
  960. * @return bool
  961. */
  962. function has_cap( $db_cap ) {
  963. $version = $this->db_version();
  964. switch ( strtolower( $db_cap ) ) :
  965. case 'collation' : // @since 2.5.0
  966. case 'group_concat' : // @since 2.7
  967. case 'subqueries' : // @since 2.7
  968. return version_compare($version, '4.1', '>=');
  969. break;
  970. endswitch;
  971. return false;
  972. }
  973. /**
  974. * Retrieve the name of the function that called wpdb.
  975. *
  976. * Requires PHP 4.3 and searches up the list of functions until it reaches
  977. * the one that would most logically had called this method.
  978. *
  979. * @since 2.5.0
  980. *
  981. * @return string The name of the calling function
  982. */
  983. function get_caller() {
  984. // requires PHP 4.3+
  985. if ( !is_callable('debug_backtrace') )
  986. return '';
  987. $bt = debug_backtrace();
  988. $caller = array();
  989. $bt = array_reverse( $bt );
  990. foreach ( (array) $bt as $call ) {
  991. if ( @$call['class'] == __CLASS__ )
  992. continue;
  993. $function = $call['function'];
  994. if ( isset( $call['class'] ) )
  995. $function = $call['class'] . "->$function";
  996. $caller[] = $function;
  997. }
  998. $caller = join( ', ', $caller );
  999. return $caller;
  1000. }
  1001. /**
  1002. * The database version number
  1003. * @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.
  1004. * @return false|string false on failure, version number on success
  1005. */
  1006. function db_version() {
  1007. return preg_replace('/[^0-9.].*/', '', mysql_get_server_info( $this->dbh ));
  1008. }
  1009. }
  1010. if ( ! isset($wpdb) ) {
  1011. /**
  1012. * WordPress Database Object, if it isn't set already in wp-content/db.php
  1013. * @global object $wpdb Creates a new wpdb object based on wp-config.php Constants for the database
  1014. * @since 0.71
  1015. */
  1016. $wpdb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
  1017. }
  1018. ?>