Cache.php 13.1 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
<?php

namespace WP_Rocket\Engine\Preload\Database\Queries;

use WP_Rocket\Logger\Logger;
use WP_Rocket\Dependencies\Database\Query;
use WP_Rocket\Engine\Preload\Database\Rows\CacheRow;
use WP_Rocket\Engine\Preload\Database\Schemas\Cache as Schema;

class Cache extends Query {

	/**
	 * Logger instance.
	 *
	 * @var Logger
	 */
	protected $logger;

	/**
	 * Name of the database table to query.
	 *
	 * @var   string
	 */
	protected $table_name = 'wpr_rocket_cache';

	/**
	 * String used to alias the database table in MySQL statement.
	 *
	 * Keep this short, but descriptive. I.E. "tr" for term relationships.
	 *
	 * This is used to avoid collisions with JOINs.
	 *
	 * @var   string
	 */
	protected $table_alias = 'wpr_cache';
	/**
	 * Name of class used to setup the database schema.
	 *
	 * @var string
	 */
	protected $table_schema = Schema::class;

	/** Item ******************************************************************/

	/**
	 * Name for a single item.
	 *
	 * Use underscores between words. I.E. "term_relationship"
	 *
	 * This is used to automatically generate action hooks.
	 *
	 * @var   string
	 */
	protected $item_name = 'cache';

	/**
	 * Plural version for a group of items.
	 *
	 * Use underscores between words. I.E. "term_relationships"
	 *
	 * This is used to automatically generate action hooks.
	 *
	 * @var string
	 */
	protected $item_name_plural = 'caches';

	/**
	 * Name of class used to turn IDs into first-class objects.
	 *
	 * This is used when looping through return values to guarantee their shape.
	 *
	 * @var mixed
	 */
	protected $item_shape = CacheRow::class;

	/**
	 * Instantiate query.
	 *
	 * @param Logger       $logger logger instance.
	 *
	 * @param string|array $query {
	 *     Optional. Array or query string of item query parameters.
	 *     Default empty.
	 *
	 *     @type string       $fields            Site fields to return. Accepts 'ids' (returns an array of item IDs)
	 *                                           or empty (returns an array of complete item objects). Default empty.
	 *                                           To do a date query against a field, append the field name with _query
	 *     @type bool         $count             Whether to return a item count (true) or array of item objects.
	 *                                           Default false.
	 *     @type int          $number            Limit number of items to retrieve. Use 0 for no limit.
	 *                                           Default 100.
	 *     @type int          $offset            Number of items to offset the query. Used to build LIMIT clause.
	 *                                           Default 0.
	 *     @type bool         $no_found_rows     Whether to disable the `SQL_CALC_FOUND_ROWS` query.
	 *                                           Default true.
	 *     @type string|array $orderby           Accepts false, an empty array, or 'none' to disable `ORDER BY` clause.
	 *                                           Default 'id'.
	 *     @type string       $item              How to item retrieved items. Accepts 'ASC', 'DESC'.
	 *                                           Default 'DESC'.
	 *     @type string       $search            Search term(s) to retrieve matching items for.
	 *                                           Default empty.
	 *     @type array        $search_columns    Array of column names to be searched.
	 *                                           Default empty array.
	 *     @type bool         $update_item_cache Whether to prime the cache for found items.
	 *                                           Default false.
	 *     @type bool         $update_meta_cache Whether to prime the meta cache for found items.
	 *                                           Default false.
	 * }
	 */
	public function __construct( Logger $logger, $query = [] ) {
		parent::__construct( $query );
		$this->logger = $logger;
	}

	/**
	 * Create new resource row or update its contents if not created before.
	 *
	 * @since 3.9
	 *
	 * @param array $resource Resource array.
	 *
	 * @return bool
	 */
	public function create_or_update( array $resource ) {
		$url = untrailingslashit( strtok( $resource['url'], '?' ) );

		if ( $this->is_rejected( $resource['url'] ) ) {
			return false;
		}

		// check the database if those resources added before.
		$rows = $this->query(
			[
				'url' => $url,
			],
			false
		);

		if ( count( $rows ) === 0 ) {
			// Create this new row in DB.
			$resource_id = $this->add_item(
				[
					'url'           => $url,
					'status'        => key_exists( 'status', $resource ) ? $resource['status'] : 'pending',
					'is_locked'     => key_exists( 'is_locked', $resource ) ? $resource['is_locked'] : false,
					'last_accessed' => current_time( 'mysql', true ),
				]
			);

			if ( $resource_id ) {
				return $resource_id;
			}

			$this->logger->error( "Cannot insert {$resource['url']} into {$this->table_name}" );

			return false;
		}

		$db_row = array_pop( $rows );

		$data = [
			'url'       => $url,
			'status'    => key_exists( 'status', $resource ) ? $resource['status'] : $db_row->status,
			'is_locked' => key_exists( 'is_locked', $resource ) ? $resource['is_locked'] : $db_row->is_locked,
			'modified'  => current_time( 'mysql', true ),
		];

		if ( key_exists( 'last_accessed', $resource ) && (bool) $resource['last_accessed'] ) {
			$data['last_accessed'] = current_time( 'mysql', true );
		}

		// Update this row with the new content.
		$this->update_item(
			$db_row->id,
			$data
		);

		return $db_row->id;
	}

	/**
	 * Create new resource row or update its contents if not created before.
	 *
	 * @since 3.9
	 *
	 * @param array $resource Resource array.
	 *
	 * @return bool
	 */
	public function create_or_nothing( array $resource ) {

		if ( $this->is_rejected( $resource['url'] ) ) {
			return false;
		}

		$url = strtok( $resource['url'], '?' );

		// check the database if those resources added before.
		$rows = $this->query(
			[
				'url' => untrailingslashit( $url ),
			],
			false
		);

		if ( count( $rows ) > 0 ) {
			return false;
		}

		// Create this new row in DB.
		$resource_id = $this->add_item(
			[
				'url'           => untrailingslashit( $url ),
				'status'        => key_exists( 'status', $resource ) ? $resource['status'] : 'pending',
				'is_locked'     => key_exists( 'is_locked', $resource ) ? $resource['is_locked'] : false,
				'last_accessed' => current_time( 'mysql', true ),
			]
		);

		if ( $resource_id ) {
			return $resource_id;
		}

		$this->logger->error( "Cannot insert {$resource['url']} into {$this->table_name}" );

		return false;
	}

	/**
	 * Get all rows with the same url (desktop and mobile versions).
	 *
	 * @param string $url Page url.
	 *
	 * @return array|false
	 */
	public function get_rows_by_url( string $url ) {

		$url = strtok( $url, '?' );

		$query = $this->query(
			[
				'url' => untrailingslashit( $url ),
			]
		);

		if ( empty( $query ) ) {
			return false;
		}

		return $query;
	}

	/**
	 * Delete DB row by url.
	 *
	 * @param string $url Page url to be deleted.
	 *
	 * @return bool
	 */
	public function delete_by_url( string $url ) {
		$items = $this->get_rows_by_url( $url );

		if ( ! $items ) {
			return false;
		}

		$deleted = true;
		foreach ( $items as $item ) {
			if ( ! is_bool( $item ) ) {
				$deleted = $deleted && $this->delete_item( $item->id );
			}
		}

		return $deleted;
	}

	/**
	 * Get all preload caches which were not accessed in the last month.
	 *
	 * @return array
	 */
	public function get_old_cache() : array {
		// Get the database interface.
		$db = $this->get_db();

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

		$prefixed_table_name = $db->prefix . $this->table_name;
		$query               = "SELECT id FROM `$prefixed_table_name` WHERE `last_accessed` <= date_sub(now(), interval 1 month)";
		$rows_affected       = $db->get_results( $query );

		return $rows_affected;
	}

	/**
	 * Remove all completed rows one by one.
	 *
	 * @return void
	 */
	public function remove_all_not_accessed_rows() {
		$rows = $this->get_old_cache();

		foreach ( $rows as $row ) {
			if ( ! is_bool( $row ) ) {
				$this->delete_item( $row->id );
			}
		}
	}

	/**
	 * Fetch pending jobs.
	 *
	 * @param int $total total of jobs to fetch.
	 * @return array
	 */
	public function get_pending_jobs( int $total = 45 ) {
		$inprogress_count = $this->query(
			[
				'count'     => true,
				'status'    => 'in-progress',
				'is_locked' => false,
			],
			false
		);

		if ( $inprogress_count >= $total ) {
			return [];
		}

		$orderby = 'modified';

		/**
		 * Filter order for preloading pending urls.
		 *
		 * @param bool $orderby order for preloading pending urls.
		 *
		 * @returns bool
		 */
		if ( apply_filters( 'rocket_preload_order', false ) ) {
			$orderby = 'id';
		}

		return $this->query(
			[
				'number'         => ( $total - $inprogress_count ),
				'status'         => 'pending',
				'fields'         => [
					'id',
					'url',
				],
				'job_id__not_in' => [
					'not_in' => '',
				],
				'is_locked'      => false,
				'orderby'        => $orderby,
				'order'          => 'asc',
			]
		);
	}

	/**
	 * Change the status from the task to inprogress.
	 *
	 * @param int $id id from the task.
	 * @return bool
	 */
	public function make_status_inprogress( int $id ) {
		return $this->update_item(
			$id,
			[
				'status' => 'in-progress',
			]
		);
	}

	/**
	 * Make the status from the task to complete.
	 *
	 * @param string $url url from the task.
	 * @return bool
	 */
	public function make_status_complete( string $url ) {
		$tasks = $this->query(
			[
				'url' => $url,
			]
		);

		if ( count( $tasks ) === 0 ) {
			return false;
		}

		$task = array_pop( $tasks );

		return $this->update_item(
			$task->id,
			[
				'status' => 'completed',
			]
		);
	}

	/**
	 * Check if pending jobs are remaining.
	 *
	 * @return bool
	 */
	public function has_pending_jobs() {
		$pending_count = $this->query(
			[
				'count'  => true,
				'status' => 'pending',
			]
		);
		return 0 !== $pending_count;
	}

	/**
	 * Revert in-progress urls.
	 *
	 * @return void
	 */
	public function revert_in_progress() {
		$in_progress_list = $this->query(
			[
				'status' => 'in-progress',
			]
		);
		foreach ( $in_progress_list as $in_progress ) {
			$this->update_item(
				$in_progress->id,
				[
					'status' => 'pending',
				]
				);
		}
	}

	/**
	 * Revert old in-progress rows
	 */
	public function revert_old_in_progress() {
		// Get the database interface.
		$db = $this->get_db();

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

		$prefixed_table_name = $db->prefix . $this->table_name;
		$db->query( "UPDATE `$prefixed_table_name` SET status = 'pending' WHERE status = 'in-progress' AND `modified` <= date_sub(now(), interval 12 hour)" );
	}

	/**
	 * Set all rows to pending.
	 */
	public function set_all_to_pending() {
		// Get the database interface.
		$db = $this->get_db();

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

		$prefixed_table_name = $db->prefix . $this->table_name;

		/**
		 * Filter condition for cleaning URLS in the database.
		 *
		 * @param string $condition condition for cleaning URLS in the database.
		 * @returns string
		 */
		$condition = apply_filters( 'rocket_preload_all_to_pending_condition', ' WHERE 1 = 1' );

		$db->query( "UPDATE `$prefixed_table_name` SET status = 'pending'$condition" );
	}

	/**
	 * Check if the page is preloaded.
	 *
	 * @param string $url url from the page to check.
	 * @return bool
	 */
	public function is_preloaded( string $url ): bool {

		$pending_count = $this->query(
			[
				'count'  => true,
				'status' => 'in-progress',
				'url'    => untrailingslashit( $url ),
			]
		);
		return 0 !== $pending_count;
	}

	/**
	 * Check if the page is pending.
	 *
	 * @param string $url url from the page to check.
	 * @return bool
	 */
	public function is_pending( string $url ): bool {
		$pending_count = $this->query(
			[
				'count'  => true,
				'status' => 'pending',
				'url'    => untrailingslashit( $url ),
			]
		);

		return 0 !== $pending_count;
	}

	/**
	 * Remove all entries from the table.
	 *
	 * @return false|void
	 */
	public function remove_all() {
		// Get the database interface.
		$db = $this->get_db();

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

		$prefixed_table_name = $db->prefix . $this->table_name;

		$db->query( "DELETE FROM `$prefixed_table_name` WHERE 1 = 1" );
	}

	/**
	 * Lock a URL.
	 *
	 * @param string $url URL to lock.
	 *
	 * @return void
	 */
	public function lock( string $url ) {
		$this->create_or_update(
			[
				'url'       => $url,
				'is_locked' => true,
			]
			);
	}

	/**
	 * Unlock a URL.
	 *
	 * @param string $url URL to unlock.
	 *
	 * @return void
	 */
	public function unlock( string $url ) {
		$this->create_or_update(
			[
				'url'       => $url,
				'is_locked' => false,
			]
			);
	}

	/**
	 * Check if the url is rejected.
	 *
	 * @param string $url url to check.
	 * @return bool
	 */
	protected function is_rejected( string $url ): bool {
		$extensions = [
			'php' => 1,
			'xml' => 1,
			'xsl' => 1,
			'kml' => 1,
		];

		$extension = pathinfo( $url, PATHINFO_EXTENSION );

		return $extension && isset( $extensions[ $extension ] );
	}
}