Commit inicial powerservice

This commit is contained in:
Gabriel
2026-10-19 12:45:45 -06:00
commit ad85486fe2
10158 changed files with 2736804 additions and 0 deletions
@@ -0,0 +1,471 @@
<?php
namespace AIOSEO\TableOfContents\Admin;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Handles all general admin code.
*
* @since 1.0.0
*/
class Admin {
/**
* The main page slug.
*
* @since 1.0.0
*
* @var string
*/
private $pageSlug = 'table-of-contents';
/**
* The current page.
* This gets set as soon as we've identified that we're on a Table of Contents Plus page.
*
* @since 1.0.0
*
* @var string
*/
private $currentPage = '';
/**
* An list of asset slugs to use.
*
* @since 1.0.0
*
* @var array
*/
private $assetSlugs = [
'pages' => 'src/vue/pages/{page}/main.js'
];
/**
* The plugin basename.
*
* @since 1.1.0
*
* @var string
*/
public $plugin = '';
/**
* The list of pages.
*
* @since 1.2.0
*
* @var array
*/
private $pages = [];
/**
* Class constructor.
*
* @since 1.0.0
*/
public function __construct() {
if ( ! is_admin() ) {
return;
}
add_action( 'admin_menu', [ $this, 'registerMenu' ] );
add_action( 'admin_menu', [ $this, 'hideScheduledActionsMenu' ], 999 );
add_filter( 'language_attributes', [ $this, 'addDirAttribute' ], 3000 );
add_filter( 'plugin_row_meta', [ $this, 'registerRowMeta' ], 10, 2 );
add_filter( 'plugin_action_links_' . AIOSEO_TABLE_OF_CONTENTS_PLUGIN_BASENAME, [ $this, 'registerActionLinks' ], 10, 2 );
add_action( 'admin_footer', [ $this, 'addAioseoModalPortal' ] );
}
/**
* Checks whether the current page is a Table of Contents Plus page.
*
* @since 1.0.0
*
* @return bool Whether the current page is a Table of Contents Plus page.
*/
public function isTableOfContentsPage() {
return ! empty( $this->currentPage );
}
/**
* Add the dir attribute to the HTML tag.
*
* @since 1.0.0
*
* @param string $output The HTML language attribute.
* @return string The modified HTML language attribute.
*/
public function addDirAttribute( $output ) {
if ( is_rtl() || preg_match( '/dir=[\'"](ltr|rtl|auto)[\'"]/i', (string) $output ) ) {
return $output;
}
return 'dir="ltr" ' . $output;
}
/**
* Registers the menu.
*
* @since 1.0.0
*
* @return void
*/
public function registerMenu() {
$hook = add_menu_page(
__( 'Table of Contents Plus', 'table-of-contents-plus' ),
__( 'ToC+', 'table-of-contents-plus' ),
'manage_options',
$this->pageSlug,
[ $this, 'renderMenuPage' ],
'data:image/svg+xml;base64,' . base64_encode( $this->getMenuIcon() )
);
add_action( "load-{$hook}", [ $this, 'checkCurrentPage' ] );
$this->registerMenuPages();
}
/**
* Renders the element that we mount our Vue UI on.
*
* @since 1.0.0
*
* @return void
*/
public function renderMenuPage() {
echo '<div id="table-of-contents-plus-app"></div>';
}
/**
* Returns the branded menu icon (anchor badge) as SVG markup.
*
* @since 202607.1
*
* @return string The SVG markup.
*/
private function getMenuIcon() {
return '<svg width="20" height="20" viewBox="0 0 128 128" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" clip-rule="evenodd" d="M64 128C99.3462 128 128 99.3462 128 64C128 28.6538 99.3462 0 64 0C28.6538 0 0 28.6538 0 64C0 99.3462 28.6538 128 64 128Z M64.1538 25.5384C67.5385 25.5384 70.6154 26.7692 72.9231 29.3846C75.2308 31.6923 76.3077 34.6153 76.4615 37.8461V38.4615C76.4615 41.2307 75.6923 43.6923 74.1538 45.8461C72.9231 47.5384 71.3846 48.923 69.5385 49.8461V52.923H76.3077C78.3077 52.923 80 54.6153 80 56.6153V60.6153C80 62.6153 78.3077 64.3077 76.3077 64.3077H69.5385V89.2307C72.3077 88.6153 74.9231 87.3846 77.5385 85.8461C80.3077 84.1538 82.4615 82.1538 83.8461 80L80.9231 76.923C79.3846 75.3846 79.5385 72.7692 81.3846 71.3846L91.2308 63.6923C93.6923 61.8461 97.0769 63.5384 97.0769 66.6153V74.1538C97.0769 78 96 81.6923 93.8461 85.0769C91.8461 88.3076 89.0769 91.2307 86 93.5384C82.7692 96 79.2308 97.8461 75.3846 99.2307C71.5385 100.615 67.6923 101.385 63.8461 101.385C60 101.385 56.3077 100.615 52.3077 99.2307C48.4615 97.8461 44.9231 96 41.6923 93.5384C38.4615 91.0769 35.8461 88.3076 33.8461 85.0769C31.6923 81.6923 30.6154 78 30.6154 74.1538V66.6153C30.6154 63.5384 34 61.8461 36.4615 63.6923L46.3077 71.3846C48 72.7692 48.1538 75.3846 46.7692 76.923L43.8461 80C45.3846 82.1538 47.3846 84 50.1538 85.8461C52.7692 87.3846 55.5385 88.6153 58.1538 89.2307V64.4615H51.3846C49.3846 64.4615 47.6923 62.7692 47.6923 60.7692V56.7692C47.6923 54.7692 49.3846 53.0769 51.3846 53.0769H58.4615V50C56.6154 49.0769 55.0769 47.6923 53.8461 46C52.3077 44 51.5385 41.5384 51.5385 39.0769V38.6153C51.5385 35.0769 52.7692 32 55.0769 29.5384C57.6923 26.923 60.6154 25.5384 64.1538 25.5384ZM64.1538 34.1538C62.9231 34.1538 62 34.6153 61.2308 35.3846C60.4615 36.1538 60 37.2307 60 38.4615C60 39.6923 60.4615 40.7692 61.2308 41.5384C62 42.3077 62.9231 42.7692 64.1538 42.7692C65.3846 42.7692 66.3077 42.3077 67.0769 41.5384C67.8461 40.7692 68.3077 39.6923 68.3077 38.4615C68.3077 37.2307 67.8461 36.1538 67.0769 35.3846C66.3077 34.6153 65.3846 34.1538 64.1538 34.1538Z" fill="#a7aaad"/></svg>'; // phpcs:ignore Generic.Files.LineLength.MaxExceeded
}
/**
* Registers our menu pages.
*
* @since 1.0.0
*
* @return void
*/
public function registerMenuPages() {
// Relabel the auto-created first submenu (which otherwise inherits the "ToC+"
// menu title) to "Settings" for clarity.
add_submenu_page(
$this->pageSlug,
__( 'Settings', 'table-of-contents-plus' ),
__( 'Settings', 'table-of-contents-plus' ),
'manage_options',
$this->pageSlug,
[ $this, 'renderMenuPage' ]
);
$hook = add_submenu_page(
$this->pageSlug,
__( 'About Us', 'table-of-contents-plus' ),
__( 'About Us', 'table-of-contents-plus' ),
'manage_options',
$this->pageSlug . '-about',
[ $this, 'renderMenuPage' ]
);
$this->pages[] = $this->pageSlug . '-about';
add_action( "load-{$hook}", [ $this, 'checkCurrentPage' ] );
}
/**
* Checks if the current page is a Table of Contents Plus page and if so, starts enqueing the relevant assets.
*
* @since 1.0.0
*
* @return void
*/
public function checkCurrentPage() {
global $admin_page_hooks; // phpcs:ignore Squiz.NamingConventions.ValidVariableName.NotCamelCaps
$currentScreen = function_exists( 'get_current_screen' ) ? get_current_screen() : false;
if ( empty( $currentScreen->id ) || empty( $admin_page_hooks ) ) { // phpcs:ignore Squiz.NamingConventions.ValidVariableName.NotCamelCaps
return;
}
$pages = [
'about'
];
foreach ( $pages as $page ) {
$addScripts = false;
if ( 'toplevel_page_table-of-contents' === $currentScreen->id ) {
$page = 'settings';
$addScripts = true;
}
if ( strpos( $currentScreen->id, 'table-of-contents-' . $page ) !== false ) {
$addScripts = true;
}
if ( ! $addScripts ) {
continue;
}
// We don't want other plugins adding notices to our screens. Let's clear them out here.
remove_all_actions( 'admin_notices' );
remove_all_actions( 'network_admin_notices' );
remove_all_actions( 'all_admin_notices' );
$this->currentPage = $page;
add_action( 'admin_enqueue_scripts', [ $this, 'enqueueMenuAssets' ], 11 );
add_filter( 'admin_footer_text', [ $this, 'addFooterText' ] );
break;
}
}
/**
* Enqueues our menu assets, based on the current page.
*
* @since 1.0.0
*
* @return void
*/
public function enqueueMenuAssets() {
if ( ! $this->currentPage ) {
return;
}
$scriptHandle = str_replace( '{page}', $this->currentPage, $this->assetSlugs['pages'] );
aioseoTableOfContents()->core->assets->load( $scriptHandle, [], aioseoTableOfContents()->helpers->getVueData( $this->currentPage ) );
}
/**
* Hides the Scheduled Actions menu.
*
* @since 1.0.0
*
* @return void
*/
public function hideScheduledActionsMenu() {
// Don't hide it for developers when the main plugin isn't active.
if ( defined( 'AIOSEO_TABLE_OF_CONTENTS_DEV' ) && ! function_exists( 'aioseo' ) ) {
return;
}
global $submenu;
if ( ! isset( $submenu['tools.php'] ) ) {
return;
}
// phpcs:disable WordPress.Security.NonceVerification.Recommended, HM.Security.NonceVerification.Recommended
// Don't hide it if we're on the Scheduled Actions menu page.
$page = isset( $_GET['page'] )
? sanitize_text_field( wp_unslash( $_GET['page'] ) )
: '';
// phpcs:enable
if ( 'action-scheduler' === $page || aioseoTableOfContents()->helpers->isDev() ) {
return;
}
foreach ( $submenu['tools.php'] as $index => $props ) {
if ( ! empty( $props[2] ) && 'action-scheduler' === $props[2] ) {
unset( $submenu['tools.php'][ $index ] );
return;
}
}
}
/**
* Registers our row meta for the plugins page.
*
* @since 1.0.0
*
* @param array $actions List of existing actions.
* @param string $pluginFile The plugin file.
* @return array List of action links.
*/
public function registerRowMeta( $actions, $pluginFile ) {
$reviewLabel = str_repeat( '<span class="dashicons dashicons-star-filled" style="font-size: 18px; width:16px; height: 16px; color: #ffb900;"></span>', 5 );
$actionLinks = [
'suggest-feature' => [
// Translators: This is an action link users can click to open a feature request.
'label' => __( 'Suggest a Feature', 'table-of-contents-plus' ),
'url' => aioseoTableOfContents()->helpers->utmUrl( AIOSEO_TABLE_OF_CONTENTS_MARKETING_URL . 'table-of-contents-suggest-a-feature/', 'plugin-row-meta', 'feature' ),
],
'review' => [
'label' => $reviewLabel,
'url' => aioseoTableOfContents()->helpers->utmUrl( 'https://aioseo.com/table-of-contents-plus-rating', 'plugin-row-meta', 'review' ),
]
];
return $this->parseActionLinks( $actions, $pluginFile, $actionLinks );
}
/**
* Registers our action links for the plugins page.
*
* @since 1.0.0
*
* @param array $actions List of existing actions.
* @param string $pluginFile The plugin file.
* @return array List of action links.
*/
public function registerActionLinks( $actions, $pluginFile ) {
$actionLinks = [
'support' => [
// Translators: This is an action link users can click to open our support.
'label' => __( 'Support', 'table-of-contents-plus' ),
'url' => aioseoTableOfContents()->helpers->utmUrl( AIOSEO_TABLE_OF_CONTENTS_MARKETING_URL . 'contact/', 'plugin-action-links', 'Support' ),
]
];
if ( isset( $actions['edit'] ) ) {
unset( $actions['edit'] );
}
$actions = $this->parseActionLinks( $actions, $pluginFile, $actionLinks, 'before' );
// Prepend an internal Settings link. Built separately from the links above
// because those open in a new tab, whereas Settings should stay in the admin.
$settingsLink = sprintf(
'<a href="%1$s">%2$s</a>',
esc_url( admin_url( 'admin.php?page=' . $this->pageSlug ) ),
esc_html__( 'Settings', 'table-of-contents-plus' )
);
return array_merge( [ 'settings' => $settingsLink ], $actions );
}
/**
* Parses the action links.
*
* @since 1.0.0
*
* @param array $actions The actions.
* @param string $pluginFile The plugin file.
* @param array $actionLinks The action links.
* @param string $position The position.
* @return array The parsed actions.
*/
private function parseActionLinks( $actions, $pluginFile, $actionLinks = [], $position = 'after' ) {
if ( empty( $this->plugin ) ) {
$this->plugin = AIOSEO_TABLE_OF_CONTENTS_PLUGIN_BASENAME;
}
if ( $this->plugin === $pluginFile && ! empty( $actionLinks ) ) {
foreach ( $actionLinks as $key => $value ) {
$link = [
$key => sprintf(
'<a href="%1$s" %2$s target="_blank">%3$s</a>',
esc_url( $value['url'] ),
isset( $value['title'] ) ? 'title="' . esc_attr( $value['title'] ) . '"' : '',
$value['label']
)
];
$actions = 'after' === $position ? array_merge( $actions, $link ) : array_merge( $link, $actions );
}
}
return $actions;
}
/**
* Add the div for the modal portal.
*
* @since 1.1.0
*
* @return void
*/
public function addAioseoModalPortal() {
if ( ! function_exists( 'aioseo' ) ) {
echo '<div id="aioseo-modal-portal"></div>';
}
}
/**
* Checks whether the current page is a Table of Contents Plus menu page.
*
* @since 1.2.0
*
* @return bool Whether the current page is a Table of Contents Plus menu page.
*/
public function isTableOfContentsScreen() {
$currentScreen = aioseoTableOfContents()->helpers->getCurrentScreen();
if ( empty( $currentScreen->id ) ) {
return false;
}
$adminPages = array_keys( $this->pages );
$adminPages = array_map( function( $slug ) {
if ( 'aioseo' === $slug ) {
return 'toplevel_page_table-of-contents';
}
return 'table-of-contents_page_' . $slug;
}, $adminPages );
return in_array( $currentScreen->id, $adminPages, true );
}
/**
* Add footer text to the WordPress admin screens.
*
* @since 1.2.0
*
* @return string The footer text.
*/
public function addFooterText() {
$linkText = esc_html__( 'Give us a 5-star rating!', 'table-of-contents-plus' );
$href = 'https://aioseo.com/table-of-contents-plus-rating';
$link1 = sprintf(
'<a href="%1$s" target="_blank" title="%2$s">&#9733;&#9733;&#9733;&#9733;&#9733;</a>',
$href,
$linkText
);
$link2 = sprintf(
'<a href="%1$s" target="_blank" title="%2$s">WordPress.org</a>',
$href,
$linkText
);
printf(
// Translators: 1 - The plugin name, 2 - Star icons, 3 - "WordPress.org", 4 - The plugin name.
esc_html__( 'Please rate %1$s %2$s on %3$s to help us spread the word. Thank you!', 'table-of-contents-plus' ),
sprintf( '<strong>%1$s</strong>', esc_html( AIOSEO_TABLE_OF_CONTENTS_PLUGIN_NAME ) ),
wp_kses_post( $link1 ),
wp_kses_post( $link2 )
);
// Stop WP Core from outputting its version number and instead add both theirs & ours.
global $wp_version; // phpcs:ignore Squiz.NamingConventions.ValidVariableName.NotCamelCaps
printf(
wp_kses_post( '<p class="alignright">%1$s</p>' ),
sprintf(
// Translators: 1 - WP Core version number, 2 - version number.
esc_html__( 'WordPress %1$s | Table of Contents Plus %2$s', 'table-of-contents-plus' ),
esc_html( $wp_version ), // phpcs:ignore Squiz.NamingConventions.ValidVariableName.NotCamelCaps
esc_html( AIOSEO_TABLE_OF_CONTENTS_VERSION )
)
);
remove_filter( 'update_footer', 'core_update_footer' );
return '';
}
}
@@ -0,0 +1,233 @@
<?php
namespace AIOSEO\TableOfContents\Admin\Notices;
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Review plugin notice.
*
* @since 1.2.0
*/
class Review {
/**
* Class constructor.
*
* @since 1.2.0
*/
public function __construct() {
add_action( 'wp_ajax_table-of-contents-plus-dismiss-review-plugin-cta', [ $this, 'dismissNotice' ] );
}
/**
* Go through all the checks to see if we should show the notice.
*
* @since 1.2.0
*
* @return void
*/
public function maybeShowNotice() {
// Don't show to users that cannot interact with the plugin.
if ( ! current_user_can( 'edit_posts' ) ) {
return;
}
if ( aioseoTableOfContents()->admin->isTableOfContentsScreen() ) {
return;
}
$dismissed = get_user_meta( get_current_user_id(), '_aioseo_table_of_contents_plugin_review_dismissed', true );
if ( '3' === $dismissed || '4' === $dismissed ) {
return;
}
if ( ! empty( $dismissed ) && $dismissed > time() ) {
return;
}
// Show once plugin has been active for 2 weeks.
if ( ! aioseoTableOfContents()->internalOptions->internal->firstActivated ) {
aioseoTableOfContents()->internalOptions->internal->firstActivated = time();
}
$activated = aioseoTableOfContents()->internalOptions->internal->firstActivated( time() );
if ( $activated > strtotime( '-2 weeks' ) ) {
return;
}
$this->showNotice();
// Print the script to the footer.
add_action( 'admin_footer', [ $this, 'printScript' ] );
}
/**
* Actually show the review plugin 2.0.
*
* @since 1.2.0
*
* @return void
*/
public function showNotice() {
$string1 = sprintf(
// Translators: 1 - The plugin name ("Table of Contents Plus").
__( 'Hey, we noticed you have been using %1$s for some time - that’s awesome! Could you please do us a BIG favor and give it a 5-star rating on WordPress to help us spread the word and boost our motivation?', 'table-of-contents-plus' ), // phpcs:ignore Generic.Files.LineLength.MaxExceeded
'<strong>' . esc_html( AIOSEO_TABLE_OF_CONTENTS_PLUGIN_NAME ) . '</strong>'
);
// Translators: 1 - The plugin name ("Table of Contents Plus").
$string9 = __( 'Ok, you deserve it', 'table-of-contents-plus' );
$string10 = __( 'Nope, maybe later', 'table-of-contents-plus' );
$string11 = __( 'I already did', 'table-of-contents-plus' );
?>
<div class="notice notice-info table-of-contents-plus-review-plugin-cta is-dismissible">
<div class="step-3">
<p><?php echo $string1; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></p>
<p>
<?php // phpcs:ignore Generic.Files.LineLength.MaxExceeded ?>
<a href="https://aioseo.com/table-of-contents-plus-rating" class="table-of-contents-plus-dismiss-review-notice" target="_blank" rel="noopener noreferrer">
<?php echo esc_html( $string9 ); ?>
</a>&nbsp;&bull;&nbsp;
<a href="#" class="table-of-contents-plus-dismiss-review-notice-delay" target="_blank" rel="noopener noreferrer">
<?php echo esc_html( $string10 ); ?>
</a>&nbsp;&bull;&nbsp;
<a href="#" class="table-of-contents-plus-dismiss-review-notice" target="_blank" rel="noopener noreferrer">
<?php echo esc_html( $string11 ); ?>
</a>
</p>
</div>
</div>
<?php
}
/**
* Print the script for dismissing the notice.
*
* @since 1.2.0
*
* @return void
*/
public function printScript() {
// Create a nonce.
$nonce = wp_create_nonce( 'table-of-contents-plus-dismiss-review' );
?>
<style>
@keyframes dismissBtnVisible {
from { opacity: 0.99; }
to { opacity: 1; }
}
.table-of-contents-plus-review-plugin-cta button.notice-dismiss {
animation-duration: 0.001s;
animation-name: dismissBtnVisible;
}
</style>
<script>
window.addEventListener('load', function () {
var aioseoTableOfContentsSetupButton,
dismissBtn,
interval
aioseoTableOfContentsSetupButton = function (dismissBtn) {
var notice = document.querySelector('.notice.table-of-contents-plus-review-plugin-cta'),
delay = false,
relay = true,
stepOne = notice.querySelector('.step-1'),
stepTwo = notice.querySelector('.step-2'),
stepThree = notice.querySelector('.step-3')
// Add an event listener to the dismiss button.
dismissBtn.addEventListener('click', function (event) {
var httpRequest = new XMLHttpRequest(),
postData = ''
// Build the data to send in our request.
postData += '&delay=' + delay
postData += '&relay=' + relay
postData += '&action=table-of-contents-plus-dismiss-review-plugin-cta'
postData += '&nonce=<?php echo esc_html( $nonce ); ?>'
httpRequest.open('POST', '<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>')
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
httpRequest.send(postData)
})
notice.addEventListener('click', function (event) {
if (event.target.matches('.table-of-contents-plus-review-switch-step-3')) {
event.preventDefault()
stepOne.style.display = 'none'
stepTwo.style.display = 'none'
stepThree.style.display = 'block'
}
if (event.target.matches('.table-of-contents-plus-review-switch-step-2')) {
event.preventDefault()
stepOne.style.display = 'none'
stepThree.style.display = 'none'
stepTwo.style.display = 'block'
}
if (event.target.matches('.table-of-contents-plus-dismiss-review-notice-delay')) {
event.preventDefault()
delay = true
relay = false
dismissBtn.click()
}
if (event.target.matches('.table-of-contents-plus-dismiss-review-notice')) {
if ('#' === event.target.getAttribute('href')) {
event.preventDefault()
}
relay = false
dismissBtn.click()
}
})
}
dismissBtn = document.querySelector('.table-of-contents-plus-review-plugin-cta .notice-dismiss')
if (!dismissBtn) {
document.addEventListener('animationstart', function (event) {
if (event.animationName == 'dismissBtnVisible') {
dismissBtn = document.querySelector('.table-of-contents-plus-review-plugin-cta .notice-dismiss')
if (dismissBtn) {
aioseoTableOfContentsSetupButton(dismissBtn)
}
}
}, false)
} else {
aioseoTableOfContentsSetupButton(dismissBtn)
}
});
</script>
<?php
}
/**
* Dismiss the review plugin CTA.
*
* @since 1.2.0
*
* @return void
*/
public function dismissNotice() {
// Early exit if we're not on a table-of-contents-plus-dismiss-review-plugin-cta action.
if ( ! isset( $_POST['action'] ) || 'table-of-contents-plus-dismiss-review-plugin-cta' !== $_POST['action'] ) {
return;
}
check_ajax_referer( 'table-of-contents-plus-dismiss-review', 'nonce' );
$delay = isset( $_POST['delay'] ) ? 'true' === sanitize_text_field( wp_unslash( $_POST['delay'] ) ) : false;
$relay = isset( $_POST['relay'] ) ? 'true' === sanitize_text_field( wp_unslash( $_POST['relay'] ) ) : false;
if ( ! $delay ) {
update_user_meta( get_current_user_id(), '_aioseo_table_of_contents_plugin_review_dismissed', $relay ? '4' : '3' );
wp_send_json_success();
return;
}
update_user_meta( get_current_user_id(), '_aioseo_table_of_contents_plugin_review_dismissed', strtotime( '+1 week' ) );
wp_send_json_success();
}
}
@@ -0,0 +1,360 @@
<?php
namespace AIOSEO\TableOfContents\Admin;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
use AIOSEO\TableOfContents\Models;
/**
* Handles our notifications.
*
* @since 1.0.0
*/
class Notifications {
/**
* The URL of the notifications endpoint.
*
* @since 1.0.0
*
* @var string
*/
private $url = 'https://table-of-contents-plugin-cdn.aioseo.com/notifications.json';
/**
* The review notice class instance.
*
* @since 1.0.0
*
* @var Notices\Review
*/
private $reviewNotice;
/**
* Class constructor.
*
* @since 1.0.0
*/
public function __construct() {
add_action( 'aioseo_table_of_contents_admin_notifications_update', [ $this, 'update' ] );
if ( ! is_admin() ) {
return;
}
add_action( 'init', [ $this, 'init' ], 2 );
add_action( 'admin_notices', [ $this, 'renderNotices' ] );
}
/**
* Initialize notifications.
*
* @since 1.0.0
*
* @return void
*/
public function init() {
// If our tables do not exist, let runUpdates() handle creation.
// Calling updateDbSchema() here AND in runUpdates() causes duplicate
// dbDelta() calls which triggers "table already exists" errors.
if ( ! aioseoTableOfContents()->core->db->tableExists( 'aioseo_table_of_contents_notifications' ) ) {
return;
}
$this->checkForUpdates();
$this->reviewNotice = new Notices\Review();
}
/**
* Renders the notices.
*
* @since 1.2.0
*
* @return void
*/
public function renderNotices() {
if ( ! is_admin() ) {
return;
}
// reviewNotice is only instantiated once our tables exist (see init()).
if ( ! $this->reviewNotice ) {
return;
}
$this->reviewNotice->maybeShowNotice();
}
/**
* Checks if we should update our notifications.
*
* @since 1.0.0
*
* @return void
*/
private function checkForUpdates() {
$nextRun = aioseoTableOfContents()->core->cache->get( 'admin_notifications_update' );
if ( null !== $nextRun && time() < $nextRun ) {
return;
}
aioseoTableOfContents()->actionScheduler->scheduleAsync( 'aioseo_table_of_contents_admin_notifications_update' );
aioseoTableOfContents()->core->cache->update( 'admin_notifications_update', time() + DAY_IN_SECONDS );
}
/**
* Pulls in the notifications from our remote endpoint and stores them in the DB.
*
* @since 1.0.0
*
* @return void
*/
public function update() {
$notifications = $this->fetch();
if ( empty( $notifications ) ) {
return;
}
foreach ( $notifications as $notification ) {
// First, let's check to see if the notification exists. If so, we want to override it.
$aioseoNotification = aioseoTableOfContents()->core->db
->start( 'aioseo_table_of_contents_notifications' )
->where( 'notification_id', $notification->id )
->run()
->model( 'AIOSEO\\TableOfContents\\Models\\Notification' );
$buttons = [
'button1' => [
'label' => ! empty( $notification->btns->main->text ) ? sanitize_text_field( $notification->btns->main->text ) : null,
'url' => ! empty( $notification->btns->main->url ) ? esc_url_raw( $notification->btns->main->url ) : null
],
'button2' => [
'label' => ! empty( $notification->btns->alt->text ) ? sanitize_text_field( $notification->btns->alt->text ) : null,
'url' => ! empty( $notification->btns->alt->url ) ? esc_url_raw( $notification->btns->alt->url ) : null
]
];
if ( ! $aioseoNotification->exists() ) {
$aioseoNotification = new Models\Notification();
$aioseoNotification->slug = uniqid();
$aioseoNotification->dismissed = 0;
}
$aioseoNotification->notification_id = $notification->id;
$aioseoNotification->title = sanitize_text_field( $notification->title );
$aioseoNotification->content = sanitize_text_field( $notification->content );
$aioseoNotification->type = ! empty( $notification->notification_type ) ? sanitize_text_field( $notification->notification_type ) : 'info';
$aioseoNotification->level = $notification->type;
$aioseoNotification->start = ! empty( $notification->start ) ? sanitize_text_field( $notification->start ) : null;
$aioseoNotification->end = ! empty( $notification->end ) ? sanitize_text_field( $notification->end ) : null;
$aioseoNotification->button1_label = $buttons['button1']['label'];
$aioseoNotification->button1_action = $buttons['button1']['url'];
$aioseoNotification->button2_label = $buttons['button2']['label'];
$aioseoNotification->button2_action = $buttons['button2']['url'];
$aioseoNotification->save();
// Trigger the drawer to open.
aioseoTableOfContents()->core->cache->update( 'show_notifications_drawer', true );
}
}
/**
* Pulls in the notifications from the remote feed.
*
* @since 1.0.0
*
* @return array A list of notifications.
*/
private function fetch() {
$response = aioseoTableOfContents()->helpers->wpRemoteGet( $this->getUrl() );
if ( is_wp_error( $response ) ) {
return [];
}
$body = wp_remote_retrieve_body( $response );
if ( empty( $body ) ) {
return [];
}
$notifications = json_decode( $body );
if ( empty( $notifications ) ) {
return [];
}
return $this->verify( $notifications );
}
/**
* Verifies a notification to see if it's valid before it is stored.
*
* @since 1.0.0
*
* @param array $notifications List of notifications items to verify.
* @return array List of verified notifications.
*/
private function verify( $notifications ) {
if ( ! is_array( $notifications ) || empty( $notifications ) ) {
return [];
}
$data = [];
foreach ( $notifications as $notification ) {
// The content and type should never be empty. If they are, ignore the notification.
if ( empty( $notification->content ) || empty( $notification->type ) ) {
continue;
}
if ( ! is_array( $notification->type ) ) {
$notification->type = [ $notification->type ];
}
foreach ( $notification->type as $type ) {
$type = sanitize_text_field( $type );
// Ignore the notification if not a single type matches.
if ( ! $this->validateType( $type ) ) {
continue 2;
}
}
// Ignore the notification if it already expired.
if ( ! empty( $notification->end ) && time() > strtotime( $notification->end ) ) {
continue;
}
// Ignore the notification if it existed before installing Table of Contents Plus.
// Prevents spamming the user with notifications after activation.
$activated = aioseoTableOfContents()->internalOptions->internal->firstActivated( time() );
if ( ! empty( $notification->start ) && $activated > strtotime( $notification->start ) ) {
continue;
}
$data[] = $notification;
}
return $data;
}
/**
* Validates the notification type.
*
* @since 1.0.0
*
* @param string $type The notification type we are targeting.
* @return bool Whether the notification is valid.
*/
public function validateType( $type ) {
if ( 'all' === $type ) {
return true;
}
// Table of Contents Plus is a free plugin with no license, so all users are unlicensed.
if ( 'free' === $type ) {
return true;
}
// There are no licensed users to target.
if ( 'licensed' === $type ) {
return false;
}
// Store notice if version matches.
if ( $this->versionMatch( aioseoTableOfContents()->version, $type ) ) {
return true;
}
return false;
}
/**
* Checks whether two versions are equal.
*
* @since 1.0.0
*
* @param string $currentVersion The current version being used.
* @param string|array $compareVersion The version to compare with.
* @return bool Whether it is a match.
*/
private function versionMatch( $currentVersion, $compareVersion ) {
if ( is_array( $compareVersion ) ) {
foreach ( $compareVersion as $compare_single ) {
$recursiveResult = $this->versionMatch( $currentVersion, $compare_single );
if ( $recursiveResult ) {
return true;
}
}
return false;
}
$currentParse = explode( '.', $currentVersion );
if ( strpos( $compareVersion, '-' ) ) {
$compareParse = explode( '-', $compareVersion );
} elseif ( strpos( $compareVersion, '.' ) ) {
$compareParse = explode( '.', $compareVersion );
} else {
return false;
}
$currentCount = count( $currentParse );
$compareCount = count( $compareParse );
for ( $i = 0; $i < $currentCount || $i < $compareCount; $i++ ) {
if ( isset( $compareParse[ $i ] ) && 'x' === strtolower( $compareParse[ $i ] ) ) {
unset( $compareParse[ $i ] );
}
if ( ! isset( $currentParse[ $i ] ) ) {
unset( $compareParse[ $i ] );
} elseif ( ! isset( $compareParse[ $i ] ) ) {
unset( $currentParse[ $i ] );
}
}
foreach ( $compareParse as $index => $subNumber ) {
if ( $currentParse[ $index ] !== $subNumber ) {
return false;
}
}
return true;
}
/**
* Returns the URL for the notifications endpoint.
*
* @since 1.0.0
*
* @return string The URL.
*/
private function getUrl() {
if ( defined( 'AIOSEO_TABLE_OF_CONTENTS_NOTIFICATIONS_URL' ) ) {
return AIOSEO_TABLE_OF_CONTENTS_NOTIFICATIONS_URL;
}
return $this->url;
}
/**
* Extends a notice by a (default) 1 week start date.
*
* @since 1.0.0
*
* @param string $notice The notice name.
* @param string $start How long to extend the notice.
* @return void
*/
public function remindMeLater( $notice, $start = '+1 week' ) {
$notification = Models\Notification::getNotificationByName( $notice );
if ( ! $notification->exists() ) {
return;
}
$notification->start = gmdate( 'Y-m-d H:i:s', strtotime( $start ) );
$notification->save();
}
}
@@ -0,0 +1,201 @@
<?php
namespace AIOSEO\TableOfContents\Api;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Handles the registration, validation and authorization of API routes.
*
* @since 1.0.0
*/
class Api {
/**
* The REST API namespace.
*
* @since 1.0.0
*
* @var string
*/
public $namespace = 'aioseoTableOfContents/v1';
/**
* The routes we use in the rest API.
*
* @since 1.0.0
*
* @var array
*/
private $routes = [
// phpcs:disable WordPress.Arrays.ArrayDeclarationSpacing.AssociativeArrayFound
'GET' => [
'options' => [ 'callback' => [ 'VueSettings', 'getOptions' ], 'access' => 'any' ],
'toc-settings' => [ 'callback' => [ 'TocSettings', 'getSettings' ], 'access' => 'aioseo_table_of_contents_page' ],
'ping' => [ 'callback' => [ 'Ping', 'ping' ], 'access' => 'any' ]
],
'POST' => [
'notifications/dismiss' => [ 'callback' => [ 'Notifications', 'dismissNotifications' ], 'access' => 'any' ],
'objects' => [ 'callback' => [ 'PostsTerms', 'searchForObjects' ], 'access' => [ 'aioseo_table_of_contents_page' ] ],
'options' => [ 'callback' => [ 'VueSettings', 'saveChanges' ], 'access' => 'aioseo_table_of_contents_page' ],
'plugins/deactivate' => [ 'callback' => [ 'Plugins', 'deactivatePlugins' ], 'access' => 'install_plugins' ],
'plugins/install' => [ 'callback' => [ 'Plugins', 'installPlugins' ], 'access' => 'install_plugins' ],
'toc-settings' => [ 'callback' => [ 'TocSettings', 'saveSettings' ], 'access' => 'aioseo_table_of_contents_page' ],
'settings/toggle-radio' => [ 'callback' => [ 'VueSettings', 'toggleRadio' ], 'access' => 'aioseo_table_of_contents_page' ],
'settings/items-per-page' => [ 'callback' => [ 'VueSettings', 'changeItemsPerPage' ], 'access' => 'aioseo_table_of_contents_page' ]
]
// phpcs:enable WordPress.Arrays.ArrayDeclarationSpacing.AssociativeArrayFound
];
/**
* Class contructor.
*
* @since 1.0.0
*/
public function __construct() {
add_filter( 'rest_allowed_cors_headers', [ $this, 'allowedHeaders' ] );
add_action( 'rest_api_init', [ $this, 'registerRoutes' ] );
}
/**
* Registers the API routes.
*
* @since 1.0.0
*
* @return void
*/
public function registerRoutes() {
$class = new \ReflectionClass( get_called_class() );
foreach ( $this->routes as $method => $data ) {
foreach ( $data as $route => $options ) {
register_rest_route(
$this->namespace,
$route,
[
'methods' => $method,
'permission_callback' => empty( $options['permissions'] ) ? [ $this, 'validRequest' ] : [ $this, $options['permissions'] ],
'callback' => is_array( $options['callback'] )
? [
(
! empty( $options['callback'][2] )
? $options['callback'][2] . '\\' . $options['callback'][0]
: (
class_exists( $class->getNamespaceName() . '\\' . $options['callback'][0] )
? $class->getNamespaceName() . '\\' . $options['callback'][0]
: __NAMESPACE__ . '\\' . $options['callback'][0]
)
),
$options['callback'][1]
]
: [ $this, $options['callback'] ]
]
);
}
}
}
/**
* Sets headers that are allowed for our API routes.
*
* @since 1.0.0
*
* @param array $allowHeaders The allowed request headers.
* @return array The allowed request headers.
*/
public function allowedHeaders( $allowHeaders ) {
if ( ! array_search( 'X-WP-Nonce', $allowHeaders, true ) ) {
$allowHeaders[] = 'X-WP-Nonce';
}
return $allowHeaders;
}
/**
* Determine if the user is logged in and has the proper permissions.
*
* @since 1.0.0
*
* @param \WP_REST_Request $request The REST Request.
* @return bool Whether the user is allowed access to the route.
*/
public function validRequest( $request ) {
return is_user_logged_in() && $this->validateAccess( $request );
}
/**
* Validates access for the routes.
*
* @since 1.0.0
*
* @param \WP_REST_Request $request The REST Request.
* @return bool Whether the user is allowed access to the route.
*/
private function validateAccess( $request ) {
$routeData = $this->getRouteData( $request );
if ( empty( $routeData ) || empty( $routeData['access'] ) ) {
return false;
}
// Admins users always have access.
if ( aioseoTableOfContents()->access->isAdmin() ) {
return true;
}
switch ( $routeData['access'] ) {
case 'any':
// Users with any Table of Contents Plus permission can access the route.
$user = wp_get_current_user();
foreach ( $user->get_role_caps() as $capability => $enabled ) {
if ( $enabled && preg_match( '/^aioseo_table_of_contents_/', (string) $capability ) ) {
return true;
}
}
return false;
default:
// The user has access if he has any of the required capabilities.
if ( ! is_array( $routeData['access'] ) ) {
$routeData['access'] = [ $routeData['access'] ];
}
foreach ( $routeData['access'] as $access ) {
if ( current_user_can( $access ) ) {
return true;
}
}
return false;
}
}
/**
* Returns the data for the route that is being accessed.
*
* @since 1.0.0
*
* @param \WP_REST_Request $request The REST Request.
* @return array The route data.
*/
private function getRouteData( $request ) {
// NOTE: Since WordPress uses case-insensitive patterns to match routes,
// we are forcing everything to lower case to ensure we have the proper route.
// This prevents users with lower privileges from accessing routes they shouldn't.
$route = aioseoTableOfContents()->helpers->toLowercase( $request->get_route() );
$route = untrailingslashit( str_replace( '/' . $this->namespace . '/', '', $route ) );
$routeData = isset( $this->routes[ $request->get_method() ][ $route ] ) ? $this->routes[ $request->get_method() ][ $route ] : [];
// No direct route name, let's try the regexes.
if ( empty( $routeData ) ) {
foreach ( $this->routes[ $request->get_method() ] as $routeRegex => $routeInfo ) {
$routeRegex = str_replace( '@', '\@', $routeRegex );
if ( preg_match( "@{$routeRegex}@", (string) $route ) ) {
$routeData = $routeInfo;
break;
}
}
}
return $routeData;
}
}
@@ -0,0 +1,70 @@
<?php
namespace AIOSEO\TableOfContents\Api;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
use AIOSEO\TableOfContents\Models;
/**
* Handles notification related routes.
*
* @since 1.0.0
*/
class Notifications {
/**
* This allows us to not repeat code over and over.
*
* @since 1.0.0
*
* @param string $slug The slug of the reminder.
* @return \WP_REST_Response The response.
*/
public static function reminder( $slug ) {
aioseoTableOfContents()->notifications->remindMeLater( $slug );
return new \WP_REST_Response( [
'success' => true,
'notifications' => Models\Notification::getNotifications()
], 200 );
}
/**
* Dismiss notifications.
*
* @since 1.0.0
*
* @param \WP_REST_Request $request The REST Request
* @return \WP_REST_Response The response.
*/
public static function dismissNotifications( $request ) {
$slugs = $request->get_json_params();
$notifications = aioseoTableOfContents()->core->db
->start( 'aioseo_table_of_contents_notifications' )
->whereIn( 'slug', $slugs )
->run()
->models( 'AIOSEO\\TableOfContents\\Models\\Notification' );
foreach ( $notifications as $notification ) {
$notification->dismissed = 1;
$notification->save();
}
// Dismiss static notifications.
if ( in_array( 'notification-review', $slugs, true ) ) {
update_user_meta( get_current_user_id(), '_aioseo_table_of_contents_notification_plugin_review_dismissed', '3' );
}
if ( in_array( 'notification-review-delay', $slugs, true ) ) {
update_user_meta( get_current_user_id(), '_aioseo_table_of_contents_notification_plugin_review_dismissed', strtotime( '+1 week' ) );
}
return new \WP_REST_Response( [
'success' => true,
'notifications' => Models\Notification::getNotifications()
], 200 );
}
}
@@ -0,0 +1,124 @@
<?php
namespace AIOSEO\TableOfContents\Api;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Handles plugin install/deinstall.
*
* @since 1.0.0
*/
class Plugins {
/**
* Installs plugins.
*
* @since 1.0.0
*
* @param \WP_REST_Request $request The REST Request
* @return \WP_REST_Response The response.
*/
public static function installPlugins( $request ) {
$body = $request->get_json_params();
$plugins = ! empty( $body['plugins'] ) ? $body['plugins'] : [];
$network = ! empty( $body['network'] ) ? $body['network'] : false;
$error = esc_html__( 'Installation failed. Please check permissions and try again.', 'table-of-contents-plus' );
if ( ! is_array( $plugins ) ) {
return new \WP_REST_Response( [
'success' => false,
'message' => $error
], 400 );
}
if ( ! aioseoTableOfContents()->helpers->canInstall() ) {
return new \WP_REST_Response( [
'success' => false,
'message' => $error
], 400 );
}
require_once ABSPATH . 'wp-admin/includes/plugin.php';
$failed = [];
$completed = [];
foreach ( $plugins as $plugin ) {
if ( empty( $plugin['plugin'] ) ) {
return new \WP_REST_Response( [
'success' => false,
'message' => $error
], 400 );
}
$result = aioseoTableOfContents()->helpers->installAddon( $plugin['plugin'], $network );
if ( ! $result ) {
$failed[] = $plugin['plugin'];
} else {
$completed[ $plugin['plugin'] ] = $result;
}
}
return new \WP_REST_Response( [
'success' => true,
'completed' => $completed,
'failed' => $failed
], 200 );
}
/**
* Deactivates plugins.
*
* @since 1.0.0
*
* @param \WP_REST_Request $request The REST Request
* @return \WP_REST_Response The response.
*/
public static function deactivatePlugins( $request ) {
$body = $request->get_json_params();
$plugins = ! empty( $body['plugins'] ) ? $body['plugins'] : [];
$network = ! empty( $body['network'] ) ? $body['network'] : false;
$error = esc_html__( 'Deactivation failed. Please check permissions and try again.', 'table-of-contents-plus' );
if ( ! is_array( $plugins ) ) {
return new \WP_REST_Response( [
'success' => false,
'message' => $error
], 400 );
}
if ( ! current_user_can( 'install_plugins' ) ) {
return new \WP_REST_Response( [
'success' => false,
'message' => $error
], 400 );
}
require_once ABSPATH . 'wp-admin/includes/plugin.php';
$failed = [];
$completed = [];
foreach ( $plugins as $plugin ) {
if ( empty( $plugin['plugin'] ) ) {
return new \WP_REST_Response( [
'success' => false,
'message' => $error
], 400 );
}
$deactivated = deactivate_plugins( $plugin['plugin'], false, $network );
if ( is_wp_error( $deactivated ) ) {
$failed[] = $plugin['plugin'];
}
$completed[] = $plugin['plugin'];
}
return new \WP_REST_Response( [
'success' => true,
'completed' => $completed,
'failed' => $failed
], 200 );
}
}
@@ -0,0 +1,79 @@
<?php
namespace AIOSEO\TableOfContents\Api;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
use AIOSEO\TableOfContents\Models;
/**
* Handles post/term lookups.
*
* @since 1.0.0
*/
class PostsTerms {
/**
* Returns posts by ID/name.
*
* @since 1.0.0
*
* @param \WP_REST_Request $request The REST Request
* @return \WP_REST_Response The response.
*/
public static function searchForObjects( $request ) {
$body = $request->get_json_params();
$searchTerm = ! empty( $body['query'] ) ? sanitize_text_field( $body['query'] ) : null;
$type = ! empty( $body['type'] ) ? sanitize_text_field( $body['type'] ) : null;
if ( empty( $searchTerm ) || empty( $type ) ) {
return new \WP_REST_Response( [
'success' => false,
'message' => 'No search term or object type was provided.'
], 400 );
}
$wpdb = aioseoTableOfContents()->core->db->db;
$like = '%' . $wpdb->esc_like( $searchTerm ) . '%';
$objects = [];
if ( 'posts' === $body['type'] ) {
$postTypes = aioseoTableOfContents()->helpers->getPublicPostTypes( true );
$objects = aioseoTableOfContents()->core->db
->start( 'posts' )
->select( 'ID, post_type, post_title, post_name' )
->whereRaw( $wpdb->prepare( '( post_title LIKE %s OR post_name LIKE %s OR ID = %d )', $like, $like, $searchTerm ) )
->whereIn( 'post_type', $postTypes )
->whereIn( 'post_status', [ 'publish', 'draft', 'future', 'pending' ] )
->orderBy( 'post_title' )
->limit( 10 )
->run()
->result();
}
if ( empty( $objects ) ) {
return new \WP_REST_Response( [
'success' => true,
'objects' => []
], 200 );
}
$parsedObjects = [];
foreach ( $objects as $object ) {
if ( 'posts' === $type ) {
$parsedObjects[] = [
'value' => (int) $object->ID,
'slug' => $object->post_name,
'label' => $object->post_title,
'type' => $object->post_type,
'link' => get_permalink( $object->ID )
];
}
}
return new \WP_REST_Response( [
'success' => true,
'objects' => $parsedObjects
], 200 );
}
}
@@ -0,0 +1,213 @@
<?php
namespace AIOSEO\TableOfContents\Api;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Reads and writes the table of contents settings.
*
* The frontend engine still stores its settings in the legacy 'toc-options'
* option, so this controller bridges the Vue settings UI to that store and
* mirrors the sanitization the legacy admin page used.
*
* Follow-up (tech debt): migrate these user settings onto the modern Options
* framework the other AIOSEO plugins use. That store persists on activation and
* version-tracks reliably, which would remove the existing-install detection
* gymnastics in {@see \AIOSEO\TableOfContents\Main\Updates::migrateAppearanceDefaults()}.
*
* @since 1.0.0
*/
class TocSettings {
/**
* Returns the current settings merged with the defaults, plus the data the UI needs.
*
* @since 1.0.0
*
* @return \WP_REST_Response The response.
*/
public static function getSettings() {
$engine = aioseoTableOfContents()->standalone->frontend;
return new \WP_REST_Response( [
'success' => true,
'settings' => $engine->get_options(),
'postTypes' => self::getPostTypes()
], 200 );
}
/**
* Saves the settings to the legacy 'toc-options' option.
*
* @since 1.0.0
*
* @param \WP_REST_Request $request The REST request.
* @return \WP_REST_Response The response.
*/
public static function saveSettings( $request ) {
$engine = aioseoTableOfContents()->standalone->frontend;
$defaults = $engine->get_defaults();
$body = $request->get_json_params();
if ( empty( $body ) || ! is_array( $body ) ) {
return new \WP_REST_Response( [ 'success' => false ], 400 );
}
$string = function ( $key ) use ( $body, $defaults ) {
return isset( $body[ $key ] ) ? trim( sanitize_text_field( wp_unslash( $body[ $key ] ) ) ) : $defaults[ $key ];
};
$bool = function ( $key ) use ( $body ) {
return ! empty( $body[ $key ] );
};
$int = function ( $key ) use ( $body, $defaults ) {
return isset( $body[ $key ] ) ? intval( $body[ $key ] ) : $defaults[ $key ];
};
$color = function ( $key, $default ) use ( $engine, $body ) {
return ! empty( $body[ $key ] ) ? $engine->hex_value( trim( wp_unslash( $body[ $key ] ) ), $default ) : $default;
};
$enum = function ( $key, $allowed ) use ( $string, $defaults ) {
$value = $string( $key );
return in_array( $value, $allowed, true ) ? $value : $defaults[ $key ];
};
$restrictPath = $string( 'restrict_path' );
if ( $restrictPath && 0 !== strpos( $restrictPath, '/' ) ) {
// The restrict path must start with a forward slash, otherwise clear it.
$restrictPath = '';
}
$sanitized = [
'fragment_prefix' => $string( 'fragment_prefix' ),
'position' => $int( 'position' ),
'start' => $int( 'start' ),
'show_heading_text' => $bool( 'show_heading_text' ),
'heading_text' => $string( 'heading_text' ),
'heading_alignment' => $enum( 'heading_alignment', [ 'left', 'center', 'right' ] ),
'auto_insert_post_types' => self::sanitizeStringArray( $body, 'auto_insert_post_types' ),
'show_heirarchy' => $bool( 'show_heirarchy' ),
'ordered_list' => $bool( 'ordered_list' ),
'numbering_style' => $enum( 'numbering_style', [ 'hierarchical', 'decimal', 'upper-roman', 'lower-roman', 'upper-alpha', 'lower-alpha' ] ),
'smooth_scroll' => $bool( 'smooth_scroll' ),
'smooth_scroll_offset' => $int( 'smooth_scroll_offset' ),
'visibility' => $bool( 'visibility' ),
'visibility_show' => $string( 'visibility_show' ),
'visibility_hide' => $string( 'visibility_hide' ),
'toggle_style' => $enum( 'toggle_style', [ 'plus_minus', 'caret', 'brackets' ] ),
'visibility_hide_by_default' => $bool( 'visibility_hide_by_default' ),
'width' => $string( 'width' ),
'width_custom' => isset( $body['width_custom'] ) ? floatval( $body['width_custom'] ) : $defaults['width_custom'],
'width_custom_units' => $string( 'width_custom_units' ),
'wrapping' => $int( 'wrapping' ),
'font_size' => isset( $body['font_size'] ) ? floatval( $body['font_size'] ) : $defaults['font_size'],
'font_size_units' => $string( 'font_size_units' ),
'theme' => $int( 'theme' ),
'custom_background_colour' => $color( 'custom_background_colour', TOC_DEFAULT_BACKGROUND_COLOUR ),
'custom_border_colour' => $color( 'custom_border_colour', TOC_DEFAULT_BORDER_COLOUR ),
'custom_title_colour' => $color( 'custom_title_colour', TOC_DEFAULT_TITLE_COLOUR ),
'custom_links_colour' => $color( 'custom_links_colour', TOC_DEFAULT_LINKS_COLOUR ),
'custom_links_hover_colour' => $color( 'custom_links_hover_colour', TOC_DEFAULT_LINKS_HOVER_COLOUR ),
'custom_links_visited_colour' => $color( 'custom_links_visited_colour', TOC_DEFAULT_LINKS_VISITED_COLOUR ),
'lowercase' => $bool( 'lowercase' ),
'hyphenate' => $bool( 'hyphenate' ),
'bullet_spacing' => $bool( 'bullet_spacing' ),
'include_homepage' => $bool( 'include_homepage' ),
'exclude_css' => $bool( 'exclude_css' ),
'heading_levels' => self::sanitizeIntArray( $body, 'heading_levels' ),
'exclude' => $string( 'exclude' ), // phpcs:ignore WordPressVIPMinimum.Performance.WPQueryParams.PostNotIn_exclude
'restrict_path' => $restrictPath,
'css_container_class' => $string( 'css_container_class' ),
'sitemap_show_page_listing' => $bool( 'sitemap_show_page_listing' ),
'sitemap_show_category_listing' => $bool( 'sitemap_show_category_listing' ),
'sitemap_heading_type' => $int( 'sitemap_heading_type' ),
'sitemap_pages' => $string( 'sitemap_pages' ),
'sitemap_categories' => $string( 'sitemap_categories' ),
'show_toc_in_widget_only' => $bool( 'show_toc_in_widget_only' ),
'show_toc_in_widget_only_post_types' => self::sanitizeStringArray( $body, 'show_toc_in_widget_only_post_types' ),
'rest_toc_output' => $bool( 'rest_toc_output' )
];
$options = array_merge( $engine->get_options(), $sanitized );
update_option( 'toc-options', $options );
$engine->set_option( $options );
return new \WP_REST_Response( [
'success' => true,
'settings' => $options
], 200 );
}
/**
* Sanitizes an array of strings from the request body.
*
* @since 1.0.0
*
* @param array $body The request body.
* @param string $key The key to sanitize.
* @return array The sanitized array.
*/
private static function sanitizeStringArray( $body, $key ) {
if ( empty( $body[ $key ] ) || ! is_array( $body[ $key ] ) ) {
return [];
}
return array_values( array_map( 'sanitize_text_field', array_map( 'wp_unslash', $body[ $key ] ) ) );
}
/**
* Sanitizes an array of integers from the request body.
*
* @since 1.0.0
*
* @param array $body The request body.
* @param string $key The key to sanitize.
* @return array The sanitized array.
*/
private static function sanitizeIntArray( $body, $key ) {
if ( empty( $body[ $key ] ) || ! is_array( $body[ $key ] ) ) {
return [];
}
return array_values( array_map( 'intval', $body[ $key ] ) );
}
/**
* Returns the public post types the table of contents can be enabled for.
*
* @since 1.0.0
*
* @return array The post types as { name, label, icon } objects.
*/
public static function getPostTypes() {
$exclude = [ 'attachment', 'revision', 'nav_menu_item', 'safecss' ];
$builtinIcons = [
'post' => 'dashicons-admin-post',
'page' => 'dashicons-admin-page'
];
$postTypes = [];
foreach ( get_post_types( [ 'public' => true ], 'objects' ) as $postType ) {
if ( in_array( $postType->name, $exclude, true ) ) {
continue;
}
if ( isset( $builtinIcons[ $postType->name ] ) ) {
$icon = $builtinIcons[ $postType->name ];
} elseif ( is_string( $postType->menu_icon ) && 0 === strpos( $postType->menu_icon, 'dashicons-' ) ) {
$icon = $postType->menu_icon;
} else {
$icon = 'dashicons-admin-post';
}
$postTypes[] = [
'name' => $postType->name,
'label' => $postType->labels->name,
'icon' => $icon
];
}
return $postTypes;
}
}
@@ -0,0 +1,111 @@
<?php
namespace AIOSEO\TableOfContents\Api;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
use AIOSEO\TableOfContents\Models;
/**
* Handles the user Vue settings (toggled radios, table pagination, etc.).
*
* @since 1.0.0
*/
class VueSettings {
/**
* Returns the settings.
*
* @since 1.0.0
*
* @return \WP_REST_Response The response.
*/
public static function getOptions() {
return new \WP_REST_Response( [
'success' => true,
'options' => aioseoTableOfContents()->options->all(),
'internalOptions' => aioseoTableOfContents()->internalOptions->all(),
'settings' => aioseoTableOfContents()->vueSettings->all()
], 200 );
}
/**
* Toggles a radio in the settings.
*
* @since 1.0.0
*
* @param \WP_REST_Request $request The REST Request
* @return \WP_REST_Response The response.
*/
public static function toggleRadio( $request ) {
$body = $request->get_json_params();
$radio = ! empty( $body['radio'] ) ? sanitize_text_field( $body['radio'] ) : null;
$value = ! empty( $body['value'] ) ? sanitize_text_field( $body['value'] ) : null;
$radios = aioseoTableOfContents()->vueSettings->toggledRadio;
if ( ! array_key_exists( $radio, $radios ) ) {
return new \WP_REST_Response( [
'success' => false
], 400 );
}
$radios[ $radio ] = $value;
aioseoTableOfContents()->vueSettings->toggledRadio = $radios;
return new \WP_REST_Response( [
'success' => true
], 200 );
}
/**
* Toggles a table's items per page setting.
*
* @since 1.0.0
*
* @param \WP_REST_Request $request The REST Request
* @return \WP_REST_Response The response.
*/
public static function changeItemsPerPage( $request ) {
$body = $request->get_json_params();
$table = ! empty( $body['table'] ) ? sanitize_text_field( $body['table'] ) : null;
$value = ! empty( $body['value'] ) ? intval( $body['value'] ) : null;
$tables = aioseoTableOfContents()->vueSettings->tablePagination;
if ( ! array_key_exists( $table, $tables ) ) {
return new \WP_REST_Response( [
'success' => false
], 400 );
}
$tables[ $table ] = $value;
aioseoTableOfContents()->vueSettings->tablePagination = $tables;
return new \WP_REST_Response( [
'success' => true
], 200 );
}
/**
* Save options from the frontend.
*
* @since 1.0.0
*
* @param \WP_REST_Request $request The REST Request
* @return \WP_REST_Response The response.
*/
public static function saveChanges( $request ) {
$body = $request->get_json_params();
$options = ! empty( $body['options'] ) ? $body['options'] : []; // The options class will sanitize them.
aioseoTableOfContents()->options->sanitizeAndSave( $options );
// Re-initialize the notices.
aioseoTableOfContents()->notifications->init();
return new \WP_REST_Response( [
'success' => true,
'notifications' => Models\Notification::getNotifications()
], 200 );
}
}
@@ -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;
}
}
@@ -0,0 +1,99 @@
<?php
namespace AIOSEO\TableOfContents\Db;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Database Schema for Table of Contents Plus tables.
*
* This class defines the complete, current state of all database tables
* used by the Table of Contents Plus addon. These schemas are used with WordPress's
* dbDelta() function to automatically create tables and add missing columns.
*
* @since 202607
*/
class Schema {
/**
* Get all table schemas for Table of Contents Plus tables.
*
* Returns an array of CREATE TABLE statements for all tables
* used by Table of Contents Plus. These will be processed by dbDelta() to ensure
* the database schema matches the definitions.
*
* @since 202607
*
* @return array Array of SQL CREATE TABLE statements.
*/
public function getSchema() {
return [
$this->getNotificationsTableSchema(),
$this->getCacheTableSchema()
];
}
/**
* Get the schema for aioseo_table_of_contents_notifications table.
*
* @since 202607
*
* @return string SQL CREATE TABLE statement.
*/
private function getNotificationsTableSchema() {
$tableName = aioseoTableOfContents()->core->db->db->prefix . 'aioseo_table_of_contents_notifications';
$charsetCollate = aioseoTableOfContents()->core->db->db->get_charset_collate();
return "CREATE TABLE {$tableName} (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
notification_id bigint(20) unsigned DEFAULT NULL,
notification_name varchar(255) DEFAULT NULL,
slug varchar(13) NOT NULL,
title text NOT NULL,
content longtext NOT NULL,
type varchar(64) NOT NULL,
level text NOT NULL,
start datetime DEFAULT NULL,
end datetime DEFAULT NULL,
button1_label varchar(255) DEFAULT NULL,
button1_action varchar(255) DEFAULT NULL,
button2_label varchar(255) DEFAULT NULL,
button2_action varchar(255) DEFAULT NULL,
dismissed tinyint(1) NOT NULL DEFAULT 0,
new tinyint(1) NOT NULL DEFAULT 1,
created datetime NOT NULL,
updated datetime NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY ndx__aioseo_table_of_contents_notifications_slug (slug),
KEY ndx__aioseo_table_of_contents_notifications_dates (start, end),
KEY ndx__aioseo_table_of_contents_notifications_type (type),
KEY ndx__aioseo_table_of_contents_notifications_dismissed (dismissed)
) {$charsetCollate};";
}
/**
* Get the schema for aioseo_table_of_contents_cache table.
*
* @since 202607
*
* @return string SQL CREATE TABLE statement.
*/
public function getCacheTableSchema() {
$tableName = aioseoTableOfContents()->core->db->db->prefix . 'aioseo_table_of_contents_cache';
$charsetCollate = aioseoTableOfContents()->core->db->db->get_charset_collate();
return "CREATE TABLE {$tableName} (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
name varchar(80) NOT NULL,
value longtext NOT NULL,
is_object TINYINT(1) DEFAULT 0,
expiration datetime DEFAULT NULL,
created datetime NOT NULL,
updated datetime NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY ndx_aioseo_table_of_contents_cache_name (name),
KEY ndx_aioseo_table_of_contents_cache_expiration (expiration)
) {$charsetCollate};";
}
}
@@ -0,0 +1,56 @@
<?php
namespace AIOSEO\TableOfContents\Main;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Handles plugin (de)activation.
*
* @since 1.0.0
*/
class Activate {
/**
* Class constructor.
*
* @since 1.0.0
*/
public function __construct() {
register_activation_hook( AIOSEO_TABLE_OF_CONTENTS_FILE, [ $this, 'activate' ] );
register_deactivation_hook( AIOSEO_TABLE_OF_CONTENTS_FILE, [ $this, 'deactivate' ] );
}
/**
* Runs on activation.
*
* @since 1.0.0
*
* @return void
*/
public function activate() {
aioseoTableOfContents()->access->addCapabilities();
// Set the activation timestamps.
$time = time();
aioseoTableOfContents()->internalOptions->internal->activated = $time;
if ( ! aioseoTableOfContents()->internalOptions->internal->firstActivated ) {
aioseoTableOfContents()->internalOptions->internal->firstActivated = $time;
}
aioseoTableOfContents()->core->cache->clear();
}
/**
* Runs on deactivation.
*
* @since 1.0.0
*
* @return void
*/
public function deactivate() {
aioseoTableOfContents()->access->removeCapabilities();
}
}
@@ -0,0 +1,28 @@
<?php
namespace AIOSEO\TableOfContents\Main;
use AIOSEO\TableOfContents\Highlighter;
use AIOSEO\TableOfContents\Links;
use AIOSEO\TableOfContents\LinkStatus;
use AIOSEO\TableOfContents\Models;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Main class where core features are handled/registered.
*
* @since 1.0.0
*/
class Main {
/**
* Class constructor.
*
* @since 1.0.0
*/
public function __construct() {
new Activate();
}
}
@@ -0,0 +1,68 @@
<?php
namespace AIOSEO\TableOfContents\Main\Migrations;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Contract for a discrete, individually-logged migration.
*
* Migrations registered with the {@see MigrationRunner} are tracked by name in
* the migration log option. The runner uses {@see self::verify()} as the source
* of truth for completion — up()'s exit status is not trusted, because that's
* the failure mode that historically left sites half-applied (the version flag
* advanced even when the work hadn't actually landed).
*
* @since 202607
*/
interface Migration {
/**
* Stable identifier. Becomes the key in the migration log option.
*
* IMPORTANT: never rename after the migration has shipped — the runner
* keys log entries off this string. A rename would cause the migration
* to re-run on every site that already had it.
*
* Convention: snake_case verb_noun, no version suffix.
*
* @since 202607
*
* @return string
*/
public function name();
/**
* Release this migration was introduced in. Diagnostic only.
*
* @since 202607
*
* @return string
*/
public function version();
/**
* Perform the migration. Throw on hard failure — the runner catches and
* logs as status = 0 so the migration is retried on the next request.
*
* Must be idempotent: the runner may invoke up() multiple times across
* retries (e.g. when verify() returned false after a previous up()).
*
* @since 202607
*
* @return void
*/
public function up();
/**
* Post-condition check. Returns true when the migration's intended state
* is in place. Called BEFORE up() to short-circuit when already applied,
* and AFTER up() to confirm success.
*
* @since 202607
*
* @return bool
*/
public function verify();
}
@@ -0,0 +1,102 @@
<?php
namespace AIOSEO\TableOfContents\Main\Migrations;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Wraps the `aioseo_table_of_contents_migrations_log` option that tracks
* per-migration execution state for the {@see MigrationRunner}.
*
* The option is stored without autoload — healthy sites short-circuit on
* `lastSchemaVersion === aioseoTableOfContents()->version` before the runner ever
* reads the log, so paying autoload overhead on every request would be wasted
* work.
*
* @since 202607
*/
class MigrationLog {
/**
* Option name. Per-plugin namespacing means addons can each own their own
* log without colliding with the main plugin's entries.
*
* @since 202607
*
* @var string
*/
private $optionName = 'aioseo_table_of_contents_migrations_log';
/**
* Per-request cache. The runner can call read() multiple times across
* migrations within one request — no need to round-trip wp_options each
* time.
*
* Null means "not loaded yet"; array (possibly empty) means "loaded".
*
* @since 202607
*
* @var array|null
*/
private $cache = null;
/**
* Read the full log.
*
* @since 202607
*
* @return array Keyed by migration name. Empty array when the option does not exist.
*/
public function read() {
if ( null !== $this->cache ) {
return $this->cache;
}
$raw = get_option( $this->optionName, '' );
if ( empty( $raw ) ) {
$this->cache = [];
return $this->cache;
}
$decoded = json_decode( $raw, true );
if ( ! is_array( $decoded ) ) {
$this->cache = [];
return $this->cache;
}
$this->cache = $decoded;
return $this->cache;
}
/**
* Write the full log.
*
* On first write the option is created with autoload disabled. Subsequent
* writes preserve that flag automatically — WordPress's update_option()
* does not change autoload on existing options.
*
* @since 202607
*
* @param array $log Log keyed by migration name.
* @return void
*/
public function write( array $log ) {
$encoded = wp_json_encode( $log );
if ( false === $encoded ) {
return;
}
$existing = get_option( $this->optionName, null );
if ( null === $existing ) {
add_option( $this->optionName, $encoded, '', 'no' );
} else {
update_option( $this->optionName, $encoded );
}
$this->cache = $log;
}
}
@@ -0,0 +1,205 @@
<?php
namespace AIOSEO\TableOfContents\Main\Migrations;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Discovers, executes, and logs {@see Migration} instances.
*
* The runner closes the half-applied failure mode: the version flag is only
* advanced when EVERY registered migration's verify() returns true. A
* concurrent-request lock loser bails without touching state; a lock holder
* that dies mid-migration leaves the relevant log entry at status = 0 (or
* absent), and the runner retries on the next request until verify() actually
* passes.
*
* @since 202607
*/
class MigrationRunner {
/**
* Registered migrations, in registration order.
*
* @since 202607
*
* @var Migration[]
*/
private $migrations = [];
/**
* Log accessor.
*
* @since 202607
*
* @var MigrationLog
*/
private $log;
/**
* Lock name. MySQL GET_LOCK is per-connection, so this serializes across
* concurrent PHP processes for the same site.
*
* @since 202607
*
* @var string
*/
private $lockName = 'aioseo_table_of_contents_migration_runner';
/**
* @since 202607
*/
public function __construct() {
$this->log = new MigrationLog();
}
/**
* Register a migration. Order is preserved — later registrations run
* after earlier ones within the same request.
*
* @since 202607
*
* @param Migration $migration The migration to register.
* @return void
*/
public function register( Migration $migration ) {
$this->migrations[] = $migration;
}
/**
* Execute pending migrations.
*
* Short-circuits early when the recorded schema version matches the
* current plugin version — healthy sites never touch the log option.
* Lock losers exit silently and do NOT advance any version flag, so a
* future-bumped lastSchemaVersion can't strand work.
*
* @since 202607
*
* @return void
*/
public function run() {
if ( aioseoTableOfContents()->internalOptions->internal->lastSchemaVersion === aioseoTableOfContents()->version ) {
return;
}
if ( empty( $this->migrations ) ) {
aioseoTableOfContents()->internalOptions->internal->lastSchemaVersion = aioseoTableOfContents()->version;
return;
}
if ( ! aioseoTableOfContents()->core->db->acquireLock( $this->lockName, 0 ) ) {
return;
}
try {
$log = $this->log->read();
$allDone = true;
foreach ( $this->migrations as $migration ) {
$name = $migration->name();
if ( $this->verifySafely( $migration ) ) {
if ( ! isset( $log[ $name ] ) || 1 !== ( $log[ $name ]['status'] ?? 0 ) ) {
$log[ $name ] = $this->successEntry( $migration, $log );
}
continue;
}
try {
$migration->up();
$verified = $this->verifySafely( $migration );
$log[ $name ] = $verified
? $this->successEntry( $migration, $log )
: $this->failureEntry( $migration, $log, 'verify() returned false after up()' );
if ( ! $verified ) {
$allDone = false;
}
} catch ( \Throwable $e ) {
$log[ $name ] = $this->failureEntry( $migration, $log, $e->getMessage() );
$allDone = false;
}
}
$this->log->write( $log );
if ( $allDone ) {
aioseoTableOfContents()->internalOptions->internal->lastSchemaVersion = aioseoTableOfContents()->version;
}
} finally {
// Explicit release shrinks the hold window to the migration work itself.
// acquireLock() also registers a shutdown function as belt-and-braces in
// case execution exits before we reach this point.
aioseoTableOfContents()->core->db->releaseLock( $this->lockName );
}
}
/**
* Wrap verify() so a throwing implementation degrades to "not verified"
* instead of bringing down the runner. The error surfaces via the log's
* failureEntry on the next up()/verify() cycle.
*
* @since 202607
*
* @param Migration $migration The migration to verify.
* @return bool
*/
private function verifySafely( Migration $migration ) {
try {
return (bool) $migration->verify();
} catch ( \Throwable $e ) {
return false;
}
}
/**
* Build a success log entry, preserving the prior attempts counter so
* support can see how many retries it took to land.
*
* @since 202607
*
* @param Migration $migration The migration.
* @param array $log The current log state.
* @return array
*/
private function successEntry( Migration $migration, array $log ) {
$name = $migration->name();
$attempts = isset( $log[ $name ]['attempts'] ) ? (int) $log[ $name ]['attempts'] : 0;
return [
'version' => $migration->version(),
'ran_at' => aioseoTableOfContents()->helpers->timeToMysql( time() ),
'status' => 1,
'attempts' => $attempts + 1,
'last_error' => null
];
}
/**
* Build a failure log entry, incrementing attempts so retry pressure is
* visible in the log.
*
* @since 202607
*
* @param Migration $migration The migration.
* @param array $log The current log state.
* @param string $error Reason for the failure.
* @return array
*/
private function failureEntry( Migration $migration, array $log, $error ) {
$name = $migration->name();
$attempts = isset( $log[ $name ]['attempts'] ) ? (int) $log[ $name ]['attempts'] : 0;
return [
'version' => $migration->version(),
'ran_at' => aioseoTableOfContents()->helpers->timeToMysql( time() ),
'status' => 0,
'attempts' => $attempts + 1,
'last_error' => $error
];
}
}
@@ -0,0 +1,65 @@
<?php
namespace AIOSEO\TableOfContents\Main;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* This class contains pre-updates necessary for the main Updates class to run.
*
* @since 1.0.0
*/
class PreUpdates {
/**
* Class constructor.
*
* @since 1.0.0
*/
public function __construct() {
// We don't want an AJAX request check here since the plugin might be installed/activated for the first time via AJAX.
// If that's the case, the cache table needs to be created before the cron job runs.
if ( wp_doing_cron() ) {
return;
}
$lastActiveVersion = aioseoTableOfContents()->internalOptions->internal->lastActiveVersion;
if ( version_compare( $lastActiveVersion, '202607', '<' ) ) {
// Delete the cache table transient BEFORE migration so that
// isCacheTableAvailable() will re-verify the table structure.
delete_transient( 'aioseo_plugin_cache_table_exists' );
$this->createCacheTable();
aioseoTableOfContents()->core->cache->delete( 'db_schema' );
}
}
/**
* Creates the cache table.
*
* @since 1.0.0
*
* @return void
*/
public function createCacheTable() {
if ( ! function_exists( 'dbDelta' ) ) {
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
}
$tableName = aioseoTableOfContents()->core->db->db->prefix . 'aioseo_table_of_contents_cache';
// Use dbDelta to create the cache table based on schema definition
$schema = aioseoTableOfContents()->dbSchema->getCacheTableSchema();
dbDelta( $schema );
// Clear any existing cache rows now that the table is guaranteed to exist.
// (Running this before dbDelta errors on a fresh install where the table doesn't exist yet.)
aioseoTableOfContents()->core->db->execute(
"DELETE FROM {$tableName}"
);
// Clear the transient so isCacheTableAvailable() re-checks on the next call.
delete_transient( 'aioseo_plugin_cache_table_exists' );
}
}
@@ -0,0 +1,149 @@
<?php
namespace AIOSEO\TableOfContents\Main;
use AIOSEO\TableOfContents\Models;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Handles update migrations.
*
* @since 1.0.0
*/
class Updates {
/**
* Class constructor.
*
* @since 1.0.0
*/
public function __construct() {
if ( wp_doing_ajax() || wp_doing_cron() ) {
return;
}
add_action( 'init', [ $this, 'runUpdates' ], 1002 );
add_action( 'init', [ $this, 'updateLatestVersion' ], 3000 );
}
/**
* Runs our migrations.
*
* @since 1.0.0
*
* @return void
*/
public function runUpdates() {
$lastActiveVersion = aioseoTableOfContents()->internalOptions->internal->lastActiveVersion;
// Don't run updates if the last active version is the same as the current version.
if ( aioseoTableOfContents()->version === $lastActiveVersion ) {
return;
}
if ( version_compare( $lastActiveVersion, '1.0.0', '<' ) ) {
}
$this->migrateAppearanceDefaults();
// Sync database schema with dbDelta - this will create tables and add missing columns automatically
$this->updateDbSchema();
// Re-sync role capabilities so plugin caps are only granted to administrators,
// stripping them from any other role they were previously added to.
aioseoTableOfContents()->access->removeCapabilities();
}
/**
* Updates the latest version after all migrations and updates have run.
*
* @since 1.0.0
*
* @return void
*/
public function updateLatestVersion() {
if ( aioseoTableOfContents()->internalOptions->internal->lastActiveVersion === aioseoTableOfContents()->version ) {
return;
}
aioseoTableOfContents()->internalOptions->internal->lastActiveVersion = aioseoTableOfContents()->version;
aioseoTableOfContents()->core->db->bustCache();
aioseoTableOfContents()->core->cache->delete( 'db_schema' );
}
/**
* Preserves the pre-existing appearance behaviour for sites that already had the plugin.
*
* New installs default to a left-aligned title and a +/- collapse toggle. Existing
* installs are migrated to the previous centered title and bracketed show/hide link
* so the update doesn't visibly change their table of contents. Runs once, and only
* fills in settings the user never had (never overrides an explicit choice).
*
* @since 202607.1
*
* @return void
*/
private function migrateAppearanceDefaults() {
if ( aioseoTableOfContents()->internalOptions->internal->migratedAppearanceDefaults ) {
return;
}
// An install counts as pre-existing if it ran an earlier version (lastActiveVersion
// is set) or already saved settings (the option row exists). A brand-new install has
// neither and keeps the new defaults. lastActiveVersion is read before
// updateLatestVersion() runs later on init, so it still holds the prior version here.
$options = get_option( 'toc-options' );
$isExistingInstall = '0.0' !== aioseoTableOfContents()->internalOptions->internal->lastActiveVersion || false !== $options;
if ( $isExistingInstall ) {
if ( ! is_array( $options ) ) {
$options = [];
}
if ( ! array_key_exists( 'heading_alignment', $options ) ) {
$options['heading_alignment'] = 'center';
}
if ( ! array_key_exists( 'toggle_style', $options ) ) {
$options['toggle_style'] = 'brackets';
}
update_option( 'toc-options', $options );
}
aioseoTableOfContents()->internalOptions->internal->migratedAppearanceDefaults = true;
}
/**
* Synchronizes database schema with defined schema using dbDelta.
*
* This method uses WordPress's dbDelta() function to automatically:
* - Create tables that don't exist
* - Add missing columns to existing tables
* - Modify column definitions that have changed
*
* Note: dbDelta CANNOT drop columns or rename columns. Those operations
* must be handled separately with custom SQL in version-gated migrations.
*
* @since 202607
*
* @return void
*/
private function updateDbSchema() {
if ( ! function_exists( 'dbDelta' ) ) {
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
}
$tableName = aioseoTableOfContents()->core->db->db->prefix . 'aioseo_table_of_contents_cache';
aioseoTableOfContents()->core->db->execute(
"DELETE FROM {$tableName}"
);
// Get all schema definitions and run dbDelta
$schemas = aioseoTableOfContents()->dbSchema->getSchema();
dbDelta( $schemas );
// Clear schema cache so columnExists/tableExists work correctly
aioseoTableOfContents()->core->cache->delete( 'db_schema' );
}
}
@@ -0,0 +1,459 @@
<?php
namespace AIOSEO\TableOfContents\Models;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* The base Model class.
*
* @since 1.0.0
*/
#[\AllowDynamicProperties]
class Model implements \JsonSerializable {
/**
* Fields that should be null when saving to the database.
*
* @since 1.0.0
*
* @var array
*/
protected $nullFields = [];
/**
* Fields that should be encoded/decoded on save/get.
*
* @since 1.0.0
*
* @var array
*/
protected $jsonFields = [];
/**
* Fields that should be boolean values.
*
* @since 1.0.0
*
* @var array
*/
protected $booleanFields = [];
/**
* Fields that should be integer values.
*
* @since 1.0.0
*
* @var array
*/
protected $integerFields = [];
/**
* Fields that should be float values.
*
* @since 1.0.0
*
* @var array
*/
protected $floatValues = [];
/**
* Fields that should be hidden when serialized.
*
* @since 1.0.0
*
* @var array
*/
protected $hidden = [];
/**
* The table used in the SQL query.
*
* @since 1.0.0
*
* @var string
*/
protected $table = '';
/**
* The primary key retrieved from the table.
*
* @since 1.0.0
*
* @var string
*/
protected $pk = 'id';
/**
* An array of columns from the DB that we can use.
*
* @since 1.0.0
*
* @var array
*/
private static $columns;
/**
* Class constructor.
*
* @since 1.0.0
*
* @param mixed $var This can be the primary key of the resource, or it could be an array of data to manufacture a resource without a database query.
*/
public function __construct( $var = null ) {
$fields = [];
$skip = [ 'id', 'created', 'updated' ];
foreach ( $this->getColumns() as $column => $value ) {
if ( ! in_array( $column, $skip, true ) ) {
$fields[ $column ] = $value;
}
}
$this->applyKeys( $fields );
// Process straight through if we were given a valid array.
if ( is_array( $var ) || is_object( $var ) ) {
// Apply keys to object.
$this->applyKeys( $var );
if ( $this->exists() ) {
return true;
}
return false;
}
return $this->loadData( $var );
}
/**
* Load the data from the database!
*
* @since 1.0.0
*
* @param mixed $var The primary key to load up the model from the DB.
* @return Model Returns the current object.
*/
protected function loadData( $var = null ) {
if ( null === $var ) {
return false;
}
$query = aioseoTableOfContents()->core->db
->start( $this->table )
->where( $this->pk, $var )
->limit( 1 )
->output( 'ARRAY_A' );
$result = $query->run();
if ( ! $result || $result->nullSet() ) {
return $this;
}
$this->applyKeys( $result->result()[0] );
return $this;
}
/**
* Take the keys from the result array and add them to the Model.
*
* @since 1.0.0
*
* @param array $array The array of keys and values to add to the Model.
* @return void
*/
protected function applyKeys( $array ) {
if ( ! is_object( $array ) && ! is_array( $array ) ) {
throw new \Exception( '$array must either be an object or an array.' );
}
foreach ( (array) $array as $key => $value ) {
$key = trim( $key );
$this->$key = $value;
if ( null === $value && in_array( $key, $this->nullFields, true ) ) {
continue;
}
if ( in_array( $key, $this->jsonFields, true ) ) {
$this->$key = json_decode( (string) $value );
continue;
}
if ( in_array( $key, $this->booleanFields, true ) ) {
$this->$key = (bool) $value;
continue;
}
if ( in_array( $key, $this->integerFields, true ) ) {
$this->$key = (int) $value;
}
}
}
/**
* Let's filter out any properties we cannot save to the database.
*
* @since 1.0.0
*
* @param string $key The table column.
* @return array The array of valid columns for the database query.
*/
protected function filter( $key ) {
$fields = [];
$skip = [ 'created', 'updated' ];
$table = aioseoTableOfContents()->core->db->prefix . $this->table;
$results = aioseoTableOfContents()->core->db->execute( 'SHOW COLUMNS FROM `' . $table . '`', true );
$columns = $results->result();
foreach ( $columns as $col ) {
if ( ! in_array( $col->Field, $skip, true ) && array_key_exists( $col->Field, $key ) ) {
$fields[ $col->Field ] = $key[ $col->Field ];
}
}
return $fields;
}
/**
* Transforms the data to be null if it exists in the nullFields variables.
*
* @since 1.0.0
*
* @param array $data The data array to transform.
* @return array The transformed data.
*/
protected function transform( $data, $set = false ) {
foreach ( $this->nullFields as $field ) {
if ( isset( $data[ $field ] ) && empty( $data[ $field ] ) ) {
$data[ $field ] = null;
}
}
foreach ( $this->booleanFields as $field ) {
if ( isset( $data[ $field ] ) && '' === $data[ $field ] ) {
unset( $data[ $field ] );
} elseif ( isset( $data[ $field ] ) ) {
$data[ $field ] = (bool) $data[ $field ] ? 1 : 0;
}
}
if ( $set ) {
return $data;
}
foreach ( $this->integerFields as $field ) {
if ( isset( $data[ $field ] ) ) {
$data[ $field ] = (int) $data[ $field ];
}
}
foreach ( $this->jsonFields as $field ) {
if ( isset( $data[ $field ] ) && ! aioseoTableOfContents()->helpers->isJsonString( $data[ $field ] ) ) {
if ( is_array( $data[ $field ] ) && aioseoTableOfContents()->helpers->isArrayNumeric( $data[ $field ] ) ) {
$data[ $field ] = array_values( $data[ $field ] );
}
$data[ $field ] = wp_json_encode( $data[ $field ] );
}
}
return $data;
}
/**
* Sets a piece of data to the requested resource.
*
* @since 1.0.0
*
* @return void
*/
public function set() {
$args = func_get_args();
$count = func_num_args();
if ( ! is_array( $args[0] ) && $count < 2 ) {
throw new \Exception( 'The set method must contain at least 2 arguments: key and value. Or an array of data. Only one argument was passed and it was not an array.' );
}
$key = $args[0];
$value = ! empty( $args[1] ) ? $args[1] : null;
if ( false === $key ) {
return false;
}
if ( ! is_array( $key ) ) {
$key = [ $key => $value ];
}
$key = $this->transform( $key, true );
foreach ( $key as $k => $v ) {
if ( ! empty( $k ) ) {
$this->$k = $v;
}
}
}
/**
* Delete the row in the DB.
*
* @since 1.0.0
*
* @return null
*/
public function delete() {
aioseoTableOfContents()->core->db
->delete( $this->table )
->where( $this->pk, $this->id )
->run();
return null;
}
/**
* Saves data to the requested resource.
*
* @since 1.0.0
*
* @return void
*/
public function save() {
$fields = $this->transform( $this->filter( (array) get_object_vars( $this ) ) );
$id = null;
$date = gmdate( 'Y-m-d H:i:s' );
if ( ! empty( $fields ) ) {
$pk = $this->pk;
if ( isset( $this->$pk ) && '' !== $this->$pk ) {
// PK specified.
$pkv = $this->$pk;
$query = aioseoTableOfContents()->core->db
->start( $this->table )
->where( [ $pk => $pkv ] )
->run();
if ( ! $query->nullSet() ) {
// Row exists in database.
$fields['updated'] = $date;
aioseoTableOfContents()->core->db
->update( $this->table )
->set( $fields )
->where( [ $pk => $pkv ] )
->run();
$id = $this->$pk;
} else {
// Row does not exist.
$fields[ $pk ] = $pkv;
$fields['created'] = $date;
$fields['updated'] = $date;
$id = aioseoTableOfContents()->core->db
->insert( $this->table )
->set( $fields )
->run()
->insertId();
if ( $id ) {
$this->$pk = $id;
}
}
} else {
$fields['created'] = $date;
$fields['updated'] = $date;
$id = aioseoTableOfContents()->core->db
->insert( $this->table )
->set( $fields )
->run()
->insertId();
if ( $id ) {
$this->$pk = $id;
}
}
}
$this->reset( $id );
}
/**
* Check if the model exists in the database.
*
* @since 1.0.0
*
* @return bool Whether the model exists.
*/
public function exists() {
return ( ! empty( $this->{$this->pk} ) ) ? true : false;
}
/**
* Resets a resource by forcing internal updates to be applied.
*
* @since 1.0.0
*
* @param string $id The resource ID.
* @return void
*/
public function reset( $id = null ) {
$id = ! empty( $id ) ? $id : $this->{$this->pk};
$this->__construct( $id );
}
/**
* Helper function to remove data we don't want serialized.
*
* @since 1.0.0
*
* @return array An array of data that we are OK with serializing.
*/
#[\ReturnTypeWillChange]
// The attribute above omits a deprecation notice from PHP 8.1 that is thrown because the return type of jsonSerialize() isn't "mixed".
// Once PHP 7.x is our minimum supported version, this can be removed in favour of overriding the return type in the method signature like this -
// public function jsonSerialize() : array
public function jsonSerialize() {
$array = [];
foreach ( $this->getColumns() as $column => $value ) {
if ( in_array( $column, $this->hidden, true ) ) {
continue;
}
$array[ $column ] = isset( $this->$column ) ? $this->$column : null;
}
return $array;
}
/**
* Retrieves the columns for the model.
*
* @since 1.0.0
*
* @return array An array of columns.
*/
public function getColumns() {
if ( empty( self::$columns[ get_called_class() ] ) ) {
self::$columns[ get_called_class() ] = [];
// Let's set the columns that are available by default.
$table = aioseoTableOfContents()->core->db->prefix . $this->table;
$results = aioseoTableOfContents()->core->db->execute( 'SHOW COLUMNS FROM `' . $table . '`', true );
foreach ( $results->result() as $col ) {
self::$columns[ get_called_class() ][ $col->Field ] = $col->Default;
}
if ( ! empty( $this->appends ) ) {
foreach ( $this->appends as $append ) {
self::$columns[ get_called_class() ][ $append ] = null;
}
}
}
return self::$columns[ get_called_class() ];
}
}
@@ -0,0 +1,344 @@
<?php
namespace AIOSEO\TableOfContents\Models;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* The Notification DB model class.
*
* @since 1.0.0
*/
class Notification extends Model {
/**
* The name of the table in the database, without the prefix.
*
* @since 1.0.0
*
* @var string
*/
protected $table = 'aioseo_table_of_contents_notifications';
/**
* An array of fields to set to null if already empty when saving to the database.
*
* @since 1.0.0
*
* @var array
*/
protected $nullFields = [
'start',
'end',
'notification_id',
'notification_name',
'button1_label',
'button1_action',
'button2_label',
'button2_action'
];
/**
* Fields that should be json encoded on save and decoded on get.
*
* @since 1.0.0
*
* @var array
*/
protected $jsonFields = [ 'level' ];
/**
* Fields that should be boolean values.
*
* @since 1.0.0
*
* @var array
*/
protected $booleanFields = [ 'dismissed' ];
/**
* Fields that should be hidden when serialized.
*
* @var array
*/
protected $hidden = [ 'id' ];
/**
* An array of fields attached to this resource.
*
* @since 1.0.0
*
* @var array
*/
protected $columns = [
'id',
'slug',
'notification_id',
'notification_name',
'title',
'content',
'type',
'level',
'start',
'end',
'button1_label',
'button1_action',
'button2_label',
'button2_action',
'dismissed',
'new',
'created',
'updated'
];
/**
* Returns all notifications.
*
* @since 1.0.0
*
* @param bool $reset Whether or not to reset the new notifications.
* @return array List of notifications.
*/
public static function getNotifications( $reset = true ) {
return [
'active' => self::getAllActiveNotifications(),
'new' => self::getNewNotifications( $reset ),
'dismissed' => self::getAllDismissedNotifications()
];
}
/**
* Returns the active notifications.
*
* @since 1.0.0
*
* @return array List of active notifications.
*/
public static function getAllActiveNotifications() {
$staticNotifications = self::getStaticNotifications();
$notifications = array_values( json_decode( wp_json_encode( self::getActiveNotifications() ), true ) );
return ! empty( $staticNotifications ) ? array_merge( $staticNotifications, $notifications ) : $notifications;
}
/**
* Returns all static notifications.
*
* @since 1.2.0
*
* @return array List of static notifications.
*/
public static function getStaticNotifications() {
$notifications = [ 'review' ];
$staticNotifications = [];
foreach ( $notifications as $notification ) {
switch ( $notification ) {
case 'review':
// If dismissed, don't show again.
$originalDismissed = get_user_meta( get_current_user_id(), '_aioseo_table_of_contents_plugin_review_dismissed', true );
if ( '4' !== $originalDismissed ) {
break;
}
$dismissed = get_user_meta( get_current_user_id(), '_aioseo_table_of_contents_notification_plugin_review_dismissed', true );
if ( '3' === $dismissed ) {
break;
}
if ( ! empty( $dismissed ) && $dismissed > time() ) {
break;
}
$activated = aioseoTableOfContents()->internalOptions->internal->firstActivated( time() );
if ( $activated > strtotime( '-20 days' ) ) {
break;
}
$staticNotifications[] = [
'slug' => 'notification-' . $notification,
'component' => 'notifications-' . $notification . '2',
];
break;
default:
break;
}
}
return $staticNotifications;
}
/**
* Retrieve active notifications.
*
* @since 1.0.0
*
* @return array List of active notifications or empty.
*/
public static function getActiveNotifications() {
return self::filterNotifications(
aioseoTableOfContents()->core->db
->start( 'aioseo_table_of_contents_notifications' )
->where( 'dismissed', 0 )
->whereRaw( "(start <= '" . gmdate( 'Y-m-d H:i:s' ) . "' OR start IS NULL)" )
->whereRaw( "(end >= '" . gmdate( 'Y-m-d H:i:s' ) . "' OR end IS NULL)" )
->orderBy( 'start DESC' )
->orderBy( 'created DESC' )
->run()
->models( 'AIOSEO\\TableOfContents\\Models\\Notification' )
);
}
/**
* Returns all new notifications. After retrieving them, this will reset them.
* This means that calling this method twice will result in no results
* the second time. The only exception is to pass false as a reset variable to prevent it.
*
* @since 1.0.0
*
* @param boolean $reset Whether or not to reset the new notifications.
* @return array List of new notifications if any exist.
*/
public static function getNewNotifications( $reset = true ) {
$notifications = self::filterNotifications(
aioseoTableOfContents()->core->db
->start( 'aioseo_table_of_contents_notifications' )
->where( 'dismissed', 0 )
->where( 'new', 1 )
->whereRaw( "(start <= '" . gmdate( 'Y-m-d H:i:s' ) . "' OR start IS NULL)" )
->whereRaw( "(end >= '" . gmdate( 'Y-m-d H:i:s' ) . "' OR end IS NULL)" )
->orderBy( 'start DESC' )
->orderBy( 'created DESC' )
->run()
->models( 'AIOSEO\\TableOfContents\\Models\\Notification' )
);
if ( $reset ) {
self::resetNewNotifications();
}
return $notifications;
}
/**
* Resets all new notifications.
*
* @since 1.0.0
*
* @return void
*/
public static function resetNewNotifications() {
aioseoTableOfContents()->core->db
->update( 'aioseo_table_of_contents_notifications' )
->where( 'new', 1 )
->set( 'new', 0 )
->run();
}
/**
* Returns a list of dismissed notifications.
*
* @since 1.0.0
*
* @return array List of dismissed notifications.
*/
public static function getAllDismissedNotifications() {
return array_values( json_decode( wp_json_encode( self::getDismissedNotifications() ), true ) );
}
/**
* Retrieve dismissed notifications.
*
* @since 1.0.0
*
* @return array List of dismissed notifications or empty.
*/
public static function getDismissedNotifications() {
return self::filterNotifications(
aioseoTableOfContents()->core->db
->start( 'aioseo_table_of_contents_notifications' )
->where( 'dismissed', 1 )
->orderBy( 'updated DESC' )
->run()
->models( 'AIOSEO\\TableOfContents\\Models\\Notification' )
);
}
/**
* Returns a notification by its name.
*
* @since 1.0.0
*
* @param string $name The notification name.
* @return Notification The notification.
*/
public static function getNotificationByName( $name ) {
return aioseoTableOfContents()->core->db
->start( 'aioseo_table_of_contents_notifications' )
->where( 'notification_name', $name )
->run()
->model( 'AIOSEO\\TableOfContents\\Models\\Notification' );
}
/**
* Stores a new notification in the DB.
*
* @since 1.0.0
*
* @param array $fields The fields.
* @return Notification $notification The notification.
*/
public static function addNotification( $fields ) {
// Set the dismissed status to false.
$fields['dismissed'] = 0;
$notification = new self();
$notification->set( $fields );
$notification->save();
return $notification;
}
/**
* Deletes a notification by its name.
*
* @since 1.0.0
*
* @param string $name The notification name.
* @return void
*/
public static function deleteNotificationByName( $name ) {
aioseoTableOfContents()->core->db
->delete( 'aioseo_table_of_contents_notifications' )
->where( 'notification_name', $name )
->run();
}
/**
* Filters the notifications based on the targeted plan levels.
*
* @since 1.0.0
*
* @param array $notifications The notifications
* @return array $remainingNotifications The remaining notifications.
*/
public static function filterNotifications( $notifications ) {
$remainingNotifications = [];
foreach ( $notifications as $notification ) {
$levels = $notification->level;
if ( ! is_array( $levels ) ) {
$levels = empty( $notification->level ) ? [ 'all' ] : [ $notification->level ];
}
foreach ( $levels as $level ) {
if ( ! aioseoTableOfContents()->notifications->validateType( $level ) ) {
continue 2;
}
}
$remainingNotifications[] = $notification;
}
return $remainingNotifications;
}
}
@@ -0,0 +1,93 @@
<?php
namespace AIOSEO\TableOfContents\Options;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Class that holds all the cache for the options.
*
* @since 1.0.0
*/
class Cache {
/**
* The DB options cache.
*
* @since 1.0.0
*
* @var array
*/
private static $db = [];
/**
* The options cache.
*
* @since 1.0.0
*
* @var array
*/
private static $options = [];
/**
* Sets the cache for the DB option.
*
* @since 1.0.0
*
* @param string $name The cache name.
* @param array $value The value.
* @return void
*/
public function setDb( $name, $value ) {
self::$db[ $name ] = $value;
}
/**
* Gets the cache for the DB option.
*
* @since 1.0.0
*
* @param string $name The cache name.
* @return array The data from the cache.
*/
public function getDb( $name ) {
return ! empty( self::$db[ $name ] ) ? self::$db[ $name ] : [];
}
/**
* Sets the cache for the options.
*
* @since 1.0.0
*
* @param string $name The cache name.
* @param array $value The value.
* @return void
*/
public function setOptions( $name, $value ) {
self::$options[ $name ] = $value;
}
/**
* Gets the cache for the options.
*
* @since 1.0.0
*
* @param string $name The cache name.
* @return array The data from the cache.
*/
public function getOptions( $name ) {
return ! empty( self::$options[ $name ] ) ? self::$options[ $name ] : [];
}
/**
* Resets the DB cache.
*
* @since 1.0.0
*
* @return void
*/
public function resetDb() {
self::$db = [];
}
}
@@ -0,0 +1,119 @@
<?php
namespace AIOSEO\TableOfContents\Options;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
use AIOSEO\TableOfContents\Traits;
/**
* Class that holds all internal options for Table of Contents Plus.
*
* @since 1.0.0
*/
class InternalOptions {
use Traits\Options;
/**
* Holds a list of all the possible deprecated options.
*
* @since 1.0.0
*
* @var array
*/
protected $allDeprecatedOptions = [];
/**
* All the default options.
*
* @since 1.0.0
*
* @var array
*/
protected $defaults = [
// phpcs:disable WordPress.Arrays.ArrayDeclarationSpacing.AssociativeArrayFound
'internal' => [
'firstActivated' => [ 'type' => 'number', 'default' => 0 ],
'lastActiveVersion' => [ 'type' => 'string', 'default' => '0.0' ],
'lastSchemaVersion' => [ 'type' => 'string', 'default' => '0.0' ],
'migratedAppearanceDefaults' => [ 'type' => 'boolean', 'default' => false ],
]
// phpcs:enable WordPress.Arrays.ArrayDeclarationSpacing.AssociativeArrayFound
];
/**
* Class constructor.
*
* @since 1.0.0
*
* @param string $optionsName The options name.
*/
public function __construct( $optionsName = 'aioseo_table_of_contents_options_internal' ) {
$this->optionsName = is_network_admin() ? $optionsName . '_network' : $optionsName;
$this->init();
add_action( 'shutdown', [ $this, 'save' ] );
}
/**
* Initializes the options.
*
* @since 1.0.0
*
* @return void
*/
protected function init() {
// Options from the DB.
$dbOptions = $this->getDbOptions( $this->optionsName );
// Refactor options.
$this->defaultsMerged = array_replace_recursive( $this->defaults, $this->defaultsMerged );
$options = array_replace_recursive(
$this->defaultsMerged,
$this->addValueToValuesArray( $this->defaultsMerged, $dbOptions )
);
aioseoTableOfContents()->core->optionsCache->setOptions( $this->optionsName, apply_filters( 'aioseo_table_of_contents_get_options_internal', $options ) );
}
/**
* Get all the deprecated options.
*
* @since 1.0.0
*
* @return void
*/
public function getAllDeprecatedOptions() {
return $this->allDeprecatedOptions;
}
/**
* Sanitizes, then saves the options to the database.
*
* @since 1.0.0
*
* @param array $options An array of options to sanitize, then save.
* @return void
*/
public function sanitizeAndSave( $options ) {
if ( ! is_array( $options ) ) {
return;
}
// Refactor options.
$cachedOptions = aioseoTableOfContents()->core->optionsCache->getOptions( $this->optionsName );
$dbOptions = array_replace_recursive(
$cachedOptions,
$this->addValueToValuesArray( $cachedOptions, $options, [], true )
);
aioseoTableOfContents()->core->optionsCache->setOptions( $this->optionsName, $dbOptions );
// Update values.
$this->save( true );
}
}
@@ -0,0 +1,124 @@
<?php
namespace AIOSEO\TableOfContents\Options;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
use AIOSEO\TableOfContents\Traits;
/**
* Handles the main options.
*
* @since 1.0.0
*/
class Options {
use Traits\Options;
/**
* All the default options.
*
* @since 1.0.0
*
* @var array
*/
protected $defaults = [
// phpcs:disable WordPress.Arrays.ArrayDeclarationSpacing.AssociativeArrayFound
'general' => [
// Define options here.
]
// phpcs:enable WordPress.Arrays.ArrayDeclarationSpacing.AssociativeArrayFound
];
/**
* The Construct method.
*
* @since 1.0.0
*
* @param string $optionsName An array of options.
*/
public function __construct( $optionsName = 'aioseo_table_of_contents_options' ) {
$this->optionsName = $optionsName;
$this->init();
add_action( 'shutdown', [ $this, 'save' ] );
}
/**
* Initializes the options.
*
* @since 1.0.0
*
* @return void
*/
protected function init() {
$options = $this->getTableOfContentsDbOptions();
aioseoTableOfContents()->core->optionsCache->setOptions( $this->optionsName, apply_filters( 'aioseo_table_of_contents_get_options', $options ) );
}
/**
* Get the DB options.
*
* @since 1.0.0
*
* @return array An array of options.
*/
public function getTableOfContentsDbOptions() {
// Options from the DB.
$dbOptions = $this->getDbOptions( $this->optionsName );
// Refactor options.
$this->defaultsMerged = array_replace_recursive( $this->defaults, $this->defaultsMerged );
return array_replace_recursive(
$this->defaultsMerged,
$this->addValueToValuesArray( $this->defaultsMerged, $dbOptions )
);
}
/**
* Sanitizes, then saves the options to the database.
*
* @since 1.0.0
*
* @param array $newOptions An array of options to sanitize, then save.
* @return void
*/
public function sanitizeAndSave( $newOptions ) {
$this->init();
if ( ! is_array( $newOptions ) ) {
return;
}
// First, recursively replace the new options into the cached state.
// It's important we use the helper method since we want to replace populated arrays with empty ones if needed (when a setting was cleared out).
$cachedOptions = aioseoTableOfContents()->core->optionsCache->getOptions( $this->optionsName );
$dbOptions = aioseoTableOfContents()->helpers->arrayReplaceRecursive(
$cachedOptions,
$this->addValueToValuesArray( $cachedOptions, $newOptions, [], true )
);
// Now, we must also intersect both arrays to delete any individual keys that were unset.
// We must do this because, while arrayReplaceRecursive will update the values for keys or empty them out,
// it will keys that aren't present in the replacement array unaffected in the target array.
$dbOptions = aioseoTableOfContents()->helpers->arrayIntersectRecursive(
$dbOptions,
$this->addValueToValuesArray( $cachedOptions, $newOptions, [], true ),
'value'
);
if ( isset( $newOptions['advanced']['excludeDomains'] ) ) {
$dbOptions['advanced']['excludeDomains'] = preg_replace( '/\h/', "\n", (string) $newOptions['advanced']['excludeDomains'] );
}
// Update the cache state.
aioseoTableOfContents()->core->optionsCache->setOptions( $this->optionsName, $dbOptions );
// Finally, save the new values to the DB.
$this->save( true );
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,45 @@
<?php
namespace AIOSEO\TableOfContents\Standalone;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Registers the standalone components.
*
* @since 1.0.0
*/
class Standalone {
/**
* The frontend engine instance.
*
* @since 1.0.0
*
* @var Frontend
*/
public $frontend = null;
/**
* Class constructor.
*
* @since 1.0.0
*/
public function __construct() {
// The global constants (TOC_VERSION, TOC_POSITION_*, etc.) and the toc_get_index() API
// function are part of the plugin's public surface, so they stay global and are loaded
// explicitly (they are not PSR-4 autoloaded like the classes).
require_once __DIR__ . '/globals.php';
require_once __DIR__ . '/functions.php';
$this->frontend = new Frontend();
// Preserve the historical global and class name so themes and snippets that reference
// $toc_plus or the TOC_Plus class keep working.
$GLOBALS['toc_plus'] = $this->frontend; // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
if ( ! class_exists( 'TOC_Plus' ) ) {
class_alias( Frontend::class, 'TOC_Plus' );
}
}
}
@@ -0,0 +1,149 @@
<?php
namespace AIOSEO\TableOfContents\Standalone;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class Widget extends \WP_Widget {
public function __construct() {
$widget_options = [
'classname' => 'toc_widget',
'description' => __( 'Display the table of contents in the sidebar with this widget', 'table-of-contents-plus' ),
];
$control_options = [
'width' => 250,
'height' => 350,
'id_base' => 'toc-widget',
];
parent::__construct( 'toc-widget', 'TOC+', $widget_options, $control_options );
}
/**
* Widget output to the public
*/
public function widget( $args, $instance ) {
global $toc_plus, $wp_query;
if ( is_null( $wp_query->post ) ) {
return;
}
$html = '';
$items = '';
$find = [];
$replace = [];
$toc_options = $toc_plus->get_options();
$post = get_post( $wp_query->post->ID );
if ( $toc_plus->is_eligible() ) {
$items = $toc_plus->extract_headings( $find, $replace, wptexturize( do_shortcode( $post->post_content ) ) );
$title = ( array_key_exists( 'title', $instance ) ) ? apply_filters( 'widget_title', $instance['title'] ) : '';
if ( false !== strpos( $title, '%PAGE_TITLE%' ) ) {
$title = str_replace( '%PAGE_TITLE%', get_the_title(), $title );
}
if ( false !== strpos( $title, '%PAGE_NAME%' ) ) {
$title = str_replace( '%PAGE_NAME%', get_the_title(), $title );
}
$hide_inline = $toc_options['show_toc_in_widget_only'];
$css_classes = '';
// bullets?
if ( $toc_options['bullet_spacing'] ) {
$css_classes .= ' have_bullets';
} else {
$css_classes .= ' no_bullets';
}
if ( $items ) {
// before widget (defined by themes)
$html .= $args['before_widget'];
// display the widget title if one was input (before and after titles defined by themes)
if ( $title ) {
$html .= $args['before_title'] . $title . $args['after_title'];
}
// display the list
$html .= '<ul class="toc_widget_list' . $css_classes . '">' . $items . '</ul>';
// after widget (defined by themes)
$html .= $args['after_widget'];
echo wp_kses_post( $html );
}
}
}
/**
* Update the widget settings
*/
public function update( $new_instance, $old_instance ) {
global $toc_plus;
$instance = $old_instance;
// strip tags for title to remove HTML (important for text inputs)
$instance['title'] = wp_strip_all_tags( trim( $new_instance['title'] ) );
// no need to strip tags for the following
//$instance['hide_inline'] = $new_instance['hide_inline'];
$toc_plus->set_show_toc_in_widget_only( $new_instance['hide_inline'] );
$toc_plus->set_show_toc_in_widget_only_post_types( (array) $new_instance['show_toc_in_widget_only_post_types'] );
return $instance;
}
/**
* Displays the widget settings on the widget panel.
*/
public function form( $instance ) {
global $toc_plus;
$toc_options = $toc_plus->get_options();
$defaults = [ 'title' => $toc_options['heading_text'] ];
$instance = wp_parse_args( (array) $instance, $defaults );
?>
<p>
<label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php esc_html_e( 'Title', 'table-of-contents-plus' ); ?>:</label>
<input type="text" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" value="<?php echo esc_attr( $instance['title'] ); ?>" style="width: 100%;">
</p>
<p>
<input class="checkbox" type="checkbox" <?php checked( $toc_options['show_toc_in_widget_only'], 1 ); ?> id="<?php echo esc_attr( $this->get_field_id( 'hide_inline' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'hide_inline' ) ); ?>" value="1">
<label for="<?php echo esc_attr( $this->get_field_id( 'hide_inline' ) ); ?>"> <?php esc_html_e( 'Show the table of contents only in the sidebar', 'table-of-contents-plus' ); ?></label>
</p>
<div class="show_toc_in_widget_only_post_types" style="margin: 0 0 25px 25px; display: <?php echo ( 1 === $toc_options['show_toc_in_widget_only'] ) ? 'block' : 'none'; ?>;">
<p><?php esc_html_e( 'For the following content types:', 'table-of-contents-plus' ); ?></p>
<?php
foreach ( get_post_types() as $post_type ) {
// make sure the post type isn't on the exclusion list
if ( ! in_array( $post_type, $toc_plus->get_exclude_post_types(), true ) ) {
echo '<input type="checkbox" value="' . esc_attr( $post_type ) . '" id="' . esc_attr( $this->get_field_id( 'show_toc_in_widget_only_post_types_' . $post_type ) ) . '" name="' . esc_attr( $this->get_field_name( 'show_toc_in_widget_only_post_types' ) ) . '[]"';
if ( in_array( $post_type, $toc_options['show_toc_in_widget_only_post_types'], true ) ) {
echo ' checked="checked"';
}
echo ' /><label for="' . esc_attr( $this->get_field_id( 'show_toc_in_widget_only_post_types_' . $post_type ) ) . '"> ' . esc_html( $post_type ) . '</label><br />';
}
}
?>
</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#<?php echo esc_js( $this->get_field_id( 'hide_inline' ) ); ?>').click(function() {
$(this).parent().siblings('div.show_toc_in_widget_only_post_types').toggle('fast');
});
});
</script>
<?php
}
}
@@ -0,0 +1,51 @@
<?php
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Returns a HTML formatted string of the table of contents without the surrounding UL or OL
* tags to enable the theme editor to supply their own ID and/or classes to the outer list.
*
* There are three optional parameters you can feed this function with:
*
* - $content is the entire content with headings. If blank, will default to the current $post
*
* - $link is the URL to prefix the anchor with. If provided a string, will use it as the prefix.
* If set to true then will try to obtain the permalink from the $post object.
*
* - $apply_eligibility bool, defaults to false. When set to true, will apply the check to
* see if bit of content has the prerequisites needed for a TOC, eg minimum number of headings
* enabled post type, etc.
*/
function toc_get_index( $content = '', $prefix_url = '', $apply_eligibility = false ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound
global $wp_query, $toc_plus;
$return = '';
$find = [];
$replace = [];
$proceed = true;
if ( ! $content ) {
$post = get_post( $wp_query->post->ID );
$content = wptexturize( $post->post_content );
}
if ( $apply_eligibility ) {
if ( ! $toc_plus->is_eligible() ) {
$proceed = false;
}
} else {
$toc_plus->set_option( [ 'start' => 0 ] );
}
if ( $proceed ) {
$return = $toc_plus->extract_headings( $find, $replace, $content );
if ( $prefix_url ) {
$return = str_replace( 'href="#', 'href="' . $prefix_url . '#', $return );
}
}
return $return;
}
@@ -0,0 +1,32 @@
<?php
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
define( 'TOC_VERSION', '202609.1' );
define( 'TOC_POSITION_BEFORE_FIRST_HEADING', 1 );
define( 'TOC_POSITION_TOP', 2 );
define( 'TOC_POSITION_BOTTOM', 3 );
define( 'TOC_POSITION_AFTER_FIRST_HEADING', 4 );
define( 'TOC_POSITION_BEFORE_FIRST_PARAGRAPH', 5 );
define( 'TOC_POSITION_AFTER_FIRST_PARAGRAPH', 6 );
define( 'TOC_MIN_START', 2 );
define( 'TOC_MAX_START', 10 );
define( 'TOC_SMOOTH_SCROLL_OFFSET', 30 );
define( 'TOC_WRAPPING_NONE', 0 );
define( 'TOC_WRAPPING_LEFT', 1 );
define( 'TOC_WRAPPING_RIGHT', 2 );
define( 'TOC_THEME_GREY', 1 );
define( 'TOC_THEME_LIGHT_BLUE', 2 );
define( 'TOC_THEME_WHITE', 3 );
define( 'TOC_THEME_BLACK', 4 );
define( 'TOC_THEME_TRANSPARENT', 99 );
define( 'TOC_THEME_CUSTOM', 100 );
define( 'TOC_DEFAULT_BACKGROUND_COLOUR', '#f9f9f9' );
define( 'TOC_DEFAULT_BORDER_COLOUR', '#aaaaaa' );
define( 'TOC_DEFAULT_TITLE_COLOUR', '#' );
define( 'TOC_DEFAULT_LINKS_COLOUR', '#' );
define( 'TOC_DEFAULT_LINKS_HOVER_COLOUR', '#' );
define( 'TOC_DEFAULT_LINKS_VISITED_COLOUR', '#' );
define( 'TOC_PLUGIN_PATH', plugins_url( '', AIOSEO_TABLE_OF_CONTENTS_FILE ) );
@@ -0,0 +1,363 @@
<?php
namespace AIOSEO\TableOfContents {
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* The main TableOfContents class.
*
* @since 1.0.0
*/
final class TableOfContents {
/**
* Holds the instance of the plugin currently in use.
*
* @since 1.0.0
*
* @var TableOfContents
*/
private static $instance;
/**
* Plugin version for enqueueing, etc.
* The value is retrieved from the AIOSEO_TABLE_OF_CONTENTS_VERSION constant.
*
* @since 1.0.0
*
* @var string
*/
public $version = '';
/**
* Whether we're in a dev environment.
*
* @since 1.0.0
*
* @var bool
*/
public $isDev = false;
/**
* Core class instance.
*
* @since 1.0.0
*
* @var Core\Core
*/
public $core;
/**
* Database Schema class instance.
*
* @since 202607
*
* @var Db\Schema
*/
public $dbSchema;
/**
* InternalOptions class instance.
*
* @since 1.0.0
*
* @var Options\InternalOptions
*/
public $internalOptions;
/**
* Pre updates class instance.
*
* @since 1.0.0
*
* @var Main\PreUpdates
*/
public $preUpdates;
/**
* Helpers class instance.
*
* @since 1.0.0
*
* @var Utils\Helpers
*/
public $helpers;
/**
* Options class instance.
*
* @since 1.0.0
*
* @var Options\Options
*/
public $options;
/**
* Updates class instance.
*
* @since 1.0.0
*
* @var Main\Updates
*/
public $updates;
/**
* Action scheduler class.
*
* @since 1.0.0
*
* @var Utils\ActionScheduler
*/
public $actionScheduler;
/**
* Access class.
*
* @since 1.0.0
*
* @var Utils\Access
*/
public $access;
/**
* Main class instance.
*
* @since 1.0.0
*
* @var Main\Main
*/
public $main;
/**
* API class instance.
*
* @since 1.0.0
*
* @var Api\Api
*/
public $api;
/**
* Standalone class instance.
*
* @since 1.0.0
*
* @var Standalone\Standalone
*/
public $standalone;
/**
* Notifications class instance.
*
* @since 1.0.0
*
* @var Admin\Notifications
*/
public $notifications;
/**
* VueSettings class instance.
*
* @since 1.1.0
*
* @var Utils\VueSettings
*/
public $vueSettings;
/**
* Admin class instance.
*
* @since 1.2.0
*
* @var Admin\Admin
*/
public $admin;
/**
* The main TableOfContents Instance.
*
* Insures that only one instance of TableOfContents exists in memory at any one
* time. Also prevents needing to define globals all over the place.
*
* @since 1.0.0
*
* @return TableOfContents The Table of Contents Plus instance.
*/
public static function instance() {
if ( null === self::$instance || ! self::$instance instanceof self ) {
self::$instance = new self();
self::$instance->init();
}
return self::$instance;
}
/**
* Initialize Table of Contents Plus!
*
* @since 1.0.0
*
* @return void
*/
private function init() {
$this->constants();
$this->includes();
$this->preLoad();
$this->load();
}
/**
* Setup plugin constants.
* All the path/URL related constants are defined in main plugin file.
*
* @since 1.0.0
*
* @return void
*/
private function constants() {
$defaultHeaders = [
'name' => 'Table of Contents Plus',
'version' => 'Version',
];
$pluginData = get_file_data( AIOSEO_TABLE_OF_CONTENTS_FILE, $defaultHeaders );
$constants = [
'AIOSEO_TABLE_OF_CONTENTS_PLUGIN_BASENAME' => plugin_basename( AIOSEO_TABLE_OF_CONTENTS_FILE ),
'AIOSEO_TABLE_OF_CONTENTS_PLUGIN_NAME' => 'Table of Contents Plus',
'AIOSEO_TABLE_OF_CONTENTS_PLUGIN_URL' => plugin_dir_url( AIOSEO_TABLE_OF_CONTENTS_FILE ),
'AIOSEO_TABLE_OF_CONTENTS_VERSION' => $pluginData['version'],
'AIOSEO_TABLE_OF_CONTENTS_MARKETING_URL' => 'https://aioseo.com/',
'AIOSEO_TABLE_OF_CONTENTS_MARKETING_DOMAIN' => 'aioseo.com'
];
foreach ( $constants as $constant => $value ) {
if ( ! defined( $constant ) ) {
define( $constant, $value ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.VariableConstantNameFound
}
}
$this->version = AIOSEO_TABLE_OF_CONTENTS_VERSION;
}
/**
* Including the new files with PHP 5.3 style.
*
* @since 1.0.0
*
* @return void
*/
private function includes() {
$dependencies = [
'/vendor/autoload.php',
'/vendor/woocommerce/action-scheduler/action-scheduler.php'
];
foreach ( $dependencies as $path ) {
if ( ! file_exists( AIOSEO_TABLE_OF_CONTENTS_DIR . $path ) ) {
// Something is not right.
status_header( 500 );
wp_die( esc_html__( 'Plugin is missing required dependencies. Please contact support for more information.', 'table-of-contents-plus' ) );
}
require_once AIOSEO_TABLE_OF_CONTENTS_DIR . $path;
}
$this->loadVersion();
}
/**
* Load the version of the plugin we are currently using.
*
* @since 1.0.0
*
* @return void
*/
private function loadVersion() {
if (
! class_exists( '\Dotenv\Dotenv' ) ||
! file_exists( AIOSEO_TABLE_OF_CONTENTS_DIR . '/build/.env' )
) {
return;
}
$dotenv = \Dotenv\Dotenv::createUnsafeImmutable( AIOSEO_TABLE_OF_CONTENTS_DIR, '/build/.env' );
$dotenv->load();
$devPort = strtolower( getenv( 'VITE_AIOSEO_TABLE_OF_CONTENTS_DEV_PORT' ) );
if ( ! empty( $devPort ) ) {
$this->isDev = true;
// Fix SSL certificate invalid in our local environments.
add_filter( 'https_ssl_verify', '__return_false' );
}
}
/**
* Runs before we load the plugin.
*
* @since 1.0.0
*
* @return void
*/
private function preLoad() {
$this->core = new Core\Core();
$this->helpers = new Utils\Helpers();
$this->dbSchema = new Db\Schema();
$this->internalOptions = new Options\InternalOptions();
$this->preUpdates = new Main\PreUpdates();
}
/**
* Load our classes.
*
* @since 1.0.0
*
* @return void
*/
public function load() {
$this->options = new Options\Options();
$this->updates = new Main\Updates();
$this->actionScheduler = new Utils\ActionScheduler();
$this->access = new Utils\Access();
$this->main = new Main\Main();
$this->api = new Api\Api();
$this->standalone = new Standalone\Standalone();
$this->notifications = new Admin\Notifications();
$this->admin = new Admin\Admin();
add_action( 'init', [ $this, 'loadInit' ], 999 );
}
/**
* Things that need to load after init.
*
* @since 1.0.0
*
* @return void
*/
public function loadInit() {
$this->vueSettings = new Utils\VueSettings( '_aioseo_table_of_contents_settings' );
}
}
}
namespace {
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* The function which returns the one AIOSEO instance.
*
* @since 1.0.0
*
* @return AIOSEO\TableOfContents\TableOfContents The instance.
*/
function aioseoTableOfContents() {
return AIOSEO\TableOfContents\TableOfContents::instance();
}
}
@@ -0,0 +1,117 @@
<?php
namespace AIOSEO\TableOfContents\Traits\Helpers;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Contains API specific helper methods.
*
* @since 1.0.0
*/
trait Api {
/**
* Request the remote URL via wp_remote_post and return a json decoded response.
*
* @since 1.0.0
*
* @param array $body The content to retrieve from the remote URL.
* @param array $headers The headers to send to the remote URL.
* @return string|null JSON decoded response on success, false on failure.
*/
public function sendRequest( $url, $body = [], $headers = [] ) {
$body = wp_json_encode( $body );
// Build the headers of the request.
$headers = wp_parse_args(
$headers,
[
'Content-Type' => 'application/json'
]
);
// Setup variable for wp_remote_post.
$requestArgs = [
'headers' => $headers,
'body' => $body,
'timeout' => 20
];
// Perform the query and retrieve the response.
$response = $this->wpRemotePost( $url, $requestArgs );
$responseBody = wp_remote_retrieve_body( $response );
// Bail out early if there are any errors.
if ( ! $responseBody ) {
return null;
}
// Return the json decoded content.
return json_decode( $responseBody );
}
/**
* Sends a request using wp_remote_post.
*
* @since 1.0.0
*
* @param string $url The URL to send the request to.
* @param array $args The args to use in the request.
* @return array|\WP_Error The response as an array or WP_Error on failure.
*/
public function wpRemotePost( $url, $args = [] ) {
return wp_remote_post( $url, array_replace_recursive( $this->getWpApiRequestDefaults(), $args ) );
}
/**
* Sends a request using wp_remote_get.
*
* @since 1.0.0
*
* @param string $url The URL to send the request to.
* @param array $args The args to use in the request.
* @return array|\WP_Error The response as an array or WP_Error on failure.
*/
public function wpRemoteGet( $url, $args = [] ) {
return wp_remote_get( $url, array_replace_recursive( $this->getWpApiRequestDefaults(), $args ) );
}
/**
* Default arguments for wp_remote_get and wp_remote_post.
*
* @since 1.0.0
*
* @return array An array of default arguments for the request.
*/
private function getWpApiRequestDefaults() {
return [
'timeout' => 10,
'headers' => aioseoTableOfContents()->helpers->getApiHeaders(),
'user-agent' => aioseoTableOfContents()->helpers->getApiUserAgent()
];
}
/**
* Returns the headers for internal API requests.
*
* @since 1.0.0
*
* @return array An array of headers.
*/
private function getApiHeaders() {
return [];
}
/**
* Returns the User Agent for internal API requests.
*
* @since 1.0.0
*
* @return string The User Agent.
*/
private function getApiUserAgent() {
return 'WordPress/' . get_bloginfo( 'version' ) . '; ' . get_bloginfo( 'url' ) . '; AIOSEO/TableOfContents/' . AIOSEO_TABLE_OF_CONTENTS_VERSION;
}
}
@@ -0,0 +1,112 @@
<?php
namespace AIOSEO\TableOfContents\Traits\Helpers;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Contains array specific helper methods.
*
* @since 1.0.0
*/
trait Arrays {
/**
* Checks whether the given array is associative.
* Arrays that only have consecutive, sequential numeric keys are numeric.
* Otherwise they are associative.
*
* @since 1.0.0
*
* @param array $array The array.
* @return bool Whether the array is associative.
*/
public function isArrayAssociative( $array ) {
return 0 < count( array_filter( array_keys( $array ), 'is_string' ) );
}
/**
* Checks whether the given array is numeric.
*
* @since 1.0.0
*
* @param array $array The array.
* @return bool Whether the array is numeric.
*/
public function isArrayNumeric( $array ) {
return ! $this->isArrayAssociative( $array );
}
/**
* Recursively replaces the values from one array with the ones from another.
* This function should act identical to the built-in array_replace_recursive(), with the exception that it also replaces array values with empty arrays.
*
* @since 1.0.0
*
* @param array $targetArray The target array
* @param array $replacementArray The array with values to replace in the target array.
* @return array The modified array.
*/
public function arrayReplaceRecursive( $targetArray, $replacementArray ) {
// In some cases the target array isn't an array yet (due to e.g. race conditions in InternalOptions), so in that case we can just return the replacement array.
if ( ! is_array( $targetArray ) ) {
return $replacementArray;
}
foreach ( $replacementArray as $k => $v ) {
// If the key does not exist yet on the target array, add it.
if ( ! isset( $targetArray[ $k ] ) ) {
$targetArray[ $k ] = $replacementArray[ $k ];
continue;
}
// If the value is an array, only try to recursively replace it if the value isn't empty.
// Otherwise empty arrays will be ignored and won't override the existing value of the target array.
if ( is_array( $v ) && ! empty( $v ) ) {
$targetArray[ $k ] = $this->arrayReplaceRecursive( $targetArray[ $k ], $v );
continue;
}
// Replace with non-array value or empty array.
$targetArray[ $k ] = $v;
}
return $targetArray;
}
/**
* Recursively intersects the two given arrays.
* You can pass in an optional argument (allowedKey) to restrict the intersect to arrays with a specific key.
* This is needed when we are e.g. sanitizing array values before setting/saving them to an option.
*
* @since 1.0.0
*
* @param array $array1 The first array.
* @param array $array2 The second array.
* @param string $allowedKey The only key the method should run for (optional).
* @param string $parentKey The parent key.
* @return array The intersected array.
*/
public function arrayIntersectRecursive( $array1, $array2, $allowedKey = '', $parentKey = '' ) {
if ( ! $allowedKey || $allowedKey === $parentKey ) {
$array1 = array_intersect_assoc( $array1, $array2 );
}
if ( empty( $array1 ) ) {
return [];
}
foreach ( $array1 as $k => $v ) {
if ( is_array( $v ) && isset( $array2[ $k ] ) ) {
$array1[ $k ] = $this->arrayIntersectRecursive( $array1[ $k ], $array2[ $k ], $allowedKey, $k );
}
}
if ( $this->isArrayNumeric( $array1 ) ) {
$array1 = array_values( $array1 );
}
return $array1;
}
}
@@ -0,0 +1,25 @@
<?php
namespace AIOSEO\TableOfContents\Traits\Helpers;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Contains constant specific helper methods.
*
* @since 1.0.0
*/
trait Constants {
/**
* Returns the plugin menu icon.
*
* @since 1.0.0
*
* @return string The icon as a string.
*/
public function icon() {
return '<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="16" cy="6" r="2.8" stroke="white" stroke-width="2.4"/><path d="M16 8.8V26.6M10.4 12.2H21.6" stroke="white" stroke-width="2.6" stroke-linecap="round"/><path d="M7 16.4H4.3a11.7 11.7 0 0 0 23.4 0H25" stroke="white" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"/></svg>'; // phpcs:ignore Generic.Files.LineLength.MaxExceeded
}
}
@@ -0,0 +1,28 @@
<?php
namespace AIOSEO\TableOfContents\Traits\Helpers;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Contains date/time specific helper methods.
*
* @since 1.0.0
*/
trait DateTime {
/**
* Returns a MySQL formatted date.
*
* @since 1.0.0
*
* @param int|string $time Any format accepted by strtotime.
* @return false|string The MySQL formatted string.
*/
public function timeToMysql( $time ) {
$time = is_string( $time ) ? strtotime( $time ) : $time;
return date( 'Y-m-d H:i:s', $time ); // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date
}
}
@@ -0,0 +1,284 @@
<?php
namespace AIOSEO\TableOfContents\Traits\Helpers;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Contains string specific helper methods.
*
* @since 1.0.0
*/
trait Strings {
/**
* Escapes special regex characters.
*
* @since 1.0.0
*
* @param string $string The string.
* @param string $delimiter The delimiter character.
* @return string The escaped string.
*/
public function escapeRegex( $string, $delimiter = '/' ) {
static $escapeRegex = [];
if ( isset( $escapeRegex[ $string ] ) ) {
return $escapeRegex[ $string ];
}
$escapeRegex[ $string ] = preg_quote( (string) $string, $delimiter );
return $escapeRegex[ $string ];
}
/**
* Escapes special regex characters inside the replacement string.
*
* @since 1.0.0
*
* @param string $string The string.
* @return string The escaped string.
*/
public function escapeRegexReplacement( $string ) {
static $escapeRegexReplacement = [];
if ( isset( $escapeRegexReplacement[ $string ] ) ) {
return $escapeRegexReplacement[ $string ];
}
$escapeRegexReplacement[ $string ] = str_replace( '$', '\$', $string );
return $escapeRegexReplacement[ $string ];
}
/**
* preg_replace but with the replacement escaped.
*
* @since 1.0.0
*
* @param string $pattern The pattern to search for.
* @param string $replacement The replacement string.
* @param string $subject The subject to search in.
* @return string The subject with matches replaced.
*/
public function pregReplace( $pattern, $replacement, $subject ) {
$key = $pattern . $replacement . $subject;
static $pregReplace = [];
if ( isset( $pregReplace[ $key ] ) ) {
return $pregReplace[ $key ];
}
// We can use the following pattern for this - (?<!\\)([\/.^$*+?|()[{}\]]{1})
// The pattern above will only escape special characters if they're not escaped yet, which makes it compatible with all our patterns that are already escaped.
// The caveat is that we'd need to first trim off slash delimiters and add them back later - otherwise they'd be escaped as well.
$replacement = $this->escapeRegexReplacement( $replacement );
$pregReplace[ $key ] = preg_replace( $pattern, $replacement, (string) $subject );
return $pregReplace[ $key ];
}
/**
* Returns the index of a substring in a string.
*
* @since 1.0.0
*
* @param string $stack The stack.
* @param string $needle The needle.
* @param int $offset The offset.
* @return int|bool The index where the string starts or false if it does not exist.
*/
public function stringIndex( $stack, $needle, $offset = 0 ) {
$key = $stack . $needle . $offset;
static $stringIndex = [];
if ( isset( $stringIndex[ $key ] ) ) {
return $stringIndex[ $key ];
}
$stringIndex[ $key ] = function_exists( 'mb_strpos' ) ? mb_strpos( $stack, $needle, $offset, get_option( 'blog_charset' ) ) : strpos( $stack, $needle, $offset );
return $stringIndex[ $key ];
}
/**
* Checks if the given string contains the given substring.
*
* @since 1.0.0
*
* @param string $stack The stack.
* @param string $needle The needle.
* @param int $offset The offset.
* @return bool Whether the substring occurs in the main string.
*/
public function stringContains( $stack, $needle, $offset = 0 ) {
$key = $stack . $needle . $offset;
static $stringContains = [];
if ( isset( $stringContains[ $key ] ) ) {
return $stringContains[ $key ];
}
$stringContains[ $key ] = false !== $this->stringIndex( $stack, $needle, $offset );
return $stringContains[ $key ];
}
/**
* Check if a string is JSON encoded or not.
*
* @since 1.0.0
*
* @param string $string The string to check.
* @return bool True if it is JSON or false if not.
*/
public function isJsonString( $string ) {
if ( ! is_string( $string ) ) {
return false;
}
json_decode( $string );
// Return a boolean whether or not the last error matches.
return json_last_error() === JSON_ERROR_NONE;
}
/**
* Returns the string after all HTML entities have been decoded.
*
* @since 1.0.0
*
* @param string $string The string to decode.
* @return string The decoded string.
*/
public function decodeHtmlEntities( $string ) {
static $decodeHtmlEntities = [];
if ( isset( $decodeHtmlEntities[ $string ] ) ) {
return $decodeHtmlEntities[ $string ];
}
// We must manually decode non-breaking spaces since html_entity_decode doesn't do this.
$string = $this->pregReplace( '/&nbsp;/', ' ', $string );
$decodeHtmlEntities[ $string ] = html_entity_decode( (string) $string, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 );
return $decodeHtmlEntities[ $string ];
}
/**
* Returns the string with script tags stripped.
*
* @since 1.0.0
*
* @param string $string The string.
* @return string The modified string.
*/
public function stripScriptTags( $string ) {
static $stripScriptTags = [];
if ( isset( $stripScriptTags[ $string ] ) ) {
return $stripScriptTags[ $string ];
}
$stripScriptTags[ $string ] = $this->pregReplace( '/<script(.*?)>(.*?)<\/script>/is', '', $string );
return $stripScriptTags[ $string ];
}
/**
* Returns the string with incomplete HTML tags stripped.
* Incomplete tags are not unopened/unclosed pairs but rather single tags that aren't properly formed.
* e.g. <a href='something'
* e.g. href='something' >
*
* @since 1.0.0
*
* @param string $string The string.
* @return string The modified string.
*/
public function stripIncompleteHtmlTags( $string ) {
static $stripIncompleteHtmlTags = [];
if ( isset( $stripIncompleteHtmlTags[ $string ] ) ) {
return $stripIncompleteHtmlTags[ $string ];
}
$stripIncompleteHtmlTags[ $string ] = $this->pregReplace( '/(^(?!<).*?(\/>)|<[^>]*?(?!\/>)$)/is', '', $string );
return $stripIncompleteHtmlTags[ $string ];
}
/**
* Trims HTML paragraph from the start/end of the given string.
*
* @since 1.0.0
*
* @param string $string The string.
* @return string The modified string.
*/
public function trimParagraphTags( $string ) {
$string = preg_replace( '/^<p[^>]*>/', '', (string) $string );
$string = preg_replace( '/<\/p>/', '', (string) $string );
return trim( $string );
}
/**
* Implodes an array into a WHEREIN clause useable string.
*
* @since 1.0.0
*
* @param array $array The array.
* @param bool $outerQuotes Whether outer quotes should be added.
* @return string The imploded array.
*/
public function implodeWhereIn( $array, $outerQuotes = false ) {
// Reset the keys first in case there is no 0 index.
$array = array_values( $array );
if ( ! isset( $array[0] ) ) {
return '';
}
if ( is_numeric( $array[0] ) ) {
return implode( ', ', $array );
}
return $outerQuotes ? "'" . implode( "', '", $array ) . "'" : implode( "', '", $array );
}
/**
* Returns string after converting it to lowercase.
*
* @since 1.0.0
*
* @param string $string The original string.
* @return string The string converted to lowercase.
*/
public function toLowerCase( $string ) {
static $lowerCased = [];
if ( isset( $lowerCased[ $string ] ) ) {
return $lowerCased[ $string ];
}
$lowerCased[ $string ] = function_exists( 'mb_strtolower' ) ? mb_strtolower( $string, $this->getCharset() ) : strtolower( $string );
return $lowerCased[ $string ];
}
/**
* Convert to camelCase.
*
* @since 1.1.0
*
* @param string $string The string to convert.
* @param bool $capitalize Whether to capitalize the first letter.
* @return string The converted string.
*/
public function toCamelCase( $string, $capitalize = false ) {
$string[0] = strtolower( $string[0] );
if ( $capitalize ) {
$string[0] = strtoupper( $string[0] );
}
return preg_replace_callback( '/_([a-z0-9])/', function ( $value ) {
return strtoupper( $value[1] );
}, $string );
}
}
@@ -0,0 +1,47 @@
<?php
namespace AIOSEO\TableOfContents\Traits\Helpers;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Contains helper methods for other plugins/themes.
*
* @since 1.0.0
*/
trait ThirdParty {
/**
* Checks whether WooCommerce is active.
*
* @since 1.0.0
*
* @return boolean Whether WooCommerce is active.
*/
public function isWooCommerceActive() {
return class_exists( 'woocommerce' );
}
/**
* Checks whether the queried object is the WooCommerce shop page.
*
* @since 1.0.0
*
* @param int $id The post ID to check against (optional).
* @return bool Whether the current page is the WooCommerce shop page.
*/
public function isWooCommerceShopPage( $id = 0 ) {
if ( ! $this->isWooCommerceActive() ) {
return false;
}
if ( ! is_admin() && ! aioseoTableOfContents()->helpers->isAjaxCronRestRequest() && function_exists( 'is_shop' ) ) {
return is_shop();
}
$id = ! $id && ! empty( $_GET['post'] ) ? absint( wp_unslash( $_GET['post'] ) ) : (int) $id; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
return $id && wc_get_page_id( 'shop' ) === $id;
}
}
@@ -0,0 +1,178 @@
<?php
namespace AIOSEO\TableOfContents\Traits\Helpers;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
use AIOSEO\TableOfContents\Api;
use AIOSEO\TableOfContents\Models;
/**
* Generates the data we need for Vue.
*
* @since 1.0.0
*/
trait Vue {
/**
* The data to pass to Vue.
*
* @since 1.0.0
*
* @var array
*/
private $vueData = [];
/**
* Returns the data for Vue.
*
* @since 1.0.0
*
* @param string $currentPage The current page.
* @return array The data.
*/
public function getVueData( $currentPage = null ) {
global $wp_version;
static $showNotificationsDrawer = null;
if ( null === $showNotificationsDrawer ) {
$showNotificationsDrawer = aioseoTableOfContents()->core->cache->get( 'show_notifications_drawer' ) ? true : false;
// IF this is set to true, let's disable it now so it doesn't pop up again.
if ( $showNotificationsDrawer ) {
aioseoTableOfContents()->core->cache->delete( 'show_notifications_drawer' );
}
}
$this->vueData = [
// The following data is needed on all screens.
'wpVersion' => $wp_version,
'page' => $currentPage,
'screen' => aioseoTableOfContents()->helpers->getCurrentScreen(),
'internalOptions' => aioseoTableOfContents()->internalOptions->all(),
'options' => aioseoTableOfContents()->options->all(),
'settings' => aioseoTableOfContents()->vueSettings->all(),
'tocSettings' => aioseoTableOfContents()->standalone->frontend->get_options(),
'tocPostTypes' => Api\TocSettings::getPostTypes(),
'notifications' => array_merge( Models\Notification::getNotifications( false ), [ 'force' => $showNotificationsDrawer ] ),
'helpPanel' => [],
'urls' => [
'domain' => $this->getSiteDomain(),
'mainSiteUrl' => $this->getSiteUrl(),
'home' => home_url(),
'restUrl' => rest_url(),
'editScreen' => admin_url( 'edit.php' ),
'publicPath' => aioseoTableOfContents()->core->assets->normalizeAssetsHost( plugin_dir_url( AIOSEO_TABLE_OF_CONTENTS_FILE ) ),
'assetsPath' => aioseoTableOfContents()->core->assets->getAssetsPath(),
'marketingSite' => $this->getMarketingSiteUrl(),
'connect' => admin_url( 'index.php?page=table-of-contents-connect' )
],
'isDev' => $this->isDev(),
'isAioseoActive' => function_exists( 'aioseo' ),
'isAioseoInstalled' => file_exists( WP_PLUGIN_DIR . '/all-in-one-seo-pack/all_in_one_seo_pack.php' )
|| file_exists( WP_PLUGIN_DIR . '/all-in-one-seo-pack-pro/all_in_one_seo_pack.php' ),
'isBrokenLinkCheckerActive' => function_exists( 'aioseoBrokenLinkChecker' ),
'isBrokenLinkCheckerInstalled' => file_exists( WP_PLUGIN_DIR . '/broken-link-checker-seo/aioseo-broken-link-checker.php' )
|| file_exists( WP_PLUGIN_DIR . '/aioseo-broken-link-checker/aioseo-broken-link-checker.php' ),
'isSsl' => is_ssl(),
'isMultisite' => is_multisite(),
'isNetworkAdmin' => is_network_admin(),
'mainSite' => is_main_site(),
'hasUrlTrailingSlash' => '/' === user_trailingslashit( '' ),
'nonce' => wp_create_nonce( 'wp_rest' ),
'translations' => $this->getJedLocaleData( 'table-of-contents-plus' )
];
// In multisite, super admins may not have explicit roles on subsites.
// Ensure they have administrator role and capabilities for proper access.
$userData = wp_get_current_user();
$roles = $userData->roles;
$capabilities = $userData->allcaps;
// If the user is a network admin, and doesn't have a user on the subsite, give him admin role/caps.
if ( is_multisite() && is_super_admin() && empty( $roles ) ) {
$roles = [ 'administrator' ];
$adminRole = get_role( 'administrator' );
if ( is_a( $adminRole, 'WP_Role' ) ) {
$capabilities = $adminRole->capabilities;
}
}
$this->vueData['user'] = [
'canManage' => aioseoTableOfContents()->access->canManage(),
'roles' => $roles,
'capabilities' => $capabilities,
'locale' => function_exists( 'get_user_locale' ) ? get_user_locale() : get_locale()
];
switch ( $currentPage ) {
case 'about':
$this->addAboutData();
break;
default:
break;
}
return $this->vueData;
}
/**
* Adds the data for the About Us screen.
*
* @since 1.0.0
*
* @return void
*/
private function addAboutData() {
$this->vueData['plugins'] = $this->getPluginData();
}
/**
* Returns Jed-formatted localization data.
*
* @since 1.0.0
*
* @param string $domain The text domain.
* @return array The information of the locale.
*/
private function getJedLocaleData( $domain ) {
$translations = get_translations_for_domain( $domain );
$locale = [
'' => [
'domain' => $domain,
'lang' => is_admin() && function_exists( 'get_user_locale' ) ? get_user_locale() : get_locale(),
],
];
if ( ! empty( $translations->headers['Plural-Forms'] ) ) {
$locale['']['plural_forms'] = $translations->headers['Plural-Forms'];
}
foreach ( $translations->entries as $msgid => $entry ) {
if ( empty( $entry->translations ) || ! is_array( $entry->translations ) ) {
continue;
}
$locale[ $msgid ] = $entry->translations;
}
return $locale;
}
/**
* Returns the marketing site URL.
*
* @since 1.0.0
*
* @return string The marketing site URL.
*/
private function getMarketingSiteUrl() {
if ( defined( 'AIOSEO_MARKETING_SITE_URL' ) && AIOSEO_MARKETING_SITE_URL ) {
return AIOSEO_MARKETING_SITE_URL;
}
return 'https://aioseo.com/';
}
}
@@ -0,0 +1,470 @@
<?php
namespace AIOSEO\TableOfContents\Traits\Helpers;
use AIOSEO\TableOfContents\Utils;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Contains all WP related helper methods.
*
* @since 1.0.0
*/
trait Wp {
/**
* Returns all registered post statuses.
*
* @since 1.0.0
*
* @param boolean $statusesOnly Whether or not to only return statuses.
* @return array List of post statuses.
*/
public function getPublicPostStatuses( $statusesOnly = false ) {
$allStatuses = get_post_stati( [ 'show_in_admin_all_list' => true ], 'objects' );
$postStatuses = [];
foreach ( $allStatuses as $status => $data ) {
if (
! $data->public &&
! $data->protected &&
! $data->private
) {
continue;
}
if ( $statusesOnly ) {
$postStatuses[] = $status;
continue;
}
$postStatuses[] = [
'label' => $data->label,
'status' => $status
];
}
return $postStatuses;
}
/**
* Returns a list of public post types with slugs/icons.
*
* @since 1.0.0
*
* @param boolean $namesOnly Whether only the names should be returned.
* @param boolean $hasArchivesOnly Whether or not to only include post types which have archives.
* @param boolean $rewriteType Whether or not to rewrite the type slugs.
* @return array List of public post types.
*/
public function getPublicPostTypes( $namesOnly = false, $hasArchivesOnly = false, $rewriteType = false ) {
$postTypes = [];
$postTypeObjects = get_post_types( [ 'public' => true ], 'objects' );
$woocommerce = class_exists( 'woocommerce' );
foreach ( $postTypeObjects as $postTypeObject ) {
if ( empty( $postTypeObject->label ) ) {
continue;
}
// We don't want to include archives for the WooCommerce shop page.
if (
$hasArchivesOnly &&
(
! $postTypeObject->has_archive ||
( 'product' === $postTypeObject->name && $woocommerce )
)
) {
continue;
}
if ( $namesOnly ) {
$postTypes[] = $postTypeObject->name;
continue;
}
if ( 'attachment' === $postTypeObject->name ) {
// We have to check if the 'init' action has been fired to avoid a PHP notice
// in WP 6.7+ due to loading translations too early.
if ( did_action( 'init' ) ) {
$postTypeObject->label = __( 'Attachments', 'table-of-contents-plus' );
}
}
if ( 'product' === $postTypeObject->name && $woocommerce ) {
$postTypeObject->menu_icon = 'dashicons-products';
}
$name = $postTypeObject->name;
if ( 'type' === $postTypeObject->name && $rewriteType ) {
$name = '_aioseo_type';
}
$postTypes[] = [
'name' => $name,
'label' => ucwords( $postTypeObject->label ),
'singular' => ucwords( $postTypeObject->labels->singular_name ),
'icon' => $postTypeObject->menu_icon,
'hasExcerpt' => post_type_supports( $postTypeObject->name, 'excerpt' ),
'hasArchive' => $postTypeObject->has_archive,
'hierarchical' => $postTypeObject->hierarchical,
'taxonomies' => get_object_taxonomies( $name ),
'slug' => isset( $postTypeObject->rewrite['slug'] ) ? $postTypeObject->rewrite['slug'] : $name
];
}
return apply_filters( 'aioseo_table_of_contents_public_post_types', $postTypes, $namesOnly, $hasArchivesOnly );
}
/**
* Checks if the current user can edit posts of the given post type.
*
* @since 1.0.0
*
* @param string $postType The name of the post type.
* @return bool Whether the user can edit posts of the given post type.
*/
public function canEditPostType( $postType ) {
$capabilities = $this->getPostTypeCapabilities( $postType );
return current_user_can( $capabilities['edit_posts'] );
}
/**
* Returns a list of capabilities for the given post type.
*
* @since 1.0.0
*
* @param string $postType The name of the post type.
* @return array The capabilities.
*/
public function getPostTypeCapabilities( $postType ) {
static $capabilities = [];
if ( isset( $capabilities[ $postType ] ) ) {
return $capabilities[ $postType ];
}
$postTypeObject = get_post_type_object( $postType );
if ( ! is_a( $postTypeObject, 'WP_Post_Type' ) ) {
$capabilities[ $postType ] = [];
return $capabilities[ $postType ];
}
$capabilities[ $postType ] = (array) $postTypeObject->cap;
return $capabilities[ $postType ];
}
/**
* Returns the current post object.
*
* @since 1.0.0
*
* @param int|null $postId The post ID.
* @return \WP_Post|null The post object.
*/
public function getPost( $postId = null ) {
$postId = is_a( $postId, 'WP_Post' ) ? $postId->ID : $postId;
if ( $this->isWooCommerceShopPage( $postId ) ) {
return get_post( wc_get_page_id( 'shop' ) );
}
if ( is_front_page() || is_home() ) {
$showOnFront = 'page' === get_option( 'show_on_front' );
if ( $showOnFront ) {
if ( is_front_page() ) {
$pageOnFront = (int) get_option( 'page_on_front' );
return get_post( $pageOnFront );
} elseif ( is_home() ) {
$pageForPosts = (int) get_option( 'page_for_posts' );
return get_post( $pageForPosts );
}
}
}
// We need to check these conditions and cannot always return get_post() because we'll return the first post on archive pages (dynamic homepage, term pages, etc.).
// https://github.com/awesomemotive/aioseo/issues/2419
if (
$this->isScreenBase( 'post' ) ||
$postId ||
is_singular()
) {
return get_post( $postId );
}
return null;
}
/**
* Returns true if the request is a non-legacy REST API request.
* This function was copied from WooCommerce and improved.
*
* @since 1.0.0
*
* @return bool True if this is a REST API request.
*/
public function isRestApiRequest() {
if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
return true;
}
global $wp_rewrite;
if ( empty( $wp_rewrite ) ) {
return false;
}
if ( empty( $_SERVER['REQUEST_URI'] ) ) {
return false;
}
$restUrl = wp_parse_url( get_rest_url() );
$restUrl = $restUrl['path'] . ( ! empty( $restUrl['query'] ) ? '?' . $restUrl['query'] : '' );
$isRestApiRequest = ( 0 === strpos( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ), $restUrl ) );
return apply_filters( 'aioseo_is_rest_api_request', $isRestApiRequest );
}
/**
* Checks whether the current request is an AJAX, CRON or REST request.
*
* @since 1.0.0
*
* @return bool Wether the request is an AJAX, CRON or REST request.
*/
public function isAjaxCronRestRequest() {
return wp_doing_ajax() || wp_doing_cron() || $this->isRestApiRequest();
}
/**
* Check if the post passed in is a valid post, not a revision or autosave.
*
* @since 1.0.0
*
* @param \WP_Post $post The Post object to check.
* @param array $allowedPostStatuses Allowed post statuses.
* @return bool True if valid, false if not.
*/
public function isValidPost( $post, $allowedPostStatuses = [ 'publish' ] ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return false;
}
if ( ! is_object( $post ) ) {
$post = get_post( $post );
}
// In order to prevent recursion, we are skipping scheduled-action posts.
if (
! is_object( $post ) ||
'scheduled-action' === $post->post_type ||
'revision' === $post->post_type ||
! in_array( $post->post_status, $allowedPostStatuses, true )
) {
return false;
}
return true;
}
/**
* Returns a list of plugins with the active status.
*
* @since 1.0.0
*
* @return array List of plugins with active status.
*/
public function getPluginData() {
static $pluginData = [];
if ( ! empty( $pluginData ) ) {
return $pluginData;
}
$pluginUpgrader = new Utils\PluginUpgraderSilentAjax();
$installedPlugins = array_keys( get_plugins() );
foreach ( $pluginUpgrader->pluginSlugs as $key => $slug ) {
$pluginData[ $key ] = [
'basename' => $slug,
'installed' => in_array( $slug, $installedPlugins, true ),
'activated' => is_plugin_active( $slug ),
'adminUrl' => admin_url( $pluginUpgrader->pluginAdminUrls[ $key ] ),
'canInstall' => $this->canInstall(),
'canActivate' => $this->canActivate(),
'canUpdate' => $this->canUpdate(),
'wpLink' => ! empty( $pluginUpgrader->wpPluginLinks[ $key ] ) ? $pluginUpgrader->wpPluginLinks[ $key ] : null
];
}
return $pluginData;
}
/**
* Installs and activates a given addon or plugin.
*
* @since 1.0.0
*
* @param string $name The addon name/SKU.
* @param bool $network Whether or not we are in a network environment.
* @return bool Whether or not the installation was succesful.
*/
public function installAddon( $name, $network = false ) {
if ( ! $this->canInstall() ) {
return false;
}
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/template.php';
require_once ABSPATH . 'wp-admin/includes/class-wp-screen.php';
require_once ABSPATH . 'wp-admin/includes/screen.php';
// Set the current screen to avoid undefined notices.
set_current_screen( 'toplevel_page_table-of-contents' );
// Prepare variables.
$url = esc_url_raw(
add_query_arg(
[
'page' => 'table-of-contents-links'
],
admin_url( 'admin.php' )
)
);
// Do not allow WordPress to search/download translations, as this will break JS output.
remove_action( 'upgrader_process_complete', [ 'Language_Pack_Upgrader', 'async_upgrade' ], 20 );
// Create the plugin upgrader with our custom skin.
$installer = new Utils\PluginUpgraderSilentAjax( new Utils\PluginUpgraderSkin() );
// Activate the plugin silently.
$pluginUrl = ! empty( $installer->pluginSlugs[ $name ] ) ? $installer->pluginSlugs[ $name ] : $name;
$activated = activate_plugin( $pluginUrl, '', $network );
if ( ! is_wp_error( $activated ) ) {
return $name;
}
// Using output buffering to prevent the FTP form from being displayed in the screen.
ob_start();
$creds = request_filesystem_credentials( $url, '', false, false, null );
ob_end_clean();
// Check for file system permissions.
$fs = aioseoTableOfContents()->core->fs->noConflict();
$fs->init( $creds );
if ( false === $creds || ! $fs->isWpfsValid() ) {
return false;
}
// Error check.
if ( ! method_exists( $installer, 'install' ) ) {
return false;
}
$installLink = ! empty( $installer->pluginLinks[ $name ] ) ? $installer->pluginLinks[ $name ] : null;
// Check if this is an addon and if we have a download link.
if ( empty( $installLink ) ) {
return false;
}
$installer->install( $installLink );
// Flush the cache and return the newly installed plugin basename.
wp_cache_flush();
$pluginBasename = $installer->plugin_info();
if ( ! $pluginBasename ) {
return false;
}
// Activate the plugin silently.
$activated = activate_plugin( $pluginBasename, '', $network );
if ( is_wp_error( $activated ) ) {
return false;
}
return $pluginBasename;
}
/**
* Determine if plugins can be installed.
*
* @since 1.0.0
*
* @return bool Whether the plugin can be installed.
*/
public function canInstall() {
if ( ! current_user_can( 'install_plugins' ) ) {
return false;
}
// Determine whether file modifications are allowed.
if ( ! wp_is_file_mod_allowed( 'aioseo_table_of_contents_can_install' ) ) {
return false;
}
return true;
}
/**
* Determine if plugins can be updated.
*
* @since 1.0.0
*
* @return bool Whether the plugin can be updated.
*/
public function canUpdate() {
if ( ! current_user_can( 'update_plugins' ) ) {
return false;
}
// Determine whether file modifications are allowed.
if ( ! wp_is_file_mod_allowed( 'aioseo_table_of_contents_can_update' ) ) {
return false;
}
return true;
}
/**
* Determine if plugins can be activated.
*
* @since 1.0.0
*
* @return bool Whether the plugin can be activated.
*/
public function canActivate() {
if ( ! current_user_can( 'activate_plugins' ) ) {
return false;
}
return true;
}
/**
* Returns the charset for the site.
*
* @since 1.0.0
*
* @return string The name of the charset.
*/
public function getCharset() {
static $charset = null;
if ( null !== $charset ) {
return $charset;
}
$charset = get_option( 'blog_charset' );
$charset = $charset ? $charset : 'UTF-8';
return $charset;
}
}
@@ -0,0 +1,47 @@
<?php
namespace AIOSEO\TableOfContents\Traits\Helpers;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Contains all context related helper methods.
* This includes methods to check the context of the current request, but also get WP objects.
*
* @since 1.0.0
*/
trait WpContext {
/**
* Checks whether we're on the given screen.
*
* @since 1.0.0
*
* @param string $screenName The screen name.
* @return boolean Whether we're on the given screen.
*/
public function isScreenBase( $screenName ) {
$screen = $this->getCurrentScreen();
if ( ! $screen || ! isset( $screen->base ) ) {
return false;
}
return $screen->base === $screenName;
}
/**
* Gets current admin screen
*
* @since 1.0.0
*
* @return false|\WP_Screen|null
*/
public function getCurrentScreen() {
if ( ! is_admin() || ! function_exists( 'get_current_screen' ) ) {
return false;
}
return get_current_screen();
}
}
@@ -0,0 +1,78 @@
<?php
namespace AIOSEO\TableOfContents\Traits\Helpers;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Contains methods related to multisites.
*
* @since 1.0.0
*/
trait WpMultisite {
/**
* Returns the current site.
*
* @since 1.0.0
*
* @return \WP_Site|Object A WP_Site instance of the current site or an object representing the same.
*/
public function getSite() {
if ( is_multisite() ) {
return get_site();
}
return (object) [
'domain' => $this->getSiteDomain(),
'path' => $this->getHomePath()
];
}
/**
* Returns the network ID.
*
* @since 1.0.0
*
* @return int The integer of the blog/site id.
*/
public function getNetworkId() {
if ( is_multisite() ) {
return get_network()->site_id;
}
return get_current_blog_id();
}
/**
* Wrapper for switch_to_blog especially for non-multisite setups.
*
* @since 1.0.0
*
* @param int $blogId The blog ID to switch to.
* @return bool True in all cases.
*/
public function switchToBlog( $blogId ) {
if ( ! is_multisite() ) {
return true;
}
return switch_to_blog( $blogId );
}
/**
* Wrapper for restore_current_blog especially for non-multisite setups.
*
* @since 1.0.0
*
* @return bool Whether we're already on the current blog or not in a multisite environment.
*/
public function restoreCurrentBlog() {
if ( ! is_multisite() ) {
return false;
}
return restore_current_blog();
}
}
@@ -0,0 +1,75 @@
<?php
namespace AIOSEO\TableOfContents\Traits\Helpers;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Contains all WordPress related URL, URI, path, slug, etc. related helper methods.
*
* @since 1.0.0
*/
trait WpUri {
/**
* Returns the site domain.
*
* @since 1.0.0
*
* @param bool $unfiltered Whether to get the unfiltered value.
* @return string The site's domain.
*/
public function getSiteDomain( $unfiltered = false ) {
return wp_parse_url( $this->getHomeUrl( $unfiltered ), PHP_URL_HOST );
}
/**
* Returns the site URL.
* NOTE: For multisites inside a sub-directory, this returns the URL for the main site.
* This is intentional.
*
* @since 1.0.0
*
* @param bool $unfiltered Whether to get the unfiltered value.
* @return string The site's domain.
*/
public function getSiteUrl( $unfiltered = false ) {
$homeUrl = $this->getHomeUrl( $unfiltered );
return wp_parse_url( $homeUrl, PHP_URL_SCHEME ) . '://' . wp_parse_url( $homeUrl, PHP_URL_HOST );
}
/**
* Retrieve the home path.
*
* @since 1.0.0
*
* @param bool $unfiltered Whether to get the unfiltered value.
* @return string The home path.
*/
public function getHomePath( $unfiltered = false ) {
$path = wp_parse_url( $this->getHomeUrl( $unfiltered ), PHP_URL_PATH );
return $path ? trailingslashit( $path ) : '/';
}
/**
* Returns the home URL.
*
* @since 1.0.0
*
* @param bool $unfiltered Whether to get the unfiltered value.
* @return string The home URL.
*/
private function getHomeUrl( $unfiltered = false ) {
$homeUrl = home_url();
if ( $unfiltered ) {
// We want to get this value straight from the DB to prevent plugins like WPML from filtering it.
// This will otherwise mess with things like license activation requests and redirects.
$homeUrl = get_option( 'home' );
}
return $homeUrl;
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,214 @@
<?php
namespace AIOSEO\TableOfContents\Utils;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class Access {
/**
* Capabilities for our users.
*
* @since 1.0.0
*
* @var array
*/
protected $capabilities = [
'aioseo_table_of_contents_about_us_page'
];
/**
* Roles we check capabilities against.
*
* @since 1.0.0
*
* @var array
*/
protected $roles = [
'superadmin' => 'superadmin',
'administrator' => 'administrator'
];
/**
* Whether or not we are updating roles.
*
* @since 1.1.0
*
* @var bool
*/
private $isUpdatingRoles = false;
/**
* Adds capabilities into WordPress for the current user.
*
* @since 1.0.0
*
* @return void
*/
public function addCapabilities() {
foreach ( $this->roles as $wpRole => $role ) {
$roleObject = get_role( $wpRole );
if ( ! is_object( $roleObject ) ) {
continue;
}
if ( current_user_can( 'edit_posts' ) || $this->isAdmin() ) {
foreach ( $this->capabilities as $cap ) {
$roleObject->add_cap( $cap );
}
}
}
$this->removeCapabilities();
}
/**
* Removes capabilities for any unknown role.
*
* @since 1.0.0
*
* @return void
*/
public function removeCapabilities() {
$this->isUpdatingRoles = true;
// Clear out capabilities for unknown roles.
$wpRoles = wp_roles();
$allRoles = $wpRoles->roles;
foreach ( $allRoles as $key => $wpRole ) {
$checkRole = is_multisite() ? 'superadmin' : 'administrator';
if ( $checkRole === $key ) {
continue;
}
if ( in_array( $key, $this->roles, true ) ) {
continue;
}
$role = get_role( $key );
if ( empty( $role ) ) {
continue;
}
if ( $this->isAdmin( $key ) ) {
continue;
}
foreach ( $this->capabilities as $capability ) {
if ( $role->has_cap( $capability ) ) {
$role->remove_cap( $capability );
}
}
}
}
/**
* Checks if the current user has the capability.
*
* @since 1.0.0
*
* @param string $capability The capability to check against.
* @param string|null $checkRole A role to check against.
* @return bool Whether or not the user has this capability.
*/
public function hasCapability( $capability, $checkRole = null ) {
// Only admins have access.
if ( $this->isAdmin( $checkRole ) ) {
return true;
}
if (
(
$this->can( 'publish_posts', $checkRole ) ||
$this->can( 'edit_posts', $checkRole )
) &&
false !== strpos( $capability, 'aioseo_table_of_contents_' )
) {
return true;
}
return false;
}
/**
* Gets all the capabilities for the current user.
*
* @since 1.0.0
*
* @param string|null $role A role to check against.
* @return array An array of capabilities.
*/
public function getAllCapabilities( $role = null ) {
$capabilities = [];
foreach ( $this->capabilities as $cap ) {
$capabilities[ $cap ] = $this->hasCapability( $cap, $role );
}
return $capabilities;
}
/**
* If the current user is an admin, or superadmin, they have access to all caps regardless.
*
* @since 1.0.0
*
* @param string|null $role The role to check admin privileges if we have one.
* @return bool Whether not the user/role is an admin.
*/
public function isAdmin( $role = null ) {
if ( $role ) {
if ( ( is_multisite() && 'superadmin' === $role ) || 'administrator' === $role ) {
return true;
}
return false;
}
if ( ( is_multisite() && current_user_can( 'superadmin' ) ) || current_user_can( 'administrator' ) ) {
return true;
}
return false;
}
/**
* Whether the current user (or role) can manage the plugin.
*
* @since 1.0.0
*
* @param string|null $checkRole The role to check.
* @return bool Whether the user/role can manage the plugin.
*/
public function canManage( $checkRole = null ) {
return $this->isAdmin( $checkRole );
}
/**
* Check if the passed in role can publish posts.
*
* @since 1.0.0
*
* @param string $capability The capability to check against.
* @param string $role The role to check.
* @return boolean True if the role can publish.
*/
protected function can( $capability, $role ) {
if ( empty( $role ) ) {
return current_user_can( $capability );
}
$wpRoles = wp_roles();
$allRoles = $wpRoles->roles;
foreach ( $allRoles as $key => $wpRole ) {
if ( $key === $role ) {
$r = get_role( $key );
if ( $r->has_cap( $capability ) ) {
return true;
}
}
}
return false;
}
}
@@ -0,0 +1,304 @@
<?php
namespace AIOSEO\TableOfContents\Utils;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* This class makes sure the Action Scheduler tables always exist.
*
* @since 1.0.0
*/
class ActionScheduler {
/**
* The Action Scheduler group.
*
* @since 1.0.0
*
* @var string
*/
private $actionSchedulerGroup = 'aioseo_table_of_contents';
/**
* Class constructor.
*
* @since 1.0.0
*/
public function __construct() { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
add_action( 'action_scheduler_after_execute', [ $this, 'cleanup' ], 1000, 2 );
add_action( 'plugins_loaded', [ $this, 'maybeRecreateTables' ] );
}
/**
* Maybe register the `{$table_prefix}_actionscheduler_{$suffix}` tables with WordPress and create them if needed.
* Hooked into `plugins_loaded` action hook.
*
* @since 1.0.0
*
* @return void
*/
public function maybeRecreateTables() {
if ( ! is_admin() ) {
return;
}
if ( ! apply_filters( 'action_scheduler_enable_recreate_data_store', true ) ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
return;
}
if (
! class_exists( 'ActionScheduler' ) ||
! class_exists( 'ActionScheduler_HybridStore' ) ||
! class_exists( 'ActionScheduler_StoreSchema' ) ||
! class_exists( 'ActionScheduler_LoggerSchema' )
) {
return;
}
$store = \ActionScheduler::store();
if ( ! is_a( $store, 'ActionScheduler_HybridStore' ) ) {
$store = new \ActionScheduler_HybridStore();
}
$tableList = [
'actionscheduler_actions',
'actionscheduler_logs',
'actionscheduler_groups',
'actionscheduler_claims',
];
foreach ( $tableList as $tableName ) {
if ( ! aioseoTableOfContents()->core->db->tableExists( $tableName ) ) {
add_action( 'action_scheduler/created_table', [ $store, 'set_autoincrement' ], 10, 2 );
$storeSchema = new \ActionScheduler_StoreSchema();
$loggerSchema = new \ActionScheduler_LoggerSchema();
$storeSchema->register_tables( true );
$loggerSchema->register_tables( true );
remove_action( 'action_scheduler/created_table', [ $store, 'set_autoincrement' ] );
break;
}
}
}
/**
* Cleans up the Action Scheduler tables after one of our actions completes.
* Hooked into `action_scheduler_after_execute` action hook.
*
* @since 1.0.0
*
* @param int $actionId The action ID processed.
* @param \ActionScheduler_Action $action Class instance.
* @return void
*/
public function cleanup( $actionId, $action ) {
if (
// Bail if this isn't one of our actions or if we're in a dev environment.
$this->actionSchedulerGroup !== $action->get_group() ||
defined( 'AIOSEO_TABLE_OF_CONTENTS_DEV_VERSION' ) ||
// Bail if the tables don't exist.
! aioseoTableOfContents()->core->db->tableExists( 'actionscheduler_actions' ) ||
! aioseoTableOfContents()->core->db->tableExists( 'actionscheduler_groups' )
) {
return;
}
$prefix = aioseoTableOfContents()->core->db->db->prefix;
// Clean up logs associated with entries in the actions table.
aioseoTableOfContents()->core->db->execute(
"DELETE al FROM {$prefix}actionscheduler_logs as al
JOIN {$prefix}actionscheduler_actions as aa on `aa`.`action_id` = `al`.`action_id`
JOIN {$prefix}actionscheduler_groups as ag on `ag`.`group_id` = `aa`.`group_id`
WHERE `ag`.`slug` = '{$this->actionSchedulerGroup}'
AND `aa`.`status` IN ('complete', 'failed', 'canceled');"
);
// Clean up actions.
aioseoTableOfContents()->core->db->execute(
"DELETE aa FROM {$prefix}actionscheduler_actions as aa
JOIN {$prefix}actionscheduler_groups as ag on `ag`.`group_id` = `aa`.`group_id`
WHERE `ag`.`slug` = '{$this->actionSchedulerGroup}'
AND `aa`.`status` IN ('complete', 'failed', 'canceled');"
);
// Clean up logs where there was no group.
aioseoTableOfContents()->core->db->execute(
"DELETE al FROM {$prefix}actionscheduler_logs as al
JOIN {$prefix}actionscheduler_actions as aa on `aa`.`action_id` = `al`.`action_id`
WHERE `aa`.`hook` LIKE '{$this->actionSchedulerGroup}_%'
AND `aa`.`group_id` = 0
AND `aa`.`status` IN ('complete', 'failed', 'canceled');"
);
// Clean up actions that start with aioseo_ and have no group.
aioseoTableOfContents()->core->db->execute(
"DELETE aa FROM {$prefix}actionscheduler_actions as aa
WHERE `aa`.`hook` LIKE '{$this->actionSchedulerGroup}_%'
AND `aa`.`group_id` = 0
AND `aa`.`status` IN ('complete', 'failed', 'canceled');"
);
}
/**
* Schedules a single action at a specific time in the future.
* @NOTE: This method differs from the one in the main plugin!
*
* @since 1.0.0
* @version 202608.2 Added the $forceSchedule parameter.
*
* @param string $actionName The action name.
* @param int $time The time to add to the current time.
* @param array $args Args passed down to the action.
* @param bool $forceSchedule Whether we should schedule a new action regardless of whether one is already set.
* @return boolean Whether the action was scheduled.
*/
public function scheduleSingle( $actionName, $time, $args = [], $forceSchedule = false ) {
try {
if ( $forceSchedule || empty( $this->getPendingActions( $actionName, $args ) ) ) {
as_schedule_single_action( time() + $time, $actionName, $args, $this->actionSchedulerGroup );
return true;
}
} catch ( \RuntimeException $e ) {
// Nothing needs to happen.
}
return false;
}
/**
* Checks if a given action is already scheduled.
*
* @since 1.0.0
*
* @param string $actionName The action name.
* @param array $args Args passed down to the action.
* @return boolean Whether the action is already scheduled.
*/
public function isScheduled( $actionName, $args = [] ) {
$actions = array_merge(
$this->getRunningActions( $actionName, $args ),
$this->getPendingActions( $actionName, $args )
);
return ! empty( $actions );
}
/**
* Returns the running actions for a given action.
*
* @since 1.0.0
*
* @param string $actionName The action name.
* @param array $args Args passed down to the action.
* @return array The actions.
*/
public function getRunningActions( $actionName, $args = [] ) {
$runningArgs = [
'hook' => $actionName,
'status' => \ActionScheduler_Store::STATUS_RUNNING,
'per_page' => 1
];
if ( empty( $args ) ) {
$runningArgs['args'] = $args;
}
$actions = as_get_scheduled_actions( $runningArgs );
return $actions;
}
/**
* Returns the pending actions for a given action.
*
* @since 1.0.0
*
* @param string $actionName The action name.
* @param array $args Args passed down to the action.
* @return array The actions.
*/
public function getPendingActions( $actionName, $args = [] ) {
$pendingArgs = [
'hook' => $actionName,
'status' => \ActionScheduler_Store::STATUS_PENDING,
'per_page' => 1
];
if ( empty( $args ) ) {
$pendingArgs['args'] = $args;
}
$actions = as_get_scheduled_actions( $pendingArgs );
return $actions;
}
/**
* Unschedule an action.
*
* @since 1.0.0
*
* @param string $actionName The action name to unschedule.
* @param array $args Args passed down to the action.
* @return void
*/
public function unschedule( $actionName, $args = [] ) {
try {
if ( as_next_scheduled_action( $actionName ) ) {
as_unschedule_action( $actionName, $args, $this->actionSchedulerGroup );
}
} catch ( \Exception $e ) {
// Do nothing.
}
}
/**
* Schedules a recurring action.
*
* @since 1.0.0
*
* @param string $actionName The action name.
* @param int $time The seconds to add to the current time.
* @param int $interval The interval in seconds.
* @param array $args Args passed down to the action.
* @return boolean Whether the action was scheduled.
*/
public function scheduleRecurrent( $actionName, $time, $interval = 60, $args = [] ) {
try {
if ( ! $this->isScheduled( $actionName ) ) {
as_schedule_recurring_action( time() + $time, $interval, $actionName, $args, $this->actionSchedulerGroup );
return true;
}
} catch ( \RuntimeException $e ) {
// Nothing needs to happen.
}
return false;
}
/**
* Schedule a single async action.
*
* @since 1.0.0
*
* @param string $actionName The name of the action.
* @param array $args Any relevant arguments.
* @return void
*/
public function scheduleAsync( $actionName, $args = [] ) {
try {
// Run the task immediately using an async action.
as_enqueue_async_action( $actionName, $args, $this->actionSchedulerGroup );
} catch ( \Exception $e ) {
// Do nothing.
}
}
}
@@ -0,0 +1,124 @@
<?php
namespace AIOSEO\TableOfContents\Utils;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
use AIOSEO\TableOfContents\Traits\Helpers as TraitHelpers;
/**
* Contains helper functions
*
* @since 1.0.0
*/
class Helpers {
use TraitHelpers\Api;
use TraitHelpers\Arrays;
use TraitHelpers\Constants;
use TraitHelpers\DateTime;
use TraitHelpers\Strings;
use TraitHelpers\ThirdParty;
use TraitHelpers\Vue;
use TraitHelpers\Wp;
use TraitHelpers\WpContext;
use TraitHelpers\WpMultisite;
use TraitHelpers\WpUri;
/**
* Checks if we are in a dev environment or not.
*
* @since 1.0.0
*
* @return boolean True if we are, false if not.
*/
public function isDev() {
return aioseoTableOfContents()->isDev || isset( $_REQUEST['aioseo-dev'] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
}
/**
* Generates a UTM URL from the URL and medium/content that are passed in.
*
* @since 1.0.0
*
* @param string $url The URL to parse.
* @param string $medium The UTM medium parameter.
* @param string|null $content The UTM content parameter or null.
* @param boolean $esc Whether or not to escape the URL.
* @return string The new URL.
*/
public function utmUrl( $url, $medium, $content = null, $esc = true ) {
// First, remove any existing utm parameters on the URL.
$url = remove_query_arg( [
'utm_source',
'utm_medium',
'utm_campaign',
'utm_content'
], $url );
// Generate the new arguments.
$args = [
'utm_source' => 'WordPress',
'utm_campaign' => 'toc-plugin',
'utm_medium' => $medium
];
// Content is not used by default.
if ( $content ) {
$args['utm_content'] = $content;
}
// Return the new URL.
$url = add_query_arg( $args, $url );
return $esc ? esc_url( $url ) : $url;
}
/**
* Returns the excluded domains.
*
* @since 1.1.1
*
* @return array The excluded domains.
*/
public function getExcludedDomains() {
if ( ! aioseoTableOfContents()->options->advanced->enable ) {
return [];
}
$excludedDomains = aioseoTableOfContents()->options->advanced->excludeDomains;
if ( ! is_string( $excludedDomains ) ) {
return [];
}
$pattern = '/([\.?!][\r\n\s]+|\r|\n|\s{2,})/u';
return array_map( 'trim', preg_split( $pattern, (string) $excludedDomains, -1, PREG_SPLIT_NO_EMPTY ) );
}
/**
* Checks if the given string is serialized, and if so, unserializes it.
* If the serialized string contains an object, we abort to prevent PHP object injection.
*
* @since 1.2.0
*
* @param string $string The string.
* @return string|array The string or unserialized data.
*/
public function maybeUnserialize( $string ) {
if ( ! is_string( $string ) ) {
return $string;
}
$string = trim( $string );
if ( is_serialized( $string ) && ! $this->stringContains( $string, ';O:' ) ) {
// We want to add extra hardening for PHP versions greater than 5.6.
return version_compare( PHP_VERSION, '7.0', '<' )
? @unserialize( $string )
: @unserialize( $string, [ 'allowed_classes' => false ] ); // phpcs:disable PHPCompatibility.FunctionUse.NewFunctionParameters.unserialize_optionsFound
}
return $string;
}
}
@@ -0,0 +1,222 @@
<?php
namespace AIOSEO\TableOfContents\Utils;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
use WP_Error;
/** \WP_Upgrader class */
require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
/** \Plugin_Upgrader class */
require_once ABSPATH . 'wp-admin/includes/class-plugin-upgrader.php';
/**
* In WP 5.3 a PHP 5.6 splat operator (...$args) was added to \WP_Upgrader_Skin::feedback().
* We need to remove all calls to *Skin::feedback() method, as we can't override it in own Skins
* without breaking support for PHP 5.3-5.5.
*
* @internal Please do not use this class outside of core AIOSEO development.
*
* @since 1.0.0
*/
class PluginUpgraderSilentAjax extends \Plugin_Upgrader {
/**
* An array of links to install the plugins from.
*
* @since 1.0.0
*
* @var array
*/
public $pluginLinks = [
'aioseo' => 'https://downloads.wordpress.org/plugins/all-in-one-seo-pack.zip',
'brokenLinkChecker' => 'https://downloads.wordpress.org/plugin/broken-link-checker-seo.zip',
'optinMonster' => 'https://downloads.wordpress.org/plugin/optinmonster.zip',
'wpForms' => 'https://downloads.wordpress.org/plugin/wpforms-lite.zip',
'wpConsent' => 'https://downloads.wordpress.org/plugin/wpconsent-cookies-banner-privacy-suite.zip',
'wpVibe' => 'https://downloads.wordpress.org/plugin/vibe-ai.zip',
'universally' => 'https://downloads.wordpress.org/plugin/universally-language-translation-multilingual-tool.zip',
'miLite' => 'https://downloads.wordpress.org/plugin/google-analytics-for-wordpress.zip',
'emLite' => 'https://downloads.wordpress.org/plugin/google-analytics-dashboard-for-wp.zip',
'wpMail' => 'https://downloads.wordpress.org/plugin/wp-mail-smtp.zip',
'rafflePress' => 'https://downloads.wordpress.org/plugin/rafflepress.zip',
'seedProd' => 'https://downloads.wordpress.org/plugin/coming-soon.zip',
'instagramFeed' => 'https://downloads.wordpress.org/plugin/instagram-feed.zip',
'facebookFeed' => 'https://downloads.wordpress.org/plugin/custom-facebook-feed.zip',
'twitterFeed' => 'https://downloads.wordpress.org/plugin/custom-twitter-feeds.zip',
'youTubeFeed' => 'https://downloads.wordpress.org/plugin/feeds-for-youtube.zip',
'pushEngage' => 'https://downloads.wordpress.org/plugins/pushengage.zip',
'sugarCalendar' => 'https://downloads.wordpress.org/plugins/sugar-calendar-lite.zip',
'wpSimplePay' => 'https://downloads.wordpress.org/plugins/stripe.zip',
'easyDigitalDownloads' => 'https://downloads.wordpress.org/plugins/easy-digital-downloads.zip',
'wpcode' => 'https://downloads.wordpress.org/plugin/insert-headers-and-footers.zip',
'searchWp' => '',
'affiliateWp' => '',
'charitable' => 'https://downloads.wordpress.org/plugin/charitable.zip',
'duplicator' => 'https://downloads.wordpress.org/plugin/duplicator.zip',
'uncannyAutomator' => 'https://downloads.wordpress.org/plugin/uncanny-automator.zip',
'pdfEmbedder' => 'https://downloads.wordpress.org/plugin/pdf-embedder.zip',
'reviewsFeed' => 'https://downloads.wordpress.org/plugin/reviews-feed.zip',
'enviraGallery' => 'https://downloads.wordpress.org/plugin/envira-gallery-lite.zip',
'userFeedback' => 'https://downloads.wordpress.org/plugin/userfeedback-lite.zip',
'activeLayer' => 'https://downloads.wordpress.org/plugin/activelayer-anti-spam-spam-protection-for-forms-comments.zip',
'wpChat' => 'https://downloads.wordpress.org/plugin/smashballoon-wpchat-livechat-customer-support.zip'
];
/**
* An array of links to install the plugins from wordpress.org.
*
* @since 1.0.0
*
* @var array
*/
public $wpPluginLinks = [
'aioseo' => 'https://wordpress.org/plugins/all-in-one-seo-pack/',
'optinMonster' => 'https://wordpress.org/plugin/optinmonster/',
'wpForms' => 'https://wordpress.org/plugin/wpforms-lite/',
'wpConsent' => 'https://wordpress.org/plugins/wpconsent-cookies-banner-privacy-suite/',
'wpVibe' => 'https://wordpress.org/plugins/vibe-ai/',
'universally' => 'https://wordpress.org/plugins/universally-language-translation-multilingual-tool/',
'miLite' => 'https://wordpress.org/plugin/google-analytics-for-wordpress/',
'emLite' => 'https://wordpress.org/plugin/google-analytics-dashboard-for-wp/',
'wpMail' => 'https://wordpress.org/plugin/wp-mail-smtp/',
'rafflePress' => 'https://wordpress.org/plugin/rafflepress/',
'seedProd' => 'https://wordpress.org/plugin/coming-soon/',
'instagramFeed' => 'https://wordpress.org/plugin/instagram-feed/',
'facebookFeed' => 'https://wordpress.org/plugin/custom-facebook-feed/',
'twitterFeed' => 'https://wordpress.org/plugin/custom-twitter-feeds/',
'youTubeFeed' => 'https://wordpress.org/plugin/feeds-for-youtube/',
'pushEngage' => 'https://wordpress.org/plugins/pushengage/',
'sugarCalendar' => 'https://wordpress.org/plugins/sugar-calendar-lite/',
'wpSimplePay' => 'https://wordpress.org/plugins/stripe/',
'searchWp' => 'https://searchwp.com/',
'affiliateWp' => 'https://affiliatewp.com/',
'wpcode' => 'https://wordpress.org/plugins/insert-headers-and-footers/',
'charitable' => 'https://wordpress.org/plugins/charitable/',
'duplicator' => 'https://wordpress.org/plugins/duplicator/',
'uncannyAutomator' => 'https://wordpress.org/plugins/uncanny-automator/',
'pdfEmbedder' => 'https://wordpress.org/plugins/pdf-embedder/',
'reviewsFeed' => 'https://wordpress.org/plugins/reviews-feed/',
'enviraGallery' => 'https://wordpress.org/plugins/envira-gallery-lite/',
'userFeedback' => 'https://wordpress.org/plugins/userfeedback-lite/',
'activeLayer' => 'https://wordpress.org/plugins/activelayer-anti-spam-spam-protection-for-forms-comments/',
'wpChat' => 'https://wordpress.org/plugins/smashballoon-wpchat-livechat-customer-support/'
];
/**
* An array of slugs to check if plugins are activated.
*
* @since 1.0.0
*
* @var array
*/
public $pluginSlugs = [
'aioseo' => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
'aioseoPro' => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
'brokenLinkChecker' => 'broken-link-checker-seo/aioseo-broken-link-checker.php',
'optinMonster' => 'optinmonster/optin-monster-wp-api.php',
'wpForms' => 'wpforms-lite/wpforms.php',
'wpFormsPro' => 'wpforms/wpforms.php',
'wpConsent' => 'wpconsent-cookies-banner-privacy-suite/wpconsent.php',
'wpVibe' => 'vibe-ai/vibe-ai.php',
'universally' => 'universally-language-translation-multilingual-tool/universally.php',
'miLite' => 'google-analytics-for-wordpress/googleanalytics.php',
'miPro' => 'google-analytics-premium/googleanalytics-premium.php',
'emLite' => 'google-analytics-dashboard-for-wp/gadwp.php',
'emPro' => 'exactmetrics-premium/exactmetrics-premium.php',
'wpMail' => 'wp-mail-smtp/wp_mail_smtp.php',
'wpMailPro' => 'wp-mail-smtp-pro/wp_mail_smtp.php',
'rafflePress' => 'rafflepress/rafflepress.php',
'rafflePressPro' => 'rafflepress-pro/rafflepress-pro.php',
'seedProd' => 'coming-soon/coming-soon.php',
'seedProdPro' => 'seedprod-coming-soon-pro-5/seedprod-coming-soon-pro-5.php',
'instagramFeed' => 'instagram-feed/instagram-feed.php',
'instagramFeedPro' => 'instagram-feed-pro/instagram-feed.php',
'facebookFeed' => 'custom-facebook-feed/custom-facebook-feed.php',
'facebookFeedPro' => 'custom-facebook-feed-pro/custom-facebook-feed.php',
'twitterFeed' => 'custom-twitter-feeds/custom-twitter-feed.php',
'twitterFeedPro' => 'custom-twitter-feeds-pro/custom-twitter-feed.php',
'youTubeFeed' => 'feeds-for-youtube/youtube-feed.php',
'youTubeFeedPro' => 'youtube-feed-pro/youtube-feed.php',
'pushEngage' => 'pushengage/main.php',
'sugarCalendar' => 'sugar-calendar-lite/sugar-calendar-lite.php',
'sugarCalendarPro' => 'sugar-calendar/sugar-calendar.php',
'wpSimplePay' => 'stripe/stripe-checkout.php',
'wpSimplePayPro' => 'wp-simple-pay-pro-3/simple-pay.php',
'easyDigitalDownloads' => 'easy-digital-downloads/easy-digital-downloads.php',
'easyDigitalDownloadsPro' => 'easy-digital-downloads-pro/easy-digital-downloads.php',
'searchWp' => 'searchwp/index.php',
'affiliateWp' => 'affiliate-wp/affiliate-wp.php',
'wpcode' => 'insert-headers-and-footers/ihaf.php',
'wpcodePro' => 'wpcode-premium/wpcode.php',
'charitable' => 'charitable/charitable.php',
'duplicator' => 'duplicator/duplicator.php',
'uncannyAutomator' => 'uncanny-automator/uncanny-automator.php',
'pdfEmbedder' => 'pdf-embedder/pdf_embedder.php',
'reviewsFeed' => 'reviews-feed/sb-reviews.php',
'enviraGallery' => 'envira-gallery-lite/envira-gallery-lite.php',
'userFeedback' => 'userfeedback-lite/userfeedback.php',
'activeLayer' => 'activelayer-anti-spam-spam-protection-for-forms-comments/activelayer-anti-spam-spam-protection-for-forms-comments.php',
'wpChat' => 'smashballoon-wpchat-livechat-customer-support/wp-chat.php'
];
/**
* An array of links for admin settings.
*
* @since 1.0.0
*
* @var array
*/
public $pluginAdminUrls = [
'aioseo' => 'admin.php?page=aioseo-settings',
'aioseoPro' => 'admin.php?page=aioseo-settings',
'brokenLinkChecker' => 'admin.php?page=broken-link-checker',
'optinMonster' => 'admin.php?page=optin-monster-api-settings',
'wpForms' => 'admin.php?page=wpforms-settings',
'wpFormsPro' => 'admin.php?page=wpforms-settings',
'wpConsent' => 'admin.php?page=wpconsent',
'wpVibe' => 'admin.php?page=vibe-ai',
'universally' => 'admin.php?page=universally_settings',
'miLite' => 'admin.php?page=monsterinsights_settings#/',
'miPro' => 'admin.php?page=monsterinsights_settings#/',
'emLite' => 'admin.php?page=exactmetrics_settings#/',
'emPro' => 'admin.php?page=exactmetrics_settings#/',
'wpMail' => 'admin.php?page=wp-mail-smtp',
'wpMailPro' => 'admin.php?page=wp-mail-smtp',
'seedProd' => 'admin.php?page=seedprod_lite',
'seedProdPro' => 'admin.php?page=seedprod_pro',
'rafflePress' => 'admin.php?page=rafflepress_lite#/settings',
'rafflePressPro' => 'admin.php?page=rafflepress_pro#/settings',
'instagramFeed' => 'admin.php?page=sb-instagram-feed',
'instagramFeedPro' => 'admin.php?page=sb-instagram-feed',
'facebookFeed' => 'admin.php?page=cff-top',
'facebookFeedPro' => 'admin.php?page=cff-top',
'twitterFeed' => 'admin.php?page=ctf-settings',
'twitterFeedPro' => 'admin.php?page=ctf-settings',
'youTubeFeed' => 'admin.php?page=youtube-feed-settings',
'youTubeFeedPro' => 'admin.php?page=youtube-feed-settings',
'pushEngage' => 'admin.php?page=pushengage',
'sugarCalendar' => 'admin.php?page=sugar-calendar',
'sugarCalendarPro' => 'admin.php?page=sugar-calendar',
'wpSimplePay' => 'edit.php?post_type=simple-pay',
'wpSimplePayPro' => 'edit.php?post_type=simple-pay',
'easyDigitalDownloads' => 'edit.php?post_type=download&page=edd-settings',
'easyDigitalDownloadsPro' => 'edit.php?post_type=download&page=edd-settings',
'searchWp' => 'options-general.php?page=searchwp',
'affiliateWp' => 'admin.php?page=affiliate-wp',
'wpcode' => 'admin.php?page=wpcode',
'wpcodePro' => 'admin.php?page=wpcode',
'charitable' => 'admin.php?page=charitable-settings',
'duplicator' => 'admin.php?page=duplicator-settings',
'uncannyAutomator' => 'edit.php?post_type=uo-recipe',
'pdfEmbedder' => 'options-general.php?page=pdf_embedder',
'reviewsFeed' => 'admin.php?page=sbr',
'enviraGallery' => 'edit.php?post_type=envira',
'userFeedback' => 'admin.php?page=userfeedback',
'activeLayer' => 'admin.php?page=activelayer',
'wpChat' => 'admin.php?page=wpchat'
];
}
@@ -0,0 +1,67 @@
<?php
namespace AIOSEO\TableOfContents\Utils;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
require_once ABSPATH . 'wp-admin/includes/plugin.php';
require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader-skin.php';
/**
* The PluginSilentUpgraderSkin class.
*
* @internal Please do not use this class outside of core AIOSEO development.
*
* @since 1.0.0
*/
class PluginUpgraderSkin extends \WP_Upgrader_Skin {
/**
* Empty out the header of its HTML content and only check to see if it has
* been performed or not.
*
* @since 1.0.0
*/
public function header() {}
/**
* Empty out the footer of its HTML contents.
*
* @since 1.0.0
*/
public function footer() {}
/**
* Instead of outputting HTML for errors, just return them.
* AJAX request will just ignore it.
*
* @since 1.0.0
*
* @param array $errors Array of errors with the install process.
* @return void
*/
public function error( $errors ) {
if ( ! empty( $errors ) ) {
wp_send_json_error( $errors );
}
}
/**
* Empty out JavaScript output that calls function to decrement the update counts.
*
* @since 1.0.0
*
* @param string $type Type of update count to decrement.
*/
public function decrement_update_count( $type ) {} // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable, PSR1.Methods.CamelCapsMethodName.NotCamelCaps
/**
* @since 1.0.0
*
* @param string $feedback Message data.
* @param mixed ...$args Optional text replacements.
* @return void
*/
public function feedback( $feedback, ...$args ) {} // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
}
@@ -0,0 +1,166 @@
<?php
namespace AIOSEO\TableOfContents\Utils;
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Vue Settings for the user.
*
* @since 1.0.0
*/
class VueSettings {
/**
* The name to lookup the settings with.
*
* @since 1.0.0
*
* @var string
*/
private $settingsName = '';
/**
* The settings array.
*
* @since 1.0.0
*
* @var array
*/
private $settings = [];
/**
* All the default settings.
*
* @since 1.0.0
*
* @var array
*/
private $defaults = [
'toggledRadio' => [],
'tablePagination' => []
];
/**
* Class constructor.
*
* @since 1.0.0
*
* @param string $settings List of settings.
*/
public function __construct( $settings = '_aioseo_table_of_contents_settings' ) {
$this->settingsName = $settings;
$userMeta = get_user_meta( get_current_user_id(), $settings, true );
$this->settings = ! empty( $userMeta ) ? array_replace_recursive( $this->defaults, $userMeta ) : $this->defaults;
}
/**
* Retrieves all settings.
*
* @since 1.0.0
*
* @return array List of settings.
*/
public function all() {
return array_replace_recursive( $this->defaults, $this->settings );
}
/**
* Retrieve a setting or null if missing.
*
* @since 1.0.0
*
* @param string $name The name of the property that is missing on the class.
* @param array $arguments The arguments passed into the method.
* @return mixed The value from the settings or default/null.
*/
public function __call( $name, $arguments = [] ) {
$value = isset( $this->settings[ $name ] ) ? $this->settings[ $name ] : ( ! empty( $arguments[0] ) ? $arguments[0] : $this->getDefault( $name ) );
return $value;
}
/**
* Retrieve a setting or null if missing.
*
* @since 1.0.0
*
* @param string $name The name of the property that is missing on the class.
* @return mixed The value from the settings or default/null.
*/
public function __get( $name ) {
$value = isset( $this->settings[ $name ] ) ? $this->settings[ $name ] : $this->getDefault( $name );
return $value;
}
/**
* Sets the settings value and saves to the database.
*
* @since 1.0.0
*
* @param string $name The name of the settings.
* @param mixed $value The value to set.
* @return void
*/
public function __set( $name, $value ) {
$this->settings[ $name ] = $value;
$this->update();
}
/**
* Checks if an settings is set or returns null if not.
*
* @since 1.0.0
*
* @param string $name The name of the settings.
* @return mixed True or null.
*/
public function __isset( $name ) {
return isset( $this->settings[ $name ] ) ? false === empty( $this->settings[ $name ] ) : null;
}
/**
* Unsets the settings value and saves to the database.
*
* @since 1.0.0
*
* @param string $name The name of the settings.
* @return void
*/
public function __unset( $name ) {
if ( ! isset( $this->settings[ $name ] ) ) {
return;
}
unset( $this->settings[ $name ] );
$this->update();
}
/**
* Gets the default value for a setting.
*
* @since 1.0.0
*
* @param string $name The settings name.
* @return mixed The default value.
*/
public function getDefault( $name ) {
return isset( $this->defaults[ $name ] ) ? $this->defaults[ $name ] : null;
}
/**
* Updates the settings in the database.
*
* @since 1.0.0
*
* @return void
*/
public function update() {
update_user_meta( get_current_user_id(), $this->settingsName, $this->settings );
}
}
@@ -0,0 +1,26 @@
<?php
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
if ( ! function_exists( 'aioseo_table_of_contents_is_plugin_disabled' ) ) {
/**
* Disable the plugin if triggered externally.
*
* @since 1.0.0
*
* @return bool True if the plugin should be disabled.
*/
function aioseo_table_of_contents_is_plugin_disabled() {
if ( ! defined( 'AIOSEO_DEV_VERSION' ) && ! isset( $_REQUEST['aioseo-dev'] ) ) { // phpcs:ignore HM.Security.NonceVerification.Recommended, WordPress.Security.NonceVerification.Recommended
return false;
}
if ( ! isset( $_REQUEST['aioseo-disable-table-of-contents'] ) ) { // phpcs:ignore HM.Security.NonceVerification.Recommended, WordPress.Security.NonceVerification.Recommended
return false;
}
return true;
}
}
@@ -0,0 +1,199 @@
<?php
// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
// phpcs:disable Generic.Arrays.DisallowLongArraySyntax.Found
if ( ! function_exists( 'aioseo_table_of_contents_php_notice' ) ) {
/**
* Display the notice after deactivation.
*
* @since 1.0.0
*/
function aioseo_table_of_contents_php_notice() {
$medium = 'plugin';
?>
<div class="notice notice-error">
<p>
<?php
echo wp_kses(
sprintf(
// Translators: 1 - Opening HTML bold tag, 2 - Closing HTML bold tag, 3 - Opening HTML link tag, 4 - Closing HTML link tag.
__( 'Your site is running an %1$sinsecure version%2$s of PHP that is no longer supported. Please contact your web hosting provider to update your PHP version or switch to a %3$srecommended WordPress hosting company%4$s.', 'table-of-contents-plus' ), // phpcs:ignore Generic.Files.LineLength.MaxExceeded
'<strong>',
'</strong>',
'<a href="https://www.wpbeginner.com/wordpress-hosting/" target="_blank" rel="noopener noreferrer">',
'</a>'
),
array(
'a' => array(
'href' => array(),
'target' => array(),
'rel' => array(),
),
'strong' => array(),
)
);
?>
<br><br>
<?php
echo wp_kses(
sprintf(
// Translators: 1 - Opening HTML bold tag, 2 - Closing HTML bold tag, 3 - The short plugin name ("AIOSEO"), 4 - Opening HTML link tag, 5 - Closing HTML link tag.
__( '%1$sNote:%2$s %3$s plugin is disabled on your site until you fix the issue. %4$sRead more for additional information.%5$s', 'table-of-contents-plus' ),
'<strong>',
'</strong>',
'AIOSEO',
'<a href="https://aioseo.com/docs/supported-php-version/?utm_source=WordPress&utm_medium=' . $medium . '&utm_campaign=outdated-php-notice" target="_blank" rel="noopener noreferrer">', // phpcs:ignore Generic.Files.LineLength.MaxExceeded
'</a>'
),
array(
'a' => array(
'href' => array(),
'target' => array(),
'rel' => array(),
),
'strong' => array(),
)
);
?>
</p>
</div>
<?php
// In case this is on plugin activation.
if ( isset( $_GET['activate'] ) ) { // phpcs:ignore HM.Security.NonceVerification.Recommended, WordPress.Security.NonceVerification.Recommended
unset( $_GET['activate'] );
}
}
}
if ( ! function_exists( 'aioseo_table_of_contents_php_notice_deprecated' ) ) {
/**
* Display the notice after deactivation.
*
* @since 1.0.0
*/
function aioseo_table_of_contents_php_notice_deprecated() {
$medium = 'plugin';
?>
<div class="notice notice-error">
<p>
<?php
echo wp_kses(
sprintf(
// Translators: 1 - Opening HTML bold tag, 2 - Closing HTML bold tag, 3 - The plugin short name ("AIOSEO"), 4 - Opening HTML link tag, 5 - Closing HTML link tag.
__( 'Your site is running an %1$soutdated version%2$s of PHP that is no longer supported and may cause issues with %3$s. Please contact your web hosting provider to update your PHP version or switch to a %4$srecommended WordPress hosting company%5$s.', 'table-of-contents-plus' ), // phpcs:ignore Generic.Files.LineLength.MaxExceeded
'<strong>',
'</strong>',
'<strong>AIOSEO</strong>',
'<a href="https://www.wpbeginner.com/wordpress-hosting/" target="_blank" rel="noopener noreferrer">',
'</a>'
),
array(
'a' => array(
'href' => array(),
'target' => array(),
'rel' => array(),
),
'strong' => array(),
)
);
?>
<br><br>
<?php
echo wp_kses(
sprintf(
// phpcs:ignore Generic.Files.LineLength.MaxExceeded
// Translators: 1 - Opening HTML bold tag, 2 - Closing HTML bold tag, 3 - The PHP version, 4 - The current year, 5 - The short plugin name ("AIOSEO"), 6 - Opening HTML link tag, 7 - Closing HTML link tag.
__( '%1$sNote:%2$s Support for PHP %3$s will be discontinued in %4$s. After this, if no further action is taken, %5$s functionality will be disabled. %6$sRead more for additional information.%7$s', 'table-of-contents-plus' ), // phpcs:ignore Generic.Files.LineLength.MaxExceeded
'<strong>',
'</strong>',
PHP_VERSION,
gmdate( 'Y' ),
'AIOSEO',
'<a href="https://aioseo.com/docs/supported-php-version/?utm_source=WordPress&utm_medium=' . $medium . '&utm_campaign=outdated-php-notice" target="_blank" rel="noopener noreferrer">', // phpcs:ignore Generic.Files.LineLength.MaxExceeded
'</a>'
),
array(
'a' => array(
'href' => array(),
'target' => array(),
'rel' => array(),
),
'strong' => array(),
)
);
?>
</p>
</div>
<?php
// In case this is on plugin activation.
if ( isset( $_GET['activate'] ) ) { // phpcs:ignore HM.Security.NonceVerification.Recommended, WordPress.Security.NonceVerification.Recommended
unset( $_GET['activate'] );
}
}
}
if ( ! function_exists( 'aioseo_table_of_contents_wordpress_notice' ) ) {
/**
* Display the notice after deactivation.
*
* @since 1.0.0
*/
function aioseo_table_of_contents_wordpress_notice() {
$medium = 'plugin';
?>
<div class="notice notice-error">
<p>
<?php
echo wp_kses(
sprintf(
// Translators: 1 - Opening HTML bold tag, 2 - Closing HTML bold tag, 3 - The plugin name ("All in One SEO").
__( 'Your site is running an %1$sinsecure version%2$s of WordPress that is no longer supported. Please update your site to the latest version of WordPress in order to continue using %3$s.', 'table-of-contents-plus' ), // phpcs:ignore Generic.Files.LineLength.MaxExceeded
'<strong>',
'</strong>',
'All in One SEO'
),
array(
'strong' => array(),
)
);
?>
<br><br>
<?php
echo wp_kses(
sprintf(
// phpcs:ignore Generic.Files.LineLength.MaxExceeded
// Translators: 1 - Opening HTML bold tag, 2 - Closing HTML bold tag, 3 - The short plugin name ("AIOSEO"), 4 - The WordPress version, 5 - The current year, 6 - Opening HTML link tag, 7 - Closing HTML link tag.
__( '%1$sNote:%2$s %3$s will be discontinuing support for WordPress versions older than version %4$s by the end of %5$s. %6$sRead more for additional information.%7$s', 'table-of-contents-plus' ), // phpcs:ignore Generic.Files.LineLength.MaxExceeded
'<strong>',
'</strong>',
'AIOSEO',
'6.0',
gmdate( 'Y' ),
'<a href="https://aioseo.com/docs/update-wordpress/?utm_source=WordPress&utm_medium=' . $medium . '&utm_campaign=outdated-wordpress-notice" target="_blank" rel="noopener noreferrer">', // phpcs:ignore Generic.Files.LineLength.MaxExceeded
'</a>'
),
array(
'a' => array(
'href' => array(),
'target' => array(),
'rel' => array(),
),
'strong' => array(),
)
);
?>
</p>
</div>
<?php
// In case this is on plugin activation.
if ( isset( $_GET['activate'] ) ) { // phpcs:ignore HM.Security.NonceVerification.Recommended, WordPress.Security.NonceVerification.Recommended
unset( $_GET['activate'] );
}
}
}