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,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' );
}
}