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

/svntrunk/bp-forums/bbpress/bb-includes/backpress/class.bpdb.php

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