diff --git a/.github/workflows/deploy-to-wordpress.yml b/.github/workflows/deploy-to-wordpress.yml index a7c75c2f..fcb769d7 100644 --- a/.github/workflows/deploy-to-wordpress.yml +++ b/.github/workflows/deploy-to-wordpress.yml @@ -33,8 +33,25 @@ jobs: # Build release assets using our release:build script - name: Build release assets + env: + COMPOSER_AUTH: '{}' + COMPOSER_HOME: ${{ runner.temp }}/composer-release run: npm run release:build + - name: Verify assembled WordPress.org tree + run: node bin/verify-release-artifact.js --release-tree "${{ env.BUILD_DIR }}" + + - name: Run WordPress Plugin Check + uses: wordpress/plugin-check-action@v1 + with: + build-dir: ${{ env.BUILD_DIR }} + slug: content-control + exclude-checks: plugin_review_phpcs + exclude-directories: | + vendor + vendor-prefixed + ignore-warnings: true + # Deploy to WordPress.org - name: WordPress Plugin Deploy id: deploy diff --git a/.github/workflows/draft-release.yml b/.github/workflows/draft-release.yml index 360f3a60..6a3d5e1a 100644 --- a/.github/workflows/draft-release.yml +++ b/.github/workflows/draft-release.yml @@ -39,6 +39,9 @@ jobs: # Build release assets using our release:build script - name: Build release assets + env: + COMPOSER_AUTH: '{}' + COMPOSER_HOME: ${{ runner.temp }}/composer-release run: npm run release:build # zip the build folder into slug.zip @@ -47,6 +50,9 @@ jobs: mv $BUILD_DIR ${{ env.SLUG }} zip -r ${{ env.SLUG }}_${{ github.ref_name }}.zip ${{ env.SLUG }} + - name: Verify release zip + run: node bin/verify-release-artifact.js "${{ env.SLUG }}_${{ github.ref_name }}.zip" + # Create draft release - name: Create Draft Release id: create_release diff --git a/.github/workflows/php-ci-tests.yml b/.github/workflows/php-ci-tests.yml index 2ee6195a..451c9df5 100644 --- a/.github/workflows/php-ci-tests.yml +++ b/.github/workflows/php-ci-tests.yml @@ -21,11 +21,11 @@ jobs: - name: Setup PHP uses: shivammathur/setup-php@v2 with: - php-version: '8.2' + php-version: '8.3' tools: composer:v2, cs2pr - name: Install dependencies - run: composer install --no-progress --no-suggest --prefer-dist --optimize-autoloader --no-interaction + run: composer install --no-progress --prefer-dist --optimize-autoloader --no-interaction --no-scripts - name: Run PHP Code Sniffer run: vendor/bin/phpcs --standard=.phpcs.xml.dist -q --report=checkstyle | cs2pr @@ -42,11 +42,17 @@ jobs: - name: Setup PHP uses: shivammathur/setup-php@v2 with: - php-version: '8.2' + php-version: '8.3' tools: composer:v2 - name: Install dependencies - run: composer install --no-progress --no-suggest + run: composer install --no-progress --no-scripts + + - name: Build prefixed dependencies + env: + COMPOSER_AUTH: '{}' + COMPOSER_HOME: ${{ runner.temp }}/composer-strauss + run: composer run strauss - name: Run PHPStan run: composer run phpstan diff --git a/.github/workflows/plugin-check.yml b/.github/workflows/plugin-check.yml new file mode 100644 index 00000000..da0d7ac4 --- /dev/null +++ b/.github/workflows/plugin-check.yml @@ -0,0 +1,58 @@ +name: WordPress Plugin Check + +on: + pull_request: + push: + branches: + - master + - develop + - 'release/**' + +permissions: + contents: read + +concurrency: + group: plugin-check-${{ github.ref }} + cancel-in-progress: true + +jobs: + plugin-check: + name: Check assembled plugin + runs-on: ubuntu-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '8.3' + tools: composer:v2 + coverage: none + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: '16' + cache: npm + + - name: Install dependencies + run: npm ci + + - name: Assemble release plugin + env: + COMPOSER_AUTH: '{}' + COMPOSER_HOME: ${{ runner.temp }}/composer-release + run: npm run release:build + + - name: Run WordPress Plugin Check + uses: wordpress/plugin-check-action@v1 + with: + build-dir: ./build + slug: content-control + exclude-checks: plugin_review_phpcs + exclude-directories: | + vendor + vendor-prefixed + ignore-warnings: true diff --git a/.phpstorm.meta.php b/.phpstorm.meta.php index 9ff66e73..42b5fba1 100644 --- a/.phpstorm.meta.php +++ b/.phpstorm.meta.php @@ -23,11 +23,9 @@ override( \ContentControl\Plugin\Core::get(0), map( [ // Controllers. '' => '@', - 'connect' => \ContentControl\Plugin\Connect::class, 'license' => \ContentControl\Plugin\License::class, 'logging' => \ContentControl\Plugin\Logging::class, 'options' => \ContentControl\Plugin\Options::class, - 'upgrader' => \ContentControl\Plugin\Upgrader::class, 'rules' => \ContentControl\RuleEngine\Rules::class, 'restrictions' => \ContentControl\Services\Restrictions::class, 'globals' => \ContentControl\Services\Globals::class, @@ -41,11 +39,9 @@ override ( \ContentControl\plugin(0), map( [ // Controllers. '' => '@', - 'connect' => \ContentControl\Plugin\Connect::class, 'license' => \ContentControl\Plugin\License::class, 'logging' => \ContentControl\Plugin\Logging::class, 'options' => \ContentControl\Plugin\Options::class, - 'upgrader' => \ContentControl\Plugin\Upgrader::class, 'rules' => \ContentControl\RuleEngine\Rules::class, 'restrictions' => \ContentControl\Services\Restrictions::class, 'globals' => \ContentControl\Services\Globals::class, @@ -59,11 +55,9 @@ override ( \ContentControl\Base\Container::get(0), map( [ // Controllers. '' => '@', - 'connect' => \ContentControl\Plugin\Connect::class, 'license' => \ContentControl\Plugin\License::class, 'logging' => \ContentControl\Plugin\Logging::class, 'options' => \ContentControl\Plugin\Options::class, - 'upgrader' => \ContentControl\Plugin\Upgrader::class, 'rules' => \ContentControl\RuleEngine\Rules::class, 'restrictions' => \ContentControl\Services\Restrictions::class, 'globals' => \ContentControl\Services\Globals::class, @@ -77,11 +71,9 @@ override ( \ContentControl\Base\Container::offsetGet(0), map( [ // Controllers. '' => '@', - 'connect' => \ContentControl\Plugin\Connect::class, 'license' => \ContentControl\Plugin\License::class, 'logging' => \ContentControl\Plugin\Logging::class, 'options' => \ContentControl\Plugin\Options::class, - 'upgrader' => \ContentControl\Plugin\Upgrader::class, 'rules' => \ContentControl\RuleEngine\Rules::class, 'restrictions' => \ContentControl\Services\Restrictions::class, 'globals' => \ContentControl\Services\Globals::class, diff --git a/bin/stubs/content-control.php b/bin/stubs/content-control.php index 4557d73b..07a9c3b3 100644 --- a/bin/stubs/content-control.php +++ b/bin/stubs/content-control.php @@ -436,287 +436,6 @@ public static function deactivate_site() { public static function uninstall_site() { } } - /** - * Upgrader class. - * - * NOTE: For wordpress.org admins: This is only used if: - * - The user explicitly entered a license key. - * - They further opened a window to our site allowing the user to authorize the connection & installation of the pro upgrade. - * - * @package ContentControl - */ - class Upgrader { - - /** - * Container. - * - * @var Container - */ - private $c; - /** - * Initialize license management. - * - * @param Container $c Container. - */ - public function __construct( $c ) { - } - /** - * Maybe load functions & classes required for upgrade. - * - * Purely here due to prevent possible random errors. - * - * @return void - */ - public function maybe_load_required_files() { - } - /** - * Log a message to the debug log if enabled. - * - * Here to prevent constant conditional checks for the debug mode. - * - * @param string $message Message. - * @param string $type Type. - * - * @return void - */ - public function debug_log( $message, $type = 'INFO' ) { - } - /** - * Get credentials for the current request. - * - * @return bool - */ - public function get_fs_creds() { - } - /** - * Activate a plugin. - * - * @param string $plugin_basename The plugin basename. - * @return bool|\WP_Error - */ - public function activate_plugin( $plugin_basename ) { - } - /** - * Install a plugin from file. - * - * @param string $file The plugin file. - * - * @return bool|\WP_Error - */ - public function install_plugin( $file ) { - } - } - /** - * Connection management. - * - * NOTE: For wordpress.org admins: This is not called in the free, hosted version. This is only used if: - * - The user explicitly entered a license key. - * - This then opens a window to our site allowing the user to authorize the connection & installation of pro. - * - * @package ContentControl - */ - class Connect { - - const API_URL = 'https://upgrade.contentcontrolplugin.com/'; - const TOKEN_OPTION_NAME = 'content_control_connect_token'; - const NONCE_OPTION_NAME = 'content_control_connect_nonce'; - const ERROR_REFERRER = 1; - const ERROR_AUTHENTICATION = 2; - const ERROR_USER_AGENT = 3; - const ERROR_SIGNATURE = 4; - const ERROR_NONCE = 5; - const ERROR_WEBHOOK_ARGS = 6; - /** - * Container. - * - * @var \ContentControl\Base\Container - */ - private $c; - /** - * Initialize license management. - * - * @param \ContentControl\Base\Container $c Container. - */ - public function __construct( $c ) { - } - /** - * Check if debug mode is enabled. - * - * @return bool - */ - public function debug_mode_enabled() { - } - /** - * Generate a new authorizatin token. - * - * @return string - */ - public function generate_token() { - } - /** - * Get the current token. - * - * @return string|false - */ - public function get_access_token() { - } - /** - * Get the current nonce. - * - * @param string $token Token. - * - * @return string|false - */ - public function get_nonce_name( $token ) { - } - /** - * Log a message to the debug log if enabled. - * - * Here to prevent constant conditional checks for the debug mode. - * - * @param string $message Message. - * @param string $type Type. - * - * @return void - */ - public function debug_log( $message, $type = 'INFO' ) { - } - /** - * Get header Authorization - * - * @return null|string - */ - public function get_request_authorization_header() { - } - /** - * Get access token from header. - * - * @return string|null - */ - public function get_request_token() { - } - /** - * Get nonce from header. - * - * @return string|null - */ - public function get_request_nonce() { - } - /** - * Get the OAuth connect URL. - * - * @param string $license_key License key. - * - * @return array{url:string,back_url:string} - */ - public function get_connect_info( $license_key ) { - } - /** - * Kill the connection with no permission. - * - * @param int $error_no Error number. - * @param string|false $message Error message. - * - * @return void - */ - public function kill_connection( $error_no = self::ERROR_REFERRER, $message = false ) { - } - /** - * Verify the user agent. - * - * @return void - */ - public function verify_user_agent() { - } - /** - * Verify the referrer. - * - * @return void - */ - public function verify_referrer() { - } - /** - * Verify the nonce. - * - * @deprecated 2.0.0 Don't use, it doesn't work as its a separate server making request. - * - * @return void - */ - public function verify_nonce() { - } - /** - * Verify the authentication token. - * - * @return void - */ - public function verify_authentication() { - } - /** - * Generate signature hash. - * - * This must match the hash generated on the server. - * - * @see \ontentControlUpgrader\App::generate_hash() - * - * @param array|string $data Data to hash. - * @param string $token Token to hash with. - * @return string - */ - public function generate_hash( $data, $token ) { - } - /** - * Verify the signature of the requester. - * - * @return void - */ - public function verify_signature() { - } - /** - * Validate the connection. - * - * @return void - */ - public function validate_connection() { - } - /** - * Verify the connection. - * - * @return void - */ - public function process_verify_connection() { - } - /** - * Get the webhook args. - * - * @return array{file:string,type:string,slug:string,force:boolean} - */ - public function get_webhook_args() { - } - /** - * Verify and return webhook args. - * - * @param array{file:string,type:string,slug:string,force:bool} $args The webhook args. - * - * @return void - */ - public function verify_webhook_args( $args ) { - } - /** - * Listen for incoming secure webhooks from the API server. - * - * @return void - */ - public function process_webhook() { - } - /** - * Install a plugin. - * - * @param array{file:string,type:string,slug:string,force:bool} $args The file args. - * @return void - */ - public function install_plugin( $args ) { - } - } /** * License management. * @@ -3452,20 +3171,6 @@ public function render_page() { */ public function enqueue_scripts( $hook ) { } - /** - * Verify the connection. - * - * @return void - */ - public function process_verify_connection() { - } - /** - * Listen for incoming secure webhooks from the API server. - * - * @return void - */ - public function process_webhook() { - } } /** * UserExperience controller class. @@ -4548,206 +4253,6 @@ public function set_restriction_matches_in_cache( $content_id = null, $matches = } } -namespace ContentControl\Installers { - /** - * Class PluginSilentUpgraderSkin. - * - * @internal Please do not use this class outside of core plugin development. May be removed at any time. - * - * @since 2.0.0 - */ - class PluginSilentUpgraderSkin extends \WP_Upgrader_Skin { - - /** - * Empty out the header of its HTML content and only check to see if it has - * been performed or not. - * - * @return void - */ - public function header() { - } - /** - * Empty out the footer of its HTML contents. - * - * @return void - */ - public function footer() { - } - /** - * Instead of outputting HTML for errors, just return them. - * Ajax request will just ignore it. - * - * @param string|\WP_Error $errors Array of errors with the install process. - * - * @return string|\WP_Error - */ - public function error( $errors ) { - } - /** - * Empty out JavaScript output that calls function to decrement the update counts. - * - * @param string $type Type of update count to decrement. - * - * @return void - */ - public function decrement_update_count( $type ) { - } - } - /** - * Skin for on-the-fly addon installations. - * - * @since 1.0.0 - * @since 2.0.0 Extend PluginSilentUpgraderSkin and clean up the class. - */ - class Install_Skin extends \ContentControl\Installers\PluginSilentUpgraderSkin { - - /** - * Instead of outputting HTML for errors, json_encode the errors and send them - * back to the Ajax script for processing. - * - * @since 2.0.0 - * - * @param string|\WP_Error $errors Array of errors with the install process. - */ - public function error( $errors ) { - } - } - /** - * 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 plugin development. May be removed at any time. - * - * @since 2.0.0 - */ - class PluginSilentUpgrader extends \Plugin_Upgrader { - - /** - * Run an upgrade/installation. - * - * Attempt to download the package (if it is not a local file), unpack it, and - * install it in the destination folder. - * - * @since 2.0.0 - * - * @param array{package:string,destination:string,clear_destination:bool,clear_working:bool,abort_if_destination_exists:bool,is_multi:bool,hook_extra:array} $options { - * Array or string of arguments for upgrading/installing a package. - * - * @type string $package The full path or URI of the package to install. - * Default empty. - * @type string $destination The full path to the destination folder. - * Default empty. - * @type bool $clear_destination Whether to delete any files already in the - * destination folder. Default false. - * @type bool $clear_working Whether to delete the files form the working - * directory after copying to the destination. - * Default false. - * @type bool $abort_if_destination_exists Whether to abort the installation if the destination - * folder already exists. When true, `$clear_destination` - * should be false. Default true. - * @type bool $is_multi Whether this run is one of multiple upgrade/installation - * actions being performed in bulk. When true, the skin - * WP_Upgrader::header() and WP_Upgrader::footer() - * aren't called. Default false. - * @type array $hook_extra Extra arguments to pass to the filter hooks called by - * WP_Upgrader::run(). - * } - * @return array{source:string,source_files:string[],destination:string,destination_name:string,local_destination:string,remote_destination:string,clear_destination:bool}|\WP_Error|bool The result from self::install_package() on success, otherwise a WP_Error, - * or false if unable to connect to the filesystem. - */ - public function run( $options ) { - } - /** - * Toggle maintenance mode for the site. - * - * Create/delete the maintenance file to enable/disable maintenance mode. - * - * @since 2.8.0 - * - * @global WP_Filesystem_Base $wp_filesystem Subclass - * - * @param bool $enable True to enable maintenance mode, false to disable. - * - * @return void - */ - public function maintenance_mode( $enable = false ) { - } - /** - * Download a package. - * - * @since 2.8.0 - * @since 5.5.0 Added the `$hook_extra` parameter. - * - * @param string $package The URI of the package. If this is the full path to an - * existing local file, it will be returned untouched. - * @param bool $check_signatures Whether to validate file signatures. Default false. - * @param array $hook_extra Extra arguments to pass to the filter hooks. Default empty array. - * @return string|WP_Error The full path to the downloaded package file, or a WP_Error object. - */ - public function download_package( $package, $check_signatures = false, $hook_extra = [] ) { - } - /** - * Unpack a compressed package file. - * - * @since 2.8.0 - * - * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. - * - * @param string $package Full path to the package file. - * @param bool $delete_package Optional. Whether to delete the package file after attempting - * to unpack it. Default true. - * @return string|WP_Error The path to the unpacked contents, or a WP_Error on failure. - */ - public function unpack_package( $package, $delete_package = true ) { - } - /** - * Install a package. - * - * Copies the contents of a package form a source directory, and installs them in - * a destination directory. Optionally removes the source. It can also optionally - * clear out the destination folder if it already exists. - * - * @since 2.8.0 - * - * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. - * @global array $wp_theme_directories - * - * @param array|array{source:string|null,destination:string,clear_destination:bool,clear_working:bool,abort_if_destination_exists:bool,hook_extra:array} $args { - * Optional. Array or string of arguments for installing a package. Default empty array. - * - * @type string $source Required path to the package source. Default empty. - * @type string $destination Required path to a folder to install the package in. - * Default empty. - * @type bool $clear_destination Whether to delete any files already in the destination - * folder. Default false. - * @type bool $clear_working Whether to delete the files form the working directory - * after copying to the destination. Default false. - * @type bool $abort_if_destination_exists Whether to abort the installation if - * the destination folder already exists. Default true. - * @type array $hook_extra Extra arguments to pass to the filter hooks called by - * WP_Upgrader::install_package(). Default empty array. - * } - * - * @return array{source:string,source_files:string[],destination:string,destination_name:string,local_destination:string,remote_destination:string,clear_destination:bool}|\WP_Error The result (also stored in `WP_Upgrader::$result`), or a WP_Error on failure. - */ - public function install_package( $args = [] ) { - } - /** - * Install a plugin package. - * - * @since 1.6.3 - * - * @param string $package The full local path or URI of the package. - * @param array $args Optional. Other arguments for installing a plugin package. Default empty array. - * - * @return bool|\WP_Error True if the installation was successful, false or a WP_Error otherwise. - */ - public function install( $package, $args = [] ) { - } - } -} - namespace { /** * Class JP_Content_Control diff --git a/bin/verify-release-artifact.js b/bin/verify-release-artifact.js new file mode 100644 index 00000000..350c4aaa --- /dev/null +++ b/bin/verify-release-artifact.js @@ -0,0 +1,309 @@ +#!/usr/bin/env node +/* eslint-disable no-console */ + +const fs = require( 'fs' ); +const path = require( 'path' ); +const { execFileSync } = require( 'child_process' ); + +const pluginRoot = 'content-control'; + +const requiredPaths = [ + 'content-control.php', + 'readme.txt', + 'dist/settings-page.js', + 'dist/settings-page.css', + 'vendor/autoload.php', +]; + +const forbiddenPathPrefixes = [ + '.git/', + '.github/', + '.svn/', + '__MACOSX/', + 'bin/', + 'docs/', + 'node_modules/', + 'packages/', + 'tests/', +]; + +/** + * Convert an archive entry to a path relative to the plugin root. + * + * @param {string} entry Archive entry. + * @return {string} Relative path. + */ +function relativeArtifactPath( entry ) { + const prefix = `${ pluginRoot }/`; + const normalized = entry.replace( /\\/g, '/' ).replace( /\/$/, '' ); + + return normalized.startsWith( prefix ) + ? normalized.slice( prefix.length ) + : normalized; +} + +/** + * Verify that every archive entry is safely contained by one plugin root. + * + * @param {string[]} entries Archive entries. + * @return {string[]} Failures. + */ +function verifyArchiveStructure( entries ) { + const failures = []; + const seenEntries = new Set(); + + for ( const entry of entries ) { + const normalized = entry.replace( /\\/g, '/' ); + const pathWithoutTrailingSlash = normalized.replace( /\/$/, '' ); + const pathParts = pathWithoutTrailingSlash.split( '/' ); + + if ( + entry !== normalized || + normalized.startsWith( '/' ) || + pathWithoutTrailingSlash.includes( '//' ) || + pathParts.includes( '.' ) || + pathParts.includes( '..' ) + ) { + failures.push( `unsafe archive path: ${ entry }` ); + } + + if ( + pluginRoot !== pathWithoutTrailingSlash && + ! normalized.startsWith( `${ pluginRoot }/` ) + ) { + failures.push( `unexpected archive root: ${ entry }` ); + } + + if ( seenEntries.has( normalized ) ) { + failures.push( `duplicate archive path: ${ entry }` ); + } + + seenEntries.add( normalized ); + } + + return [ ...new Set( failures ) ]; +} + +/** + * Whether a Composer file belongs to the minimal runtime autoloader copied by + * this repository's release builder. + * + * @param {string} relativePath Path relative to the plugin root. + * @return {boolean} Whether the path is allowed. + */ +function isAllowedRuntimeVendorPath( relativePath ) { + return ( + 'vendor' === relativePath || + 'vendor/' === relativePath || + 'vendor/composer' === relativePath || + 'vendor/composer/' === relativePath || + 'vendor/autoload.php' === relativePath || + /^vendor\/composer\/[^/]+\.(?:php|json)$/i.test( relativePath ) + ); +} + +/** + * Verify that the release contains only distributable paths. + * + * @param {string[]} entries Archive or release-tree entries. + * @return {string[]} Failures. + */ +function verifyReleaseManifest( entries ) { + const failures = []; + const relativePaths = new Set( entries.map( relativeArtifactPath ) ); + + for ( const requiredPath of requiredPaths ) { + if ( ! relativePaths.has( requiredPath ) ) { + failures.push( `missing release path: ${ requiredPath }` ); + } + } + + for ( const relativePath of relativePaths ) { + const pathParts = relativePath.split( '/' ); + const fileName = pathParts[ pathParts.length - 1 ]; + const hasForbiddenPrefix = forbiddenPathPrefixes.some( ( prefix ) => + relativePath.startsWith( prefix ) + ); + const hasForbiddenVendorPath = + relativePath.startsWith( 'vendor/' ) && + ! isAllowedRuntimeVendorPath( relativePath ); + const isRootMarkdown = /^[^/]+\.md$/i.test( relativePath ); + const isPlatformJunk = + '.DS_Store' === fileName || + 'Thumbs.db' === fileName || + fileName.startsWith( '._' ); + + if ( + hasForbiddenPrefix || + hasForbiddenVendorPath || + isRootMarkdown || + isPlatformJunk + ) { + failures.push( `forbidden release path: ${ relativePath }` ); + } + } + + return [ ...new Set( failures ) ]; +} + +/** + * Verify that ZIP entries are regular files or directories only. + * + * @param {string[]} entries Archive entries. + * @param {string[]} entryTypes Entry type characters from unzip. + * @return {string[]} Failures. + */ +function verifyArchiveEntryTypes( entries, entryTypes ) { + if ( entryTypes.length !== entries.length ) { + return [ + `could not verify archive entry types: expected ${ entries.length }, found ${ entryTypes.length }`, + ]; + } + + return entryTypes.flatMap( ( entryType, index ) => { + const entry = entries[ index ]; + + if ( + ( 'd' === entryType && ! entry.endsWith( '/' ) ) || + ( '-' === entryType && entry.endsWith( '/' ) ) + ) { + return [ `archive entry type/name mismatch in ${ entry }` ]; + } + + return '-' === entryType || 'd' === entryType + ? [] + : [ `forbidden archive entry type in ${ entry }` ]; + } ); +} + +/** + * Verify a release ZIP's structure and manifest. + * + * This verifier protects the release archive boundary produced by this + * repository. + * + * @param {string} zipPath ZIP path. + * @return {{entries:string[],failures:string[]}} Verification result. + */ +function verifyZip( zipPath ) { + if ( ! fs.existsSync( zipPath ) ) { + throw new Error( `Artifact not found: ${ zipPath }` ); + } + + const entries = execFileSync( 'unzip', [ '-Z1', zipPath ], { + encoding: 'utf8', + } ) + .split( '\n' ) + .filter( Boolean ); + const listing = execFileSync( 'unzip', [ '-Z', '-l', zipPath ], { + encoding: 'utf8', + } ); + const entryTypes = listing + .split( '\n' ) + .filter( ( line ) => /^[bcdlps-].{9}\s/.test( line ) ) + .map( ( line ) => line.charAt( 0 ) ); + const failures = [ + ...verifyArchiveStructure( entries ), + ...verifyArchiveEntryTypes( entries, entryTypes ), + ...verifyReleaseManifest( entries ), + ]; + + return { entries, failures: [ ...new Set( failures ) ] }; +} + +/** + * Collect every regular file in an assembled release tree. + * + * @param {string} root Release root. + * @param {string} directory Current directory. + * @return {string[]} Relative file paths. + */ +function walkTree( root, directory ) { + const entries = []; + + for ( const directoryEntry of fs.readdirSync( directory, { + withFileTypes: true, + } ) ) { + const entryPath = path.join( directory, directoryEntry.name ); + const relativePath = path + .relative( root, entryPath ) + .replace( /\\/g, '/' ); + + if ( directoryEntry.isDirectory() ) { + entries.push( ...walkTree( root, entryPath ) ); + } else if ( directoryEntry.isFile() ) { + entries.push( relativePath ); + } else { + entries.push( relativePath ); + } + } + + return entries; +} + +/** + * Verify an assembled release tree before it is zipped or deployed to SVN. + * + * @param {string} releaseRoot Release root. + * @return {{entries:string[],failures:string[]}} Verification result. + */ +function verifyReleaseTree( releaseRoot ) { + if ( ! fs.existsSync( releaseRoot ) ) { + throw new Error( `Release tree not found: ${ releaseRoot }` ); + } + + const entries = walkTree( releaseRoot, releaseRoot ); + const symlinkFailures = entries + .filter( ( entry ) => + fs.lstatSync( path.join( releaseRoot, entry ) ).isSymbolicLink() + ) + .map( ( entry ) => `forbidden release symlink: ${ entry }` ); + const failures = [ + ...symlinkFailures, + ...verifyReleaseManifest( entries ), + ]; + + return { entries, failures: [ ...new Set( failures ) ] }; +} + +function main() { + const treeMode = '--release-tree' === process.argv[ 2 ]; + const targetPath = path.resolve( + treeMode + ? process.argv[ 3 ] || path.join( process.cwd(), 'build' ) + : process.argv[ 2 ] || + path.join( process.cwd(), `${ pluginRoot }-latest.zip` ) + ); + const { entries, failures } = treeMode + ? verifyReleaseTree( targetPath ) + : verifyZip( targetPath ); + + if ( failures.length ) { + console.error( 'Release artifact verification failed:' ); + for ( const failure of failures ) { + console.error( `- ${ failure }` ); + } + process.exitCode = 1; + return; + } + + console.log( + `Release artifact verification passed (${ entries.length } entries checked).` + ); +} + +if ( require.main === module ) { + main(); +} + +module.exports = { + isAllowedRuntimeVendorPath, + relativeArtifactPath, + verifyArchiveEntryTypes, + verifyArchiveStructure, + verifyReleaseManifest, + verifyReleaseTree, + verifyZip, +}; + +/* eslint-enable no-console */ diff --git a/classes/Controllers/Admin/SettingsPage.php b/classes/Controllers/Admin/SettingsPage.php index 432aa3f8..09405184 100644 --- a/classes/Controllers/Admin/SettingsPage.php +++ b/classes/Controllers/Admin/SettingsPage.php @@ -24,11 +24,6 @@ class SettingsPage extends Controller { public function init() { add_action( 'admin_menu', [ $this, 'register_page' ], 999 ); add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_scripts' ] ); - // These are here to listen for incoming webhooks from the Upgrader service when user chooses to install Pro. - add_action( 'wp_ajax_content_control_connect_verify_connection', [ $this, 'process_verify_connection' ] ); - add_action( 'wp_ajax_nopriv_content_control_connect_verify_connection', [ $this, 'process_verify_connection' ] ); - add_action( 'wp_ajax_content_control_connect_webhook', [ $this, 'process_webhook' ] ); - add_action( 'wp_ajax_nopriv_content_control_connect_webhook', [ $this, 'process_webhook' ] ); } /** @@ -75,22 +70,4 @@ public function enqueue_scripts( $hook ) { wp_enqueue_script( 'content-control-settings-page' ); } - - /** - * Verify the connection. - * - * @return void - */ - public function process_verify_connection() { - $this->container->get( 'connect' )->process_verify_connection(); - } - - /** - * Listen for incoming secure webhooks from the API server. - * - * @return void - */ - public function process_webhook() { - $this->container->get( 'connect' )->process_webhook(); - } } diff --git a/classes/Controllers/Admin/UserExperience.php b/classes/Controllers/Admin/UserExperience.php index 32533d35..4033a421 100644 --- a/classes/Controllers/Admin/UserExperience.php +++ b/classes/Controllers/Admin/UserExperience.php @@ -48,7 +48,7 @@ public function plugin_action_links( $links, $file ) { ] ); - if ( $this->container->is_license_active() || $this->container->is_pro_active() ) { + if ( $this->container->is_pro_active() ) { unset( $plugin_action_links['upgrade'] ); } diff --git a/classes/Controllers/Assets.php b/classes/Controllers/Assets.php index e30f7392..f30be2f5 100644 --- a/classes/Controllers/Assets.php +++ b/classes/Controllers/Assets.php @@ -49,6 +49,8 @@ public function get_packages() { $wp_version = preg_replace( '/\.\d+$/', '', $wp_version ); $is_pro_installed = \ContentControl\is_plugin_installed( 'content-control-pro/content-control-pro.php' ); + $is_pro_active = $is_pro_installed && is_plugin_active( 'content-control-pro/content-control-pro.php' ); + $legacy_pro = $this->container->is_legacy_pro_active(); $packages = [ 'block-editor' => [ @@ -86,7 +88,8 @@ public function get_packages() { ], 'varsName' => 'contentControlCoreData', 'vars' => [ - 'currentSettings' => get_all_plugin_options(), + 'currentSettings' => get_all_plugin_options(), + 'legacyProLicense' => $legacy_pro, ], ], 'data' => [ @@ -112,17 +115,18 @@ public function get_packages() { 'handle' => 'content-control-settings-page', 'varsName' => 'contentControlSettingsPage', 'vars' => [ - 'pluginUrl' => $this->container->get( 'url' ), - 'wpVersion' => $wp_version, - 'adminUrl' => admin_url(), - 'restBase' => 'content-control/v2', - 'userRoles' => allowed_user_roles(), - 'logUrl' => current_user_can( 'manage_options' ) ? $this->container->get( 'logging' )->get_file_url() : false, - 'rolesAndCaps' => wp_roles()->roles, - 'version' => $this->container->get( 'version' ), - 'permissions' => $permissions, - 'isProInstalled' => $is_pro_installed, - 'isProActivated' => $is_pro_installed && is_plugin_active( 'content-control-pro/content-control-pro.php' ), + 'pluginUrl' => $this->container->get( 'url' ), + 'wpVersion' => $wp_version, + 'adminUrl' => admin_url(), + 'restBase' => 'content-control/v2', + 'userRoles' => allowed_user_roles(), + 'logUrl' => current_user_can( 'manage_options' ) ? $this->container->get( 'logging' )->get_file_url() : false, + 'rolesAndCaps' => wp_roles()->roles, + 'version' => $this->container->get( 'version' ), + 'permissions' => $permissions, + 'isProInstalled' => $is_pro_installed, + 'isProActivated' => $is_pro_active, + 'legacyProLicense' => $legacy_pro, ], 'styles' => true, ], diff --git a/classes/Controllers/RestAPI.php b/classes/Controllers/RestAPI.php index 1f618b21..4118e1c6 100644 --- a/classes/Controllers/RestAPI.php +++ b/classes/Controllers/RestAPI.php @@ -25,6 +25,10 @@ class RestAPI extends Controller { public function init() { add_action( 'rest_api_init', [ $this, 'register_routes' ] ); + if ( $this->container->is_legacy_pro_active() ) { + add_filter( 'rest_endpoints', [ $this, 'disable_legacy_pro_installer_route' ], PHP_INT_MAX ); + } + // Handle CPT & Taxonomy that are not registered with the `show_in_rest` arg when searching from our settings pages. add_filter( 'register_post_type_args', [ $this, 'modify_post_type_show_in_rest' ], 10 ); add_filter( 'register_taxonomy_args', [ $this, 'modify_taxonomy_show_in_rest' ], 10 ); @@ -37,11 +41,35 @@ public function init() { */ public function register_routes() { ( new \ContentControl\RestAPI\BlockTypes() )->register_routes(); - ( new \ContentControl\RestAPI\License() )->register_routes(); + + if ( $this->container->is_legacy_pro_active() ) { + ( new \ContentControl\RestAPI\License() )->register_routes(); + } + ( new \ContentControl\RestAPI\ObjectSearch() )->register_routes(); ( new \ContentControl\RestAPI\Settings() )->register_routes(); } + /** + * Remove the installer route registered by active Pro versions below 1.3.0. + * + * Those versions resolve an upgrader service that is unavailable in Core + * 2.7.0. Removing the endpoint prevents a fatal request while Pro is updated + * manually. Core does not register or implement the endpoint. + * + * @since 2.7.0 + * @deprecated 2.7.0 Remove after Pro 1.3.0 is the minimum supported version. + * + * @param array>> $endpoints Registered REST endpoints. + * + * @return array>> + */ + public function disable_legacy_pro_installer_route( $endpoints ) { + unset( $endpoints['/content-control/v2/addons/install'] ); + + return $endpoints; + } + /** * Modify show_in_rest for post types. * diff --git a/classes/Controllers/TrustedLogin.php b/classes/Controllers/TrustedLogin.php index 2de76df6..20c8f906 100644 --- a/classes/Controllers/TrustedLogin.php +++ b/classes/Controllers/TrustedLogin.php @@ -36,11 +36,15 @@ public function init() { * @return void */ public function initiate_trustedlogin() { + $license = $this->container->get( 'license' ); + $license_key = is_object( $license ) && method_exists( $license, 'get_license_key' ) + ? $license->get_license_key() + : ''; $config = [ 'auth' => [ 'api_key' => 'f97f5be6e02d1565', - 'license_key' => $this->container->get( 'license' )->get_license_key(), + 'license_key' => $license_key, ], 'vendor' => [ 'namespace' => 'content-control', diff --git a/classes/Installers/Install_Skin.php b/classes/Installers/Install_Skin.php deleted file mode 100644 index de406e1a..00000000 --- a/classes/Installers/Install_Skin.php +++ /dev/null @@ -1,35 +0,0 @@ -} $options { - * Array or string of arguments for upgrading/installing a package. - * - * @type string $package The full path or URI of the package to install. - * Default empty. - * @type string $destination The full path to the destination folder. - * Default empty. - * @type bool $clear_destination Whether to delete any files already in the - * destination folder. Default false. - * @type bool $clear_working Whether to delete the files form the working - * directory after copying to the destination. - * Default false. - * @type bool $abort_if_destination_exists Whether to abort the installation if the destination - * folder already exists. When true, `$clear_destination` - * should be false. Default true. - * @type bool $is_multi Whether this run is one of multiple upgrade/installation - * actions being performed in bulk. When true, the skin - * WP_Upgrader::header() and WP_Upgrader::footer() - * aren't called. Default false. - * @type array $hook_extra Extra arguments to pass to the filter hooks called by - * WP_Upgrader::run(). - * } - * @return array{source:string,source_files:string[],destination:string,destination_name:string,local_destination:string,remote_destination:string,clear_destination:bool}|\WP_Error|bool The result from self::install_package() on success, otherwise a WP_Error, - * or false if unable to connect to the filesystem. - */ - public function run( $options ) { - $defaults = [ - 'package' => '', // Please always pass this. - 'destination' => '', // And this. - 'clear_destination' => false, - 'abort_if_destination_exists' => true, // Abort if the Destination directory exists, Pass clear_destination as false please. - 'clear_working' => true, - 'is_multi' => false, - 'hook_extra' => [], // Pass any extra $hook_extra args here, this will be passed to any hooked filters. - ]; - - $options = wp_parse_args( $options, $defaults ); - - /** - * Filter the package options before running an update. - * - * See also {@see 'upgrader_process_complete'}. - * - * @since 4.3.0 - * - * @param array $options { - * Options used by the upgrader. - * - * @type string $package Package for update. - * @type string $destination Update location. - * @type bool $clear_destination Clear the destination resource. - * @type bool $clear_working Clear the working resource. - * @type bool $abort_if_destination_exists Abort if the Destination directory exists. - * @type bool $is_multi Whether the upgrader is running multiple times. - * @type array $hook_extra { - * Extra hook arguments. - * - * @type string $action Type of action. Default 'update'. - * @type string $type Type of update process. Accepts 'plugin', 'theme', or 'core'. - * @type bool $bulk Whether the update process is a bulk update. Default true. - * @type string $plugin Path to the plugin file relative to the plugins directory. - * @type string $theme The stylesheet or template name of the theme. - * @type string $language_update_type The language pack update type. Accepts 'plugin', 'theme', - * or 'core'. - * @type object $language_update The language pack update offer. - * } - * } - */ - $options = apply_filters( 'upgrader_package_options', $options ); - - if ( ! $options['is_multi'] ) { // call $this->header separately if running multiple times. - $this->skin->header(); - } - - // Connect to the Filesystem first. - $res = $this->fs_connect( [ WP_CONTENT_DIR, $options['destination'] ] ); - // Mainly for non-connected filesystem. - if ( ! $res ) { - if ( ! $options['is_multi'] ) { - $this->skin->footer(); - } - return false; - } - - $this->skin->before(); - - if ( is_wp_error( $res ) ) { - $this->skin->error( $res ); - $this->skin->after(); - if ( ! $options['is_multi'] ) { - $this->skin->footer(); - } - return $res; - } - - /* - * Download the package (Note, This just returns the filename - * of the file if the package is a local file) - */ - $download = $this->download_package( $options['package'], true ); - - // Allow for signature soft-fail. - // WARNING: This may be removed in the future. - if ( is_wp_error( $download ) && $download->get_error_data( 'softfail-filename' ) ) { - - // Don't output the 'no signature could be found' failure message for now. - if ( (string) $download->get_error_code() !== 'signature_verification_no_signature' || WP_DEBUG ) { - // Outout the failure error as a normal feedback, and not as an error: - // $this->skin->feedback( $download->get_error_message() );. - - // Report this failure back to WordPress.org for debugging purposes. - wp_version_check( - [ - 'signature_failure_code' => $download->get_error_code(), - 'signature_failure_data' => $download->get_error_data(), - ] - ); - } - - // Pretend this error didn't happen. - $download = $download->get_error_data( 'softfail-filename' ); - } - - if ( is_wp_error( $download ) ) { - $this->skin->error( $download ); - $this->skin->after(); - if ( ! $options['is_multi'] ) { - $this->skin->footer(); - } - return $download; - } - - $delete_package = ( (string) $download !== (string) $options['package'] ); // Do not delete a "local" file. - - // Unzips the file into a temporary directory. - $working_dir = $this->unpack_package( $download, $delete_package ); - if ( is_wp_error( $working_dir ) ) { - $this->skin->error( $working_dir ); - $this->skin->after(); - if ( ! $options['is_multi'] ) { - $this->skin->footer(); - } - return $working_dir; - } - - // With the given options, this installs it to the destination directory. - $result = $this->install_package( - [ - 'source' => $working_dir, - 'destination' => $options['destination'], - 'clear_destination' => $options['clear_destination'], - 'abort_if_destination_exists' => $options['abort_if_destination_exists'], - 'clear_working' => $options['clear_working'], - 'hook_extra' => $options['hook_extra'], - ] - ); - - $this->skin->set_result( $result ); - if ( is_wp_error( $result ) ) { - $this->skin->error( $result ); - // phpcs:disable Squiz.PHP.CommentedOutCode.Found, Squiz.Commenting.InlineComment.InvalidEndChar - // $this->skin->feedback( 'process_failed' ); - // phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedElse - } else { - // Installation succeeded. - // $this->skin->feedback( 'process_success' ); - // phpcs:enable Squiz.PHP.CommentedOutCode.Found, Squiz.Commenting.InlineComment.InvalidEndChar - } - - $this->skin->after(); - - if ( ! $options['is_multi'] ) { - - /** - * Fire when the upgrader process is complete. - * - * See also {@see 'upgrader_package_options'}. - * - * @since 3.6.0 - * @since 3.7.0 Added to WP_Upgrader::run(). - * @since 4.6.0 `$translations` was added as a possible argument to `$hook_extra`. - * - * @param WP_Upgrader $upgrader WP_Upgrader instance. In other contexts, $this, might be a - * Theme_Upgrader, Plugin_Upgrader, Core_Upgrade, or Language_Pack_Upgrader instance. - * @param array $hook_extra { - * Array of bulk item update data. - * - * @type string $action Type of action. Default 'update'. - * @type string $type Type of update process. Accepts 'plugin', 'theme', 'translation', or 'core'. - * @type bool $bulk Whether the update process is a bulk update. Default true. - * @type array $plugins Array of the basename paths of the plugins' main files. - * @type array $themes The theme slugs. - * @type array $translations { - * Array of translations update data. - * - * @type string $language The locale the translation is for. - * @type string $type Type of translation. Accepts 'plugin', 'theme', or 'core'. - * @type string $slug Text domain the translation is for. The slug of a theme/plugin or - * 'default' for core translations. - * @type string $version The version of a theme, plugin, or core. - * } - * } - */ - do_action( 'upgrader_process_complete', $this, $options['hook_extra'] ); - - $this->skin->footer(); - } - - return $result; - } - - /** - * Toggle maintenance mode for the site. - * - * Create/delete the maintenance file to enable/disable maintenance mode. - * - * @since 2.8.0 - * - * @global WP_Filesystem_Base $wp_filesystem Subclass - * - * @param bool $enable True to enable maintenance mode, false to disable. - * - * @return void - */ - public function maintenance_mode( $enable = false ) { - global $wp_filesystem; - $file = $wp_filesystem->abspath() . '.maintenance'; - if ( $enable ) { - // Create maintenance file to signal that we are upgrading. - $maintenance_string = ''; - $wp_filesystem->delete( $file ); - $wp_filesystem->put_contents( $file, $maintenance_string, FS_CHMOD_FILE ); - } elseif ( $wp_filesystem->exists( $file ) ) { - $wp_filesystem->delete( $file ); - } - } - - /** - * Download a package. - * - * @since 2.8.0 - * @since 5.5.0 Added the `$hook_extra` parameter. - * - * @param string $package The URI of the package. If this is the full path to an - * existing local file, it will be returned untouched. - * @param bool $check_signatures Whether to validate file signatures. Default false. - * @param array $hook_extra Extra arguments to pass to the filter hooks. Default empty array. - * @return string|WP_Error The full path to the downloaded package file, or a WP_Error object. - */ - public function download_package( $package, $check_signatures = false, $hook_extra = [] ) { - - /** - * Filters whether to return the package. - * - * @since 3.7.0 - * @since 5.5.0 Added the `$hook_extra` parameter. - * - * @param bool|\WP_Error $reply Whether to bail without returning the package. - * Default false. - * @param string $package The package file name. - * @param WP_Upgrader $upgrader The WP_Upgrader instance. - * @param array $hook_extra Extra arguments passed to hooked filters. - */ - $reply = apply_filters( 'upgrader_pre_download', false, $package, $this, $hook_extra ); - if ( false !== $reply ) { - return $reply; - } - - if ( ! preg_match( '!^(http|https|ftp)://!i', $package ) && file_exists( $package ) ) { // Local file or remote? - return $package; // Must be a local file. - } - - if ( empty( $package ) ) { - return new WP_Error( 'no_package', $this->strings['no_package'] ); - } - - $download_file = download_url( $package, 300, $check_signatures ); - - if ( is_wp_error( $download_file ) && ! $download_file->get_error_data( 'softfail-filename' ) ) { - return new WP_Error( 'download_failed', $this->strings['download_failed'], $download_file->get_error_message() ); - } - - return $download_file; - } - - /** - * Unpack a compressed package file. - * - * @since 2.8.0 - * - * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. - * - * @param string $package Full path to the package file. - * @param bool $delete_package Optional. Whether to delete the package file after attempting - * to unpack it. Default true. - * @return string|WP_Error The path to the unpacked contents, or a WP_Error on failure. - */ - public function unpack_package( $package, $delete_package = true ) { - global $wp_filesystem; - - $upgrade_folder = $wp_filesystem->wp_content_dir() . 'upgrade/'; - - // Clean up contents of upgrade directory beforehand. - $upgrade_files = $wp_filesystem->dirlist( $upgrade_folder ); - if ( ! empty( $upgrade_files ) ) { - foreach ( $upgrade_files as $file ) { - $wp_filesystem->delete( $upgrade_folder . $file['name'], true ); - } - } - - // We need a working directory - Strip off any .tmp or .zip suffixes. - $working_dir = $upgrade_folder . basename( basename( $package, '.tmp' ), '.zip' ); - - // Clean up working directory. - if ( $wp_filesystem->is_dir( $working_dir ) ) { - $wp_filesystem->delete( $working_dir, true ); - } - - // Unzip package to working directory. - $result = unzip_file( $package, $working_dir ); - - // Once extracted, delete the package if required. - if ( $delete_package ) { - wp_delete_file( $package ); - } - - if ( is_wp_error( $result ) ) { - $wp_filesystem->delete( $working_dir, true ); - if ( $result->get_error_code() === 'incompatible_archive' ) { - return new WP_Error( 'incompatible_archive', $this->strings['incompatible_archive'], $result->get_error_data() ); - } - - return $result; - } - - return $working_dir; - } - - /** - * Install a package. - * - * Copies the contents of a package form a source directory, and installs them in - * a destination directory. Optionally removes the source. It can also optionally - * clear out the destination folder if it already exists. - * - * @since 2.8.0 - * - * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. - * @global array $wp_theme_directories - * - * @param array|array{source:string|null,destination:string,clear_destination:bool,clear_working:bool,abort_if_destination_exists:bool,hook_extra:array} $args { - * Optional. Array or string of arguments for installing a package. Default empty array. - * - * @type string $source Required path to the package source. Default empty. - * @type string $destination Required path to a folder to install the package in. - * Default empty. - * @type bool $clear_destination Whether to delete any files already in the destination - * folder. Default false. - * @type bool $clear_working Whether to delete the files form the working directory - * after copying to the destination. Default false. - * @type bool $abort_if_destination_exists Whether to abort the installation if - * the destination folder already exists. Default true. - * @type array $hook_extra Extra arguments to pass to the filter hooks called by - * WP_Upgrader::install_package(). Default empty array. - * } - * - * @return array{source:string,source_files:string[],destination:string,destination_name:string,local_destination:string,remote_destination:string,clear_destination:bool}|\WP_Error The result (also stored in `WP_Upgrader::$result`), or a WP_Error on failure. - */ - public function install_package( $args = [] ) { - global $wp_filesystem, $wp_theme_directories; - - $defaults = [ - 'source' => '', // Please always pass this. - 'destination' => '', // and this. - 'clear_destination' => false, - 'clear_working' => false, - 'abort_if_destination_exists' => true, - 'hook_extra' => [], - ]; - - $args = wp_parse_args( $args, $defaults ); - - // These were previously extract()'d. - $source = $args['source']; - $destination = $args['destination']; - $clear_destination = $args['clear_destination']; - - // @todo does this need to be replaced? - // wpforms_set_time_limit( 300 ); - - if ( empty( $source ) || empty( $destination ) ) { - return new WP_Error( 'bad_request', $this->strings['bad_request'] ); - } - - /** - * Filter the install response before the installation has started. - * - * Returning a truthy value, or one that could be evaluated as a WP_Error - * will effectively short-circuit the installation, returning that value - * instead. - * - * @since 2.8.0 - * - * @param bool|WP_Error $response Response. - * @param array $hook_extra Extra arguments passed to hooked filters. - */ - $res = apply_filters( 'upgrader_pre_install', true, $args['hook_extra'] ); - - if ( is_wp_error( $res ) ) { - return $res; - } - - // Retain the Original source and destinations. - $remote_source = $args['source']; - $local_destination = $destination; - - $source_files = array_keys( $wp_filesystem->dirlist( $remote_source ) ); - $remote_destination = $wp_filesystem->find_folder( $local_destination ); - $count_source_files = count( $source_files ); - - // Locate which directory to copy to the new folder, This is based on the actual folder holding the files. - if ( 1 === $count_source_files && $wp_filesystem->is_dir( trailingslashit( $args['source'] ) . $source_files[0] . '/' ) ) { // Only one folder? Then we want its contents. - $source = trailingslashit( $args['source'] ) . trailingslashit( $source_files[0] ); - } elseif ( 0 === $count_source_files ) { - return new WP_Error( 'incompatible_archive_empty', $this->strings['incompatible_archive'], $this->strings['no_files'] ); // There are no files? - } else { // It's only a single file, the upgrader will use the folder name of this file as the destination folder. Folder name is based on zip filename. - $source = trailingslashit( $args['source'] ); - } - - /** - * Filter the source file location for the upgrade package. - * - * @since 2.8.0 - * @since 4.4.0 The $hook_extra parameter became available. - * - * @param string|\WP_Error $source File source location. - * @param string $remote_source Remote file source location. - * @param WP_Upgrader $upgrader WP_Upgrader instance. - * @param array $hook_extra Extra arguments passed to hooked filters. - */ - $source = apply_filters( 'upgrader_source_selection', $source, $remote_source, $this, $args['hook_extra'] ); - - if ( is_wp_error( $source ) ) { - return $source; - } - - // Has the source location changed? If so, we need a new source_files list. - if ( $source !== $remote_source ) { - $source_files = array_keys( $wp_filesystem->dirlist( $source ) ); - } - - /* - * Protection against deleting files in any important base directories. - * Theme_Upgrader & Plugin_Upgrader also trigger this, as they pass the - * destination directory (WP_PLUGIN_DIR / wp-content/themes) intending - * to copy the directory into the directory, whilst they pass the source - * as the actual files to copy. - */ - $protected_directories = [ ABSPATH, WP_CONTENT_DIR, WP_PLUGIN_DIR, WP_CONTENT_DIR . '/themes' ]; - - if ( is_array( $wp_theme_directories ) ) { - $protected_directories = array_merge( $protected_directories, $wp_theme_directories ); - } - - if ( in_array( $destination, $protected_directories, true ) ) { - $remote_destination = trailingslashit( $remote_destination ) . trailingslashit( basename( $source ) ); - $destination = trailingslashit( $destination ) . trailingslashit( basename( $source ) ); - } - - if ( $clear_destination ) { - // We're going to clear the destination if there's something there. - $removed = $this->clear_destination( $remote_destination ); - - /** - * Filter whether the upgrader cleared the destination. - * - * @since 2.8.0 - * - * @param mixed $removed Whether the destination was cleared. true on success, WP_Error on failure - * @param string $local_destination The local package destination. - * @param string $remote_destination The remote package destination. - * @param array $hook_extra Extra arguments passed to hooked filters. - */ - $removed = apply_filters( 'upgrader_clear_destination', $removed, $local_destination, $remote_destination, $args['hook_extra'] ); - - if ( is_wp_error( $removed ) ) { - return $removed; - } - } elseif ( $args['abort_if_destination_exists'] && $wp_filesystem->exists( $remote_destination ) ) { - // If we're not clearing the destination folder and something exists there already, Bail. - // But first check to see if there are actually any files in the folder. - $_files = $wp_filesystem->dirlist( $remote_destination ); - - if ( ! empty( $_files ) ) { - $wp_filesystem->delete( $remote_source, true ); // Clear out the source files. - - return new WP_Error( 'folder_exists', $this->strings['folder_exists'], $remote_destination ); - } - } - - // Create destination if needed. - if ( ! $wp_filesystem->exists( $remote_destination ) ) { - if ( ! $wp_filesystem->mkdir( $remote_destination, FS_CHMOD_DIR ) ) { - return new WP_Error( 'mkdir_failed_destination', $this->strings['mkdir_failed'], $remote_destination ); - } - } - - // Copy new version of item into place. - $result = copy_dir( $source, $remote_destination ); - - if ( is_wp_error( $result ) ) { - if ( $args['clear_working'] ) { - $wp_filesystem->delete( $remote_source, true ); - } - - return $result; - } - - // Clear the Working folder? - if ( $args['clear_working'] ) { - $wp_filesystem->delete( $remote_source, true ); - } - - $destination_name = basename( str_replace( $local_destination, '', $destination ) ); - - if ( '.' === $destination_name ) { - $destination_name = ''; - } - - $this->result = compact( 'source', 'source_files', 'destination', 'destination_name', 'local_destination', 'remote_destination', 'clear_destination' ); - - /** - * Filter the installation response after the installation has finished. - * - * @since 2.8.0 - * - * @param bool|\WP_Error $response Installation response. - * @param array $hook_extra Extra arguments passed to hooked filters. - * @param array $result Installation result data. - */ - $res = apply_filters( 'upgrader_post_install', true, $args['hook_extra'], $this->result ); - - if ( is_wp_error( $res ) ) { - $this->result = $res; - - return $res; - } - - // Bombard the calling function will all the info which we've just used. - return $this->result; - } - - /** - * Install a plugin package. - * - * @since 1.6.3 - * - * @param string $package The full local path or URI of the package. - * @param array $args Optional. Other arguments for installing a plugin package. Default empty array. - * - * @return bool|\WP_Error True if the installation was successful, false or a WP_Error otherwise. - */ - public function install( $package, $args = [] ) { - $result = parent::install( $package, $args ); - if ( true === $result ) { - do_action( 'content_control_plugin_installed', $package ); - } - - return $result; - } -} diff --git a/classes/Installers/PluginSilentUpgraderSkin.php b/classes/Installers/PluginSilentUpgraderSkin.php deleted file mode 100644 index 4ac8af03..00000000 --- a/classes/Installers/PluginSilentUpgraderSkin.php +++ /dev/null @@ -1,62 +0,0 @@ -c = $c; - } - - /** - * Check if debug mode is enabled. - * - * @return bool - */ - public function debug_mode_enabled() { - return defined( '\WP_DEBUG' ) && \WP_DEBUG; - } - - /** - * Generate a new authorizatin token. - * - * @return string - */ - public function generate_token() { - $token = hash( 'sha512', (string) wp_rand() ); - - \set_site_transient( self::TOKEN_OPTION_NAME, $token, HOUR_IN_SECONDS ); - - return $token; - } - - /** - * Get the current token. - * - * @return string|false - */ - public function get_access_token() { - return \get_site_transient( self::TOKEN_OPTION_NAME ); - } - - /** - * Get the current nonce. - * - * @param string $token Token. - * - * @return string|false - */ - public function get_nonce_name( $token ) { - return self::NONCE_OPTION_NAME . '_' . $token; - } - - /** - * Log a message to the debug log if enabled. - * - * Here to prevent constant conditional checks for the debug mode. - * - * @param string $message Message. - * @param string $type Type. - * - * @return void - */ - public function debug_log( $message, $type = 'INFO' ) { - if ( $this->debug_mode_enabled() ) { - plugin( 'logging' )->log( "Plugin\Connect.$type: $message" ); - } - } - - /** - * Get header Authorization - * - * @return null|string - */ - public function get_request_authorization_header() { - $headers = null; - - if ( isset( $_SERVER['Authorization'] ) ) { - $headers = trim( sanitize_text_field( wp_unslash( $_SERVER['Authorization'] ) ) ); - } elseif ( isset( $_SERVER['HTTP_AUTHORIZATION'] ) ) { // Nginx or fast CGI. - $headers = trim( sanitize_text_field( wp_unslash( $_SERVER['HTTP_AUTHORIZATION'] ) ) ); - } elseif ( function_exists( 'apache_request_headers' ) ) { - $request_headers = apache_request_headers(); - // Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization). - $request_headers = array_combine( array_map( 'ucwords', array_keys( $request_headers ) ), array_values( $request_headers ) ); - if ( isset( $request_headers['Authorization'] ) ) { - $headers = trim( $request_headers['Authorization'] ); - } - } - - return $headers; - } - - /** - * Get access token from header. - * - * @return string|null - */ - public function get_request_token() { - $headers = $this->get_request_authorization_header(); - // HEADER: Get the access token from the header. - if ( ! empty( $headers ) ) { - if ( preg_match( '/Bearer\s(\S+)/', $headers, $matches ) ) { - return trim( $matches[1], ', ' ); - } - } - return null; - } - - /** - * Get nonce from header. - * - * @return string|null - */ - public function get_request_nonce() { - $headers = $this->get_request_authorization_header(); - // HEADER: Get the nonce from the header. - if ( ! empty( $headers ) ) { - if ( preg_match( '/Nonce\s(\S+)/', $headers, $matches ) ) { - return trim( $matches[1], ', ' ); - } - } - return null; - } - - /** - * Get the OAuth connect URL. - * - * @param string $license_key License key. - * - * @return array{url:string,back_url:string} - */ - public function get_connect_info( $license_key ) { - $token = $this->generate_token(); - $nonce = wp_create_nonce( $this->get_nonce_name( $token ) ); - $webhook = admin_url( 'admin-ajax.php' ); - $redirect = add_query_arg( - [ - 'page' => 'content-control-settings', - 'view' => 'upgrade', - 'tab' => 'general', - ], - admin_url( 'options-general.php' ) - ); - - $url = add_query_arg( - [ - 'key' => $license_key, - 'token' => $token, - 'nonce' => $nonce, - 'webhook' => $webhook, - 'version' => plugin( 'version' ), - 'siteurl' => admin_url(), - 'homeurl' => home_url(), - // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode - 'redirect' => rawurldecode( base64_encode( $redirect ) ), - ], - self::API_URL - ); - - $this->debug_log( 'Generated new connection.' ); - $this->debug_log( 'Token: ' . $token ); - $this->debug_log( 'Nonce: ' . $nonce ); - - return [ - 'url' => $url, - 'back_url' => add_query_arg( - [ - 'action' => 'content_control_connect', - 'token' => $token, - ], - $webhook - ), - ]; - } - - /** - * Kill the connection with no permission. - * - * @param int $error_no Error number. - * @param string|false $message Error message. - * - * @return void - */ - public function kill_connection( $error_no = self::ERROR_REFERRER, $message = false ) { - $this->debug_log( "Killing connection with error ($error_no) message: " . $message, 'ERROR' ); - - wp_die( - esc_html( - $this->debug_mode_enabled() && $message ? - $message : - __( 'Sorry, You Are Not Allowed to Access This Page.', 'content-control' ) - ), - esc_attr( (string) $error_no ), - [ 'response' => 403 ] - ); - } - - /** - * Verify the user agent. - * - * @return void - */ - public function verify_user_agent() { - // Check user agent matches Content Control Upgrader. - if ( ! isset( $_SERVER['HTTP_USER_AGENT'] ) || 'ContentControlUpgrader' !== $_SERVER['HTTP_USER_AGENT'] ) { - $this->kill_connection( self::ERROR_USER_AGENT, 'User agent invalid.' ); - } - } - - /** - * Verify the referrer. - * - * @return void - */ - public function verify_referrer() { - $referer = isset( $_SERVER['HTTP_X_SENDING_DOMAIN'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_SENDING_DOMAIN'] ) ) : ''; - - if ( ! $referer ) { - // Mimic the default you don't have permission to do that screen from WordPress. - $this->kill_connection( self::ERROR_REFERRER, 'Missing referrer' ); - } - - $referer_host = wp_parse_url( $referer, PHP_URL_HOST ); - - if ( ! $referer_host ) { - $this->kill_connection( self::ERROR_REFERRER, 'Invalid referrer' ); - } - - $allowed_hosts = [ - 'contentcontrolplugin.com', - 'upgrade.contentcontrolplugin.com', - ]; - - if ( ! in_array( $referer_host, $allowed_hosts, true ) ) { - $this->debug_log( 'Referrer mismatch: ' . $referer_host, 'DEBUG' ); - $this->kill_connection( self::ERROR_REFERRER, 'Referrer doesn\'t match' ); - } - } - - /** - * Verify the nonce. - * - * @deprecated 2.0.0 Don't use, it doesn't work as its a separate server making request. - * - * @return void - */ - public function verify_nonce() { - $token = $this->get_access_token(); - $nonce = $this->get_request_nonce(); - - if ( ! $nonce ) { - $this->kill_connection( self::ERROR_NONCE, 'Missing nonce' ); - } - - if ( false === wp_verify_nonce( $nonce, $this->get_nonce_name( $token ) ) ) { - $this->debug_log( 'Nonce mismatch: ' . $nonce, 'DEBUG' ); - $this->debug_log( 'Nonce Name: ' . $this->get_nonce_name( $token ) ); - $this->kill_connection( self::ERROR_NONCE, 'Invalid nonce' ); - } - } - - /** - * Verify the authentication token. - * - * @return void - */ - public function verify_authentication() { - // Get token from header Bearer. - $token = $this->get_access_token(); - $auth_token = $this->get_request_token(); - - if ( ! $token || ! $auth_token ) { - $this->kill_connection( self::ERROR_AUTHENTICATION, 'Missing authentication' ); - } - - // Verify hashes match. - if ( ! hash_equals( $token, $auth_token ) ) { - $this->debug_log( 'Token mismatch: ' . $auth_token, 'DEBUG' ); - $this->kill_connection( self::ERROR_AUTHENTICATION, 'Invalid authentiction' ); - } - } - - /** - * Generate signature hash. - * - * This must match the hash generated on the server. - * - * @see \ontentControlUpgrader\App::generate_hash() - * - * @param array|string $data Data to hash. - * @param string $token Token to hash with. - * @return string - */ - public function generate_hash( $data, $token ) { - // Convert boolean values to their string representation. - array_walk_recursive($data, function ( &$value ) { - if ( is_bool( $value ) ) { - $value = $value ? '1' : '0'; - } - }); - - if ( ! is_string( $data ) ) { - // Sort the array before encoding it as JSON. - ksort( $data ); - - // Ignored due to wp_json_encode stripping slashes and breaking hashes. - // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode - $data = json_encode( $data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); - } - - // Generate the hash binary. - $hash = hash_hmac( 'sha256', $data, $token, true ); - - // The only deviation from ServerSide is that we optionally log the hash if debug mode is enabled. - $this->debug_log( 'Hash: ' . $hash, 'DEBUG' ); - $this->debug_log( 'Data: ' . $data, 'DEBUG' ); - - // Encode the hash in base64 to make it URL safe. - // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode - return base64_encode( $hash ); - } - - /** - * Verify the signature of the requester. - * - * @return void - */ - public function verify_signature() { - if ( ! isset( $_SERVER['HTTP_X_CONTENTCONTROL_SIGNATURE'] ) ) { - return; - } - - // Verify the webhook signature. - $signature = sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_CONTENTCONTROL_SIGNATURE'] ) ); - - // Calculate the expected signature. - // phpcs:ignore WordPress.Security.NonceVerification.Missing - $expected_signature = $this->generate_hash( $_POST, $this->get_access_token() ); - - // Compare the expected signature to the received signature. - if ( ! hash_equals( $expected_signature, $signature ) ) { - $this->debug_log( "Signature mismatch: \r\n - Webhook: " . $signature . "\r\n - Calculated: " . $expected_signature, 'DEBUG' ); - $this->kill_connection( self::ERROR_SIGNATURE, 'Invalid signature' ); - } - } - - /** - * Validate the connection. - * - * @return void - */ - public function validate_connection() { - $this->debug_log( 'Validating connection...', 'DEBUG' ); - $this->verify_user_agent(); - // If production, verify the referrer. - if ( 'production' === wp_get_environment_type() ) { - $this->verify_referrer(); - } - $this->verify_authentication(); - $this->verify_signature(); - $this->debug_log( 'Connection validated', 'DEBUG' ); - } - - /** - * Verify the connection. - * - * @return void - */ - public function process_verify_connection() { - $this->validate_connection(); - wp_send_json_success(); - } - - /** - * Get the webhook args. - * - * @return array{file:string,type:string,slug:string,force:boolean} - */ - public function get_webhook_args() { - $args = [ - // phpcs:disable WordPress.Security.NonceVerification.Recommended - 'file' => ! empty( $_REQUEST['file'] ) ? esc_url_raw( wp_unslash( $_REQUEST['file'] ) ) : '', - 'type' => ! empty( $_REQUEST['type'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['type'] ) ) : 'plugin', - 'slug' => ! empty( $_REQUEST['slug'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['slug'] ) ) : '', - 'force' => ! empty( $_REQUEST['force'] ) ? (bool) $_REQUEST['force'] : false, - // phpcs:enable WordPress.Security.NonceVerification.Recommended - ]; - - $this->verify_webhook_args( $args ); - - return $args; - } - - /** - * Verify and return webhook args. - * - * @param array{file:string,type:string,slug:string,force:bool} $args The webhook args. - * - * @return void - */ - public function verify_webhook_args( $args ) { - $file_url = ! empty( $args['file'] ) ? $args['file'] : false; - $file_type = ! empty( $args['type'] ) ? $args['type'] : false; - $file_slug = ! empty( $args['slug'] ) ? $args['slug'] : false; - $force = ! empty( $args['force'] ) ? (bool) $args['force'] : false; - - if ( ! $file_url || ! $file_type || ! $file_slug ) { - $this->kill_connection( self::ERROR_WEBHOOK_ARGS, 'Missing webhook args' ); - } - - if ( ! in_array( $file_type, [ 'plugin', 'theme' ], true ) ) { - $this->kill_connection( self::ERROR_WEBHOOK_ARGS, 'Invalid webhook args' ); - } - } - - /** - * Listen for incoming secure webhooks from the API server. - * - * @return void - */ - public function process_webhook() { - // 1. Validate the connection is secure & from the API server. - $this->validate_connection(); - - $error = esc_html__( 'There was an error while installing an upgrade. Please download the plugin from contentcontrolplugin.com and install it manually.', 'content-control' ); - - // 2. Get the webhook data. - $args = $this->get_webhook_args(); - - // 3. Validate license key. - if ( ! plugin( 'license' )->is_license_active() ) { - $this->debug_log( 'License not active', 'DEBUG' ); - wp_send_json_error( $error ); - } - - // Set the current screen to avoid undefined notices. - set_current_screen( 'settings_page_content-control-settings' ); - - // 4. Install the plugin. - switch ( $args['type'] ) { - case 'plugin': - $this->install_plugin( $args ); - break; - } - - // 5. Delete the token to prevent abuse. Doing so last means it should be possible to retry if something goes wrong. - if ( ! $this->debug_mode_enabled() ) { - $this->debug_log( 'Deleting token', 'DEBUG' ); - \delete_site_transient( self::TOKEN_OPTION_NAME ); - } - } - - /** - * Install a plugin. - * - * @param array{file:string,type:string,slug:string,force:bool} $args The file args. - * @return void - */ - public function install_plugin( $args ) { - $this->debug_log( 'Installing plugin...', 'DEBUG' ); - - // If not forcing, and already active, return success. - if ( ! $args['force'] && is_plugin_active( "{$args['slug']}/{$args['slug']}.php" ) ) { - $this->debug_log( 'Plugin already installed & active.', 'DEBUG' ); - wp_send_json_success( esc_html__( 'Plugin installed & activated.', 'content-control' ) ); - } - - // Get the upgrader. - $upgrader = $this->c->get( 'upgrader' ); - - // Install the plugin. (if installed already, this will replace it using upgrade). - $installed = $upgrader->install_plugin( $args['file'] ); - - if ( ! is_wp_error( $installed ) ) { - $this->debug_log( 'Plugin installed & activated successfully.', 'DEBUG' ); - wp_send_json_success( esc_html__( 'Plugin installed & activated.', 'content-control' ) ); - } - - switch ( $installed->get_error_code() ) { - default: - $error = $installed->get_error_message(); - } - - if ( empty( $error ) ) { - $error = esc_html__( 'There was an error while installing an upgrade. Please download the plugin from contentcontrolplugin.com and install it manually.', 'content-control' ); - } - - $this->debug_log( 'Plugin install failed: ' . $error, 'DEBUG' ); - wp_send_json_error( $installed->get_error_message() ); - } -} diff --git a/classes/Plugin/Core.php b/classes/Plugin/Core.php index de9d5890..9c761dab 100644 --- a/classes/Plugin/Core.php +++ b/classes/Plugin/Core.php @@ -191,25 +191,18 @@ function ( $c ) { return new Options( $c->get( 'option_prefix' ) ); }; - $this->container['connect'] = + if ( $this->is_legacy_pro_active() ) { + $this->container['license'] = /** - * Get plugin connect. - * - * @return Connect - */ - function ( $c ) { - return new \ContentControl\Plugin\Connect( $c ); - }; - - $this->container['license'] = - /** - * Get plugin license. + * Get the temporary old-Pro license bridge. * * @return License + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns licensing. */ - function () { - return new \ContentControl\Plugin\License(); - }; + function () { + return new \ContentControl\Plugin\License(); + }; + } $this->container['logging'] = /** @@ -221,16 +214,6 @@ function () { return new \ContentControl\Plugin\Logging(); }; - $this->container['upgrader'] = - /** - * Get plugin upgrader. - * - * @return Upgrader - */ - function ( $c ) { - return new \ContentControl\Plugin\Upgrader( $c ); - }; - $this->container['rules'] = /** * Get plugin rules. @@ -473,12 +456,34 @@ public function is_pro_active() { return $this->is_pro_installed() && function_exists( '\ContentControl\Pro\plugin' ); } + /** + * Whether an active Pro release still depends on Core's license provider. + * + * This version gate is the only reason Core retains its deprecated license + * bridge. Pro 1.3.0 and later register their own provider before use. + * + * @return boolean + */ + public function is_legacy_pro_active() { + if ( ! $this->is_pro_active() || ! function_exists( '\ContentControl\Pro\config' ) ) { + return false; + } + + $version = \ContentControl\Pro\config( 'version' ); + + return is_string( $version ) && '' !== $version && version_compare( $version, '1.3.0', '<' ); + } + /** * Check if license is active. * * @return boolean */ public function is_license_active() { - return $this->get( 'license' )->is_license_active(); + $license = $this->get( 'license' ); + + return is_object( $license ) && method_exists( $license, 'is_license_active' ) + ? $license->is_license_active() + : false; } } diff --git a/classes/Plugin/License.php b/classes/Plugin/License.php index a305e0cf..047bac42 100644 --- a/classes/Plugin/License.php +++ b/classes/Plugin/License.php @@ -12,12 +12,10 @@ defined( 'ABSPATH' ) || exit; /** - * License management. - * - * NOTE: For wordpress.org admins: This is only used if: - * - The user explicitly entered a license key. + * Temporary license provider for active Pro releases older than 1.3.0. * * @package ContentControl + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns licensing. */ class License { @@ -51,6 +49,8 @@ class License { /** * Initialize license management. + * + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns licensing. */ public function __construct() { $this->register_hooks(); @@ -60,6 +60,7 @@ public function __construct() { * Register hooks. * * @return void + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns licensing. */ public function register_hooks() { add_action( 'init', [ $this, 'autoregister' ] ); @@ -71,6 +72,7 @@ public function register_hooks() { * Autoregister license. * * @return void + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns licensing. */ public function autoregister() { $key = defined( '\CONTENT_CONTROL_LICENSE_KEY' ) && '' !== \CONTENT_CONTROL_LICENSE_KEY ? \CONTENT_CONTROL_LICENSE_KEY : false; @@ -89,6 +91,7 @@ public function autoregister() { * Schedule cron jobs. * * @return void + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns licensing. */ public function schedule_crons() { if ( ! wp_next_scheduled( 'content_control_license_status_check' ) ) { @@ -100,6 +103,7 @@ public function schedule_crons() { * Get license data. * * @return array{key:string|null,status:array|null} + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns licensing. */ public function get_license_data() { if ( ! isset( $this->license_data ) ) { @@ -131,6 +135,7 @@ public function get_license_data() { * Get license key. * * @return string + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns licensing. */ public function get_license_key() { $license_data = $this->get_license_data(); @@ -143,6 +148,7 @@ public function get_license_key() { * @param bool $refresh Whether to refresh license status. * * @return array Array of license status data. + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns licensing. */ public function get_license_status( $refresh = false ) { if ( $refresh ) { @@ -162,6 +168,7 @@ public function get_license_status( $refresh = false ) { * Only used in pro version. * * @return int Integer representing license level. + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns licensing. */ public function get_license_level() { $license_status = $this->get_license_status(); @@ -194,6 +201,7 @@ public function get_license_level() { * @param array{key:string|null,status:array|null} $license_data License data. * * @return bool + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns licensing. */ public function udpate_license_data( $license_data ) { if ( \update_option( self::OPTION_KEY, $license_data ) ) { @@ -210,6 +218,7 @@ public function udpate_license_data( $license_data ) { * @param string $key License key. * * @return void + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns licensing. */ public function update_license_key( $key ) { $license_data = $this->get_license_data(); @@ -235,6 +244,7 @@ public function update_license_key( $key ) { * @param array $license_status License status data. * * @return void + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns licensing. */ public function update_license_status( $license_status ) { $license_data = $this->get_license_data(); @@ -264,6 +274,7 @@ public function update_license_status( $license_status ) { * @param bool $as_datetime Whether to return as DateTime object. * * @return \DateTime|false|null + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns licensing. */ public function get_license_expiration( $as_datetime = false ) { $status = $this->get_license_status(); @@ -280,6 +291,7 @@ public function get_license_expiration( $as_datetime = false ) { * This is a blocking request. * * @return void + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns licensing. */ public function refresh_license_status() { $key = $this->get_license_key(); @@ -303,6 +315,7 @@ public function refresh_license_status() { * @return array License status data. * * @throws \Exception If there is an error. + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns licensing. */ private function check_license() { $api_params = [ @@ -318,9 +331,8 @@ private function check_license() { $response = wp_remote_post( self::API_URL, [ - 'timeout' => 15, - 'sslverify' => false, - 'body' => $api_params, + 'timeout' => 15, + 'body' => $api_params, ] ); @@ -345,6 +357,7 @@ private function check_license() { * @return array License status data. * * @throws \Exception If there is an error. + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns licensing. */ public function activate_license( $key = null ) { if ( ! empty( $key ) ) { @@ -365,9 +378,8 @@ public function activate_license( $key = null ) { $response = wp_remote_post( self::API_URL, [ - 'timeout' => 15, - 'sslverify' => false, - 'body' => $api_params, + 'timeout' => 15, + 'body' => $api_params, ] ); @@ -401,6 +413,7 @@ public function activate_license( $key = null ) { * @return array License status data. * * @throws \Exception If there is an error. + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns licensing. */ public function deactivate_license() { $api_params = [ @@ -416,9 +429,8 @@ public function deactivate_license() { $response = wp_remote_post( self::API_URL, [ - 'timeout' => 15, - 'sslverify' => false, - 'body' => $api_params, + 'timeout' => 15, + 'body' => $api_params, ] ); @@ -446,6 +458,7 @@ public function deactivate_license() { * @param array $license_status License status data. * * @return string + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns licensing. */ public function get_license_error_message( $license_status ) { switch ( $license_status['error'] ) { @@ -495,8 +508,15 @@ public function get_license_error_message( $license_status ) { * Remove license. * * @return void + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns licensing. */ public function remove_license() { + if ( '' === $this->get_license_key() ) { + \delete_option( self::OPTION_KEY ); + $this->license_data = null; + return; + } + try { $deactivated = $this->deactivate_license(); } catch ( \Exception $e ) { @@ -512,6 +532,7 @@ public function remove_license() { * Check if license is active. * * @return bool + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns licensing. */ public function is_license_active() { $license_status = $this->get_license_status(); diff --git a/classes/Plugin/Upgrader.php b/classes/Plugin/Upgrader.php deleted file mode 100644 index 1c75fc6e..00000000 --- a/classes/Plugin/Upgrader.php +++ /dev/null @@ -1,209 +0,0 @@ -c = $c; - } - - /** - * Maybe load functions & classes required for upgrade. - * - * Purely here due to prevent possible random errors. - * - * @return void - */ - public function maybe_load_required_files() { - if ( ! function_exists( 'request_filesystem_credentials' ) ) { - require_once ABSPATH . 'wp-admin/includes/file.php'; - } - - if ( ! function_exists( 'get_plugin_data' ) ) { - require_once ABSPATH . 'wp-admin/includes/plugin.php'; - } - } - - /** - * Log a message to the debug log if enabled. - * - * Here to prevent constant conditional checks for the debug mode. - * - * @param string $message Message. - * @param string $type Type. - * - * @return void - */ - public function debug_log( $message, $type = 'INFO' ) { - if ( defined( 'CONTENT_CONTROL_UPGRADE_DEBUG_LOGGING' ) && CONTENT_CONTROL_UPGRADE_DEBUG_LOGGING ) { - $this->c->get( 'logging' )->log( "Plugin\Upgrader.$type: $message" ); - } - } - - /** - * Get credentials for the current request. - * - * @return bool - */ - public function get_fs_creds() { - // Prepare variables. - $url = esc_url_raw( - add_query_arg( - [ - 'page' => 'content-control-settings', - 'view' => 'upgrade', - ], - admin_url( 'options-general.php' ) - ) - ); - - $creds = request_filesystem_credentials( $url, '', false, '', null ); - - if ( false === $creds || ! WP_Filesystem( $creds ) ) { - $this->debug_log( 'Unable to get filesystem credentials.', 'ERROR' ); - return false; - } - - return (bool) $creds; - } - - /** - * Activate a plugin. - * - * @param string $plugin_basename The plugin basename. - * @return bool|\WP_Error - */ - public function activate_plugin( $plugin_basename ) { - if ( empty( $plugin_basename ) ) { - return new \WP_Error( 'content_control_plugin_basename', __( 'Plugin basename empty.', 'content-control' ) ); - } - - // Activate the plugin silently. - $activated = activate_plugin( $plugin_basename, '', false, true ); - - if ( is_wp_error( $activated ) ) { - $this->debug_log( 'Plugin failed to activate: ' . $activated->get_error_message() ); - return $activated; - } - - $this->debug_log( 'Plugin activated: ' . $plugin_basename ); - - return true; - } - - /** - * Install a plugin from file. - * - * @param string $file The plugin file. - * - * @return bool|\WP_Error - */ - public function install_plugin( $file ) { - // Load required files. - $this->maybe_load_required_files(); - - // Check for file system permissions. - if ( false === $this->get_fs_creds() ) { - return new \WP_Error( 'content_control_fs_creds', __( 'Unable to get filesystem credentials.', 'content-control' ) ); - } - - // 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 ); - - $installer = new \ContentControl\Installers\PluginSilentUpgrader( new \ContentControl\Installers\Install_Skin() ); - - // 1. Check if the plugin exists already, if so upgrade it. - - // Error check. Sanity check to ensure install method exists. - // @phpstan-ignore-next-line . - if ( ! method_exists( $installer, 'install' ) ) { - return new \WP_Error( 'content_control_upgrader', __( 'Upgrader missing install method.', 'content-control' ) ); - } - - $this->debug_log( 'Installing plugin from file: ' . $file ); - - $plugin = $installer->install( $file, [ - 'overwrite_package' => true, - ] ); - - if ( is_wp_error( $plugin ) && 'folder_exists' === $plugin->get_error_code() ) { - $this->debug_log( 'Plugin already exists, upgrading instead.' ); - - // Plugin already exists, upgrade it. - $plugin_basename = $installer->plugin_info(); - - // Filter get_site_transient( 'update_plugins' ) to replace $plugin_basename->package with $file. - add_filter( 'pre_site_transient_update_plugins', function ( $current ) use ( $file, $plugin_basename ) { - if ( isset( $current->response[ $plugin_basename ] ) ) { - $current->response[ $plugin_basename ]->package = $file; - } else { - $current->response[ $plugin_basename ] = (object) [ - 'id' => '0', - 'slug' => $plugin_basename, - 'new_version' => '0', - 'url' => '', - 'package' => $file, - ]; - } - - $this->debug_log( 'Filtering update_plugins transient to replace package with file.' ); - // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_print_r - $this->debug_log( 'Current: ' . print_r( $current->response[ $plugin_basename ], true ) ); - return $current; - }, 10, 1 ); - - $this->debug_log( 'Upgrading plugin.' ); - $upgraded = $installer->upgrade( $file ); - - if ( is_wp_error( $upgraded ) ) { - $this->debug_log( 'Error upgrading plugin: ' . $upgraded->get_error_message(), 'ERROR' ); - return $upgraded; - } - - return $upgraded; - } - - if ( is_wp_error( $plugin ) ) { - $this->debug_log( 'Error installing plugin: ' . $plugin->get_error_message(), 'ERROR' ); - return $plugin; - } - - // Flush the cache and return the newly installed plugin basename. - wp_cache_flush(); - - $plugin_basename = $installer->plugin_info(); - - $this->debug_log( 'Plugin installed: ' . $plugin_basename ); - - return $this->activate_plugin( $plugin_basename ); - } -} diff --git a/classes/RestAPI/License.php b/classes/RestAPI/License.php index 9332c099..ac327549 100644 --- a/classes/RestAPI/License.php +++ b/classes/RestAPI/License.php @@ -15,7 +15,9 @@ defined( 'ABSPATH' ) || exit; /** - * Rest API Licensing Controller Class. + * Temporary REST bridge for Pro releases older than 1.3.0. + * + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns license REST routes. */ class License extends WP_REST_Controller { @@ -37,6 +39,7 @@ class License extends WP_REST_Controller { * Register API endpoint routes. * * @return void + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns license REST routes. */ public function register_routes() { register_rest_route( @@ -107,7 +110,7 @@ public function register_routes() { [ [ 'methods' => WP_REST_Server::READABLE, - 'callback' => [ $this, 'get_license_status' ], + 'callback' => [ $this, 'get_status' ], 'permission_callback' => [ $this, 'manage_license_permissions' ], ], [ @@ -117,18 +120,6 @@ public function register_routes() { ], ] ); - - register_rest_route( - $this->namespace, - '/' . $this->base . '/activate-pro', - [ - [ - 'methods' => WP_REST_Server::EDITABLE, - 'callback' => [ $this, 'activate_pro' ], - 'permission_callback' => [ $this, 'manage_license_permissions' ], - ], - ], - ); } /** @@ -136,6 +127,7 @@ public function register_routes() { * * @param array{key:string,status:array} $license_data License data. * @return array{key:string,status:array} + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns license REST routes. */ public function clean_license_data( $license_data ) { $license_data['status'] = $this->clean_license_status( $license_data['status'] ); @@ -152,6 +144,7 @@ public function clean_license_data( $license_data ) { * * @psalm-return array<'key'|'status', array|string> * @phpstan-return array{key: string, status: array|string} + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns license REST routes. */ public function clean_license_status( $license_status ) { // Remove customer_email, customer_name, payment_id, ..., checksum keys from status array. @@ -176,6 +169,7 @@ public function clean_license_status( $license_status ) { * Get plugin license. * * @return \WP_Error|\WP_REST_Response + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns license REST routes. */ public function get_license() { $license_data = plugin( 'license' )->get_license_data(); @@ -193,6 +187,7 @@ public function get_license() { * @param \WP_REST_Request> $request Request object. * * @return \WP_Error|\WP_REST_Response + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns license REST routes. */ public function update_license_key( $request ) { $license_key = sanitize_text_field( $request->get_param( 'licenseKey' ) ); @@ -202,7 +197,7 @@ public function update_license_key( $request ) { if ( $old_key === $license_key ) { $license_status = plugin( 'license' )->get_license_status(); - return new WP_REST_Response( $this->clean_license_status( $license_status ), 200 ); + return new WP_REST_Response( [ 'status' => $this->clean_license_status( $license_status ) ], 200 ); } if ( plugin( 'license' )->is_license_active() ) { @@ -213,15 +208,12 @@ public function update_license_key( $request ) { $license_status = plugin( 'license' )->activate_license( $license_key ); - $response = [ - 'status' => $this->clean_license_status( $license_status ), - ]; - - if ( ! plugin()->is_pro_installed() ) { - $response['connectInfo'] = plugin( 'connect' )->get_connect_info( $license_key ); - } - - return new WP_REST_Response( $response, 200 ); + return new WP_REST_Response( + [ + 'status' => $this->clean_license_status( $license_status ), + ], + 200 + ); } catch ( \Exception $e ) { $message = __( 'Something went wrong, the license key could not be saved.', 'content-control' ); @@ -237,6 +229,7 @@ public function update_license_key( $request ) { * Remove plugin license key. * * @return \WP_Error|\WP_REST_Response + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns license REST routes. */ public function remove_license() { plugin( 'license' )->remove_license(); @@ -254,22 +247,22 @@ public function remove_license() { * @param WP_REST_Request> $request Request object. * * @return \WP_Error|\WP_REST_Response + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns license REST routes. */ public function activate_license( $request ) { - $license_key = sanitize_text_field( $request->get_param( 'licenseKey' ) ); + $license_key = $request->has_param( 'licenseKey' ) + ? sanitize_text_field( $request->get_param( 'licenseKey' ) ) + : null; try { $license_status = plugin( 'license' )->activate_license( $license_key ); - $response = [ - 'status' => $this->clean_license_status( $license_status ), - ]; - - if ( ! plugin()->is_pro_installed() ) { - $response['connectInfo'] = plugin( 'connect' )->get_connect_info( plugin( 'license' )->get_license_key() ); - } - - return new WP_REST_Response( $response, 200 ); + return new WP_REST_Response( + [ + 'status' => $this->clean_license_status( $license_status ), + ], + 200 + ); } catch ( \Exception $e ) { $message = __( 'Something went wrong, the license could not be activated.', 'content-control' ); @@ -281,40 +274,11 @@ public function activate_license( $request ) { } } - /** - * Activate pro plugin. - * - * @return \WP_Error|\WP_REST_Response - */ - public function activate_pro() { - // Check if its installed. - if ( ! plugin()->is_pro_installed() ) { - return new WP_Error( '404', __( 'Pro plugin is not installed.', 'content-control' ), [ 'status' => 404 ] ); - } - - // Check if its active. - if ( plugin()->is_pro_active() ) { - return new WP_Error( '404', __( 'Pro plugin is already active.', 'content-control' ), [ 'status' => 404 ] ); - } - - // // Activate pro plugin. - if ( ! function_exists( 'activate_plugin' ) ) { - require_once ABSPATH . 'wp-admin/includes/plugin.php'; - } - - $activate = \activate_plugin( 'content-control-pro/content-control-pro.php', '', false, true ); - - if ( is_wp_error( $activate ) ) { - return new WP_Error( '404', __( 'Something went wrong, the pro plugin could not be activated.', 'content-control' ), [ 'status' => 404 ] ); - } - - return new WP_REST_Response( true, 200 ); - } - /** * Deactivate plugin license. * * @return \WP_Error|\WP_REST_Response + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns license REST routes. */ public function deactivate_license() { try { @@ -336,6 +300,7 @@ public function deactivate_license() { * Get plugin license status. * * @return \WP_Error|\WP_REST_Response + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns license REST routes. */ public function get_status() { $license_status = plugin( 'license' )->get_license_status(); @@ -351,6 +316,7 @@ public function get_status() { * Refresh plugin license status. * * @return \WP_Error|\WP_REST_Response + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns license REST routes. */ public function refresh_license_status() { $license_status = plugin( 'license' )->get_license_status( true ); @@ -366,8 +332,9 @@ public function refresh_license_status() { * Check update settings permissions. * * @return bool + * @deprecated 2.7.0 Content Control Pro 1.3.0+ owns license REST routes. */ public function manage_license_permissions() { - return current_user_can( 'manage_options' ) || current_user_can( 'activate_plugins' ); + return current_user_can( plugin()->get_permission( 'manage_settings' ) ); } } diff --git a/content-control.php b/content-control.php index 58451193..3d58a6b1 100644 --- a/content-control.php +++ b/content-control.php @@ -7,6 +7,8 @@ * Author: Code Atlantic * Author URI: https://code-atlantic.com/?utm_campaign=plugin-info&utm_source=php-file-header&utm_medium=plugin-ui&utm_content=author-uri * Donate link: https://code-atlantic.com/donate/?utm_campaign=donations&utm_source=php-file-header&utm_medium=plugin-ui&utm_content=donate-link + * License: GPL-2.0-or-later + * License URI: https://www.gnu.org/licenses/gpl-2.0.html * Text Domain: content-control * * Minimum PHP: 7.4 diff --git a/inc/functions.php b/inc/functions.php index 8f0a8719..bcee52d3 100644 --- a/inc/functions.php +++ b/inc/functions.php @@ -7,6 +7,8 @@ namespace ContentControl; +defined( 'ABSPATH' ) || exit; + require_once 'functions/back-compat.php'; require_once 'functions/compatibility.php'; require_once 'functions/content.php'; diff --git a/inc/functions/content.php b/inc/functions/content.php index 27244cc3..2b366b30 100644 --- a/inc/functions/content.php +++ b/inc/functions/content.php @@ -9,6 +9,8 @@ namespace ContentControl; +defined( 'ABSPATH' ) || exit; + /** * Get post excerpt or tag content for a post. * diff --git a/inc/functions/install.php b/inc/functions/install.php index b4edce84..65fdc871 100644 --- a/inc/functions/install.php +++ b/inc/functions/install.php @@ -7,6 +7,8 @@ namespace ContentControl; +defined( 'ABSPATH' ) || exit; + /** * Returns an array of the default permissions. * diff --git a/inc/functions/options.php b/inc/functions/options.php index 83814aee..c72c3075 100644 --- a/inc/functions/options.php +++ b/inc/functions/options.php @@ -7,6 +7,8 @@ namespace ContentControl; +defined( 'ABSPATH' ) || exit; + /** * Get all options * diff --git a/inc/functions/post-restrictions.php b/inc/functions/post-restrictions.php index 5551fdea..dd940189 100644 --- a/inc/functions/post-restrictions.php +++ b/inc/functions/post-restrictions.php @@ -9,6 +9,8 @@ namespace ContentControl; +defined( 'ABSPATH' ) || exit; + /** * Check if post has restrictions. * diff --git a/inc/functions/protections.php b/inc/functions/protections.php index 8f9bc61b..e0eaa566 100644 --- a/inc/functions/protections.php +++ b/inc/functions/protections.php @@ -7,6 +7,8 @@ namespace ContentControl; +defined( 'ABSPATH' ) || exit; + /** * Redirect to the appropriate location. * diff --git a/inc/functions/term-restrictions.php b/inc/functions/term-restrictions.php index 7c2102c2..62365dbc 100644 --- a/inc/functions/term-restrictions.php +++ b/inc/functions/term-restrictions.php @@ -9,6 +9,8 @@ namespace ContentControl; +defined( 'ABSPATH' ) || exit; + /** * Check if term has restrictions. * diff --git a/inc/functions/widgets.php b/inc/functions/widgets.php index 6e6a2960..9150d957 100644 --- a/inc/functions/widgets.php +++ b/inc/functions/widgets.php @@ -8,6 +8,8 @@ namespace ContentControl\Widgets; +defined( 'ABSPATH' ) || exit; + /** * Retrieve data for a widget from options table. * diff --git a/package.json b/package.json index 516aa55f..119b5bf0 100644 --- a/package.json +++ b/package.json @@ -95,8 +95,10 @@ "pretest:unit:php": "wp-env start", "test:unit:php": "wp-env run phpunit /var/www/html/wp-content/plugins/content-control/vendor/bin/phpunit -c /var/www/html/wp-content/plugins/content-control/phpunit.xml.dist --verbose", "translate": "wp-pot --src './classes/**/*.php' --src '!./build/**/*.*' --src '!./vendor/**/*.*' --src '!./dist/**/*.*' --write=true --dest-file 'languages/content-control.pot' --package 'Content Control' --domain 'content-control' --last-translator 'Code Atlantic ' --team 'Code Atlantic ' --bug-report 'https://code-atlantic.com/contact/'", - "release:build": "composer install -o --no-dev --classmap-authoritative && npm run build:release && npm run copy-build", - "release:zip": "mv build content-control && zip -r content-control_$(node -p \"require('./package.json').version\").zip content-control && rm -rf content-control", + "verify:release-artifact": "node bin/verify-release-artifact.js", + "verify:release-tree": "node bin/verify-release-artifact.js --release-tree build", + "release:build": "composer install -o --no-dev --classmap-authoritative && npm run build:release && npm run copy-build && npm run verify:release-tree", + "release:zip": "mv build content-control && zip -r content-control_$(node -p \"require('./package.json').version\").zip content-control && rm -rf content-control && node bin/verify-release-artifact.js content-control_$(node -p \"require('./package.json').version\").zip", "release:start": "git flow release start", "release:finish": "git flow release finish", "release:publish": "git push origin master --tags && git push origin master", diff --git a/packages/core-data/src/hooks/use-license.ts b/packages/core-data/src/hooks/use-license.ts index 6e7f0498..84053beb 100644 --- a/packages/core-data/src/hooks/use-license.ts +++ b/packages/core-data/src/hooks/use-license.ts @@ -4,29 +4,28 @@ import { useDispatch, useSelect } from '@wordpress/data'; const useLicense = () => { // Fetch needed data from the @content-control/core-data & @wordpress/data stores. - const { - connectInfo, - licenseKey, - licenseStatus, - isSaving, - proWasActivated, - isActivatingPro, - } = useSelect( ( select ) => { - const storeSelect = select( licenseStore ); - return { - connectInfo: storeSelect.getConnectInfo(), - licenseKey: storeSelect.getLicenseKey(), - licenseStatus: storeSelect.getLicenseStatus(), - isSaving: - storeSelect.isDispatching( 'activateLicense' ) || - storeSelect.isDispatching( 'deactivateLicense' ) || - storeSelect.isDispatching( 'checkLicenseStatus' ) || - storeSelect.isDispatching( 'updateLicenseKey' ) || - storeSelect.isDispatching( 'removeLicense' ), - isActivatingPro: storeSelect.isDispatching( 'activatePro' ), - proWasActivated: storeSelect.hasDispatched( 'activatePro' ), - }; - }, [] ); + const { licenseKey, licenseStatus, isSaving, error } = useSelect( + ( select ) => { + const storeSelect = select( licenseStore ); + return { + licenseKey: storeSelect.getLicenseKey(), + licenseStatus: storeSelect.getLicenseStatus(), + isSaving: + storeSelect.isDispatching( 'activateLicense' ) || + storeSelect.isDispatching( 'deactivateLicense' ) || + storeSelect.isDispatching( 'checkLicenseStatus' ) || + storeSelect.isDispatching( 'updateLicenseKey' ) || + storeSelect.isDispatching( 'removeLicense' ), + error: + storeSelect.getDispatchError( 'activateLicense' ) || + storeSelect.getDispatchError( 'deactivateLicense' ) || + storeSelect.getDispatchError( 'checkLicenseStatus' ) || + storeSelect.getDispatchError( 'updateLicenseKey' ) || + storeSelect.getDispatchError( 'removeLicense' ), + }; + }, + [] + ); // Grab needed action dispatchers. const { @@ -35,7 +34,6 @@ const useLicense = () => { checkLicenseStatus, updateLicenseKey, removeLicense, - activatePro, } = useDispatch( licenseStore ); // Create some helper variables. @@ -154,7 +152,6 @@ const useLicense = () => { }, [ licenseStatus?.price_id ] ); return { - connectInfo, licenseKey, licenseStatus, licenseLevel, @@ -163,11 +160,9 @@ const useLicense = () => { checkLicenseStatus, updateLicenseKey, removeLicense, - activatePro, getLicenseStatusName, isSaving, - isActivatingPro, - proWasActivated, + error, isLicenseKeyValid, isLicenseActive, isLicenseDeactivated, diff --git a/packages/core-data/src/index.ts b/packages/core-data/src/index.ts index b0ca735f..bbeb421c 100644 --- a/packages/core-data/src/index.ts +++ b/packages/core-data/src/index.ts @@ -9,6 +9,7 @@ declare global { const contentControlCoreData: { currentSettings: Settings; + legacyProLicense: boolean; }; } diff --git a/packages/core-data/src/license/actions.ts b/packages/core-data/src/license/actions.ts index 8accef4a..15f1df17 100644 --- a/packages/core-data/src/license/actions.ts +++ b/packages/core-data/src/license/actions.ts @@ -19,7 +19,6 @@ import { resolveSelect } from '@wordpress/data'; const { ACTIVATE_LICENSE, - CONNECT_SITE, DEACTIVATE_LICENSE, UPDATE_LICENSE_KEY, REMOVE_LICENSE, @@ -75,20 +74,12 @@ export function* activateLicense( licenseKey?: LicenseKey ) { ); if ( result ) { - const { status, connectInfo } = result; + const { status } = result; // thing was successfully updated so return the action object that will // update the saved thing in the state. yield changeActionStatus( actionName, Status.Success ); - if ( connectInfo !== undefined ) { - return { - type: CONNECT_SITE, - licenseStatus: status, - connectInfo, - }; - } - return { type: ACTIVATE_LICENSE, licenseStatus: status, @@ -325,51 +316,6 @@ export function* removeLicense() { } } -/** - * Activate pro version if installed. - * - * @return {Generator} Action object. - */ -export function* activatePro() { - const actionName = 'activatePro'; - - try { - yield changeActionStatus( actionName, Status.Resolving ); - - const result: boolean = yield fetch( - getResourcePath( 'activate-pro' ), - { - method: 'POST', - } - ); - - if ( result ) { - // thing was successfully updated so return the action object that will - // update the saved thing in the state. - return changeActionStatus( actionName, Status.Success ); - } - - // if execution arrives here, then thing didn't update in the state so return - // action object that will add an error to the state about this. - // returning an action object that will save the update error to the state. - return changeActionStatus( - actionName, - Status.Error, - __( - 'An error occurred, license were not saved.', - 'content-control' - ) - ); - } catch ( error ) { - // returning an action object that will save the update error to the state. - return changeActionStatus( - actionName, - Status.Error, - getErrorMessage( error ) - ); - } -} - /** * Hydrate license data. * diff --git a/packages/core-data/src/license/constants.ts b/packages/core-data/src/license/constants.ts index ad0172ea..25d806d2 100644 --- a/packages/core-data/src/license/constants.ts +++ b/packages/core-data/src/license/constants.ts @@ -4,7 +4,6 @@ export const STORE_NAME = 'content-control/license'; export const ACTION_TYPES = { ACTIVATE_LICENSE: 'ACTIVATE_LICENSE', - CONNECT_SITE: 'CONNECT_SITE', DEACTIVATE_LICENSE: 'DEACTIVATE_LICENSE', REMOVE_LICENSE: 'REMOVE_LICENSE', UPDATE_LICENSE_KEY: 'UPDATE_LICENSE_KEY', diff --git a/packages/core-data/src/license/reducer.ts b/packages/core-data/src/license/reducer.ts index d052e954..e8d3b81a 100644 --- a/packages/core-data/src/license/reducer.ts +++ b/packages/core-data/src/license/reducer.ts @@ -1,16 +1,10 @@ import { ACTION_TYPES } from './constants'; -import type { - License, - LicenseConnect, - LicenseState, - LicenseStore, -} from './types'; +import type { License, LicenseState, LicenseStore } from './types'; import type { Statuses } from '../constants'; const { ACTIVATE_LICENSE, - CONNECT_SITE, DEACTIVATE_LICENSE, REMOVE_LICENSE, UPDATE_LICENSE_KEY, @@ -25,7 +19,6 @@ interface ActionPayloadTypes { license: License; licenseKey: License[ 'key' ]; licenseStatus: License[ 'status' ]; - connectInfo: LicenseConnect; // Boilerplate. actionName: LicenseStore[ 'ActionNames' ]; status: Statuses; @@ -39,7 +32,6 @@ const reducer = ( license, licenseKey, licenseStatus, - connectInfo, // Boilerplate actionName, status, @@ -58,16 +50,6 @@ const reducer = ( }, }; - case CONNECT_SITE: - return { - ...state, - license: { - ...state.license, - status: licenseStatus, - }, - connectInfo, - }; - case UPDATE_LICENSE_KEY: return { ...state, diff --git a/packages/core-data/src/license/selectors.ts b/packages/core-data/src/license/selectors.ts index ac2feb3b..f507a713 100644 --- a/packages/core-data/src/license/selectors.ts +++ b/packages/core-data/src/license/selectors.ts @@ -7,7 +7,6 @@ import type { LicenseStatus, LicenseState, LicenseStore, - LicenseConnect, } from './types'; /** @@ -43,16 +42,6 @@ export const getLicenseStatus = ( state: LicenseState ): LicenseStatus => { }; }; -/** - * Get connect info for pro upgrade. - * - * @param state LicenseState Current state. - * @return {LicenseConnect|undefined} Current license status. - */ -export const getConnectInfo = ( - state: LicenseState -): LicenseConnect | undefined => state.connectInfo; - /** * Get current status for dispatched action. * diff --git a/packages/core-data/src/license/types.ts b/packages/core-data/src/license/types.ts index 10c5fa3b..eeee8dd3 100644 --- a/packages/core-data/src/license/types.ts +++ b/packages/core-data/src/license/types.ts @@ -27,22 +27,14 @@ export type License = { status: LicenseStatus; }; -export type LicenseConnect = { - url: string; - back_url: string; -}; - export type LicenseStatusResponse = { status: LicenseStatus; }; -export type LicenseActivationResponse = LicenseStatusResponse & { - connectInfo?: LicenseConnect; -}; +export type LicenseActivationResponse = LicenseStatusResponse; export type LicenseState = { license: License; - connectInfo?: LicenseConnect; // Boilerplate dispatchStatus?: { [ Property in LicenseStore[ 'ActionNames' ] ]?: { diff --git a/packages/data/src/index.ts b/packages/data/src/index.ts index 2cd16792..62bfb180 100644 --- a/packages/data/src/index.ts +++ b/packages/data/src/index.ts @@ -29,7 +29,9 @@ declare module '@wordpress/data' { const registry = createRegistry( {} ); registry.register( coreStore ); -registry.register( licenseStore ); +if ( contentControlCoreData.legacyProLicense ) { + registry.register( licenseStore ); +} registry.register( settingsStore ); registry.register( restrictionsStore ); registry.register( urlSearchStore ); diff --git a/packages/settings-page/src/App.tsx b/packages/settings-page/src/App.tsx index ce657e1c..bbfd5822 100644 --- a/packages/settings-page/src/App.tsx +++ b/packages/settings-page/src/App.tsx @@ -7,8 +7,6 @@ import { upgrade } from '@content-control/icons'; import { useEffect, useMemo } from '@wordpress/element'; import { Icon, Popover, SlotFillProvider } from '@wordpress/components'; -import { useLicense } from '@content-control/core-data'; - import Header from './header'; import RestrictionsView from './restrictions-view'; import SettingsView from './settings-view'; @@ -23,9 +21,10 @@ const { }, } = contentControlSettingsPage; -const App = () => { - const { isLicenseActive, isLicenseKeyValid, licenseLevel } = useLicense(); +const isProActive = !! contentControlSettingsPage.isProActivated; +const licenseLevel = contentControlSettingsPage.licenseLevel; +const App = () => { const [ { view = 'restrictions' }, setParams ] = useQueryParams( { tab: StringParam, view: StringParam, @@ -82,45 +81,56 @@ const App = () => { title: ( <> - { ! isLicenseActive - ? __( 'Upgrade to Pro', 'content-control' ) - : __( 'License Status', 'content-control' ) } + { isProActive + ? __( 'License & Updates', 'content-control' ) + : __( 'Upgrade to Pro', 'content-control' ) } ), - pageTitle: __( - 'Content Control - Upgrade to Pro', - 'content-control' - ), - heading: __( - 'Content Control - Upgrade to Pro', - 'content-control' - ), - href: ! isLicenseKeyValid - ? 'https://contentcontrolplugin.com/pricing/?utm_campaign=upgrade-to-pro&utm_source=plugin-settings-page&utm_medium=plugin-ui&utm_content=main-menu-upgrade-button' + pageTitle: isProActive + ? __( + 'Content Control - License & Updates', + 'content-control' + ) + : __( + 'Content Control - Upgrade to Pro', + 'content-control' + ), + heading: isProActive + ? __( + 'Content Control - License & Updates', + 'content-control' + ) + : __( + 'Content Control - Upgrade to Pro', + 'content-control' + ), + href: isProActive + ? undefined + : 'https://contentcontrolplugin.com/pricing/?utm_campaign=upgrade-to-pro&utm_source=plugin-settings-page&utm_medium=plugin-ui&utm_content=main-menu-upgrade-button', + target: isProActive ? undefined : '_blank', + onClick: isProActive + ? () => { + setParams( { + view: 'settings', + tab: 'license-and-updates', + } ); + + // Return false prevents tab component from rendering. + return false; + } : undefined, - target: '_blank', - onClick: () => { - setParams( { - view: 'settings', - tab: 'license-and-updates', - } ); - - // Return false prevents tab component from rendering. - return false; - }, }, ], { view, setParams, - isLicenseActive, - isLicenseKeyValid, + isProActive, licenseLevel, } ) as TabComponent[]; return _views; - }, [ isLicenseActive, isLicenseKeyValid, licenseLevel, setParams, view ] ); + }, [ setParams, view ] ); // Assign the current view from the list of views. const currentView = views.find( ( _view ) => _view.name === view ); diff --git a/packages/settings-page/src/index.tsx b/packages/settings-page/src/index.tsx index fe8a501c..ea4fc5b2 100644 --- a/packages/settings-page/src/index.tsx +++ b/packages/settings-page/src/index.tsx @@ -39,8 +39,10 @@ declare global { [ key: string ]: boolean; }; version: string; - isProInstalled?: '1' | ''; - isProActivated?: '1' | ''; + isProInstalled?: boolean; + isProActivated?: boolean; + legacyProLicense?: boolean; + licenseLevel?: number; }; } diff --git a/packages/settings-page/src/settings-view/index.tsx b/packages/settings-page/src/settings-view/index.tsx index e11011ee..4c9a99c3 100644 --- a/packages/settings-page/src/settings-view/index.tsx +++ b/packages/settings-page/src/settings-view/index.tsx @@ -44,11 +44,15 @@ const SettingsView = () => { title: __( 'Block Controls', 'content-control' ), comp: BlockControlsTab, }, - { - name: 'license-and-updates', - title: __( 'Licensing', 'content-control' ), - comp: UpgradeTab, - }, + ...( contentControlSettingsPage.isProActivated + ? [ + { + name: 'license-and-updates', + title: __( 'License & Updates', 'content-control' ), + comp: UpgradeTab, + }, + ] + : [] ), ] ) as TabComponent[]; diff --git a/packages/settings-page/src/settings-view/tabs/upgrade/editor.scss b/packages/settings-page/src/settings-view/tabs/upgrade/editor.scss deleted file mode 100644 index 0d08a727..00000000 --- a/packages/settings-page/src/settings-view/tabs/upgrade/editor.scss +++ /dev/null @@ -1,229 +0,0 @@ -.license-status-bubble { - background-color: #00a32a; - color: #fff; - border-radius: 100px; - line-height: 1.5em; - display: inline-block; - margin-left: 12px; - padding: 0 8px; -} - -.content-control__upgrade-notice { - // max-width: 600px; - - .upgrade-notice__title { - margin: 0; - } - - .upgrade-notice__description { - font-size: 14px; - font-weight: 400; - margin: 0 0 8px; - - > span { - font-size: 23px; - vertical-align: middle; - } - } - - .upgrade-features { - font-size: 15px; - - p { - // font-weight: 400; - // margin: 0 0 8px; - - strong { - font-weight: 900; - } - - a { - font-weight: 700; - } - } - - h3 { - font-size: 1.2em; - margin-bottom: 1em; - } - - .upgrade-notice__feature { - background: rgba(0, 124, 186, 0.1); - border-radius: 3px; - padding: 20px; - margin: 0 0 20px; - } - - > * { - // font-size: 14px; - color: #344054; - } - - ul { - margin: 0; - li { - margin-bottom: 16px; - line-height: 1.4; - vertical-align: baseline; - - &:last-child { - margin-bottom: 0; - } - - font-weight: 300; - - svg { - margin: -2px 2px -8px 0; - - path { - fill: #007cba; - } - } - } - } - } -} - -.content-control-license-controls { - max-width: 600px; - display: flex; - align-items: left; - gap: 12px; - margin-bottom: 10px; - justify-content: space-between; - - .components-base-control { - flex: 1; - } - - > * { - // Fixes vertical aligntments of buttons. - margin-top: auto; - } - - .components-base-control__label { - span { - font-weight: 400; - } - - strong { - font-weight: 700; - } - } - - .components-base-control__field { - margin-bottom: 0; - - .components-text-control__input { - height: 42px; - min-width: 200px; - border-radius: 3px; - } - } - - .components-spinner { - width: 24px; - height: 24px; - // margin: 0; - } - - .components-button-group { - min-width: max-content; - display: flex; - gap: 10px; - - .components-button { - height: 42px; - padding: 0 2em; - border-radius: 3px; - vertical-align: middle; - border: 1px solid #d0d5dd; - - &:not(:focus) { - box-shadow: none; - } - - // margin: 0; - - .components-spinner { - margin: 0 0 0 10px; - width: 1.25em; - height: 1.25em; - } - - &:disabled { - opacity: 0.5; - } - } - } - - .activate-license { - border-color: currentColor; - box-shadow: none; - span { - color: #fff; - } - - &:disabled { - span { - color: #fff; - } - } - } - - .deactivate-license { - } - - .remove-license { - } - - &--active { - .activate-license { - display: none; - } - } - - &--expired { - .activate-license { - display: none; - } - } - - &--missing { - .deactivate-license, - .check-license-status, - .remove-license { - display: none; - } - } - - &--deactivated { - .deactivate-license { - display: none; - } - } - - &--disabled { - } - - &--error { - } - - &--unknown { - } -} - -.content-control-license-connect-notice { - font-size: 1.2em; - - .components-popover__content { - min-width: max-content; - padding: 2em 3em; - margin-top: -10vh; - - p { - font-size: 1em; - margin: 0; - } - } -} diff --git a/packages/settings-page/src/settings-view/tabs/upgrade/index.tsx b/packages/settings-page/src/settings-view/tabs/upgrade/index.tsx index e10a6a6c..3bcfbcb6 100644 --- a/packages/settings-page/src/settings-view/tabs/upgrade/index.tsx +++ b/packages/settings-page/src/settings-view/tabs/upgrade/index.tsx @@ -4,41 +4,38 @@ import { licenseKey } from '@content-control/icons'; import { useLicense } from '@content-control/core-data'; import Section from '../../section'; - import LicenseSection from './license'; import type { IconProps } from '@wordpress/icons/build-types/icon'; import type { TabComponent } from '../../../types'; -// const { pluginUrl } = contentControlSettingsPage; - -addFilter( - 'contentControl.settingsPage.upgradeSections', - 'content-control/general-settings/license-options', - ( sections: { [ key: string ]: any }[] ) => { - const { isLicenseActive } = useLicense(); +// Keep the license management field available only while an active pre-1.3.0 +// Pro release still depends on Core. Pro 1.3.0+ owns and registers its own UI. +if ( contentControlSettingsPage.legacyProLicense ) { + addFilter( + 'contentControl.settingsPage.upgradeSections', + 'content-control/general-settings/license-options', + ( sections: { [ key: string ]: any }[] ) => { + const { isLicenseActive } = useLicense(); - return [ - ...sections, - { - name: 'license', - title: __( 'Pro Licensing', 'content-control' ), - badge: ( - <> - { isLicenseActive && ( - - { __( 'Activated', 'content-control' ) } - - ) } - - ), - icon: licenseKey, - comp: LicenseSection, - }, - ]; - }, - 5 -); + return [ + ...sections, + { + name: 'license', + title: __( 'Pro Licensing', 'content-control' ), + badge: isLicenseActive ? ( + + { __( 'Activated', 'content-control' ) } + + ) : undefined, + icon: licenseKey, + comp: LicenseSection, + }, + ]; + }, + 5 + ); +} // Filtered & mappable list of TabComponent definitions. type SectionList = ( TabComponent & { icon: IconProps[ 'icon' ] } )[]; diff --git a/packages/settings-page/src/settings-view/tabs/upgrade/license.scss b/packages/settings-page/src/settings-view/tabs/upgrade/license.scss new file mode 100644 index 00000000..129e0a73 --- /dev/null +++ b/packages/settings-page/src/settings-view/tabs/upgrade/license.scss @@ -0,0 +1,47 @@ +.license-status-bubble { + background-color: #00a32a; + color: #fff; + border-radius: 100px; + line-height: 1.5; + margin-left: 12px; + padding: 0 8px; +} + +.content-control-legacy-license { + .content-control-license-controls { + display: flex; + align-items: flex-end; + flex-wrap: wrap; + gap: 12px; + max-width: 960px; + margin: 18px 0 10px; + + .components-base-control { + flex: 1 1 320px; + margin-bottom: 0; + } + + .components-base-control__field { + margin-bottom: 0; + } + + .components-text-control__input, + .components-button { + min-height: 40px; + } + + .components-button-group { + display: flex; + flex-wrap: wrap; + gap: 8px; + } + + .components-spinner { + margin: 8px 0; + } + } + + .content-control-license-status { + margin-bottom: 0; + } +} diff --git a/packages/settings-page/src/settings-view/tabs/upgrade/license.tsx b/packages/settings-page/src/settings-view/tabs/upgrade/license.tsx index dbe6060a..862c4684 100644 --- a/packages/settings-page/src/settings-view/tabs/upgrade/license.tsx +++ b/packages/settings-page/src/settings-view/tabs/upgrade/license.tsx @@ -1,36 +1,34 @@ -import './editor.scss'; +import './license.scss'; import classNames from 'classnames'; -import { trash } from '@wordpress/icons'; +import { useEffect, useState } from '@wordpress/element'; import { __, sprintf } from '@wordpress/i18n'; -import { useEffect, useRef, useState } from '@wordpress/element'; import { Button, ButtonGroup, + Notice, TextControl, - Spinner, - Icon, - Popover, } from '@wordpress/components'; -import { useLicense } from '@content-control/core-data'; - -import UpgradeFeatures from './upgrade-features'; - -import type { LicenseKey } from '@content-control/core-data'; - -const LicenseTab = () => { +import { useLicense, type LicenseKey } from '@content-control/core-data'; + +/** + * Temporary license controls for active Pro versions older than 1.3.0. + * + * This intentionally contains no installer, connection, webhook, or package + * delivery behavior. It only exposes the license operations those Pro releases + * still use for authenticated update checks. + */ +const LicenseSection = () => { const { - connectInfo, licenseKey, licenseStatus, isSaving, + error, activateLicense, deactivateLicense, checkLicenseStatus, + updateLicenseKey, removeLicense, - activatePro, - isActivatingPro, - proWasActivated, getLicenseStatusName, isLicenseKeyValid, isLicenseActive, @@ -39,443 +37,188 @@ const LicenseTab = () => { isLicenseExpired, isLicenseOverQuota, isLicenseDisabled, - hasError, } = useLicense(); - const { expires, error_message: errorMessage } = licenseStatus; const [ value, setValue ] = useState< LicenseKey >( licenseKey ); - const [ isActivating, setIsActivating ] = useState( false ); - const [ isInstalling, setIsInstalling ] = useState( false ); - - const connectPopup = useRef< Window | null >( null ); - const [ showConnectNotice, setShowConnectNotice ] = useState( false ); - - const [ proStatus, setProStatus ] = useState< { - installed?: boolean; - activated?: boolean; - } >( { - installed: contentControlSettingsPage?.isProInstalled === '1', - activated: - contentControlSettingsPage?.isProInstalled === '1' && - contentControlSettingsPage?.isProActivated === '1', - } ); - const keyHasChanged = value !== licenseKey; useEffect( () => { - if ( typeof connectInfo === 'undefined' ) { - connectPopup.current?.close(); - connectPopup.current = null; + setValue( licenseKey ); + }, [ licenseKey ] ); + + const activate = () => { + if ( keyHasChanged ) { + updateLicenseKey( value ); return; } - setShowConnectNotice( true ); - - // Open a new sized window to connect to the license store. - connectPopup.current = window.open( - connectInfo.url, - 'content-control-license-connect', - 'width=580,height=600' - ); - - // Listen for the popup to close and check the license status. - const interval = setInterval( () => { - if ( connectPopup.current?.closed ) { - clearInterval( interval ); - checkLicenseStatus(); - setShowConnectNotice( false ); - - // Wait a second for the license status to update and then reload the page. - setTimeout( () => { - window.location.reload(); - }, 1000 ); - } - }, 1000 ); - }, [ connectInfo, checkLicenseStatus ] ); - - useEffect( () => { - if ( proWasActivated ) { - setTimeout( () => { - window.location.reload(); - }, 1000 ); - } - }, [ proWasActivated ] ); + activateLicense(); + }; - // Listen for changes from the license store and update the local state. - useEffect( () => { - if ( keyHasChanged ) { - setValue( licenseKey ); + const formattedExpiry = () => { + if ( 'lifetime' === licenseStatus.expires ) { + return __( 'and never expires', 'content-control' ); } - }, [ licenseKey, keyHasChanged ] ); - useEffect( () => { - if ( isActivating && ! isSaving ) { - setIsActivating( false ); - } - }, [ isSaving, isActivating ] ); + const expiry = new Date( licenseStatus.expires ); - useEffect( () => { - if ( isInstalling && ! isSaving ) { - setIsInstalling( false ); - setProStatus( { - ...proStatus, - installed: true, - } ); - } - }, [ isSaving, isInstalling, proStatus ] ); + return Number.isNaN( expiry.getTime() ) + ? '' + : sprintf( + /* translators: %s: license expiration date. */ + __( 'until %s', 'content-control' ), + expiry.toLocaleDateString() + ); + }; const statusMessage = () => { if ( isLicenseMissing ) { - // No lincense key has been entered. - return sprintf( - // translators: 1: opening a tag, 2: closing a tag. - __( - 'Enter your license key to activate. If you do not have a license key, you can %1$spurchase one here%2$s', - 'content-control' - ), - '', - '' + return __( + 'Enter your license key to activate it.', + 'content-control' ); } if ( isLicenseActive ) { - // The license key is active. return sprintf( - // translators: 1: date - __( - 'Your license key is active%1$s. Thank you for supporting Content Control!', - 'content-control' - ), - // format date as MM-DD-YYYY - expires !== 'lifetime' - ? ' until ' + new Date( expires ).toLocaleDateString() - : ' and never expires' + /* translators: %s: human-readable license expiration. */ + __( 'Your license is active %s.', 'content-control' ), + formattedExpiry() ); } if ( isLicenseExpired ) { - // The license key has expired. - return sprintf( - // translators: 1: date, 2: opening a tag, 3: closing a tag. - __( - 'Your license key has expired on %1$s. Please %2$srenew your license$3$s to continue receiving updates and support.', - 'content-control' - ), - new Date( expires ).toLocaleDateString(), - '', - '' + return __( + 'Your license has expired. Renew it to continue receiving updates and support.', + 'content-control' ); } if ( isLicenseOverQuota ) { - // The license key has reached its site limit. - return sprintf( - // translators: 1: opening a tag, 2: closing a tag, 3: opening a tag, 4: closing a tag. - __( - 'Your license key has reached its site limit. %1$sUpgrade your license%2$s to add more sites, or %3$slog in%4$s to manage current activations.', - 'content-control' - ), - '', - '', - '', - '' + return __( + 'Your license has reached its site activation limit.', + 'content-control' ); } if ( isLicenseDeactivated ) { - // The license key is deactivated. return __( - 'Your license key is currently deactivated. Click the button above to activate now.', + 'Your license is deactivated on this site.', 'content-control' ); } if ( isLicenseDisabled ) { - // The license key has been disabled. return __( - 'Your license key has been disabled. Please contact support.', + 'Your license has been disabled. Please contact support.', 'content-control' ); } - if ( hasError ) { - // The license key is not active. - return sprintf( - // translators: 1: error message. - __( - 'Your license key failed to activate with the following error: %1$s', - 'content-control' - ), - errorMessage - ); - } - - return __( - 'There was an error with your license key. Please check your key and try again.', - 'content-control' + return ( + licenseStatus.error_message || + __( 'The license status could not be verified.', 'content-control' ) ); }; - const buttonVariant = 'tertiary'; - - const showActivateButton = proStatus.installed && ! proStatus.activated; + const displayedValue = isLicenseKeyValid + ? value.replace( + /^(.{3})(.*)(.{5})$/, + ( _match, start, middle, end ) => + start + middle.replace( /./g, '*' ) + end + ) + : value; return ( - <> - { showConnectNotice && ( - -

- { __( - 'Please wait while we connect to the license store…', - 'content-control' - ) } -

-
+
+

+ { __( + 'Manage the license used by your installed Content Control Pro version. Pro updates continue to use this key until Pro 1.3.0 or later takes over licensing.', + 'content-control' + ) } +

+ + { error && ( + + { error } + ) } -
-

- { __( - 'Enter your Content Control License Key', +
+ - -

😄', - 'content-control' - ) - : __( - 'You are currently using Content Control Pro. Thanks for supporting us! 😄', - 'content-control' - ), - } } + placeholder={ __( + 'Paste or enter your license key', + 'content-control' + ) } + value={ displayedValue } + onChange={ setValue } + readOnly={ isSaving || isLicenseKeyValid } + disabled={ isSaving } /> -

', - '' - ), - } } - /> -

- - p1 + p2.replace( /./g, '*' ) + p3 - ) - : value - } - maxLength={ 32 } - width={ 500 } - onChange={ setValue } - readOnly={ isActivating || isLicenseKeyValid } - tabIndex={ isActivating || isLicenseKeyValid ? -1 : 0 } - onPaste={ ( event ) => { - event.preventDefault(); - const pastedText = - event.clipboardData.getData( 'text' ); - if ( ! isSaving ) { - setIsActivating( true ); - activateLicense( pastedText ); - setValue( pastedText ); - } - } } - /> - - { isLicenseActive && ( - <> - { ! proStatus.installed && ( - - ) } - { showActivateButton && ( - - ) } - - ) } + + { ! isLicenseActive && ! isLicenseExpired && ( + ) } + + { isLicenseActive && ( - { /* */ } - - -
-
+ { __( 'Check status', 'content-control' ) } + + + + - { ! isLicenseKeyValid && ( - <> -
-
- - + { isSaving && ( + { __( 'Saving…', 'content-control' ) } ) }
- { /*
{ JSON.stringify( licenseStatus, null, 2 ) }
*/ } - +

+ { statusMessage() } +

+
); }; -export default LicenseTab; +export default LicenseSection; diff --git a/packages/settings-page/src/types/index.ts b/packages/settings-page/src/types/index.ts index 54232fba..02981074 100644 --- a/packages/settings-page/src/types/index.ts +++ b/packages/settings-page/src/types/index.ts @@ -7,4 +7,6 @@ export type TabComponent = { heading: string; comp?: () => JSX.Element; onClick?: () => void | false; + href?: string; + target?: string; }; diff --git a/readme.txt b/readme.txt index 63253cf1..d8506afd 100644 --- a/readme.txt +++ b/readme.txt @@ -5,10 +5,10 @@ Author URI: https://contentcontrolplugin.com/?utm_campaign=plugin-info&utm_sourc Donate link: https://code-atlantic.com/donate/?utm_campaign=donations&utm_source=readme-header&utm_medium=plugin-ui&utm_content=donate-link Tags: membership, access control, members only, content restriction, maintenance mode Requires at least: 6.2 -Tested up to: 6.8.1 +Tested up to: 7.0 Stable tag: 2.6.5 Requires PHP: 7.4 -License: GPLv3 (or later) +License: GPL-2.0-or-later Restrict content based on login status, user roles, device type & more. Monetize your content with a paywall or members-only content. @@ -417,4 +417,4 @@ add_filter( 'content_control/query_filter_init_hook', function () { = v1.0.0 = -- Initial Release \ No newline at end of file +- Initial Release diff --git a/tests/unit/Classes/ProCompatibility.php b/tests/unit/Classes/ProCompatibility.php new file mode 100644 index 00000000..2f7034bd --- /dev/null +++ b/tests/unit/Classes/ProCompatibility.php @@ -0,0 +1,65 @@ +assertTrue( $core->is_legacy_pro_active() ); + + $GLOBALS['content_control_test_pro_version'] = '1.3.0'; + $this->assertFalse( $core->is_legacy_pro_active() ); + + $GLOBALS['content_control_test_pro_version'] = '1.4.0'; + $this->assertFalse( $core->is_legacy_pro_active() ); + + $core->pro_active = false; + $GLOBALS['content_control_test_pro_version'] = '1.2.1'; + $this->assertFalse( $core->is_legacy_pro_active() ); + } + + /** + * The incompatible Pro endpoint is removed without disturbing other routes. + */ + public function test_legacy_installer_route_is_removed() { + $controller = new RestAPI( new ProCompatibilityCoreFixture() ); + $endpoints = [ + '/content-control/v2/addons/install' => [ [ 'methods' => 'POST' ] ], + '/content-control/v2/addons' => [ [ 'methods' => 'GET' ] ], + ]; + + $filtered = $controller->disable_legacy_pro_installer_route( $endpoints ); + + $this->assertArrayNotHasKey( '/content-control/v2/addons/install', $filtered ); + $this->assertArrayHasKey( '/content-control/v2/addons', $filtered ); + } +} diff --git a/tests/unit/Fixtures/ProCompatibilityCoreFixture.php b/tests/unit/Fixtures/ProCompatibilityCoreFixture.php new file mode 100644 index 00000000..bb0d84ed --- /dev/null +++ b/tests/unit/Fixtures/ProCompatibilityCoreFixture.php @@ -0,0 +1,38 @@ +pro_active; + } +} diff --git a/tests/unit/Fixtures/ProConfig.php b/tests/unit/Fixtures/ProConfig.php new file mode 100644 index 00000000..ce370679 --- /dev/null +++ b/tests/unit/Fixtures/ProConfig.php @@ -0,0 +1,18 @@ + { + test( 'accepts the assembled runtime files in a release ZIP', () => { + const temporaryRoot = fs.mkdtempSync( + path.join( os.tmpdir(), 'content-control-release-verifier-' ) + ); + const pluginRoot = path.join( temporaryRoot, 'content-control' ); + const zipPath = path.join( temporaryRoot, 'content-control.zip' ); + + try { + for ( const relativePath of [ + 'content-control.php', + 'readme.txt', + 'dist/settings-page.js', + 'dist/settings-page.css', + 'vendor/autoload.php', + 'vendor/composer/autoload_real.php', + 'vendor/composer/installed.json', + ] ) { + const filePath = path.join( pluginRoot, relativePath ); + fs.mkdirSync( path.dirname( filePath ), { recursive: true } ); + fs.writeFileSync( filePath, ' { + expect( + verifyArchiveStructure( [ + 'content-control/', + 'content-control/classes/Rules.php', + 'content-control/classes/Rules.php', + 'decoy/classes/Rules.php', + 'content-control/../private.php', + ] ) + ).toEqual( + expect.arrayContaining( [ + 'duplicate archive path: content-control/classes/Rules.php', + 'unexpected archive root: decoy/classes/Rules.php', + 'unsafe archive path: content-control/../private.php', + ] ) + ); + } ); + + test( 'rejects mismatched and non-regular archive entry types', () => { + expect( + verifyArchiveEntryTypes( + [ + 'content-control/', + 'content-control/content-control.php', + 'content-control/linked.php', + ], + [ '-', 'd', 'l' ] + ) + ).toEqual( + expect.arrayContaining( [ + 'archive entry type/name mismatch in content-control/', + 'archive entry type/name mismatch in content-control/content-control.php', + 'forbidden archive entry type in content-control/linked.php', + ] ) + ); + } ); + + test( 'requires runtime files and rejects repository-only paths', () => { + const failures = verifyReleaseManifest( [ + 'content-control/content-control.php', + 'content-control/readme.txt', + 'content-control/vendor/autoload.php', + 'content-control/tests/fixture.php', + ] ); + + expect( failures ).toEqual( + expect.arrayContaining( [ + 'missing release path: dist/settings-page.js', + 'missing release path: dist/settings-page.css', + 'forbidden release path: tests/fixture.php', + ] ) + ); + } ); + + test( 'allows only the runtime Composer records copied by the build', () => { + expect( + verifyReleaseManifest( [ + 'content-control/content-control.php', + 'content-control/readme.txt', + 'content-control/dist/settings-page.js', + 'content-control/dist/settings-page.css', + 'content-control/vendor/', + 'content-control/vendor/autoload.php', + 'content-control/vendor/composer/', + 'content-control/vendor/composer/autoload_real.php', + 'content-control/vendor/composer/installed.json', + ] ) + ).toEqual( [] ); + + expect( + verifyReleaseManifest( [ + 'content-control/vendor/library/source.php', + ] ) + ).toContain( 'forbidden release path: vendor/library/source.php' ); + } ); + + test( 'verifies an assembled release tree without inspecting implementation names', () => { + const temporaryRoot = fs.mkdtempSync( + path.join( os.tmpdir(), 'content-control-release-tree-' ) + ); + + try { + for ( const relativePath of [ + 'content-control.php', + 'readme.txt', + 'dist/settings-page.js', + 'dist/settings-page.css', + 'vendor/autoload.php', + ] ) { + const filePath = path.join( temporaryRoot, relativePath ); + fs.mkdirSync( path.dirname( filePath ), { recursive: true } ); + fs.writeFileSync( filePath, 'release fixture' ); + } + + expect( verifyReleaseTree( temporaryRoot ).failures ).toEqual( [] ); + } finally { + fs.rmSync( temporaryRoot, { recursive: true, force: true } ); + } + } ); +} ); diff --git a/uninstall.php b/uninstall.php index 82a47c23..e1b413d0 100644 --- a/uninstall.php +++ b/uninstall.php @@ -7,6 +7,8 @@ namespace ContentControl; +defined( 'WP_UNINSTALL_PLUGIN' ) || exit; + /** * Uninstall Content Control * @@ -17,7 +19,6 @@ function remove_wp_options_data() { 'content_control_license', 'content_control_pro_activation_date', 'content_control_installed_on', - 'content_control_connect_token', 'content_control_version', 'content_control_data_versioning', 'content_control_debug_log_token', // delete log first.