Table.php 16.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
<?php
/**
 * Base Custom Database Table Class.
 *
 * @package     Index
 * @subpackage  Table
 * @copyright   Copyright (c) 2019
 * @license     https://opensource.org/licenses/gpl-2.0.php GNU Public License
 * @since       1.0.0
 */
namespace SearchWP\Index\Engine;

// Exit if accessed directly
defined( 'ABSPATH' ) || exit;

/**
 * A base database table class, which facilitates the creation of (and schema
 * changes to) individual database tables.
 *
 * This class is intended to be extended for each unique database table,
 * including global tables for multisite, and users tables.
 *
 * It exists to make managing database tables as easy as possible.
 *
 * Extending this class comes with several automatic benefits:
 * - Activation hook makes it great for plugins
 * - Tables store their versions in the database independently
 * - Tables upgrade via independent upgrade abstract methods
 * - Multisite friendly - site tables switch on "switch_blog" action
 *
 * @since 1.0.0
 */
abstract class Table extends Base {

	/**
	 * Table name, without the global table prefix.
	 *
	 * @since 1.0.0
	 * @var   string
	 */
	protected $name = '';

	/**
	 * Optional description.
	 *
	 * @since 1.0.0
	 * @var   string
	 */
	protected $description = '';

	/**
	 * Database version.
	 *
	 * @since 1.0.0
	 * @var   mixed
	 */
	protected $version = '';

	/**
	 * Is this table for a site, or global.
	 *
	 * @since 1.0.0
	 * @var   bool
	 */
	protected $global = false;

	/**
	 * Passed directly into register_activation_hook()
	 *
	 * @since 1.0.0
	 * @var   string
	 */
	protected $file = '';

	/**
	 * Database version key (saved in _options or _sitemeta)
	 *
	 * @since 1.0.0
	 * @var   string
	 */
	protected $db_version_key = '';

	/**
	 * Current database version.
	 *
	 * @since 1.0.0
	 * @var   mixed
	 */
	protected $db_version = 0;

	/**
	 * Table prefix, including the site prefix.
	 *
	 * @since 1.0.0
	 * @var   string
	 */
	protected $table_prefix = '';

	/**
	 * Table name.
	 *
	 * @since 1.0.0
	 * @var  string
	 */
	protected $table_name = '';

	/**
	 * Table name, prefixed from the base.
	 *
	 * @since 1.0.0
	 * @var   string
	 */
	protected $prefixed_name = '';

	/**
	 * Table schema.
	 *
	 * @since 1.0.0
	 * @var   string
	 */
	protected $schema = '';

	/**
	 * Database character-set & collation for table.
	 *
	 * @since 1.0.0
	 * @var   string
	 */
	protected $charset_collation = '';

	/**
	 * Key => value array of versions => methods.
	 *
	 * @since 1.0.0
	 * @var   array
	 */
	protected $upgrades = array();

	/** Methods ***************************************************************/

	/**
	 * Hook into queries, admin screens, and more!
	 *
	 * @since 1.0.0
	 */
	public function __construct() {

		// Setup the database table
		$this->setup();

		// Bail if setup failed
		if ( empty( $this->name ) || empty( $this->db_version_key ) ) {
			return;
		}

		// Add the table to the database interface
		$this->set_db_interface();

		// Set the database schema
		$this->set_schema();

		// Add hooks
		$this->add_hooks();

		// Maybe force upgrade if testing
		if ( $this->is_testing() ) {
			$this->maybe_upgrade();
		}
	}

	/** Abstract **************************************************************/

	/**
	 * Setup this database table.
	 *
	 * @since 1.0.0
	 */
	protected abstract function set_schema();

	/** Multisite *************************************************************/

	/**
	 * Update table version & references.
	 *
	 * Hooked to the "switch_blog" action.
	 *
	 * @since 1.0.0
	 *
	 * @param int $site_id The site being switched to
	 */
	public function switch_blog( $site_id = 0 ) {

		// Update DB version based on the current site
		if ( ! $this->is_global() ) {
			$this->db_version = get_blog_option( $site_id, $this->db_version_key, false );
		}

		// Update interface for switched site
		$this->set_db_interface();
	}

	/** Public Helpers ********************************************************/

	/**
	 * Maybe upgrade the database table. Handles creation & schema changes.
	 *
	 * Hooked to the `admin_init` action.
	 *
	 * @since 1.0.0
	 */
	public function maybe_upgrade() {

		// Bail if not upgradeable
		if ( ! $this->is_upgradeable() ) {
			return;
		}

		// Bail if upgrade not needed
		if ( ! $this->needs_upgrade() ) {
			return;
		}

		// Upgrade
		if ( $this->exists() ) {
			$this->upgrade();

		// Install
		} else {
			$this->install();
		}
	}

	/**
	 * Return whether this table needs an upgrade.
	 *
	 * @since 1.0.0
	 *
	 * @param mixed $version Database version to check if upgrade is needed
	 *
	 * @return bool True if table needs upgrading. False if not.
	 */
	public function needs_upgrade( $version = false ) {

		// Use the current table version if none was passed
		if ( empty( $version ) ) {
			$version = $this->version;
		}

		// Get the current database version
		$this->get_db_version();

		// Is the database table up to date?
		$is_current = version_compare( $this->db_version, $version, '>=' );

		// Return false if current, true if out of date
		return ( true === $is_current )
			? false
			: true;
	}

	/**
	 * Return whether this table can be upgraded.
	 *
	 * @since 1.0.0
	 *
	 * @return bool True if table can be upgraded. False if not.
	 */
	public function is_upgradeable() {

		// Bail if global and upgrading global tables is not allowed
		// DISABLED: wp_should_upgrade_global_tables() isn't defined. This method
		// isn't being used so instead of requiring more files, we're disabling.
		// if ( $this->is_global() && ! wp_should_upgrade_global_tables() ) {
		// 	return false;
		// }

		// Kinda weird, but assume it is
		return true;
	}

	/**
	 * Return the current table version from the database.
	 *
	 * This is public method for accessing a private variable so that it cannot
	 * be externally modified.
	 *
	 * @since 1.0.0
	 *
	 * @return string
	 */
	public function get_version() {
		$this->get_db_version();

		return $this->db_version;
	}

	/**
	 * Install a database table by creating the table and setting the version.
	 *
	 * @since 1.0.0
	 */
	public function install() {
		$created = $this->create();

		// Set the DB version if create was successful
		if ( true === $created ) {
			$this->set_db_version();
		}
	}

	/**
	 * Destroy a database table by dropping the table and deleting the version.
	 *
	 * @since 1.0.0
	 */
	public function uninstall() {
		$dropped = $this->drop();

		// Delete the DB version if drop was successful
		if ( true === $dropped ) {
			$this->delete_db_version();
		}
	}

	/** Public Management *****************************************************/

	/**
	 * Check if table already exists.
	 *
	 * @since 1.0.0
	 *
	 * @return bool
	 */
	public function exists() {

		// Get the database interface
		$db = $this->get_db();

		// Bail if no database interface is available
		if ( empty( $db ) ) {
			return;
		}

		// Query statement
		$query    = "SHOW TABLES LIKE %s";
		$like     = $db->esc_like( $this->table_name );
		$prepared = $db->prepare( $query, $like );
		$result   = $db->get_var( $prepared );

		// Does the table exist?
		return $this->is_success( $result );
	}

	/**
	 * Check if table already exists.
	 *
	 * @since 1.0.0
	 *
	 * @return bool
	 */
	public function column_exists( $name = '' ) {

		// Get the database interface
		$db = $this->get_db();

		// Bail if no database interface is available
		if ( empty( $db ) ) {
			return;
		}

		// Query statement
		$query    = "SHOW COLUMNS FROM {$this->table_name} LIKE %s";
		$like     = $db->esc_like( $name );
		$prepared = $db->prepare( $query, $like );
		$result   = $db->query( $prepared );

		// Does the table exist?
		return $this->is_success( $result );
	}

	/**
	 * Create the table.
	 *
	 * @since 1.0.0
	 *
	 * @return bool
	 */
	public function create() {

		// Get the database interface
		$db = $this->get_db();

		// Bail if no database interface is available
		if ( empty( $db ) ) {
			return;
		}

		// Query statement
		$query  = "CREATE TABLE {$this->table_name} ( {$this->schema} ) {$this->charset_collation};";
		$result = $db->query( $query );

		// Was the table created?
		return $this->is_success( $result );
	}

	/**
	 * Drop the database table.
	 *
	 * @since 1.0.0
	 *
	 * @return mixed
	 */
	public function drop() {

		// Get the database interface
		$db = $this->get_db();

		// Bail if no database interface is available
		if ( empty( $db ) ) {
			return;
		}

		// Query statement
		$query  = "DROP TABLE {$this->table_name}";
		$result = $db->query( $query );

		// Query success/fail
		return $this->is_success( $result );
	}

	/**
	 * Truncate the database table.
	 *
	 * @since 1.0.0
	 *
	 * @return mixed
	 */
	public function truncate() {

		// Get the database interface
		$db = $this->get_db();

		// Bail if no database interface is available
		if ( empty( $db ) ) {
			return;
		}

		// Query statement
		$query  = "TRUNCATE TABLE {$this->table_name}";
		$result = $db->query( $query );

		// Query success/fail
		return $this->is_success( $result );
	}

	/**
	 * Delete all items from the database table.
	 *
	 * @since 1.0.0
	 *
	 * @return mixed
	 */
	public function delete_all() {

		// Get the database interface
		$db = $this->get_db();

		// Bail if no database interface is available
		if ( empty( $db ) ) {
			return;
		}

		// Query statement
		$query   = "DELETE FROM {$this->table_name}";
		$deleted = $db->query( $query );

		// Query success/fail
		return $deleted;
	}

	/**
	 * Count the number of items in the database table.
	 *
	 * @since 1.0.0
	 *
	 * @return mixed
	 */
	public function count() {

		// Get the database interface
		$db = $this->get_db();

		// Bail if no database interface is available
		if ( empty( $db ) ) {
			return;
		}

		// Query statement
		$query = "SELECT COUNT(*) FROM {$this->table_name}";
		$count = $db->get_var( $query );

		// Query success/fail
		return $count;
	}

	/** Upgrades **************************************************************/

	/**
	 * Upgrade this database table.
	 *
	 * @since 1.0.0
	 *
	 * return bool
	 */
	public function upgrade() {
		$result = false;

		// Remove all upgrades that have already been completed
		$upgrades = array_filter( (array) $this->upgrades, function( $value ) {
			return version_compare( $value, $this->db_version, '>' );
		} );

		// Bail if no upgrades or database version is missing
		if ( empty( $upgrades ) || empty( $this->db_version ) ) {
			$this->set_db_version();
			return true;
		}

		// Try to do all known upgrades
		foreach ( $upgrades as $version => $method ) {
			$result = $this->upgrade_to( $version, $method );

			// Bail if an error occurs, to avoid skipping ahead
			if ( ! $this->is_success( $result ) ) {
				return false;
			}
		}

		// Success/fail
		return $this->is_success( $result );
	}

	/**
	 * Upgrade to a specific database version.
	 *
	 * @since 1.0.0
	 *
	 * @param mixed  $version Database version to check if upgrade is needed
	 * @param string $method
	 *
	 * @return bool
	 */
	public function upgrade_to( $version = '', $method = '' ) {

		// Bail if no upgrade is needed
		if ( ! $this->needs_upgrade( $version ) ) {
			return false;
		}

		// Allow self-named upgrade methods
		if ( empty( $method ) ) {
			$method = $version;
		}

		// Is the method callable?
		$callable = $this->get_callable( $method );

		// Bail if no callable upgrade method was found
		if ( empty( $callable ) ) {
			return false;
		}

		// Do the upgrade
		$result  = call_user_func( $callable );
		$success = $this->is_success( $result );

		// Bail if upgrade failed
		if ( true !== $success ) {
			return false;
		}

		// Set the database version to this successful version
		$this->set_db_version( $version );

		// Return success
		return true;
	}

	/** Private ***************************************************************/

	/**
	 * Setup the necessary table variables.
	 *
	 * @since 1.0.0
	 */
	private function setup() {

		// Bail if no database interface is available
		if ( ! $this->get_db() ) {
			return;
		}

		// Sanitize the database table name
		$this->name = $this->sanitize_table_name( $this->name );

		// Bail if database table name was garbage
		if ( false === $this->name ) {
			return;
		}

		// Setup the prefixed name
		$this->prefixed_name = $this->apply_prefix( $this->name );

		// Maybe create database key
		if ( empty( $this->db_version_key ) ) {
			$this->db_version_key = "wpdb_{$this->prefixed_name}_version";
		}
	}

	/**
	 * Set this table up in the database interface.
	 *
	 * This must be done directly because the database interface does not
	 * have a common mechanism for manipulating them safely.
	 *
	 * @since 1.0.0
	 */
	private function set_db_interface() {

		// Get the database once, to avoid duplicate function calls
		$db = $this->get_db();

		// Bail if no database
		if ( empty( $db ) ) {
			return;
		}

		// Set variables for global tables
		if ( $this->is_global() ) {
			$site_id = 0;
			$tables  = 'ms_global_tables';

		// Set variables for per-site tables
		} else {
			$site_id = null;
			$tables  = 'tables';
		}

		// Set the table prefix and prefix the table name
		$this->table_prefix  = $db->get_blog_prefix( $site_id );

		// Get the prefixed table name
		$prefixed_table_name = "{$this->table_prefix}{$this->prefixed_name}";

		// Set the database interface
		$db->{$this->prefixed_name} = $this->table_name = $prefixed_table_name;

		// Create the array if it does not exist
		if ( ! isset( $db->{$tables} ) ) {
			$db->{$tables} = array();
		}

		// Add the table to the global table array
		$db->{$tables}[] = $this->prefixed_name;

		// Charset
		if ( ! empty( $db->charset ) ) {
			$this->charset_collation = "DEFAULT CHARACTER SET {$db->charset}";
		}

		// Collation
		if ( ! empty( $db->collate ) ) {
			$this->charset_collation .= " COLLATE {$db->collate}";
		}
	}

	/**
	 * Set the database version for the table.
	 *
	 * @since 1.0.0
	 *
	 * @param mixed $version Database version to set when upgrading/creating
	 */
	private function set_db_version( $version = '' ) {

		// If no version is passed during an upgrade, use the current version
		if ( empty( $version ) ) {
			$version = $this->version;
		}

		// Update the DB version
		$this->is_global()
			? update_network_option( get_main_network_id(), $this->db_version_key, $version )
			:         update_option(                        $this->db_version_key, $version );

		// Set the DB version
		$this->db_version = $version;
	}

	/**
	 * Get the table version from the database.
	 *
	 * @since 1.0.0
	 */
	private function get_db_version() {
		$this->db_version = $this->is_global()
			? get_network_option( get_main_network_id(), $this->db_version_key, false )
			:         get_option(                        $this->db_version_key, false );
	}

	/**
	 * Delete the table version from the database.
	 *
	 * @since 1.0.0
	 */
	private function delete_db_version() {
		$this->db_version = $this->is_global()
			? delete_network_option( get_main_network_id(), $this->db_version_key, false )
			:         delete_option(                        $this->db_version_key, false );
	}

	/**
	 * Add class hooks to the parent application actions.
	 *
	 * @since 1.0.0
	 */
	private function add_hooks() {

		// Activation hook
		register_activation_hook( $this->file, array( $this, 'maybe_upgrade' ) );

		// Add table to the global database object
		add_action( 'switch_blog', array( $this, 'switch_blog'   ) );
		add_action( 'admin_init',  array( $this, 'maybe_upgrade' ) );
	}

	/**
	 * Check if the current request is from some kind of test.
	 *
	 * This is primarily used to skip 'admin_init' and force-install tables.
	 *
	 * @since 1.0.0
	 *
	 * @return bool
	 */
	private function is_testing() {
		return (bool)

			// Tests constant is being used
			( defined( 'WP_TESTS_DIR' ) && WP_TESTS_DIR )

			||

			// Scaffolded (https://make.wordpress.org/cli/handbook/plugin-unit-tests/)
			function_exists( '_manually_load_plugin' );
	}

	/**
	 * Check if table is global.
	 *
	 * @since 1.0.0
	 *
	 * @return bool
	 */
	private function is_global() {
		return ( true === $this->global );
	}

	/**
	 * Try to get a callable upgrade method, with some magic to avoid needing to
	 * do this dance repeatedly inside subclasses.
	 *
	 * @since 1.0.0
	 *
	 * @param string $method
	 *
	 * @return bool
	 */
	private function get_callable( $method = '' ) {
		$callable = $method;

		// Look for global function
		if ( ! is_callable( $callable ) ) {
			$callable = array( $this, $method );

			// Look for local class method
			if ( ! is_callable( $callable ) ) {
				$callable = array( $this, "__{$method}" );

				// Look for method prefixed with "__"
				if ( ! is_callable( $callable ) ) {
					$callable = false;
				}
			}
		}

		// Return callable, if any
		return $callable;
	}
}