PageRenderTime 33ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/inc/ljmc-db.php

https://bitbucket.org/lpservice-it/ljmc
PHP | 3093 lines | 1511 code | 319 blank | 1263 comment | 310 complexity | 305ade9ed68b076f8458c70731a06ec2 MD5 | raw file
Possible License(s): Apache-2.0, GPL-3.0, MIT

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * system DB Class
  4. *
  5. * Original code from {@link http://php.justinvincent.com Justin Vincent (justin@visunet.ie)}
  6. *
  7. * @package system
  8. * @subpackage Database
  9. * @since 0.71
  10. */
  11. /**
  12. * @since 0.71
  13. */
  14. define( 'EZSQL_VERSION', 'LJMC1.25' );
  15. /**
  16. * @since 0.71
  17. */
  18. define( 'OBJECT', 'OBJECT' );
  19. define( 'object', 'OBJECT' ); // Back compat.
  20. /**
  21. * @since 2.5.0
  22. */
  23. define( 'OBJECT_K', 'OBJECT_K' );
  24. /**
  25. * @since 0.71
  26. */
  27. define( 'ARRAY_A', 'ARRAY_A' );
  28. /**
  29. * @since 0.71
  30. */
  31. define( 'ARRAY_N', 'ARRAY_N' );
  32. /**
  33. * system Database Access Abstraction Object
  34. *
  35. * It is possible to replace this class with your own
  36. * by setting the $ljmcdb global variable in data/db.php
  37. * file to your class. The ljmcdb class will still be included,
  38. * so you can extend it or simply use your own.
  39. *
  40. * @link localhost/Function_Reference/ljmcdb_Class
  41. *
  42. * @package system
  43. * @subpackage Database
  44. * @since 0.71
  45. */
  46. class ljmcdb {
  47. /**
  48. * Whether to show SQL/DB errors.
  49. *
  50. * Default behavior is to show errors if both LJMC_DEBUG and LJMC_DEBUG_DISPLAY
  51. * evaluated to true.
  52. *
  53. * @since 0.71
  54. * @access private
  55. * @var bool
  56. */
  57. var $show_errors = false;
  58. /**
  59. * Whether to suppress errors during the DB bootstrapping.
  60. *
  61. * @access private
  62. * @since 2.5.0
  63. * @var bool
  64. */
  65. var $suppress_errors = false;
  66. /**
  67. * The last error during query.
  68. *
  69. * @since 2.5.0
  70. * @var string
  71. */
  72. public $last_error = '';
  73. /**
  74. * Amount of queries made
  75. *
  76. * @since 1.2.0
  77. * @access private
  78. * @var int
  79. */
  80. var $num_queries = 0;
  81. /**
  82. * Count of rows returned by previous query
  83. *
  84. * @since 0.71
  85. * @access private
  86. * @var int
  87. */
  88. var $num_rows = 0;
  89. /**
  90. * Count of affected rows by previous query
  91. *
  92. * @since 0.71
  93. * @access private
  94. * @var int
  95. */
  96. var $rows_affected = 0;
  97. /**
  98. * The ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
  99. *
  100. * @since 0.71
  101. * @access public
  102. * @var int
  103. */
  104. var $insert_id = 0;
  105. /**
  106. * Last query made
  107. *
  108. * @since 0.71
  109. * @access private
  110. * @var array
  111. */
  112. var $last_query;
  113. /**
  114. * Results of the last query made
  115. *
  116. * @since 0.71
  117. * @access private
  118. * @var array|null
  119. */
  120. var $last_result;
  121. /**
  122. * MySQL result, which is either a resource or boolean.
  123. *
  124. * @since 0.71
  125. * @access protected
  126. * @var mixed
  127. */
  128. protected $result;
  129. /**
  130. * Cached column info, for sanity checking data before inserting
  131. *
  132. * @since 4.2.0
  133. * @access protected
  134. * @var array
  135. */
  136. protected $col_meta = array();
  137. /**
  138. * Calculated character sets on tables
  139. *
  140. * @since 4.2.0
  141. * @access protected
  142. * @var array
  143. */
  144. protected $table_charset = array();
  145. /**
  146. * Whether text fields in the current query need to be sanity checked.
  147. *
  148. * @since 4.2.0
  149. * @access protected
  150. * @var bool
  151. */
  152. protected $check_current_query = true;
  153. /**
  154. * Flag to ensure we don't run into recursion problems when checking the collation.
  155. *
  156. * @since 4.2.0
  157. * @access private
  158. * @see ljmcdb::check_safe_collation()
  159. * @var boolean
  160. */
  161. private $checking_collation = false;
  162. /**
  163. * Saved info on the table column
  164. *
  165. * @since 0.71
  166. * @access protected
  167. * @var array
  168. */
  169. protected $col_info;
  170. /**
  171. * Saved queries that were executed
  172. *
  173. * @since 1.5.0
  174. * @access private
  175. * @var array
  176. */
  177. var $queries;
  178. /**
  179. * The number of times to retry reconnecting before dying.
  180. *
  181. * @since 3.9.0
  182. * @access protected
  183. * @see ljmcdb::check_connection()
  184. * @var int
  185. */
  186. protected $reconnect_retries = 5;
  187. /**
  188. * system table prefix
  189. *
  190. * You can set this to have multiple system installations
  191. * in a single database. The second reason is for possible
  192. * security precautions.
  193. *
  194. * @since 2.5.0
  195. * @access private
  196. * @var string
  197. */
  198. var $prefix = '';
  199. /**
  200. * system base table prefix.
  201. *
  202. * @since 3.0.0
  203. * @access public
  204. * @var string
  205. */
  206. public $base_prefix;
  207. /**
  208. * Whether the database queries are ready to start executing.
  209. *
  210. * @since 2.3.2
  211. * @access private
  212. * @var bool
  213. */
  214. var $ready = false;
  215. /**
  216. * Blog ID.
  217. *
  218. * @since 3.0.0
  219. * @access public
  220. * @var int
  221. */
  222. public $blogid = 0;
  223. /**
  224. * Site ID.
  225. *
  226. * @since 3.0.0
  227. * @access public
  228. * @var int
  229. */
  230. public $siteid = 0;
  231. /**
  232. * List of system per-blog tables
  233. *
  234. * @since 2.5.0
  235. * @access private
  236. * @see ljmcdb::tables()
  237. * @var array
  238. */
  239. var $tables = array( 'posts', 'comments', 'links', 'options', 'postmeta',
  240. 'terms', 'term_taxonomy', 'term_relationships', 'commentmeta' );
  241. /**
  242. * List of deprecated system tables
  243. *
  244. * categories, post2cat, and link2cat were deprecated in 2.3.0, db version 5539
  245. *
  246. * @since 2.9.0
  247. * @access private
  248. * @see ljmcdb::tables()
  249. * @var array
  250. */
  251. var $old_tables = array( 'categories', 'post2cat', 'link2cat' );
  252. /**
  253. * List of system global tables
  254. *
  255. * @since 3.0.0
  256. * @access private
  257. * @see ljmcdb::tables()
  258. * @var array
  259. */
  260. var $global_tables = array( 'users', 'usermeta' );
  261. /**
  262. * List of Multisite global tables
  263. *
  264. * @since 3.0.0
  265. * @access private
  266. * @see ljmcdb::tables()
  267. * @var array
  268. */
  269. var $ms_global_tables = array( 'blogs', 'signups', 'site', 'sitemeta',
  270. 'sitecategories', 'registration_log', 'blog_versions' );
  271. /**
  272. * system Comments table
  273. *
  274. * @since 1.5.0
  275. * @access public
  276. * @var string
  277. */
  278. public $comments;
  279. /**
  280. * system Comment Metadata table
  281. *
  282. * @since 2.9.0
  283. * @access public
  284. * @var string
  285. */
  286. public $commentmeta;
  287. /**
  288. * system Links table
  289. *
  290. * @since 1.5.0
  291. * @access public
  292. * @var string
  293. */
  294. public $links;
  295. /**
  296. * system Options table
  297. *
  298. * @since 1.5.0
  299. * @access public
  300. * @var string
  301. */
  302. public $options;
  303. /**
  304. * system Post Metadata table
  305. *
  306. * @since 1.5.0
  307. * @access public
  308. * @var string
  309. */
  310. public $postmeta;
  311. /**
  312. * system Posts table
  313. *
  314. * @since 1.5.0
  315. * @access public
  316. * @var string
  317. */
  318. public $posts;
  319. /**
  320. * system Terms table
  321. *
  322. * @since 2.3.0
  323. * @access public
  324. * @var string
  325. */
  326. public $terms;
  327. /**
  328. * system Term Relationships table
  329. *
  330. * @since 2.3.0
  331. * @access public
  332. * @var string
  333. */
  334. public $term_relationships;
  335. /**
  336. * system Term Taxonomy table
  337. *
  338. * @since 2.3.0
  339. * @access public
  340. * @var string
  341. */
  342. public $term_taxonomy;
  343. /*
  344. * Global and Multisite tables
  345. */
  346. /**
  347. * system User Metadata table
  348. *
  349. * @since 2.3.0
  350. * @access public
  351. * @var string
  352. */
  353. public $usermeta;
  354. /**
  355. * system Users table
  356. *
  357. * @since 1.5.0
  358. * @access public
  359. * @var string
  360. */
  361. public $users;
  362. /**
  363. * Multisite Blogs table
  364. *
  365. * @since 3.0.0
  366. * @access public
  367. * @var string
  368. */
  369. public $blogs;
  370. /**
  371. * Multisite Blog Versions table
  372. *
  373. * @since 3.0.0
  374. * @access public
  375. * @var string
  376. */
  377. public $blog_versions;
  378. /**
  379. * Multisite Registration Log table
  380. *
  381. * @since 3.0.0
  382. * @access public
  383. * @var string
  384. */
  385. public $registration_log;
  386. /**
  387. * Multisite Signups table
  388. *
  389. * @since 3.0.0
  390. * @access public
  391. * @var string
  392. */
  393. public $signups;
  394. /**
  395. * Multisite Sites table
  396. *
  397. * @since 3.0.0
  398. * @access public
  399. * @var string
  400. */
  401. public $site;
  402. /**
  403. * Multisite Sitewide Terms table
  404. *
  405. * @since 3.0.0
  406. * @access public
  407. * @var string
  408. */
  409. public $sitecategories;
  410. /**
  411. * Multisite Site Metadata table
  412. *
  413. * @since 3.0.0
  414. * @access public
  415. * @var string
  416. */
  417. public $sitemeta;
  418. /**
  419. * Format specifiers for DB columns. Columns not listed here default to %s. Initialized during LJMC load.
  420. *
  421. * Keys are column names, values are format types: 'ID' => '%d'
  422. *
  423. * @since 2.8.0
  424. * @see ljmcdb::prepare()
  425. * @see ljmcdb::insert()
  426. * @see ljmcdb::update()
  427. * @see ljmcdb::delete()
  428. * @see ljmc_set_ljmcdb_vars()
  429. * @access public
  430. * @var array
  431. */
  432. public $field_types = array();
  433. /**
  434. * Database table columns charset
  435. *
  436. * @since 2.2.0
  437. * @access public
  438. * @var string
  439. */
  440. public $charset;
  441. /**
  442. * Database table columns collate
  443. *
  444. * @since 2.2.0
  445. * @access public
  446. * @var string
  447. */
  448. public $collate;
  449. /**
  450. * Database Username
  451. *
  452. * @since 2.9.0
  453. * @access protected
  454. * @var string
  455. */
  456. protected $dbuser;
  457. /**
  458. * Database Password
  459. *
  460. * @since 3.1.0
  461. * @access protected
  462. * @var string
  463. */
  464. protected $dbpassword;
  465. /**
  466. * Database Name
  467. *
  468. * @since 3.1.0
  469. * @access protected
  470. * @var string
  471. */
  472. protected $dbname;
  473. /**
  474. * Database Host
  475. *
  476. * @since 3.1.0
  477. * @access protected
  478. * @var string
  479. */
  480. protected $dbhost;
  481. /**
  482. * Database Handle
  483. *
  484. * @since 0.71
  485. * @access protected
  486. * @var string
  487. */
  488. protected $dbh;
  489. /**
  490. * A textual description of the last query/get_row/get_var call
  491. *
  492. * @since 3.0.0
  493. * @access public
  494. * @var string
  495. */
  496. public $func_call;
  497. /**
  498. * Whether MySQL is used as the database engine.
  499. *
  500. * Set in LJMCDB::db_connect() to true, by default. This is used when checking
  501. * against the required MySQL version for system. Normally, a replacement
  502. * database drop-in (db.php) will skip these checks, but setting this to true
  503. * will force the checks to occur.
  504. *
  505. * @since 3.3.0
  506. * @access public
  507. * @var bool
  508. */
  509. public $is_mysql = null;
  510. /**
  511. * A list of incompatible SQL modes.
  512. *
  513. * @since 3.9.0
  514. * @access protected
  515. * @var array
  516. */
  517. protected $incompatible_modes = array( 'NO_ZERO_DATE', 'ONLY_FULL_GROUP_BY',
  518. 'STRICT_TRANS_TABLES', 'STRICT_ALL_TABLES', 'TRADITIONAL' );
  519. /**
  520. * Whether to use mysqli over mysql.
  521. *
  522. * @since 3.9.0
  523. * @access private
  524. * @var bool
  525. */
  526. private $use_mysqli = false;
  527. /**
  528. * Whether we've managed to successfully connect at some point
  529. *
  530. * @since 3.9.0
  531. * @access private
  532. * @var bool
  533. */
  534. private $has_connected = false;
  535. /**
  536. * Connects to the database server and selects a database
  537. *
  538. * PHP5 style constructor for compatibility with PHP5. Does
  539. * the actual setting up of the class properties and connection
  540. * to the database.
  541. *
  542. * @link https://core.trac.localhost/ticket/3354
  543. * @since 2.0.8
  544. *
  545. * @param string $dbuser MySQL database user
  546. * @param string $dbpassword MySQL database password
  547. * @param string $dbname MySQL database name
  548. * @param string $dbhost MySQL database host
  549. */
  550. public function __construct( $dbuser, $dbpassword, $dbname, $dbhost ) {
  551. register_shutdown_function( array( $this, '__destruct' ) );
  552. if ( LJMC_DEBUG && LJMC_DEBUG_DISPLAY )
  553. $this->show_errors();
  554. /* Use ext/mysqli if it exists and:
  555. * - LJMC_USE_EXT_MYSQL is defined as false, or
  556. * - We are a development version of system, or
  557. * - We are running PHP 5.5 or greater, or
  558. * - ext/mysql is not loaded.
  559. */
  560. if ( function_exists( 'mysqli_connect' ) ) {
  561. if ( defined( 'LJMC_USE_EXT_MYSQL' ) ) {
  562. $this->use_mysqli = ! LJMC_USE_EXT_MYSQL;
  563. } elseif ( version_compare( phpversion(), '5.5', '>=' ) || ! function_exists( 'mysql_connect' ) ) {
  564. $this->use_mysqli = true;
  565. } elseif ( false !== strpos( $GLOBALS['ljmc_version'], '-' ) ) {
  566. $this->use_mysqli = true;
  567. }
  568. }
  569. $this->dbuser = $dbuser;
  570. $this->dbpassword = $dbpassword;
  571. $this->dbname = $dbname;
  572. $this->dbhost = $dbhost;
  573. // configuration.php creation will manually connect when ready.
  574. if ( defined( 'LJMC_SETUP_CONFIG' ) ) {
  575. return;
  576. }
  577. $this->db_connect();
  578. }
  579. /**
  580. * PHP5 style destructor and will run when database object is destroyed.
  581. *
  582. * @see ljmcdb::__construct()
  583. * @since 2.0.8
  584. * @return bool true
  585. */
  586. public function __destruct() {
  587. return true;
  588. }
  589. /**
  590. * PHP5 style magic getter, used to lazy-load expensive data.
  591. *
  592. * @since 3.5.0
  593. *
  594. * @param string $name The private member to get, and optionally process
  595. * @return mixed The private member
  596. */
  597. public function __get( $name ) {
  598. if ( 'col_info' === $name )
  599. $this->load_col_info();
  600. return $this->$name;
  601. }
  602. /**
  603. * Magic function, for backwards compatibility.
  604. *
  605. * @since 3.5.0
  606. *
  607. * @param string $name The private member to set
  608. * @param mixed $value The value to set
  609. */
  610. public function __set( $name, $value ) {
  611. $protected_members = array(
  612. 'col_meta',
  613. 'table_charset',
  614. 'check_current_query',
  615. );
  616. if ( in_array( $name, $protected_members, true ) ) {
  617. return;
  618. }
  619. $this->$name = $value;
  620. }
  621. /**
  622. * Magic function, for backwards compatibility.
  623. *
  624. * @since 3.5.0
  625. *
  626. * @param string $name The private member to check
  627. *
  628. * @return bool If the member is set or not
  629. */
  630. public function __isset( $name ) {
  631. return isset( $this->$name );
  632. }
  633. /**
  634. * Magic function, for backwards compatibility.
  635. *
  636. * @since 3.5.0
  637. *
  638. * @param string $name The private member to unset
  639. */
  640. public function __unset( $name ) {
  641. unset( $this->$name );
  642. }
  643. /**
  644. * Set $this->charset and $this->collate
  645. *
  646. * @since 3.1.0
  647. */
  648. public function init_charset() {
  649. if ( function_exists('is_multisite') && is_multisite() ) {
  650. $this->charset = 'utf8';
  651. if ( defined( 'DB_COLLATE' ) && DB_COLLATE ) {
  652. $this->collate = DB_COLLATE;
  653. } else {
  654. $this->collate = 'utf8_general_ci';
  655. }
  656. } elseif ( defined( 'DB_COLLATE' ) ) {
  657. $this->collate = DB_COLLATE;
  658. }
  659. if ( defined( 'DB_CHARSET' ) ) {
  660. $this->charset = DB_CHARSET;
  661. }
  662. if ( ( $this->use_mysqli && ! ( $this->dbh instanceof mysqli ) ) || empty( $this->dbh ) ) {
  663. return;
  664. }
  665. if ( 'utf8' === $this->charset && $this->has_cap( 'utf8mb4' ) ) {
  666. $this->charset = 'utf8mb4';
  667. }
  668. if ( 'utf8mb4' === $this->charset && ( ! $this->collate || stripos( $this->collate, 'utf8_' ) === 0 ) ) {
  669. $this->collate = 'utf8mb4_unicode_ci';
  670. }
  671. }
  672. /**
  673. * Sets the connection's character set.
  674. *
  675. * @since 3.1.0
  676. *
  677. * @param resource $dbh The resource given by mysql_connect
  678. * @param string $charset Optional. The character set. Default null.
  679. * @param string $collate Optional. The collation. Default null.
  680. */
  681. public function set_charset( $dbh, $charset = null, $collate = null ) {
  682. if ( ! isset( $charset ) )
  683. $charset = $this->charset;
  684. if ( ! isset( $collate ) )
  685. $collate = $this->collate;
  686. if ( $this->has_cap( 'collation' ) && ! empty( $charset ) ) {
  687. if ( $this->use_mysqli ) {
  688. if ( function_exists( 'mysqli_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
  689. mysqli_set_charset( $dbh, $charset );
  690. } else {
  691. $query = $this->prepare( 'SET NAMES %s', $charset );
  692. if ( ! empty( $collate ) )
  693. $query .= $this->prepare( ' COLLATE %s', $collate );
  694. mysqli_query( $dbh, $query );
  695. }
  696. } else {
  697. if ( function_exists( 'mysql_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
  698. mysql_set_charset( $charset, $dbh );
  699. } else {
  700. $query = $this->prepare( 'SET NAMES %s', $charset );
  701. if ( ! empty( $collate ) )
  702. $query .= $this->prepare( ' COLLATE %s', $collate );
  703. mysql_query( $query, $dbh );
  704. }
  705. }
  706. }
  707. }
  708. /**
  709. * Change the current SQL mode, and ensure its system compatibility.
  710. *
  711. * If no modes are passed, it will ensure the current MySQL server
  712. * modes are compatible.
  713. *
  714. * @since 3.9.0
  715. *
  716. * @param array $modes Optional. A list of SQL modes to set.
  717. */
  718. public function set_sql_mode( $modes = array() ) {
  719. if ( empty( $modes ) ) {
  720. if ( $this->use_mysqli ) {
  721. $res = mysqli_query( $this->dbh, 'SELECT @@SESSION.sql_mode' );
  722. } else {
  723. $res = mysql_query( 'SELECT @@SESSION.sql_mode', $this->dbh );
  724. }
  725. if ( empty( $res ) ) {
  726. return;
  727. }
  728. if ( $this->use_mysqli ) {
  729. $modes_array = mysqli_fetch_array( $res );
  730. if ( empty( $modes_array[0] ) ) {
  731. return;
  732. }
  733. $modes_str = $modes_array[0];
  734. } else {
  735. $modes_str = mysql_result( $res, 0 );
  736. }
  737. if ( empty( $modes_str ) ) {
  738. return;
  739. }
  740. $modes = explode( ',', $modes_str );
  741. }
  742. $modes = array_change_key_case( $modes, CASE_UPPER );
  743. /**
  744. * Filter the list of incompatible SQL modes to exclude.
  745. *
  746. * @since 3.9.0
  747. *
  748. * @param array $incompatible_modes An array of incompatible modes.
  749. */
  750. $incompatible_modes = (array) apply_filters( 'incompatible_sql_modes', $this->incompatible_modes );
  751. foreach( $modes as $i => $mode ) {
  752. if ( in_array( $mode, $incompatible_modes ) ) {
  753. unset( $modes[ $i ] );
  754. }
  755. }
  756. $modes_str = implode( ',', $modes );
  757. if ( $this->use_mysqli ) {
  758. mysqli_query( $this->dbh, "SET SESSION sql_mode='$modes_str'" );
  759. } else {
  760. mysql_query( "SET SESSION sql_mode='$modes_str'", $this->dbh );
  761. }
  762. }
  763. /**
  764. * Sets the table prefix for the system tables.
  765. *
  766. * @since 2.5.0
  767. *
  768. * @param string $prefix Alphanumeric name for the new prefix.
  769. * @param bool $set_table_names Optional. Whether the table names, e.g. ljmcdb::$posts, should be updated or not.
  770. * @return string|LJMC_Error Old prefix or LJMC_Error on error
  771. */
  772. public function set_prefix( $prefix, $set_table_names = true ) {
  773. if ( preg_match( '|[^a-z0-9_]|i', $prefix ) )
  774. return new LJMC_Error('invalid_db_prefix', 'Invalid database prefix' );
  775. $old_prefix = is_multisite() ? '' : $prefix;
  776. if ( isset( $this->base_prefix ) )
  777. $old_prefix = $this->base_prefix;
  778. $this->base_prefix = $prefix;
  779. if ( $set_table_names ) {
  780. foreach ( $this->tables( 'global' ) as $table => $prefixed_table )
  781. $this->$table = $prefixed_table;
  782. if ( is_multisite() && empty( $this->blogid ) )
  783. return $old_prefix;
  784. $this->prefix = $this->get_blog_prefix();
  785. foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
  786. $this->$table = $prefixed_table;
  787. foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
  788. $this->$table = $prefixed_table;
  789. }
  790. return $old_prefix;
  791. }
  792. /**
  793. * Sets blog id.
  794. *
  795. * @since 3.0.0
  796. * @access public
  797. * @param int $blog_id
  798. * @param int $site_id Optional.
  799. * @return int previous blog id
  800. */
  801. public function set_blog_id( $blog_id, $site_id = 0 ) {
  802. if ( ! empty( $site_id ) )
  803. $this->siteid = $site_id;
  804. $old_blog_id = $this->blogid;
  805. $this->blogid = $blog_id;
  806. $this->prefix = $this->get_blog_prefix();
  807. foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
  808. $this->$table = $prefixed_table;
  809. foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
  810. $this->$table = $prefixed_table;
  811. return $old_blog_id;
  812. }
  813. /**
  814. * Gets blog prefix.
  815. *
  816. * @since 3.0.0
  817. * @param int $blog_id Optional.
  818. * @return string Blog prefix.
  819. */
  820. public function get_blog_prefix( $blog_id = null ) {
  821. if ( is_multisite() ) {
  822. if ( null === $blog_id )
  823. $blog_id = $this->blogid;
  824. $blog_id = (int) $blog_id;
  825. if ( defined( 'MULTISITE' ) && ( 0 == $blog_id || 1 == $blog_id ) )
  826. return $this->base_prefix;
  827. else
  828. return $this->base_prefix . $blog_id . '_';
  829. } else {
  830. return $this->base_prefix;
  831. }
  832. }
  833. /**
  834. * Returns an array of system tables.
  835. *
  836. * Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to
  837. * override the system users and usermeta tables that would otherwise
  838. * be determined by the prefix.
  839. *
  840. * The scope argument can take one of the following:
  841. *
  842. * 'all' - returns 'all' and 'global' tables. No old tables are returned.
  843. * 'blog' - returns the blog-level tables for the queried blog.
  844. * 'global' - returns the global tables for the installation, returning multisite tables only if running multisite.
  845. * 'ms_global' - returns the multisite global tables, regardless if current installation is multisite.
  846. * 'old' - returns tables which are deprecated.
  847. *
  848. * @since 3.0.0
  849. * @uses ljmcdb::$tables
  850. * @uses ljmcdb::$old_tables
  851. * @uses ljmcdb::$global_tables
  852. * @uses ljmcdb::$ms_global_tables
  853. *
  854. * @param string $scope Optional. Can be all, global, ms_global, blog, or old tables. Defaults to all.
  855. * @param bool $prefix Optional. Whether to include table prefixes. Default true. If blog
  856. * prefix is requested, then the custom users and usermeta tables will be mapped.
  857. * @param int $blog_id Optional. The blog_id to prefix. Defaults to ljmcdb::$blogid. Used only when prefix is requested.
  858. * @return array Table names. When a prefix is requested, the key is the unprefixed table name.
  859. */
  860. public function tables( $scope = 'all', $prefix = true, $blog_id = 0 ) {
  861. switch ( $scope ) {
  862. case 'all' :
  863. $tables = array_merge( $this->global_tables, $this->tables );
  864. if ( is_multisite() )
  865. $tables = array_merge( $tables, $this->ms_global_tables );
  866. break;
  867. case 'blog' :
  868. $tables = $this->tables;
  869. break;
  870. case 'global' :
  871. $tables = $this->global_tables;
  872. if ( is_multisite() )
  873. $tables = array_merge( $tables, $this->ms_global_tables );
  874. break;
  875. case 'ms_global' :
  876. $tables = $this->ms_global_tables;
  877. break;
  878. case 'old' :
  879. $tables = $this->old_tables;
  880. break;
  881. default :
  882. return array();
  883. }
  884. if ( $prefix ) {
  885. if ( ! $blog_id )
  886. $blog_id = $this->blogid;
  887. $blog_prefix = $this->get_blog_prefix( $blog_id );
  888. $base_prefix = $this->base_prefix;
  889. $global_tables = array_merge( $this->global_tables, $this->ms_global_tables );
  890. foreach ( $tables as $k => $table ) {
  891. if ( in_array( $table, $global_tables ) )
  892. $tables[ $table ] = $base_prefix . $table;
  893. else
  894. $tables[ $table ] = $blog_prefix . $table;
  895. unset( $tables[ $k ] );
  896. }
  897. if ( isset( $tables['users'] ) && defined( 'CUSTOM_USER_TABLE' ) )
  898. $tables['users'] = CUSTOM_USER_TABLE;
  899. if ( isset( $tables['usermeta'] ) && defined( 'CUSTOM_USER_META_TABLE' ) )
  900. $tables['usermeta'] = CUSTOM_USER_META_TABLE;
  901. }
  902. return $tables;
  903. }
  904. /**
  905. * Selects a database using the current database connection.
  906. *
  907. * The database name will be changed based on the current database
  908. * connection. On failure, the execution will bail and display an DB error.
  909. *
  910. * @since 0.71
  911. *
  912. * @param string $db MySQL database name
  913. * @param resource $dbh Optional link identifier.
  914. * @return null Always null.
  915. */
  916. public function select( $db, $dbh = null ) {
  917. if ( is_null($dbh) )
  918. $dbh = $this->dbh;
  919. if ( $this->use_mysqli ) {
  920. $success = @mysqli_select_db( $dbh, $db );
  921. } else {
  922. $success = @mysql_select_db( $db, $dbh );
  923. }
  924. if ( ! $success ) {
  925. $this->ready = false;
  926. if ( ! did_action( 'template_redirect' ) ) {
  927. ljmc_load_translations_early();
  928. $this->bail( sprintf( __( '<h1>Can&#8217;t select database</h1>
  929. <p>We were able to connect to the database server (which means your username and password is okay) but not able to select the <code>%1$s</code> database.</p>
  930. <ul>
  931. <li>Are you sure it exists?</li>
  932. <li>Does the user <code>%2$s</code> have permission to use the <code>%1$s</code> database?</li>
  933. <li>On some systems the name of your database is prefixed with your username, so it would be like <code>username_%1$s</code>. Could that be the problem?</li>
  934. </ul>
  935. <p>If you don\'t know how to set up a database you should <strong>contact your host</strong>. If all else fails you may find help at the <a href="localhost/support/">system Support Forums</a>.</p>' ), htmlspecialchars( $db, ENT_QUOTES ), htmlspecialchars( $this->dbuser, ENT_QUOTES ) ), 'db_select_fail' );
  936. }
  937. return;
  938. }
  939. }
  940. /**
  941. * Do not use, deprecated.
  942. *
  943. * Use esc_sql() or ljmcdb::prepare() instead.
  944. *
  945. * @since 2.8.0
  946. * @deprecated 3.6.0
  947. * @see ljmcdb::prepare
  948. * @see esc_sql()
  949. * @access private
  950. *
  951. * @param string $string
  952. * @return string
  953. */
  954. function _weak_escape( $string ) {
  955. if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) )
  956. _deprecated_function( __METHOD__, '3.6', 'ljmcdb::prepare() or esc_sql()' );
  957. return addslashes( $string );
  958. }
  959. /**
  960. * Real escape, using mysqli_real_escape_string() or mysql_real_escape_string()
  961. *
  962. * @see mysqli_real_escape_string()
  963. * @see mysql_real_escape_string()
  964. * @since 2.8.0
  965. * @access private
  966. *
  967. * @param string $string to escape
  968. * @return string escaped
  969. */
  970. function _real_escape( $string ) {
  971. if ( $this->dbh ) {
  972. if ( $this->use_mysqli ) {
  973. return mysqli_real_escape_string( $this->dbh, $string );
  974. } else {
  975. return mysql_real_escape_string( $string, $this->dbh );
  976. }
  977. }
  978. $class = get_class( $this );
  979. if ( function_exists( '__' ) ) {
  980. _doing_it_wrong( $class, sprintf( __( '%s must set a database connection for use with escaping.' ), $class ), E_USER_NOTICE );
  981. } else {
  982. _doing_it_wrong( $class, sprintf( '%s must set a database connection for use with escaping.', $class ), E_USER_NOTICE );
  983. }
  984. return addslashes( $string );
  985. }
  986. /**
  987. * Escape data. Works on arrays.
  988. *
  989. * @uses ljmcdb::_real_escape()
  990. * @since 2.8.0
  991. * @access private
  992. *
  993. * @param string|array $data
  994. * @return string|array escaped
  995. */
  996. function _escape( $data ) {
  997. if ( is_array( $data ) ) {
  998. foreach ( $data as $k => $v ) {
  999. if ( is_array($v) )
  1000. $data[$k] = $this->_escape( $v );
  1001. else
  1002. $data[$k] = $this->_real_escape( $v );
  1003. }
  1004. } else {
  1005. $data = $this->_real_escape( $data );
  1006. }
  1007. return $data;
  1008. }
  1009. /**
  1010. * Do not use, deprecated.
  1011. *
  1012. * Use esc_sql() or ljmcdb::prepare() instead.
  1013. *
  1014. * @since 0.71
  1015. * @deprecated 3.6.0
  1016. * @see ljmcdb::prepare()
  1017. * @see esc_sql()
  1018. *
  1019. * @param mixed $data
  1020. * @return mixed
  1021. */
  1022. public function escape( $data ) {
  1023. if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) )
  1024. _deprecated_function( __METHOD__, '3.6', 'ljmcdb::prepare() or esc_sql()' );
  1025. if ( is_array( $data ) ) {
  1026. foreach ( $data as $k => $v ) {
  1027. if ( is_array( $v ) )
  1028. $data[$k] = $this->escape( $v, 'recursive' );
  1029. else
  1030. $data[$k] = $this->_weak_escape( $v, 'internal' );
  1031. }
  1032. } else {
  1033. $data = $this->_weak_escape( $data, 'internal' );
  1034. }
  1035. return $data;
  1036. }
  1037. /**
  1038. * Escapes content by reference for insertion into the database, for security
  1039. *
  1040. * @uses ljmcdb::_real_escape()
  1041. * @since 2.3.0
  1042. * @param string $string to escape
  1043. * @return void
  1044. */
  1045. public function escape_by_ref( &$string ) {
  1046. if ( ! is_float( $string ) )
  1047. $string = $this->_real_escape( $string );
  1048. }
  1049. /**
  1050. * Prepares a SQL query for safe execution. Uses sprintf()-like syntax.
  1051. *
  1052. * The following directives can be used in the query format string:
  1053. * %d (integer)
  1054. * %f (float)
  1055. * %s (string)
  1056. * %% (literal percentage sign - no argument needed)
  1057. *
  1058. * All of %d, %f, and %s are to be left unquoted in the query string and they need an argument passed for them.
  1059. * Literals (%) as parts of the query must be properly written as %%.
  1060. *
  1061. * This function only supports a small subset of the sprintf syntax; it only supports %d (integer), %f (float), and %s (string).
  1062. * Does not support sign, padding, alignment, width or precision specifiers.
  1063. * Does not support argument numbering/swapping.
  1064. *
  1065. * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}.
  1066. *
  1067. * Both %d and %s should be left unquoted in the query string.
  1068. *
  1069. * ljmcdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 )
  1070. * ljmcdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
  1071. *
  1072. * @link http://php.net/sprintf Description of syntax.
  1073. * @since 2.3.0
  1074. *
  1075. * @param string $query Query statement with sprintf()-like placeholders
  1076. * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like
  1077. * {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if
  1078. * being called like {@link http://php.net/sprintf sprintf()}.
  1079. * @param mixed $args,... further variables to substitute into the query's placeholders if being called like
  1080. * {@link http://php.net/sprintf sprintf()}.
  1081. * @return null|false|string Sanitized query string, null if there is no query, false if there is an error and string
  1082. * if there was something to prepare
  1083. */
  1084. public function prepare( $query, $args ) {
  1085. if ( is_null( $query ) )
  1086. return;
  1087. // This is not meant to be foolproof -- but it will catch obviously incorrect usage.
  1088. if ( strpos( $query, '%' ) === false ) {
  1089. _doing_it_wrong( 'ljmcdb::prepare', sprintf( __( 'The query argument of %s must have a placeholder.' ), 'ljmcdb::prepare()' ), '3.9' );
  1090. }
  1091. $args = func_get_args();
  1092. array_shift( $args );
  1093. // If args were passed as an array (as in vsprintf), move them up
  1094. if ( isset( $args[0] ) && is_array($args[0]) )
  1095. $args = $args[0];
  1096. $query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it
  1097. $query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
  1098. $query = preg_replace( '|(?<!%)%f|' , '%F', $query ); // Force floats to be locale unaware
  1099. $query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
  1100. array_walk( $args, array( $this, 'escape_by_ref' ) );
  1101. return @vsprintf( $query, $args );
  1102. }
  1103. /**
  1104. * First half of escaping for LIKE special characters % and _ before preparing for MySQL.
  1105. *
  1106. * Use this only before ljmcdb::prepare() or esc_sql(). Reversing the order is very bad for security.
  1107. *
  1108. * Example Prepared Statement:
  1109. * $wild = '%';
  1110. * $find = 'only 43% of planets';
  1111. * $like = $wild . $ljmcdb->esc_like( $find ) . $wild;
  1112. * $sql = $ljmcdb->prepare( "SELECT * FROM $ljmcdb->posts WHERE post_content LIKE %s", $like );
  1113. *
  1114. * Example Escape Chain:
  1115. * $sql = esc_sql( $ljmcdb->esc_like( $input ) );
  1116. *
  1117. * @since 4.0.0
  1118. * @access public
  1119. *
  1120. * @param string $text The raw text to be escaped. The input typed by the user should have no
  1121. * extra or deleted slashes.
  1122. * @return string Text in the form of a LIKE phrase. The output is not SQL safe. Call $ljmcdb::prepare()
  1123. * or real_escape next.
  1124. */
  1125. public function esc_like( $text ) {
  1126. return addcslashes( $text, '_%\\' );
  1127. }
  1128. /**
  1129. * Print SQL/DB error.
  1130. *
  1131. * @since 0.71
  1132. * @global array $EZSQL_ERROR Stores error information of query and error string
  1133. *
  1134. * @param string $str The error to display
  1135. * @return false|null False if the showing of errors is disabled.
  1136. */
  1137. public function print_error( $str = '' ) {
  1138. global $EZSQL_ERROR;
  1139. if ( !$str ) {
  1140. if ( $this->use_mysqli ) {
  1141. $str = mysqli_error( $this->dbh );
  1142. } else {
  1143. $str = mysql_error( $this->dbh );
  1144. }
  1145. }
  1146. $EZSQL_ERROR[] = array( 'query' => $this->last_query, 'error_str' => $str );
  1147. if ( $this->suppress_errors )
  1148. return false;
  1149. ljmc_load_translations_early();
  1150. if ( $caller = $this->get_caller() )
  1151. $error_str = sprintf( __( 'system database error %1$s for query %2$s made by %3$s' ), $str, $this->last_query, $caller );
  1152. else
  1153. $error_str = sprintf( __( 'system database error %1$s for query %2$s' ), $str, $this->last_query );
  1154. error_log( $error_str );
  1155. // Are we showing errors?
  1156. if ( ! $this->show_errors )
  1157. return false;
  1158. // If there is an error then take note of it
  1159. if ( is_multisite() ) {
  1160. $msg = "system database error: [$str]\n{$this->last_query}\n";
  1161. if ( defined( 'ERRORLOGFILE' ) )
  1162. error_log( $msg, 3, ERRORLOGFILE );
  1163. if ( defined( 'DIEONDBERROR' ) )
  1164. ljmc_die( $msg );
  1165. } else {
  1166. $str = htmlspecialchars( $str, ENT_QUOTES );
  1167. $query = htmlspecialchars( $this->last_query, ENT_QUOTES );
  1168. print "<div id='error'>
  1169. <p class='ljmcdberror'><strong>System database error:</strong> [$str]<br />
  1170. <code>$query</code></p>
  1171. </div>";
  1172. }
  1173. }
  1174. /**
  1175. * Enables showing of database errors.
  1176. *
  1177. * This function should be used only to enable showing of errors.
  1178. * ljmcdb::hide_errors() should be used instead for hiding of errors. However,
  1179. * this function can be used to enable and disable showing of database
  1180. * errors.
  1181. *
  1182. * @since 0.71
  1183. * @see ljmcdb::hide_errors()
  1184. *
  1185. * @param bool $show Whether to show or hide errors
  1186. * @return bool Old value for showing errors.
  1187. */
  1188. public function show_errors( $show = true ) {
  1189. $errors = $this->show_errors;
  1190. $this->show_errors = $show;
  1191. return $errors;
  1192. }
  1193. /**
  1194. * Disables showing of database errors.
  1195. *
  1196. * By default database errors are not shown.
  1197. *
  1198. * @since 0.71
  1199. * @see ljmcdb::show_errors()
  1200. *
  1201. * @return bool Whether showing of errors was active
  1202. */
  1203. public function hide_errors() {
  1204. $show = $this->show_errors;
  1205. $this->show_errors = false;
  1206. return $show;
  1207. }
  1208. /**
  1209. * Whether to suppress database errors.
  1210. *
  1211. * By default database errors are suppressed, with a simple
  1212. * call to this function they can be enabled.
  1213. *
  1214. * @since 2.5.0
  1215. * @see ljmcdb::hide_errors()
  1216. * @param bool $suppress Optional. New value. Defaults to true.
  1217. * @return bool Old value
  1218. */
  1219. public function suppress_errors( $suppress = true ) {
  1220. $errors = $this->suppress_errors;
  1221. $this->suppress_errors = (bool) $suppress;
  1222. return $errors;
  1223. }
  1224. /**
  1225. * Kill cached query results.
  1226. *
  1227. * @since 0.71
  1228. * @return void
  1229. */
  1230. public function flush() {
  1231. $this->last_result = array();
  1232. $this->col_info = null;
  1233. $this->last_query = null;
  1234. $this->rows_affected = $this->num_rows = 0;
  1235. $this->last_error = '';
  1236. if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
  1237. mysqli_free_result( $this->result );
  1238. $this->result = null;
  1239. // Sanity check before using the handle
  1240. if ( empty( $this->dbh ) || !( $this->dbh instanceof mysqli ) ) {
  1241. return;
  1242. }
  1243. // Clear out any results from a multi-query
  1244. while ( mysqli_more_results( $this->dbh ) ) {
  1245. mysqli_next_result( $this->dbh );
  1246. }
  1247. } elseif ( is_resource( $this->result ) ) {
  1248. mysql_free_result( $this->result );
  1249. }
  1250. }
  1251. /**
  1252. * Connect to and select database.
  1253. *
  1254. * If $allow_bail is false, the lack of database connection will need
  1255. * to be handled manually.
  1256. *
  1257. * @since 3.0.0
  1258. * @since 3.9.0 $allow_bail parameter added.
  1259. *
  1260. * @param bool $allow_bail Optional. Allows the function to bail. Default true.
  1261. * @return null|bool True with a successful connection, false on failure.
  1262. */
  1263. public function db_connect( $allow_bail = true ) {
  1264. $this->is_mysql = true;
  1265. /*
  1266. * Deprecated in 3.9+ when using MySQLi. No equivalent
  1267. * $new_link parameter exists for mysqli_* functions.
  1268. */
  1269. $new_link = defined( 'MYSQL_NEW_LINK' ) ? MYSQL_NEW_LINK : true;
  1270. $client_flags = defined( 'MYSQL_CLIENT_FLAGS' ) ? MYSQL_CLIENT_FLAGS : 0;
  1271. if ( $this->use_mysqli ) {
  1272. $this->dbh = mysqli_init();
  1273. // mysqli_real_connect doesn't support the host param including a port or socket
  1274. // like mysql_connect does. This duplicates how mysql_connect detects a port and/or socket file.
  1275. $port = null;
  1276. $socket = null;
  1277. $host = $this->dbhost;
  1278. $port_or_socket = strstr( $host, ':' );
  1279. if ( ! empty( $port_or_socket ) ) {
  1280. $host = substr( $host, 0, strpos( $host, ':' ) );
  1281. $port_or_socket = substr( $port_or_socket, 1 );
  1282. if ( 0 !== strpos( $port_or_socket, '/' ) ) {
  1283. $port = intval( $port_or_socket );
  1284. $maybe_socket = strstr( $port_or_socket, ':' );
  1285. if ( ! empty( $maybe_socket ) ) {
  1286. $socket = substr( $maybe_socket, 1 );
  1287. }
  1288. } else {
  1289. $socket = $port_or_socket;
  1290. }
  1291. }
  1292. if ( LJMC_DEBUG ) {
  1293. mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
  1294. } else {
  1295. @mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
  1296. }
  1297. if ( $this->dbh->connect_errno ) {
  1298. $this->dbh = null;
  1299. /* It's possible ext/mysqli is misconfigured. Fall back to ext/mysql if:
  1300. * - We haven't previously connected, and
  1301. * - LJMC_USE_EXT_MYSQL isn't set to false, and
  1302. * - ext/mysql is loaded.
  1303. */
  1304. $attempt_fallback = true;
  1305. if ( $this->has_connected ) {
  1306. $attempt_fallback = false;
  1307. } elseif ( defined( 'LJMC_USE_EXT_MYSQL' ) && ! LJMC_USE_EXT_MYSQL ) {
  1308. $attempt_fallback = false;
  1309. } elseif ( ! function_exists( 'mysql_connect' ) ) {
  1310. $attempt_fallback = false;
  1311. }
  1312. if ( $attempt_fallback ) {
  1313. $this->use_mysqli = false;
  1314. $this->db_connect();
  1315. }
  1316. }
  1317. } else {
  1318. if ( LJMC_DEBUG ) {
  1319. $this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
  1320. } else {
  1321. $this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
  1322. }
  1323. }
  1324. if ( ! $this->dbh && $allow_bail ) {
  1325. ljmc_load_translations_early();
  1326. // Load custom DB error template, if present.
  1327. if ( file_exists( LJMC_CONTENT_DIR . '/db-error.php' ) ) {
  1328. require_once( LJMC_CONTENT_DIR . '/db-error.php' );
  1329. die();
  1330. }
  1331. $this->bail( sprintf( __( "
  1332. <h1>Error establishing a database connection</h1>
  1333. <p>This either means that the username and password information in your <code>configuration.php</code> file is incorrect or we can't contact the database server at <code>%s</code>. This could mean your host's database server is down.</p>
  1334. <ul>
  1335. <li>Are you sure you have the correct username and password?</li>
  1336. <li>Are you sure that you have typed the correct hostname?</li>
  1337. <li>Are you sure that the database server is running?</li>
  1338. </ul>
  1339. <p>If you're unsure what these terms mean you should probably contact your host. If you still need help you can always visit the <a href='localhost/support/'>system Support Forums</a>.</p>
  1340. " ), htmlspecialchars( $this->dbhost, ENT_QUOTES ) ), 'db_connect_fail' );
  1341. return false;
  1342. } elseif ( $this->dbh ) {
  1343. if ( ! $this->has_connected ) {
  1344. $this->init_charset();
  1345. }
  1346. $this->has_connected = true;
  1347. $this->set_charset( $this->dbh );
  1348. $this->ready = true;
  1349. $this->set_sql_mode();
  1350. $this->select( $this->dbname, $this->dbh );
  1351. return true;
  1352. }
  1353. return false;
  1354. }
  1355. /**
  1356. * Check that the connection to the database is still up. If not, try to reconnect.
  1357. *
  1358. * If this function is unable to reconnect, it will forcibly die, or if after the
  1359. * the template_redirect hook has been fired, return false instead.
  1360. *
  1361. * If $allow_bail is false, the lack of database connection will need
  1362. * to be handled manually.
  1363. *
  1364. * @since 3.9.0
  1365. *
  1366. * @param bool $allow_bail Optional. Allows the function to bail. Default true.
  1367. * @return bool|null True if the connection is up.
  1368. */
  1369. public function check_connection( $allow_bail = true ) {
  1370. if ( $this->use_mysqli ) {
  1371. if ( @mysqli_ping( $this->dbh ) ) {
  1372. return true;
  1373. }
  1374. } else {
  1375. if ( @mysql_ping( $this->dbh ) ) {
  1376. return true;
  1377. }
  1378. }
  1379. $error_reporting = false;
  1380. // Disable warnings, as we don't want to see a multitude of "unable to connect" messages
  1381. if ( LJMC_DEBUG ) {
  1382. $error_reporting = error_reporting();
  1383. error_reporting( $error_reporting & ~E_WARNING );
  1384. }
  1385. for ( $tries = 1; $tries <= $this->reconnect_retries; $tries++ ) {
  1386. // On the last try, re-enable warnings. We want to see a single instance of the
  1387. // "unable to connect" message on the bail() screen, if it appears.
  1388. if ( $this->reconnect_retries === $tries && LJMC_DEBUG ) {
  1389. error_reporting( $error_reporting );
  1390. }
  1391. if ( $this->db_connect( false ) ) {
  1392. if ( $error_reporting ) {
  1393. error_reporting( $error_reporting );
  1394. }
  1395. return true;
  1396. }
  1397. sleep( 1 );
  1398. }
  1399. // If template_redirect has already happened, it's too late for ljmc_die()/dead_db().
  1400. // Let's just return and hope for the best.
  1401. if ( did_action( 'template_redirect' ) ) {
  1402. return false;
  1403. }
  1404. if ( ! $allow_bail ) {
  1405. return false;
  1406. }
  1407. // We weren't able to reconnect, so we better bail.
  1408. $this->bail( sprintf( ( "
  1409. <h1>Error reconnecting to the database</h1>
  1410. <p>This means that we lost contact with the database server at <code>%s</code>. This could mean your host's database server is down.</p>
  1411. <ul>
  1412. <li>Are you sure that the database server is running?</li>
  1413. <li>Are you sure that the database server is not under particularly heavy load?</li>
  1414. </ul>
  1415. <p>If you're unsure what these terms mean you should probably contact your host. If you still need help you can always visit the <a href='localhost/support/'>system Support Forums</a>.</p>
  1416. " ), htmlspecialchars( $this->dbhost, ENT_QUOTES ) ), 'db_connect_fail' );
  1417. // Call dead_db() if bail didn't die, because this database is no more. It has ceased to be (at least temporarily).
  1418. dead_db();
  1419. }
  1420. /**
  1421. * Perform a MySQL database query, using current database connection.
  1422. *
  1423. * More information can be found on the system page.
  1424. *
  1425. * @since 0.71
  1426. *
  1427. * @param string $query Database query
  1428. * @return int|false Number of rows affected/selected or false on error
  1429. */
  1430. public function query( $query ) {
  1431. if ( ! $this->ready ) {
  1432. $this->check_current_query = true;
  1433. return false;
  1434. }
  1435. /**
  1436. * Filter the database query.
  1437. *
  1438. * Some queries are made before the plugins have been loaded,
  1439. * and thus cannot be filtered with this method.
  1440. *
  1441. * @since 2.1.0
  1442. *
  1443. * @param string $query Database query.
  1444. */
  1445. $query = apply_filters( 'query', $query );
  1446. $this->flush();
  1447. // Log how the function was called
  1448. $this->func_call = "\$db->query(\"$query\")";
  1449. // If we're writing to the database, make sure the query will write safely.
  1450. if ( $this->check_current_query && ! $this->check_ascii( $query ) ) {
  1451. $stripped_query = $this->strip_invalid_text_from_query( $query );
  1452. // strip_invalid_text_from_query() can perform queries, so we need
  1453. // to flush again, just to make sure everything is clear.
  1454. $this->flush();
  1455. if ( $stripped_query !== $query ) {
  1456. $this->insert_id = 0;
  1457. return false;
  1458. }
  1459. }
  1460. $this->check_current_query = true;
  1461. // Keep track of the last query for debug..
  1462. $this->last_query = $query;
  1463. $this->_do_query( $query );
  1464. // MySQL server has gone away, try to reconnect
  1465. $mysql_errno = 0;
  1466. if ( ! empty( $this->dbh ) ) {
  1467. if ( $this->use_mysqli ) {
  1468. $mysql_errno = mysqli_errno( $this->dbh );
  1469. } else {
  1470. $mysql_errno = mysql_errno( $this->dbh );
  1471. }
  1472. }
  1473. if ( empty( $this->dbh ) || 2006 == $mysql_errno ) {
  1474. if ( $this->check_connection() ) {
  1475. $this->_do_query( $query );
  1476. } else {
  1477. $this->insert_id = 0;
  1478. return false;
  1479. }
  1480. }
  1481. // If there is an error then take note of it..
  1482. if ( $this->use_mysqli ) {
  1483. $this->last_error = mysqli_error( $this->dbh );
  1484. } else {
  1485. $this->last_error = mysql_error( $this->dbh );
  1486. }
  1487. if ( $this->last_error ) {
  1488. // Clear insert_id on a subsequent failed insert.
  1489. if ( $this->insert_id && preg_match( '/^\s*(insert|replace)\s/i', $query ) )
  1490. $this->insert_id = 0;
  1491. $this->print_error();
  1492. return false;
  1493. }
  1494. if ( preg_match( '/^\s*(create|alter|truncate|drop)\s/i', $query ) ) {
  1495. $return_val = $this->result;
  1496. } elseif ( preg_match( '/^\s*(insert|delete|update|replace)\s/i', $query ) ) {
  1497. if ( $this->use_mysqli ) {
  1498. $this->rows_affected = mysqli_affected_rows( $this->dbh );
  1499. } else {
  1500. $this->rows_affected = mysql_affected_rows( $this->dbh );
  1501. }
  1502. // Take note of the insert_id
  1503. if ( preg_match( '/^\s*(insert|replace)\s/i', $query ) ) {
  1504. if ( $this->use_mysqli ) {
  1505. $this->insert_id = mysqli_insert_id( $this->dbh );
  1506. } else {
  1507. $this->insert_id = mysql_insert_id( $this->dbh );
  1508. }
  1509. }
  1510. // Return number of rows affected
  1511. $return_val = $this->rows_affected;
  1512. } else {
  1513. $num_rows = 0;
  1514. if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
  1515. while ( $row = @mysqli_fetch_object( $this->result ) ) {
  1516. $this->last_result[$num_rows] = $row;
  1517. $num_rows++;
  1518. }
  1519. } elseif ( is_resource( $this->result ) ) {
  1520. while ( $row = @mysql_fetch_object( $this->result ) ) {
  1521. $this->last_result[$num_rows] = $row;
  1522. $num_rows++;
  1523. }
  1524. }
  1525. // Log number of rows the query returned
  1526. // and return number of rows selected
  1527. $this->num_rows = $num_rows;
  1528. $return_val = $num_rows;
  1529. }
  1530. return $return_val;
  1531. }
  1532. /**
  1533. * Internal function to perform the mysql_query() call.
  1534. *
  1535. * @since 3.9.0
  1536. *
  1537. * @access private
  1538. * @see ljmcdb::query()
  1539. *
  1540. * @param string $query The query to run.
  1541. */
  1542. private function _do_query( $query ) {
  1543. if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
  1544. $this->timer_start();
  1545. }
  1546. if ( $this->use_mysqli ) {
  1547. $this->result = @mysqli_query( $this->dbh, $query );
  1548. } else {
  1549. $this->result = @mysql_query( $query, $this->dbh );
  1550. }
  1551. $this->num_queries++;
  1552. if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
  1553. $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
  1554. }
  1555. }
  1556. /**
  1557. * Insert a row into a table.
  1558. *
  1559. * ljmcdb::insert( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
  1560. * ljmcdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
  1561. *
  1562. * @since 2.5.0
  1563. * @see ljmcdb::prepare()
  1564. * @see ljmcdb::$field_types
  1565. * @see ljmc_set_ljmcdb_vars()
  1566. *
  1567. * @param string $table table name
  1568. * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  1569. * @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.
  1570. * A format is one of '%d', '%f', '%s' (integer, float, string). If omitted, all values in $data will be treated as strings unless otherwise specified in ljmcdb::$field_types.
  1571. * @return int|false The number of rows inserted, or false on error.
  1572. */
  1573. public function insert( $table, $data, $format = null ) {
  1574. return $this->_insert_replace_helper( $table, $data, $format, 'INSERT' );
  1575. }
  1576. /**
  1577. * Replace a row into a table.
  1578. *
  1579. * ljmcdb::replace( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
  1580. * ljmcdb::replace( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
  1581. *
  1582. * @since 3.0.0
  1583. * @see ljmcdb::prepare()
  1584. * @see ljmcdb::$field_types
  1585. * @see ljmc_set_ljmcdb_vars()
  1586. *
  1587. * @param string $table table name
  1588. * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  1589. * @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.
  1590. * A format is one of '%d', '%f', '%s' (integer, float, string). If omitted, all values in $data will be treated as strings unless otherwise specified in ljmcdb::$field_types.
  1591. * @return int|false The number of rows affected, or false on error.
  1592. */
  1593. public function replace( $table, $data, $format = null ) {
  1594. return $this->_insert_replace_helper( $table, $data, $format, 'REPLACE' );
  1595. }
  1596. /**
  1597. * Helper function for insert and replace.
  1598. *
  1599. * Runs an insert or replace query based on $type argument.
  1600. *
  1601. * @access private
  1602. * @since 3.0.0
  1603. * @see ljmcdb::prepare()
  1604. * @see ljmcdb::$field_types
  1605. * @see ljmc_set_ljmcdb_vars()
  1606. *
  1607. * @param string $table table name
  1608. * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  1609. * @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.
  1610. * A format is one of '%d', '%f', '%s' (integer, float, string). If omitted, all values in $data will be treated as strings unless otherwise specified in ljmcdb::$field_types.
  1611. * @param string $type Optional. What type of operation is this? INSERT or REPLACE. Defaults to INSERT.
  1612. * @return int|false The number of rows affected, or false on error.
  1613. */
  1614. function _insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' ) {
  1615. $this->insert_id = 0;
  1616. if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ) ) ) {
  1617. return false;
  1618. }
  1619. $data = $this->process_fields( $table, $data, $format );
  1620. if ( false === $data ) {
  1621. return false;
  1622. }
  1623. $formats = $values = array();
  1624. foreach ( $data as $value ) {
  1625. $formats[] = $value['format'];
  1626. $values[] = $value['value'];
  1627. }
  1628. $fields = '`' . implode( '`, `', array_keys( $data ) ) . '`';
  1629. $formats = implode( ', ', $formats );
  1630. $sql = "$type INTO `$table` ($fields) VALUES ($formats)";
  1631. $this->check_current_query = false;
  1632. return $this->query( $this->prepare( $sql, $values ) );
  1633. }
  1634. /**
  1635. * Update a row in the table
  1636. *
  1637. * ljmcdb::update( 'table', array( 'column' => 'foo', 'field' => 'bar' ), array( 'ID' => 1 ) )
  1638. * ljmcdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) )
  1639. *
  1640. * @since 2.5.0
  1641. * @see ljmcdb::prepare()
  1642. * @see ljmcdb::$field_types
  1643. * @see ljmc_set_ljmcdb_vars()
  1644. *
  1645. * @param string $table table name
  1646. * @param array $data Data to update (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  1647. * @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".
  1648. * @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.
  1649. * A format is one of '%d', '%f', '%s' (integer, float, string). If omitted, all values in $data will be treated as strings unless otherwise specified in ljmcdb::$field_types.
  1650. * @param array|string $where_format 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', '%f', '%s' (integer, float, string). If omitted, all values in $where will be treated as strings.
  1651. * @return int|false The number of rows updated, or false on error.
  1652. */
  1653. public function update( $table, $data, $where, $format = null, $where_format = null ) {
  1654. if ( ! is_array( $data ) || ! is_array( $where ) ) {
  1655. return false;
  1656. }
  1657. $data = $this->process_fields( $table, $data, $format );
  1658. if ( false === $data ) {
  1659. return false;
  1660. }
  1661. $where = $this->process_fields( $table, $where, $where_format );
  1662. if ( false === $where ) {
  1663. return false;
  1664. }
  1665. $fields = $conditions = $values = array();
  1666. foreach ( $data as $field

Large files files are truncated, but you can click here to view the full file