PageRenderTime 57ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/gp-includes/backpress/class.bpdb.php

https://bitbucket.org/moodsdesign-ondemand/reglot
PHP | 1163 lines | 592 code | 111 blank | 460 comment | 120 complexity | cff4ba5c6a8781d0d449328d1d65f426 MD5 | raw file
Possible License(s): GPL-2.0
  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 = preg_replace('/([\'"])%(\d+\$)?s\1/', '%$2s', $query ); // in case someone mistakenly already singlequoted it
  449. $query = preg_replace('/%(\d+\$)?s/', "'%$1s'", $query ); // quote the strings
  450. array_walk( $args, array( &$this, 'escape_by_ref' ) );
  451. return @vsprintf( $query, $args );
  452. }
  453. /**
  454. * Get SQL/DB error
  455. *
  456. * @since 1.0
  457. *
  458. * @param string $str Error string
  459. */
  460. function get_error( $str = '' )
  461. {
  462. if ( empty( $str ) ) {
  463. if ( $this->last_error ) {
  464. $str = $this->last_error;
  465. } else {
  466. return false;
  467. }
  468. }
  469. $caller = $this->get_caller();
  470. $error_str = sprintf( BPDB__ERROR_STRING, $str, $this->last_query, $caller );
  471. if ( class_exists( 'WP_Error' ) ) {
  472. return new WP_Error( 'db_query', $error_str, array( 'query' => $this->last_query, 'error' => $str, 'caller' => $caller ) );
  473. } else {
  474. return array( 'query' => $this->last_query, 'error' => $str, 'caller' => $caller, 'error_str' => $error_str );
  475. }
  476. }
  477. /**
  478. * Print SQL/DB error.
  479. *
  480. * @since 1.0
  481. *
  482. * @param string $str The error to display
  483. * @return bool False if the showing of errors is disabled.
  484. */
  485. function print_error( $str = '' )
  486. {
  487. if ( $this->suppress_errors ) {
  488. return false;
  489. }
  490. $error = $this->get_error( $str );
  491. if ( is_object( $error ) && is_a( $error, 'WP_Error' ) ) {
  492. $err = $error->get_error_data();
  493. $err['error_str'] = $error->get_error_message();
  494. } else {
  495. $err =& $error;
  496. }
  497. $log_file = ini_get( 'error_log' );
  498. if ( !empty( $log_file ) && ( 'syslog' != $log_file ) && is_writable( $log_file ) && function_exists( 'error_log' ) ) {
  499. error_log($err['error_str'], 0);
  500. }
  501. // Is error output turned on or not
  502. if ( !$this->show_errors ) {
  503. return false;
  504. }
  505. $str = htmlspecialchars( $err['error'], ENT_QUOTES );
  506. $query = htmlspecialchars( $err['query'], ENT_QUOTES );
  507. $caller = htmlspecialchars( $err['caller'], ENT_QUOTES );
  508. // If there is an error then take note of it
  509. printf( BPDB__ERROR_HTML, $str, $query, $caller );
  510. }
  511. /**
  512. * Enables showing of database errors.
  513. *
  514. * This function should be used only to enable showing of errors.
  515. * bpdb::hide_errors() should be used instead for hiding of errors. However,
  516. * this function can be used to enable and disable showing of database
  517. * errors.
  518. *
  519. * @since 1.0
  520. *
  521. * @param bool $show Whether to show or hide errors
  522. * @return bool Old value for showing errors.
  523. */
  524. function show_errors( $show = true )
  525. {
  526. $errors = $this->show_errors;
  527. $this->show_errors = $show;
  528. return $errors;
  529. }
  530. /**
  531. * Disables showing of database errors.
  532. *
  533. * @since 1.0
  534. *
  535. * @return bool Whether showing of errors was active or not
  536. */
  537. function hide_errors()
  538. {
  539. return $this->show_errors( false );
  540. }
  541. /**
  542. * Whether to suppress database errors.
  543. *
  544. * @since 1.0
  545. *
  546. * @param bool $suppress
  547. * @return bool previous setting
  548. */
  549. function suppress_errors( $suppress = true )
  550. {
  551. $errors = $this->suppress_errors;
  552. $this->suppress_errors = $suppress;
  553. return $errors;
  554. }
  555. /**
  556. * Kill cached query results.
  557. *
  558. * @since 1.0
  559. */
  560. function flush()
  561. {
  562. $this->last_result = array();
  563. $this->col_info = array();
  564. $this->last_query = null;
  565. $this->last_error = '';
  566. $this->num_rows = 0;
  567. }
  568. /**
  569. * Perform a MySQL database query, using current database connection.
  570. *
  571. * More information can be found on the codex page.
  572. *
  573. * @since 1.0
  574. *
  575. * @param string $query
  576. * @return int|false Number of rows affected/selected or false on error
  577. */
  578. function query( $query, $use_current = false )
  579. {
  580. if ( !$this->ready ) {
  581. return false;
  582. }
  583. // filter the query, if filters are available
  584. // NOTE: some queries are made before the plugins have been loaded, and thus cannot be filtered with this method
  585. if ( function_exists( 'apply_filters' ) ) {
  586. $query = apply_filters( 'query', $query );
  587. }
  588. // initialise return
  589. $return_val = 0;
  590. $this->flush();
  591. // Log how the function was called
  592. $this->func_call = "\$db->query(\"$query\")";
  593. // Keep track of the last query for debug..
  594. $this->last_query = $query;
  595. // Perform the query via std mysql_query function..
  596. if ( SAVEQUERIES ) {
  597. $this->timer_start();
  598. }
  599. if ( $use_current ) {
  600. $dbh =& $this->dbh;
  601. } else {
  602. $dbh = $this->db_connect( $query );
  603. }
  604. $this->result = @mysql_query( $query, $dbh );
  605. ++$this->num_queries;
  606. if ( SAVEQUERIES ) {
  607. $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
  608. }
  609. // If there is an error then take note of it..
  610. if ( is_resource( $dbh ) && $this->last_error = mysql_error( $dbh ) ) {
  611. return $this->print_error( $this->last_error );
  612. }
  613. if ( preg_match( "/^\\s*(insert|delete|update|replace|alter) /i", $query ) ) {
  614. $this->rows_affected = mysql_affected_rows( $dbh );
  615. // Take note of the insert_id
  616. if ( preg_match( "/^\\s*(insert|replace) /i", $query ) ) {
  617. $this->insert_id = mysql_insert_id( $dbh );
  618. }
  619. // Return number of rows affected
  620. $return_val = $this->rows_affected;
  621. } else {
  622. $i = 0;
  623. while ( $i < @mysql_num_fields( $this->result ) ) {
  624. $this->col_info[$i] = @mysql_fetch_field( $this->result );
  625. $i++;
  626. }
  627. $num_rows = 0;
  628. while ( $row = @mysql_fetch_object( $this->result ) ) {
  629. $this->last_result[$num_rows] = $row;
  630. $num_rows++;
  631. }
  632. @mysql_free_result( $this->result );
  633. // Log number of rows the query returned
  634. $this->num_rows = $num_rows;
  635. // Return number of rows selected
  636. $return_val = $this->num_rows;
  637. }
  638. return $return_val;
  639. }
  640. /**
  641. * Insert a row into a table.
  642. *
  643. * <code>
  644. * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
  645. * </code>
  646. *
  647. * @since 1.0
  648. * @see bpdb::prepare()
  649. *
  650. * @param string $table table name
  651. * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  652. * @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.
  653. * @return int|false The number of rows inserted, or false on error.
  654. */
  655. function insert( $table, $data, $format = null )
  656. {
  657. $formats = $format = (array) $format;
  658. $fields = array_keys( $data );
  659. $formatted_fields = array();
  660. foreach ( $fields as $field ) {
  661. if ( !empty( $format ) ) {
  662. $form = ( $form = array_shift( $formats ) ) ? $form : $format[0];
  663. } elseif ( isset( $this->field_types[$field] ) ) {
  664. $form = $this->field_types[$field];
  665. } elseif ( is_null( $data[$field] ) ) {
  666. $form = 'NULL';
  667. unset( $data[$field] );
  668. } else {
  669. $form = '%s';
  670. }
  671. $formatted_fields[] = $form;
  672. }
  673. $sql = "INSERT INTO `$table` (`" . implode( '`,`', $fields ) . "`) VALUES (" . implode( ",", $formatted_fields ) . ")";
  674. return $this->query( $this->prepare( $sql, $data ) );
  675. }
  676. /**
  677. * Update a row in the table
  678. *
  679. * <code>
  680. * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) )
  681. * </code>
  682. *
  683. * @since 1.0
  684. * @see bpdb::prepare()
  685. *
  686. * @param string $table table name
  687. * @param array $data Data to update (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  688. * @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".
  689. * @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.
  690. * @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.
  691. * @return int|false The number of rows updated, or false on error.
  692. */
  693. function update( $table, $data, $where, $format = null, $where_format = null )
  694. {
  695. if ( !is_array( $where ) ) {
  696. return false;
  697. }
  698. $formats = $format = (array) $format;
  699. $bits = $wheres = array();
  700. foreach ( (array) array_keys( $data ) as $field ) {
  701. if ( !empty( $format ) ) {
  702. $form = ( $form = array_shift( $formats ) ) ? $form : $format[0];
  703. } elseif ( isset( $this->field_types[$field] ) ) {
  704. $form = $this->field_types[$field];
  705. } elseif ( is_null( $data[$field] ) ) {
  706. $form = 'NULL';
  707. unset( $data[$field] );
  708. } else {
  709. $form = '%s';
  710. }
  711. $bits[] = "`$field` = {$form}";
  712. }
  713. $where_formats = $where_format = (array) $where_format;
  714. foreach ( (array) array_keys( $where ) as $field ) {
  715. if ( !empty( $where_format ) ) {
  716. $form = ( $form = array_shift( $where_formats ) ) ? $form : $where_format[0];
  717. } elseif ( isset( $this->field_types[$field] ) ) {
  718. $form = $this->field_types[$field];
  719. } elseif ( is_null( $where[$field] ) ) {
  720. unset( $where[$field] );
  721. $wheres[] = "`$field` IS NULL";
  722. continue;
  723. } else {
  724. $form = '%s';
  725. }
  726. $wheres[] = "`$field` = {$form}";
  727. }
  728. $sql = "UPDATE `$table` SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres );
  729. return $this->query( $this->prepare( $sql, array_merge( array_values( $data ), array_values( $where ) ) ) );
  730. }
  731. /**
  732. * Retrieve one variable from the database.
  733. *
  734. * Executes a SQL query and returns the value from the SQL result.
  735. * 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.
  736. * If $query is null, this function returns the value in the specified column and row from the previous SQL result.
  737. *
  738. * @since 1.0
  739. *
  740. * @param string|null $query SQL query. If null, use the result from the previous query.
  741. * @param int $x (optional) Column of value to return. Indexed from 0.
  742. * @param int $y (optional) Row of value to return. Indexed from 0.
  743. * @return string Database query result
  744. */
  745. function get_var( $query=null, $x = 0, $y = 0 )
  746. {
  747. $this->func_call = "\$db->get_var(\"$query\",$x,$y)";
  748. if ( $query ) {
  749. $this->query( $query );
  750. }
  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 1.0
  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. {
  772. $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
  773. if ( $query ) {
  774. $this->query( $query );
  775. } else {
  776. return null;
  777. }
  778. if ( !isset( $this->last_result[$y] ) ) {
  779. return null;
  780. }
  781. if ( $output == OBJECT ) {
  782. return $this->last_result[$y] ? $this->last_result[$y] : null;
  783. } elseif ( $output == ARRAY_A ) {
  784. return $this->last_result[$y] ? get_object_vars( $this->last_result[$y] ) : null;
  785. } elseif ( $output == ARRAY_N ) {
  786. return $this->last_result[$y] ? array_values( get_object_vars( $this->last_result[$y] ) ) : null;
  787. } else {
  788. $this->print_error( " \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N" );
  789. }
  790. }
  791. /**
  792. * Retrieve one column from the database.
  793. *
  794. * Executes a SQL query and returns the column from the SQL result.
  795. * If the SQL result contains more than one column, this function returns the column specified.
  796. * If $query is null, this function returns the specified column from the previous SQL result.
  797. *
  798. * @since 1.0
  799. *
  800. * @param string|null $query SQL query. If null, use the result from the previous query.
  801. * @param int $x Column to return. Indexed from 0.
  802. * @return array Database query result. Array indexed from 0 by SQL result row number.
  803. */
  804. function get_col( $query = null , $x = 0 )
  805. {
  806. if ( $query ) {
  807. $this->query( $query );
  808. }
  809. $new_array = array();
  810. // Extract the column values
  811. for ( $i=0; $i < count( $this->last_result ); $i++ ) {
  812. $new_array[$i] = $this->get_var( null, $x, $i );
  813. }
  814. return $new_array;
  815. }
  816. /**
  817. * Retrieve an entire SQL result set from the database (i.e., many rows)
  818. *
  819. * Executes a SQL query and returns the entire SQL result.
  820. *
  821. * @since 1.0
  822. *
  823. * @param string $query SQL query.
  824. * @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.
  825. * @return mixed Database query results
  826. */
  827. function get_results( $query = null, $output = OBJECT )
  828. {
  829. $this->func_call = "\$db->get_results(\"$query\", $output)";
  830. if ( $query ) {
  831. $this->query($query);
  832. } else {
  833. return null;
  834. }
  835. if ( $output == OBJECT ) {
  836. // Return an integer-keyed array of row objects
  837. return $this->last_result;
  838. } elseif ( $output == OBJECT_K || $output == ARRAY_K ) {
  839. // Return an array of row objects with keys from column 1
  840. // (Duplicates are discarded)
  841. $key = $this->col_info[0]->name;
  842. foreach ( $this->last_result as $row ) {
  843. if ( !isset( $new_array[ $row->$key ] ) ) {
  844. $new_array[ $row->$key ] = $row;
  845. }
  846. }
  847. if ( $output == ARRAY_K ) {
  848. return array_map( 'get_object_vars', $new_array );
  849. }
  850. return $new_array;
  851. } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
  852. // Return an integer-keyed array of...
  853. if ( $this->last_result ) {
  854. $i = 0;
  855. foreach( $this->last_result as $row ) {
  856. if ( $output == ARRAY_N ) {
  857. // ...integer-keyed row arrays
  858. $new_array[$i] = array_values( get_object_vars( $row ) );
  859. } else {
  860. // ...column name-keyed row arrays
  861. $new_array[$i] = get_object_vars( $row );
  862. }
  863. ++$i;
  864. }
  865. return $new_array;
  866. }
  867. }
  868. }
  869. /**
  870. * Retrieve column metadata from the last query.
  871. *
  872. * @since 1.0
  873. *
  874. * @param string $info_type one of name, table, def, max_length, not_null, primary_key, multiple_key, unique_key, numeric, blob, type, unsigned, zerofill
  875. * @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
  876. * @return mixed Column Results
  877. */
  878. function get_col_info( $info_type = 'name', $col_offset = -1 )
  879. {
  880. if ( $this->col_info ) {
  881. if ( $col_offset == -1 ) {
  882. $i = 0;
  883. foreach( (array) $this->col_info as $col ) {
  884. $new_array[$i] = $col->{$info_type};
  885. $i++;
  886. }
  887. return $new_array;
  888. } else {
  889. return $this->col_info[$col_offset]->{$info_type};
  890. }
  891. }
  892. }
  893. /**
  894. * Starts the timer, for debugging purposes.
  895. *
  896. * @since 1.0
  897. *
  898. * @return true
  899. */
  900. function timer_start()
  901. {
  902. $mtime = microtime();
  903. $mtime = explode( ' ', $mtime );
  904. $this->time_start = $mtime[1] + $mtime[0];
  905. return true;
  906. }
  907. /**
  908. * Stops the debugging timer.
  909. *
  910. * @since 1.0
  911. *
  912. * @return int Total time spent on the query, in milliseconds
  913. */
  914. function timer_stop()
  915. {
  916. $mtime = microtime();
  917. $mtime = explode( ' ', $mtime );
  918. $time_end = $mtime[1] + $mtime[0];
  919. $time_total = $time_end - $this->time_start;
  920. return $time_total;
  921. }
  922. /**
  923. * Wraps errors in a nice header and footer and dies.
  924. *
  925. * Will not die if bpdb::$show_errors is true
  926. *
  927. * @since 1.0
  928. *
  929. * @param string $message
  930. * @return false|void
  931. */
  932. function bail( $message )
  933. {
  934. if ( !$this->show_errors ) {
  935. if ( class_exists( 'WP_Error' ) )
  936. $this->error = new WP_Error( '500', $message );
  937. else
  938. $this->error = $message;
  939. return false;
  940. }
  941. backpress_die( $message );
  942. }
  943. /**
  944. * Whether or not MySQL database is at least the required minimum version.
  945. *
  946. * @since 1.0
  947. *
  948. * @return WP_Error
  949. */
  950. function check_database_version( $dbh_or_table = false )
  951. {
  952. // Make sure the server has MySQL 4.0
  953. if ( version_compare( $this->db_version( $dbh_or_table ), '4.0.0', '<' ) ) {
  954. return new WP_Error( 'database_version', BPDB__DB_VERSION_ERROR );
  955. }
  956. }
  957. /**
  958. * Whether of not the database supports collation.
  959. *
  960. * Called when BackPress is generating the table scheme.
  961. *
  962. * @since 1.0
  963. *
  964. * @return bool True if collation is supported, false if version does not
  965. */
  966. function supports_collation()
  967. {
  968. return $this->has_cap( 'collation' );
  969. }
  970. /**
  971. * Generic function to determine if a database supports a particular feature
  972. *
  973. * @since 1.0
  974. *
  975. * @param string $db_cap the feature
  976. * @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.
  977. * @return bool
  978. */
  979. function has_cap( $db_cap, $dbh_or_table = false )
  980. {
  981. $version = $this->db_version( $dbh_or_table );
  982. switch ( strtolower( $db_cap ) ) {
  983. case 'collation' :
  984. case 'group_concat' :
  985. case 'subqueries' :
  986. return version_compare( $version, '4.1', '>=' );
  987. break;
  988. case 'index_hint_for_join' :
  989. return version_compare( $version, '5.0', '>=' );
  990. break;
  991. case 'index_hint_lists' :
  992. case 'index_hint_for_any' :
  993. return version_compare( $version, '5.1', '>=' );
  994. break;
  995. }
  996. return false;
  997. }
  998. /**
  999. * The database version number
  1000. *
  1001. * @since 1.0
  1002. *
  1003. * @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.
  1004. * @return false|string false on failure, version number on success
  1005. */
  1006. function db_version( $dbh_or_table = false )
  1007. {
  1008. if ( !$dbh_or_table ) {
  1009. $dbh =& $this->dbh;
  1010. } elseif ( is_resource( $dbh_or_table ) ) {
  1011. $dbh =& $dbh_or_table;
  1012. } else {
  1013. $dbh = $this->db_connect( "DESCRIBE $dbh_or_table" );
  1014. }
  1015. if ( $dbh ) {
  1016. return preg_replace( '|[^0-9\.]|', '', mysql_get_server_info( $dbh ) );
  1017. }
  1018. return false;
  1019. }
  1020. /**
  1021. * Retrieve the name of the function that called bpdb.
  1022. *
  1023. * Requires PHP 4.3 and searches up the list of functions until it reaches
  1024. * the one that would most logically had called this method.
  1025. *
  1026. * @since 1.0
  1027. *
  1028. * @return string The name of the calling function
  1029. */
  1030. function get_caller()
  1031. {
  1032. // requires PHP 4.3+
  1033. if ( !is_callable( 'debug_backtrace' ) ) {
  1034. return '';
  1035. }
  1036. $bt = debug_backtrace();
  1037. $caller = array();
  1038. $bt = array_reverse( $bt );
  1039. foreach ( (array) $bt as $call ) {
  1040. if ( @$call['class'] == __CLASS__ ) {
  1041. continue;
  1042. }
  1043. $function = $call['function'];
  1044. if ( isset( $call['class'] ) ) {
  1045. $function = $call['class'] . "->$function";
  1046. }
  1047. $caller[] = $function;
  1048. }
  1049. $caller = join( ', ', $caller );
  1050. return $caller;
  1051. }
  1052. }