Commit inicial, se subio el proyecto
This commit is contained in:
@@ -0,0 +1,655 @@
|
||||
<?php
|
||||
namespace AIOSEO\TableOfContents\Core;
|
||||
|
||||
// Exit if accessed directly.
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the loading of our file assets.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*/
|
||||
class Assets {
|
||||
/**
|
||||
* Whether we should load dev scripts.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @var boolean|null
|
||||
*/
|
||||
private $shouldLoadDevScripts = null;
|
||||
|
||||
/**
|
||||
* The script handle to use for asset enqueuing.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private $scriptHandle = 'table-of-contents-plus';
|
||||
|
||||
/**
|
||||
* Holds the location of the manifest file.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private $manifestFile = '';
|
||||
|
||||
/**
|
||||
* True if we are in a dev environment. This mirrors the global isDev.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
private $isDev = false;
|
||||
|
||||
/**
|
||||
* Asset handles that should load as regular JS and not as modern JS module.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @var array An array of handles.
|
||||
*/
|
||||
private $noModuleTag = [];
|
||||
|
||||
/**
|
||||
* Core class instance.
|
||||
*
|
||||
* @since 1.1.0
|
||||
*
|
||||
* @var Core
|
||||
*/
|
||||
public $core = null;
|
||||
|
||||
/**
|
||||
* The plugin version.
|
||||
*
|
||||
* @since 1.1.0
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public $version = 0;
|
||||
|
||||
/**
|
||||
* The domain.
|
||||
*
|
||||
* @since 1.1.0
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
public $domain = '';
|
||||
|
||||
/**
|
||||
* The port.
|
||||
*
|
||||
* @since 1.1.0
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public $port = 0;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param Core $core The AIOSEO Core class.
|
||||
*/
|
||||
public function __construct( $core ) {
|
||||
$this->core = $core;
|
||||
$this->version = aioseoTableOfContents()->version;
|
||||
$this->manifestFile = AIOSEO_TABLE_OF_CONTENTS_DIR . '/dist/manifest.php';
|
||||
$this->isDev = aioseoTableOfContents()->isDev;
|
||||
|
||||
if ( $this->isDev ) {
|
||||
$this->domain = getenv( 'VITE_AIOSEO_TABLE_OF_CONTENTS_DOMAIN' );
|
||||
$this->port = getenv( 'VITE_AIOSEO_TABLE_OF_CONTENTS_DEV_PORT' );
|
||||
}
|
||||
|
||||
add_filter( 'script_loader_tag', [ $this, 'scriptLoaderTag' ], 10, 3 );
|
||||
}
|
||||
|
||||
/**
|
||||
* The asset to load.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $asset The asset to load.
|
||||
* @param array $dependencies An array of dependencies.
|
||||
* @param mixed $data Any data to be localized.
|
||||
* @param string $objectName The object name to use when localizing.
|
||||
* @return void
|
||||
*/
|
||||
public function load( $asset, $dependencies = [], $data = null, $objectName = 'aioseoTableOfContents' ) {
|
||||
$this->jsPreloadImports( $asset );
|
||||
$this->loadCss( $asset );
|
||||
$this->enqueueJs( $asset, $dependencies, $data, $objectName );
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter the script loader tag if this is our script.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $tag The tag that is going to be output.
|
||||
* @param string $handle The handle for the script.
|
||||
* @return string The modified tag.
|
||||
*/
|
||||
public function scriptLoaderTag( $tag, $handle, $src ) {
|
||||
if ( $this->skipModuleTag( $handle ) ) {
|
||||
return $tag;
|
||||
}
|
||||
|
||||
$tag = str_replace( $src, $this->normalizeAssetsHost( $src ), $tag );
|
||||
|
||||
// Remove the type and re-add it as module.
|
||||
$tag = preg_replace( '/type=[\'"].*?[\'"]/', '', (string) $tag );
|
||||
$tag = preg_replace( '/<script/', '<script type="module"', (string) $tag );
|
||||
|
||||
return $tag;
|
||||
}
|
||||
|
||||
/**
|
||||
* Preload JS imports.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $asset The asset to load imports for.
|
||||
* @return void
|
||||
*/
|
||||
private function jsPreloadImports( $asset ) {
|
||||
static $urls = []; // Prevent script from being loaded multiple times.
|
||||
|
||||
$res = '';
|
||||
foreach ( $this->importsUrls( $asset ) as $url ) {
|
||||
if ( isset( $urls[ $url ] ) ) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$urls[ $url ] = true;
|
||||
|
||||
$res .= '<link rel="modulepreload" href="' . esc_attr( $url ) . "\">\n";
|
||||
}
|
||||
|
||||
$allowedHtml = [
|
||||
'link' => [
|
||||
'rel' => [],
|
||||
'href' => []
|
||||
]
|
||||
];
|
||||
|
||||
if ( ! empty( $res ) ) {
|
||||
if ( ! function_exists( 'wp_enqueue_script_module' ) ) {
|
||||
add_action( 'admin_head', function () use ( &$res, $allowedHtml ) {
|
||||
echo wp_kses( $res, $allowedHtml );
|
||||
} );
|
||||
add_action( 'wp_head', function () use ( &$res, $allowedHtml ) {
|
||||
echo wp_kses( $res, $allowedHtml );
|
||||
} );
|
||||
} else {
|
||||
add_action( 'admin_print_footer_scripts', function () use ( &$res, $allowedHtml ) {
|
||||
echo wp_kses( $res, $allowedHtml );
|
||||
}, 1000 );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads CSS for an asset from the manifest file.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $asset The script to load CSS for.
|
||||
* @return void
|
||||
*/
|
||||
private function loadCss( $asset ) {
|
||||
if ( $this->shouldLoadDev() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ( $this->getCssUrls( $asset ) as $file => $url ) {
|
||||
wp_enqueue_style( $this->cssHandle( $file ), $url, [], $this->version );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a CSS asset.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $asset The script to load CSS for.
|
||||
* @param array $dependencies An array of dependencies.
|
||||
* @param string $devPath The file's dev path.
|
||||
* @return void
|
||||
*/
|
||||
public function registerCss( $asset, $dependencies = [], $devPath = '' ) {
|
||||
$handle = $this->cssHandle( $asset );
|
||||
if ( wp_style_is( $handle, 'registered' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$devPath = $devPath ?: $asset;
|
||||
|
||||
$url = $this->shouldLoadDev()
|
||||
? $this->getDevUrl() . ltrim( $devPath, '/' )
|
||||
: $this->assetUrl( $asset );
|
||||
|
||||
if ( ! $url ) {
|
||||
return;
|
||||
}
|
||||
|
||||
wp_register_style( $handle, $url, $dependencies, $this->version );
|
||||
}
|
||||
|
||||
/**
|
||||
* Enqueue css.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $asset The css to load.
|
||||
* @param string $devPath The file's dev path.
|
||||
* @param array $dependencies An array of dependencies.
|
||||
* @return void
|
||||
*/
|
||||
public function enqueueCss( $asset, $dependencies = [], $devPath = '' ) {
|
||||
$this->registerCss( $asset, $dependencies, $devPath );
|
||||
|
||||
$handle = $this->cssHandle( $asset );
|
||||
if ( wp_style_is( $handle, 'enqueued' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
wp_enqueue_style( $handle );
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the JS to enqueue.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $asset The script to load.
|
||||
* @param array $dependencies An array of dependencies.
|
||||
* @param mixed $data Any data to be localized.
|
||||
* @param string $objectName The object name to use when localizing.
|
||||
* @return void
|
||||
*/
|
||||
public function registerJs( $asset, $dependencies = [], $data = null, $objectName = 'aioseoTableOfContents' ) {
|
||||
$handle = $this->jsHandle( $asset );
|
||||
if ( wp_script_is( $handle, 'registered' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
$url = $this->shouldLoadDev()
|
||||
? $this->getDevUrl() . ltrim( $asset, '/' )
|
||||
: $this->jsUrl( $asset );
|
||||
|
||||
if ( ! $url ) {
|
||||
return;
|
||||
}
|
||||
|
||||
wp_register_script( $handle, $url, $dependencies, $this->version, true );
|
||||
|
||||
if ( empty( $data ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
wp_localize_script(
|
||||
$handle,
|
||||
$objectName,
|
||||
$data
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the JS to enqueue.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $asset The script to load.
|
||||
* @param array $dependencies An array of dependencies.
|
||||
* @param mixed $data Any data to be localized.
|
||||
* @param string $objectName The object name to use when localizing.
|
||||
* @return void
|
||||
*/
|
||||
public function enqueueJs( $asset, $dependencies = [], $data = null, $objectName = 'aioseoTableOfContents' ) {
|
||||
$this->registerJs( $asset, $dependencies, $data, $objectName );
|
||||
|
||||
$handle = $this->jsHandle( $asset );
|
||||
if ( wp_script_is( $handle, 'enqueued' ) ) {
|
||||
return;
|
||||
}
|
||||
|
||||
wp_enqueue_script( $handle );
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the dev URL.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @return string The dev URL.
|
||||
*/
|
||||
private function getDevUrl() {
|
||||
$protocol = is_ssl() ? 'https://' : 'http://';
|
||||
|
||||
return $protocol . $this->domain . ':' . $this->port . '/';
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the asset URL.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $asset The asset to find the URL for.
|
||||
* @return string The URL for the asset.
|
||||
*/
|
||||
private function assetUrl( $asset ) {
|
||||
$assetManifest = $this->getAssetManifestItem( $asset );
|
||||
|
||||
return ! empty( $assetManifest['file'] )
|
||||
? $this->basePath() . $assetManifest['file']
|
||||
: $this->basePath() . ltrim( $asset, '/' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the JS URL.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $asset The asset to find the URL for.
|
||||
* @return string The URL for the asset.
|
||||
*/
|
||||
public function jsUrl( $asset ) {
|
||||
$manifestAsset = $this->getManifestItem( $asset );
|
||||
|
||||
return ! empty( $manifestAsset['file'] )
|
||||
? $this->basePath() . $manifestAsset['file']
|
||||
: $this->basePath() . ltrim( $asset, '/' );
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an item from the manifest.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $asset The asset to find.
|
||||
* @return string Manifest object.
|
||||
*/
|
||||
private function getManifestItem( $asset ) {
|
||||
$manifest = $this->getManifest();
|
||||
|
||||
$asset = ltrim( $asset, '/' );
|
||||
|
||||
return isset( $manifest[ $asset ] ) ? $manifest[ $asset ] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the CSS asset handle.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $asset The asset to find the handle for.
|
||||
* @return string The asset handle.
|
||||
*/
|
||||
public function cssHandle( $asset ) {
|
||||
return "{$this->scriptHandle}/css/$asset";
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the JS asset handle.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $asset The asset to find the handle for.
|
||||
* @return string The asset handle.
|
||||
*/
|
||||
public function jsHandle( $asset = '' ) {
|
||||
return "{$this->scriptHandle}/js/$asset";
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the manifest to load assets from.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @return array An array of files.
|
||||
*/
|
||||
private function getManifest() {
|
||||
static $file = null;
|
||||
if ( $file ) {
|
||||
return $file;
|
||||
}
|
||||
|
||||
$manifestJson = ''; // This is set in the view.
|
||||
if ( file_exists( $this->manifestFile ) ) {
|
||||
require_once $this->manifestFile;
|
||||
}
|
||||
|
||||
$file = json_decode( $manifestJson, true );
|
||||
|
||||
return $file;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an item from the asset manifest.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $item An item to retrieve.
|
||||
* @return string|null The asset item.
|
||||
*/
|
||||
private function getAssetManifestItem( $item ) {
|
||||
$assetManifest = $this->getManifest();
|
||||
|
||||
return ! empty( $assetManifest[ $item ] ) ? $assetManifest[ $item ] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an asset's array of URLs to import.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $asset The asset to find imports for.
|
||||
* @return array An array of imports.
|
||||
*/
|
||||
private function importsUrls( $asset ) {
|
||||
$urls = [];
|
||||
$manifestAsset = $this->getManifestItem( $asset );
|
||||
if ( ! empty( $manifestAsset['imports'] ) ) {
|
||||
foreach ( $manifestAsset['imports'] as $import ) {
|
||||
$importAsset = $this->getManifestItem( $import );
|
||||
if ( ! empty( $importAsset['file'] ) ) {
|
||||
$urls[] = $this->getPublicUrlBase() . $importAsset['file'];
|
||||
|
||||
// Load the import's CSS if any.
|
||||
$this->loadCss( $import );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $urls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an asset's CSS urls.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $asset The asset to find CSS URLs for.
|
||||
* @return array An array of CSS URLs to load.
|
||||
*/
|
||||
private function getCssUrls( $asset ) {
|
||||
$urls = [];
|
||||
$manifestAsset = $this->getManifestItem( $asset );
|
||||
|
||||
if ( ! empty( $manifestAsset['css'] ) ) {
|
||||
foreach ( $manifestAsset['css'] as $file ) {
|
||||
$urls[ $file ] = $this->getPublicUrlBase() . $file;
|
||||
}
|
||||
}
|
||||
|
||||
return $urls;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if we should load the dev watcher scripts.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @return boolean True if we should load the dev watcher scripts.
|
||||
*/
|
||||
private function shouldLoadDev() {
|
||||
if ( null !== $this->shouldLoadDevScripts ) {
|
||||
return $this->shouldLoadDevScripts;
|
||||
}
|
||||
|
||||
if (
|
||||
! $this->isDev ||
|
||||
(
|
||||
defined( 'AIOSEO_TABLE_OF_CONTENTS_LOAD_DEV_SCRIPTS' ) &&
|
||||
false === AIOSEO_TABLE_OF_CONTENTS_LOAD_DEV_SCRIPTS
|
||||
)
|
||||
) {
|
||||
$this->shouldLoadDevScripts = false;
|
||||
|
||||
return $this->shouldLoadDevScripts;
|
||||
}
|
||||
|
||||
if ( ! $this->domain && ! $this->port ) {
|
||||
$this->shouldLoadDevScripts = false;
|
||||
|
||||
return $this->shouldLoadDevScripts;
|
||||
}
|
||||
|
||||
set_error_handler( function() {} ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_set_error_handler
|
||||
$connection = fsockopen( $this->domain, $this->port ); // phpcs:ignore WordPress.WP.AlternativeFunctions
|
||||
restore_error_handler();
|
||||
|
||||
if ( ! $connection ) {
|
||||
$this->shouldLoadDevScripts = false;
|
||||
|
||||
return $this->shouldLoadDevScripts;
|
||||
}
|
||||
|
||||
$this->shouldLoadDevScripts = true;
|
||||
|
||||
return $this->shouldLoadDevScripts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the path for the assets.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param bool $maybeDev Whether to try and load dev scripts.
|
||||
* @return string The path for the assets.
|
||||
*/
|
||||
public function getAssetsPath( $maybeDev = true ) {
|
||||
return $maybeDev && $this->shouldLoadDev()
|
||||
? $this->getDevUrl()
|
||||
: $this->basePath();
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds out if a handle should be loaded as regular JS and not as modern JS module.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $handle The script handle.
|
||||
* @return bool Should the module tag be skipped.
|
||||
*/
|
||||
public function skipModuleTag( $handle ) {
|
||||
if ( ! aioseoTableOfContents()->helpers->stringContains( $handle, $this->jsHandle( '' ) ) ) {
|
||||
return true;
|
||||
}
|
||||
|
||||
foreach ( $this->noModuleTag as $tag ) {
|
||||
if ( aioseoTableOfContents()->helpers->stringContains( $handle, $tag ) ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize the assets host. Some sites manually set the WP_PLUGINS_URL
|
||||
* and if that domain has www. and the site_url does not, then it will fail to load
|
||||
* our assets. This doesn't fix the issue 100% because it will still fail on
|
||||
* sub-domains that don't have the proper CORS headers. Those sites will need
|
||||
* manual fixes.
|
||||
*
|
||||
* 4.1.10
|
||||
*
|
||||
* @param string $path The path to normalize.
|
||||
* @return string The normalized path.
|
||||
*/
|
||||
public function normalizeAssetsHost( $path ) {
|
||||
static $paths = [];
|
||||
if ( isset( $paths[ $path ] ) ) {
|
||||
return apply_filters( 'aioseo_table_of_contents_normalize_assets_host', $paths[ $path ] );
|
||||
}
|
||||
|
||||
// We need to verify the domain on the $path attribute matches
|
||||
// what's in site_url() for our assets or they won't load.
|
||||
$siteUrl = site_url();
|
||||
$siteUrlEscaped = aioseoTableOfContents()->helpers->escapeRegex( $siteUrl );
|
||||
if ( preg_match( "/^$siteUrlEscaped/i", (string) $path ) ) {
|
||||
$paths[ $path ] = $path;
|
||||
|
||||
return apply_filters( 'aioseo_table_of_contents_normalize_assets_host', $paths[ $path ] );
|
||||
}
|
||||
|
||||
// We now know that the path doesn't contain the site_url().
|
||||
$newPath = $path;
|
||||
$siteUrlParsed = wp_parse_url( $siteUrl );
|
||||
$host = aioseoTableOfContents()->helpers->escapeRegex( str_replace( 'www.', '', $siteUrlParsed['host'] ) );
|
||||
$scheme = aioseoTableOfContents()->helpers->escapeRegex( $siteUrlParsed['scheme'] );
|
||||
|
||||
$siteUrlHasWww = preg_match( "/^{$scheme}:\/\/www\.$host/", (string) $siteUrl );
|
||||
$pathHasWww = preg_match( "/^{$scheme}:\/\/www\.$host/", (string) $path );
|
||||
|
||||
// Check if the path contains www.
|
||||
if ( $pathHasWww && ! $siteUrlHasWww ) {
|
||||
// If the path contains www., we want to strip it out.
|
||||
$newPath = preg_replace( "/^({$scheme}:\/\/)(www\.)($host)/", '$1$3', (string) $path );
|
||||
}
|
||||
|
||||
// Check if the site_url contains www.
|
||||
if ( $siteUrlHasWww && ! $pathHasWww ) {
|
||||
// If the site_url contains www., we want to add it in to the path.
|
||||
$newPath = preg_replace( "/^({$scheme}:\/\/)($host)/", '$1www.$2', (string) $path );
|
||||
}
|
||||
|
||||
$paths[ $path ] = $newPath;
|
||||
|
||||
return apply_filters( 'aioseo_table_of_contents_normalize_assets_host', $paths[ $path ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the public URL base.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @return string The URL base.
|
||||
*/
|
||||
private function getPublicUrlBase() {
|
||||
return $this->shouldLoadDev() ? $this->getDevUrl() . 'dist/assets/' : $this->basePath();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the base path URL.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @return string The base path URL.
|
||||
*/
|
||||
private function basePath() {
|
||||
return $this->normalizeAssetsHost( plugins_url( 'dist/assets/', AIOSEO_TABLE_OF_CONTENTS_FILE ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,637 @@
|
||||
<?php
|
||||
namespace AIOSEO\TableOfContents\Core;
|
||||
|
||||
// Exit if accessed directly.
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles our cache.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*/
|
||||
class Cache {
|
||||
/**
|
||||
* The name of our cache table.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private $table = 'aioseo_table_of_contents_cache';
|
||||
|
||||
/**
|
||||
* Our cache.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private static $cache = [];
|
||||
|
||||
/**
|
||||
* Prefix for this cache.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $prefix = 'aioseo_table_of_contents_';
|
||||
|
||||
/**
|
||||
* Whether to use transients as fallback.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @var bool|null
|
||||
*/
|
||||
private $useTransientFallback = null;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @since 4.7.8
|
||||
*/
|
||||
public function __construct() {
|
||||
add_action( 'init', [ $this, 'checkIfTableExists' ] ); // This needs to run on init because the DB
|
||||
// class gets instantiated along with the cache class.
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the cache table exists and creates it if it doesn't.
|
||||
*
|
||||
* @since 4.7.8
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function checkIfTableExists() {
|
||||
if ( ! aioseoTableOfContents()->core->db->tableExists( $this->table ) ) {
|
||||
aioseoTableOfContents()->preUpdates->createCacheTable();
|
||||
}
|
||||
|
||||
// Table is guaranteed to exist now. Skip future re-checks this request
|
||||
// and refresh the transient so isCacheTableAvailable() won't query next request either.
|
||||
$this->useTransientFallback = false;
|
||||
set_transient( 'aioseo_plugin_cache_table_exists', 1, WEEK_IN_SECONDS );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the cache value if it exists and isn't expired.
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @version 202607 Renamed key to name
|
||||
*
|
||||
* @param string $key The key of the cache. Use a '%' for a LIKE query.
|
||||
* @return mixed The value or null if the cache does not exist.
|
||||
*/
|
||||
public function get( $key ) {
|
||||
$key = $this->prepareKey( $key );
|
||||
|
||||
// Check if we're supposed to do a LIKE get.
|
||||
$isLikeGet = preg_match( '/%/', (string) $key );
|
||||
|
||||
// Check static cache first (only for non-LIKE queries)
|
||||
if ( ! $isLikeGet && isset( self::$cache[ $key ] ) ) {
|
||||
return self::$cache[ $key ];
|
||||
}
|
||||
|
||||
// Check if we should use transients
|
||||
if ( ! $this->isCacheTableAvailable() ) {
|
||||
if ( $isLikeGet ) {
|
||||
// Use custom query for LIKE patterns
|
||||
return $this->getTransientLike( $key );
|
||||
}
|
||||
|
||||
$value = $this->getTransient( $key );
|
||||
if ( null !== $value ) {
|
||||
self::$cache[ $key ] = $value;
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
$result = aioseoTableOfContents()->core->db
|
||||
->start( $this->table )
|
||||
->select( '`name`, `value`, `is_object`' )
|
||||
->whereRaw( '( `expiration` IS NULL OR `expiration` > \'' . aioseoTableOfContents()->helpers->timeToMysql( time() ) . '\' )' );
|
||||
|
||||
if ( $isLikeGet ) {
|
||||
$key = esc_sql( aioseoTableOfContents()->core->db->db->esc_like( $key ) );
|
||||
$result->whereRaw( '`name` LIKE \'' . $key . '\'' );
|
||||
} else {
|
||||
$key = esc_sql( $key );
|
||||
$result->where( 'name', $key );
|
||||
}
|
||||
|
||||
$result->output( ARRAY_A )->run();
|
||||
|
||||
// If we have nothing in the cache, let's return null.
|
||||
$values = $result->nullSet() ? null : $result->result();
|
||||
|
||||
// If we have something, let's normalize it.
|
||||
if ( $values ) {
|
||||
foreach ( $values as &$value ) {
|
||||
// Use is_object flag to determine decode type: if 0 (false) decode to array, if 1 (true) decode to object.
|
||||
$value['value'] = json_decode( $value['value'], empty( $value['is_object'] ) );
|
||||
}
|
||||
// Return only the single cache value.
|
||||
if ( ! $isLikeGet ) {
|
||||
$values = $values[0]['value'];
|
||||
}
|
||||
}
|
||||
|
||||
// Return values without a static cache.
|
||||
// This is here because clearing the LIKE cache is not simple.
|
||||
if ( $isLikeGet ) {
|
||||
return $values;
|
||||
}
|
||||
|
||||
self::$cache[ $key ] = $values;
|
||||
|
||||
return self::$cache[ $key ];
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the given cache or creates it if it doesn't exist.
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @version 202607 Renamed key to name
|
||||
*
|
||||
* @param string $key The name of the cache.
|
||||
* @param mixed $value The value.
|
||||
* @param int $expiration The expiration time in seconds. Defaults to 24 hours. 0 to no expiration.
|
||||
* @return void
|
||||
*/
|
||||
public function update( $key, $value, $expiration = DAY_IN_SECONDS ) {
|
||||
$key = $this->prepareKey( $key );
|
||||
|
||||
// If the value is null we'll convert it and give it a shorter expiration.
|
||||
if ( null === $value ) {
|
||||
$value = false;
|
||||
$expiration = 10 * MINUTE_IN_SECONDS;
|
||||
}
|
||||
|
||||
// Check if we should use transients
|
||||
if ( ! $this->isCacheTableAvailable() ) {
|
||||
$this->updateTransient( $key, $value, $expiration );
|
||||
$this->updateStatic( $key, $value );
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$isObject = is_object( $value );
|
||||
$jsonValue = wp_json_encode( $value );
|
||||
$expiration = 0 < $expiration ? aioseoTableOfContents()->helpers->timeToMysql( time() + $expiration ) : null;
|
||||
|
||||
// Handle JSON encoding errors.
|
||||
if ( false === $jsonValue && JSON_ERROR_NONE !== json_last_error() ) {
|
||||
if ( aioseoTableOfContents()->helpers->isDev() ) {
|
||||
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
|
||||
error_log( 'AIOSEO Plugin Cache: JSON encode failed for name "' . $key . '" - ' . json_last_error_msg() );
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
aioseoTableOfContents()->core->db->insert( $this->table )
|
||||
->set( [
|
||||
'name' => $this->prepareKey( $key ),
|
||||
'value' => $jsonValue,
|
||||
'is_object' => $isObject,
|
||||
'expiration' => $expiration,
|
||||
'created' => aioseoTableOfContents()->helpers->timeToMysql( time() ),
|
||||
'updated' => aioseoTableOfContents()->helpers->timeToMysql( time() )
|
||||
] )->onDuplicate( [
|
||||
'value' => $jsonValue,
|
||||
'is_object' => $isObject,
|
||||
'expiration' => $expiration,
|
||||
'updated' => aioseoTableOfContents()->helpers->timeToMysql( time() )
|
||||
] )
|
||||
->run();
|
||||
|
||||
$this->updateStatic( $key, $value );
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the cache record with the given key.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $key The name of the cache.
|
||||
* @return void
|
||||
*/
|
||||
public function delete( $key ) {
|
||||
$key = $this->prepareKey( $key );
|
||||
|
||||
// Check if we should use transients
|
||||
if ( ! $this->isCacheTableAvailable() ) {
|
||||
$this->deleteTransient( $key );
|
||||
$this->clearStatic( $key );
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
aioseoTableOfContents()->core->db->delete( $this->table )
|
||||
->where( 'name', $key )
|
||||
->run();
|
||||
|
||||
$this->clearStatic( $key );
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares the key before using the cache.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $key The name of the cache to prepare.
|
||||
* @return string The prepared key.
|
||||
*/
|
||||
private function prepareKey( $key ) {
|
||||
$key = trim( (string) $key );
|
||||
$key = $this->prefix && 0 !== strpos( $key, $this->prefix ) ? $this->prefix . $key : $key;
|
||||
|
||||
if ( aioseoTableOfContents()->helpers->isDev() && 80 < mb_strlen( $key, 'UTF-8' ) ) {
|
||||
throw new \Exception( 'You are using a cache name that is too large, shorten your name and try again: [' . esc_html( $key ) . ']' );
|
||||
}
|
||||
|
||||
return $key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears all of our cache.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function clear() {
|
||||
if ( $this->prefix ) {
|
||||
$this->clearPrefix( '' );
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if we should use transients
|
||||
if ( ! $this->isCacheTableAvailable() ) {
|
||||
// Delete all AIOSEO plugin cache transients
|
||||
$this->deleteAllTransients();
|
||||
$this->clearStatic();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
aioseoTableOfContents()->core->db->truncate( $this->table )->run();
|
||||
|
||||
$this->clearStatic();
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears all of our cache under a certain prefix.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $prefix A prefix to clear or empty to clear everything.
|
||||
* @return void
|
||||
*/
|
||||
public function clearPrefix( $prefix ) {
|
||||
$prefix = $this->prepareKey( $prefix );
|
||||
|
||||
// Check if we should use transients
|
||||
if ( ! $this->isCacheTableAvailable() ) {
|
||||
// Delete transients by prefix
|
||||
$this->deleteTransientsByPrefix( $prefix );
|
||||
$this->clearStaticPrefix( $prefix );
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
aioseoTableOfContents()->core->db->delete( $this->table )
|
||||
->whereRaw( "`name` LIKE '$prefix%'" )
|
||||
->run();
|
||||
|
||||
$this->clearStaticPrefix( $prefix );
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears all of our static in-memory cache of a prefix.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $prefix The prefix to clear.
|
||||
* @return void
|
||||
*/
|
||||
private function clearStaticPrefix( $prefix ) {
|
||||
$prefix = $this->prepareKey( $prefix );
|
||||
foreach ( array_keys( self::$cache ) as $key ) {
|
||||
if ( 0 === strpos( $key, $prefix ) ) {
|
||||
unset( self::$cache[ $key ] );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears all of our static in-memory cache.
|
||||
*
|
||||
* @since 1.0.0
|
||||
* @version 202607 Renamed key to name
|
||||
*
|
||||
* @param string $key The name of the cache to clear.
|
||||
* @return void
|
||||
*/
|
||||
private function clearStatic( $key = null ) {
|
||||
if ( empty( $key ) ) {
|
||||
self::$cache = [];
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
unset( self::$cache[ $this->prepareKey( $key ) ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the static in-memory cache for a single given key.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $key The key to update.
|
||||
* @param mixed $value The value to cache.
|
||||
* @return void
|
||||
*/
|
||||
private function updateStatic( $key = null, $value = null ) {
|
||||
if ( empty( $key ) ) {
|
||||
$this->clearStatic( $key );
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
self::$cache[ $this->prepareKey( $key ) ] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the cache table is available for use.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @return bool True if table exists and is accessible.
|
||||
*/
|
||||
private function isCacheTableAvailable() {
|
||||
if ( null !== $this->useTransientFallback ) {
|
||||
return ! $this->useTransientFallback;
|
||||
}
|
||||
|
||||
// Check transient first to avoid a DB query on every request.
|
||||
if ( get_transient( 'aioseo_plugin_cache_table_exists' ) ) {
|
||||
$this->useTransientFallback = false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Transient not set — check the DB directly (avoids circular dependency with Database::tableExists).
|
||||
global $wpdb;
|
||||
$tableName = $wpdb->prefix . $this->table;
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
|
||||
$tableExists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $tableName ) );
|
||||
|
||||
if ( ! $tableExists ) {
|
||||
$this->useTransientFallback = true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Verify the table has the expected 'name' column. During upgrades from older versions
|
||||
// the table may still have the legacy 'key' column. If the migration hasn't run yet,
|
||||
// we must fall back to transients to avoid "Unknown column 'name'" errors.
|
||||
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
|
||||
$nameColumnExists = $wpdb->get_var(
|
||||
$wpdb->prepare(
|
||||
"SELECT COLUMN_NAME
|
||||
FROM INFORMATION_SCHEMA.COLUMNS
|
||||
WHERE TABLE_SCHEMA = DATABASE()
|
||||
AND TABLE_NAME = %s
|
||||
AND COLUMN_NAME = 'name'",
|
||||
$tableName
|
||||
)
|
||||
);
|
||||
|
||||
if ( ! $nameColumnExists ) {
|
||||
$this->useTransientFallback = true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
set_transient( 'aioseo_plugin_cache_table_exists', 1, WEEK_IN_SECONDS );
|
||||
$this->useTransientFallback = false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the transient name for a cache key.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $key The cache key.
|
||||
* @return string The transient name.
|
||||
*/
|
||||
private function getTransientName( $key ) {
|
||||
// Store the original key to maintain compatibility with LIKE queries
|
||||
return 'aioseo_plugin_cache_' . $key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a value from transients.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $key The cache key.
|
||||
* @return mixed The cached value or null.
|
||||
*/
|
||||
private function getTransient( $key ) {
|
||||
$transientName = $this->getTransientName( $key );
|
||||
$data = get_transient( $transientName );
|
||||
|
||||
if ( false === $data ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Decode the wrapper structure
|
||||
$wrapper = json_decode( $data, true );
|
||||
if ( ! is_array( $wrapper ) || ! isset( $wrapper['value'] ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Decode JSON value using is_object flag (matching database cache behavior)
|
||||
// If is_object is 1 (true), decode to object; if 0 (false), decode to array
|
||||
$decoded = json_decode( $wrapper['value'], empty( $wrapper['is_object'] ) );
|
||||
|
||||
return $decoded;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets multiple transients using a LIKE query.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $pattern The pattern to match (with % wildcards).
|
||||
* @return mixed Array of matching cache entries or null.
|
||||
*/
|
||||
private function getTransientLike( $pattern ) {
|
||||
global $wpdb;
|
||||
|
||||
$transientPattern = $this->getTransientName( $pattern );
|
||||
|
||||
// Query for non-expired transients matching the pattern
|
||||
$results = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
|
||||
$wpdb->prepare(
|
||||
"SELECT REPLACE(option_name, '_transient_', '') as `key`, option_value as `value`
|
||||
FROM {$wpdb->options}
|
||||
WHERE option_name LIKE %s
|
||||
AND option_name NOT LIKE %s
|
||||
AND (
|
||||
NOT EXISTS (
|
||||
SELECT 1 FROM {$wpdb->options} timeout
|
||||
WHERE timeout.option_name = CONCAT('_transient_timeout_', REPLACE(option_name, '_transient_', ''))
|
||||
AND CAST(timeout.option_value AS UNSIGNED) > 0
|
||||
AND CAST(timeout.option_value AS UNSIGNED) < UNIX_TIMESTAMP()
|
||||
)
|
||||
)",
|
||||
'_transient_' . implode( '%', array_map( [ $wpdb, 'esc_like' ], explode( '%', $transientPattern ) ) ),
|
||||
'_transient_timeout_%'
|
||||
),
|
||||
ARRAY_A
|
||||
);
|
||||
|
||||
if ( empty( $results ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Decode JSON values with is_object flag
|
||||
foreach ( $results as &$result ) {
|
||||
$result['key'] = str_replace( 'aioseo_plugin_cache_', '', $result['key'] );
|
||||
|
||||
// Decode the wrapper structure
|
||||
$wrapper = json_decode( $result['value'], true );
|
||||
if ( is_array( $wrapper ) && isset( $wrapper['value'] ) ) {
|
||||
// Decode JSON value using is_object flag (matching database cache behavior)
|
||||
// If is_object is 1 (true), decode to object; if 0 (false), decode to array
|
||||
$result['value'] = json_decode( $wrapper['value'], empty( $wrapper['is_object'] ) );
|
||||
} else {
|
||||
// Fallback for malformed data
|
||||
$result['value'] = null;
|
||||
}
|
||||
}
|
||||
|
||||
return $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates a transient value.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $key The cache key.
|
||||
* @param mixed $value The value to cache.
|
||||
* @param int $expiration Expiration in seconds.
|
||||
* @return void
|
||||
*/
|
||||
private function updateTransient( $key, $value, $expiration ) {
|
||||
$transientName = $this->getTransientName( $key );
|
||||
|
||||
// Detect if value is an object to match database cache behavior
|
||||
$isObject = is_object( $value );
|
||||
|
||||
// Encode as JSON to match database cache behavior
|
||||
$jsonValue = wp_json_encode( $value );
|
||||
|
||||
if ( false === $jsonValue && JSON_ERROR_NONE !== json_last_error() ) {
|
||||
if ( aioseoTableOfContents()->helpers->isDev() ) {
|
||||
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
|
||||
error_log( 'AIOSEO Plugin Cache: JSON encode failed for key "' . $key . '" - ' . json_last_error_msg() );
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// Wrap the value with metadata including is_object flag
|
||||
$wrapper = [
|
||||
'value' => $jsonValue,
|
||||
'is_object' => $isObject
|
||||
];
|
||||
|
||||
$wrappedValue = wp_json_encode( $wrapper );
|
||||
|
||||
if ( false === $wrappedValue ) {
|
||||
if ( aioseoTableOfContents()->helpers->isDev() ) {
|
||||
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
|
||||
error_log( 'AIOSEO Plugin Cache: JSON encode failed for wrapper on key "' . $key . '"' );
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
set_transient( $transientName, $wrappedValue, $expiration );
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a transient.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $key The cache key.
|
||||
* @return void
|
||||
*/
|
||||
private function deleteTransient( $key ) {
|
||||
$transientName = $this->getTransientName( $key );
|
||||
delete_transient( $transientName );
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes all transients matching a prefix.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $prefix The prefix to match.
|
||||
* @return void
|
||||
*/
|
||||
private function deleteTransientsByPrefix( $prefix ) {
|
||||
global $wpdb;
|
||||
|
||||
$escapedPrefix = $wpdb->esc_like( $this->getTransientName( $prefix ) );
|
||||
|
||||
// Delete both the transient and its timeout
|
||||
$wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
|
||||
$wpdb->prepare(
|
||||
"DELETE FROM {$wpdb->options}
|
||||
WHERE option_name LIKE %s
|
||||
OR option_name LIKE %s",
|
||||
'_transient_' . $escapedPrefix . '%',
|
||||
'_transient_timeout_' . $escapedPrefix . '%'
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes all AIOSEO plugin cache transients.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private function deleteAllTransients() {
|
||||
global $wpdb;
|
||||
|
||||
$prefix = 'aioseo_plugin_cache_%';
|
||||
|
||||
// Delete both transients and their timeouts
|
||||
$wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
|
||||
$wpdb->prepare(
|
||||
"DELETE FROM {$wpdb->options}
|
||||
WHERE option_name LIKE %s
|
||||
OR option_name LIKE %s",
|
||||
'_transient_' . $wpdb->esc_like( $prefix ),
|
||||
'_transient_timeout_' . $wpdb->esc_like( $prefix )
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
namespace AIOSEO\TableOfContents\Core;
|
||||
|
||||
// Exit if accessed directly.
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
use AIOSEO\TableOfContents\Options;
|
||||
use AIOSEO\TableOfContents\Utils;
|
||||
|
||||
/**
|
||||
* Loads core classes.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*/
|
||||
class Core {
|
||||
/**
|
||||
* DB class instance.
|
||||
*
|
||||
* @since 1.1.0
|
||||
*
|
||||
* @var Database
|
||||
*/
|
||||
public $db = null;
|
||||
|
||||
/**
|
||||
* Filesystem class instance.
|
||||
*
|
||||
* @since 1.1.0
|
||||
*
|
||||
* @var Filesystem
|
||||
*/
|
||||
public $fs = null;
|
||||
|
||||
/**
|
||||
* Assets class instance.
|
||||
*
|
||||
* @since 1.1.0
|
||||
*
|
||||
* @var Assets
|
||||
*/
|
||||
public $assets = null;
|
||||
|
||||
/**
|
||||
* Cache class instance.
|
||||
*
|
||||
* @since 1.1.0
|
||||
*
|
||||
* @var Cache
|
||||
*/
|
||||
public $cache = null;
|
||||
|
||||
/**
|
||||
* NetworkCache class instance.
|
||||
*
|
||||
* @since 1.1.0
|
||||
*
|
||||
* @var NetworkCache
|
||||
*/
|
||||
public $networkCache = null;
|
||||
|
||||
/**
|
||||
* Options Cache class instance.
|
||||
*
|
||||
* @since 1.1.0
|
||||
*
|
||||
* @var \AIOSEO\TableOfContents\Options\Cache
|
||||
*/
|
||||
public $optionsCache = null;
|
||||
|
||||
/**
|
||||
* Uninstall class instance.
|
||||
*
|
||||
* @since 1.1.0
|
||||
*
|
||||
* @var Uninstall
|
||||
*/
|
||||
public $uninstall = null;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public function __construct() {
|
||||
$this->db = new Database();
|
||||
$this->fs = new Filesystem( $this );
|
||||
$this->assets = new Assets( $this );
|
||||
$this->cache = new Cache();
|
||||
$this->networkCache = new NetworkCache();
|
||||
$this->optionsCache = new Options\Cache();
|
||||
$this->uninstall = new Uninstall();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,280 @@
|
||||
<?php
|
||||
// phpcs:disable WordPress.WP.AlternativeFunctions
|
||||
namespace AIOSEO\TableOfContents\Core;
|
||||
|
||||
// Exit if accessed directly.
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface for the filesystem.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*/
|
||||
class Filesystem {
|
||||
/**
|
||||
* Holds the WP filesystem instance.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @var \WP_Filesystem_Base
|
||||
*/
|
||||
public $fs = null;
|
||||
|
||||
/**
|
||||
* Core class instance.
|
||||
*
|
||||
* @since 1.1.0
|
||||
*
|
||||
* @var Core
|
||||
*/
|
||||
public $core = null;
|
||||
|
||||
/**
|
||||
* Class constructor.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param Core $core The Core class.
|
||||
* @param array $args Optional arguments needed to construct the class with.
|
||||
*/
|
||||
public function __construct( $core, $args = [] ) {
|
||||
$this->core = $core;
|
||||
$this->init( $args );
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the filesystem.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param array $args List of arguments for the WP_Filesystem class.
|
||||
* @return void
|
||||
*/
|
||||
public function init( $args = [] ) {
|
||||
require_once ABSPATH . 'wp-admin/includes/file.php';
|
||||
|
||||
WP_Filesystem( $args );
|
||||
|
||||
global $wp_filesystem;
|
||||
if ( is_object( $wp_filesystem ) ) {
|
||||
$this->fs = $wp_filesystem;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrapper method to check if a file exists.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $filename The filename to check if it exists.
|
||||
* @return bool Returns true if the file or dir specified exists; false otherwise.
|
||||
*/
|
||||
public function exists( $filename ) {
|
||||
if ( ! $this->isWpfsValid() ) {
|
||||
return @file_exists( $filename );
|
||||
}
|
||||
|
||||
return $this->fs->exists( $filename );
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve the contents of a file.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $filename The filename to get the contents for.
|
||||
* @return string|bool The function returns the read data or false on failure.
|
||||
*/
|
||||
public function getContents( $filename ) {
|
||||
if ( ! $this->exists( $filename ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( ! $this->isWpfsValid() ) {
|
||||
return @file_get_contents( $filename );
|
||||
}
|
||||
|
||||
return $this->fs->get_contents( $filename );
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads entire file into an array.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $file Path to the file.
|
||||
* @return array|bool File contents in an array on success, false on failure.
|
||||
*/
|
||||
public function getContentsArray( $file ) {
|
||||
if ( ! $this->exists( $file ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ( ! $this->isWpfsValid() ) {
|
||||
return @file( $file );
|
||||
}
|
||||
|
||||
return $this->fs->get_contents_array( $file );
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the access and modification times of a file.
|
||||
* Note: If $file doesn't exist, it will be created.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $file Path to file.
|
||||
* @param int $time Optional. Modified time to set for file. Default 0.
|
||||
* @param int $atime Optional. Access time to set for file. Default 0.
|
||||
* @return bool True on success, false on failure.
|
||||
*/
|
||||
public function touch( $file, $time = 0, $atime = 0 ) {
|
||||
if ( 0 === $time ) {
|
||||
$time = time();
|
||||
}
|
||||
|
||||
if ( 0 === $atime ) {
|
||||
$atime = time();
|
||||
}
|
||||
|
||||
if ( ! $this->isWpfsValid() ) {
|
||||
return @touch( $file, $time, $atime );
|
||||
}
|
||||
|
||||
return $this->fs->touch( $file, $time, $atime );
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a string to a file.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $file Remote path to the file where to write the data.
|
||||
* @param string $contents The data to write.
|
||||
* @param int|false $mode Optional. The file permissions as octal number, usually 0644. Default false.
|
||||
* @return int|bool True on success, false on failure.
|
||||
*/
|
||||
public function putContents( $file, $contents, $mode = false ) {
|
||||
if ( ! $this->isWpfsValid() ) {
|
||||
return @file_put_contents( $file, $contents );
|
||||
}
|
||||
|
||||
return $this->fs->put_contents( $file, $contents, $mode );
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a file or dir is writable.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $file Path to file or dir.
|
||||
* @return bool Whether $file is writable.
|
||||
*/
|
||||
public function isWritable( $file ) {
|
||||
if ( ! $this->isWpfsValid() ) {
|
||||
return @is_writable( $file );
|
||||
}
|
||||
|
||||
return $this->fs->is_writable( $file );
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a file is readable.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $file Path to file.
|
||||
* @return bool Whether $file is readable.
|
||||
*/
|
||||
public function isReadable( $file ) {
|
||||
if ( ! $this->isWpfsValid() ) {
|
||||
return @is_readable( $file );
|
||||
}
|
||||
|
||||
return $this->fs->is_readable( $file );
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the file size (in bytes).
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $file Path to file.
|
||||
* @return int|bool Size of the file in bytes on success, false on failure.
|
||||
*/
|
||||
public function size( $file ) {
|
||||
if ( ! $this->isWpfsValid() ) {
|
||||
return @filesize( $file );
|
||||
}
|
||||
|
||||
return $this->fs->size( $file );
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if resource is a file.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $file File path.
|
||||
* @return bool Whether $file is a file.
|
||||
*/
|
||||
public function isFile( $file ) {
|
||||
if ( ! $this->isWpfsValid() ) {
|
||||
return @is_file( $file );
|
||||
}
|
||||
|
||||
return $this->fs->is_file( $file );
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if resource is a directory.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $path Directory path.
|
||||
* @return bool Whether $path is a directory.
|
||||
*/
|
||||
public function isDir( $path ) {
|
||||
if ( ! $this->isWpfsValid() ) {
|
||||
return @is_dir( $path );
|
||||
}
|
||||
|
||||
return $this->fs->is_dir( $path );
|
||||
}
|
||||
|
||||
/**
|
||||
* A simple check to ensure that the WP_Filesystem is valid.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @return bool True if valid, false if not.
|
||||
*/
|
||||
public function isWpfsValid() {
|
||||
if (
|
||||
! is_a( $this->fs, 'WP_Filesystem_Base' ) ||
|
||||
(
|
||||
// Errors is a WP_Error object.
|
||||
! empty( $this->fs->errors ) &&
|
||||
// We check if the errors array is empty for compatibility with WP < 5.1.
|
||||
! empty( $this->fs->errors->errors )
|
||||
)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* In order to prevent conflicts, we need to return a clone.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @return Filesystem The cloned Filesystem object.
|
||||
*/
|
||||
public function noConflict() {
|
||||
return clone $this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
<?php
|
||||
namespace AIOSEO\TableOfContents\Core;
|
||||
|
||||
// Exit if accessed directly.
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles our network cache.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*/
|
||||
class NetworkCache extends Cache {
|
||||
/**
|
||||
* Returns the cache value for a key if it exists and is not expired.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $key The cache key name. Use a '%' for a like query.
|
||||
* @return mixed The value or null if the cache does not exist.
|
||||
*/
|
||||
public function get( $key ) {
|
||||
if ( ! is_multisite() ) {
|
||||
return parent::get( $key );
|
||||
}
|
||||
|
||||
aioseoTableOfContents()->helpers->switchToBlog( aioseoTableOfContents()->helpers->getNetworkId() );
|
||||
$value = parent::get( $key );
|
||||
aioseoTableOfContents()->helpers->restoreCurrentBlog();
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the given cache or creates it if it doesn't exist.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $key The cache key name.
|
||||
* @param mixed $value The value.
|
||||
* @param int $expiration The expiration time in seconds. Defaults to 24 hours. 0 to no expiration.
|
||||
* @return void
|
||||
*/
|
||||
public function update( $key, $value, $expiration = DAY_IN_SECONDS ) {
|
||||
if ( ! is_multisite() ) {
|
||||
parent::update( $key, $value, $expiration );
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
aioseoTableOfContents()->helpers->switchToBlog( aioseoTableOfContents()->helpers->getNetworkId() );
|
||||
parent::update( $key, $value, $expiration );
|
||||
aioseoTableOfContents()->helpers->restoreCurrentBlog();
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the given cache key.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $key The cache key.
|
||||
* @return void
|
||||
*/
|
||||
public function delete( $key ) {
|
||||
if ( ! is_multisite() ) {
|
||||
parent::delete( $key );
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
aioseoTableOfContents()->helpers->switchToBlog( aioseoTableOfContents()->helpers->getNetworkId() );
|
||||
parent::delete( $key );
|
||||
aioseoTableOfContents()->helpers->restoreCurrentBlog();
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears all of our cache.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function clear() {
|
||||
if ( ! is_multisite() ) {
|
||||
parent::clear();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
aioseoTableOfContents()->helpers->switchToBlog( aioseoTableOfContents()->helpers->getNetworkId() );
|
||||
parent::clear();
|
||||
aioseoTableOfContents()->helpers->restoreCurrentBlog();
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears all of our cache under a certain prefix.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param string $prefix A prefix to clear or empty to clear everything.
|
||||
* @return void
|
||||
*/
|
||||
public function clearPrefix( $prefix ) {
|
||||
if ( ! is_multisite() ) {
|
||||
parent::clearPrefix( $prefix );
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
aioseoTableOfContents()->helpers->switchToBlog( aioseoTableOfContents()->helpers->getNetworkId() );
|
||||
parent::clearPrefix( $prefix );
|
||||
aioseoTableOfContents()->helpers->restoreCurrentBlog();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
namespace AIOSEO\TableOfContents\Core;
|
||||
|
||||
// Exit if accessed directly.
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles plugin deinstallation.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*/
|
||||
class Uninstall {
|
||||
/**
|
||||
* Removes all our tables and options.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @param bool $force Whether we should ignore the uninstall option or not. We ignore it when we reset all data via the Debug Panel.
|
||||
* @return void
|
||||
*/
|
||||
public function dropData( $force = false ) {
|
||||
// Confirm that user has decided to remove all data, otherwise stop.
|
||||
if (
|
||||
! $force &&
|
||||
( ! aioseoTableOfContents()->options->advanced->enable || ! aioseoTableOfContents()->options->advanced->uninstall )
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Delete all our custom tables.
|
||||
global $wpdb;
|
||||
foreach ( $this->getDbTables() as $tableName ) {
|
||||
$wpdb->query( 'DROP TABLE IF EXISTS ' . $tableName ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
|
||||
}
|
||||
|
||||
// Delete all the plugin settings.
|
||||
$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE 'aioseo\_table_of_contents\_%'" );
|
||||
|
||||
// Remove any transients we've left behind.
|
||||
$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE '\_aioseo\_table_of_contents\_%'" );
|
||||
|
||||
// Delete all entries from the action scheduler table.
|
||||
$wpdb->query( "DELETE FROM {$wpdb->prefix}actionscheduler_actions WHERE hook LIKE 'aioseo\_table_of_contents\_%'" );
|
||||
$wpdb->query( "DELETE FROM {$wpdb->prefix}actionscheduler_groups WHERE slug = 'aioseo\_table_of_contents'" );
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns all the DB tables with their prefix.
|
||||
*
|
||||
* @since 1.0.0
|
||||
*
|
||||
* @return array List of tables.
|
||||
*/
|
||||
private function getDbTables() {
|
||||
global $wpdb;
|
||||
|
||||
$tables = [];
|
||||
foreach ( aioseoTableOfContents()->core->db->customTables as $tableName ) {
|
||||
$tables[] = $wpdb->prefix . $tableName;
|
||||
}
|
||||
|
||||
return $tables;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user