* @since 1.50.0 */ namespace AdvancedAds\License; use AdvancedAds\Constants; use AdvancedAds\Framework\Interfaces\Routes_Interface; use AdvancedAds\License\License; use AdvancedAds\Updater\Auto_Update; use AdvancedAds\Updater\Installer; use AdvancedAds\Utilities\Addons; use AdvancedAds\Utilities\Conditional; use WP_Error; use WP_REST_Request; use WP_REST_Response; use WP_REST_Server; defined( 'ABSPATH' ) || exit; /** * License REST route. */ class Routes implements Routes_Interface { /** * Registers routes with WordPress. * * @return void */ public function register_routes(): void { register_rest_route( Constants::REST_BASE, '/licenses', [ 'methods' => WP_REST_Server::READABLE, 'callback' => [ $this, 'get_licenses' ], 'permission_callback' => [ $this, 'can_manage' ], ] ); $license_key = [ 'required' => true, 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', ]; // Every action answers with the license card list, same as GET /licenses. register_rest_route( Constants::REST_BASE, '/licenses/disconnect', [ 'methods' => WP_REST_Server::CREATABLE, 'callback' => [ $this, 'disconnect_account' ], 'permission_callback' => [ $this, 'can_manage' ], ] ); register_rest_route( Constants::REST_BASE, '/licenses/sync', [ 'methods' => WP_REST_Server::CREATABLE, 'callback' => [ $this, 'sync_licenses' ], 'permission_callback' => [ $this, 'can_manage' ], ] ); register_rest_route( Constants::REST_BASE, '/licenses/activate', [ 'methods' => WP_REST_Server::CREATABLE, 'callback' => [ $this, 'activate_license' ], 'permission_callback' => [ $this, 'can_manage' ], 'args' => [ 'licenseKey' => $license_key ], ] ); register_rest_route( Constants::REST_BASE, '/licenses/deactivate', [ 'methods' => WP_REST_Server::CREATABLE, 'callback' => [ $this, 'deactivate_license' ], 'permission_callback' => [ $this, 'can_manage' ], 'args' => [ 'licenseKey' => $license_key ], ] ); register_rest_route( Constants::REST_BASE, '/licenses/addons', [ 'methods' => WP_REST_Server::CREATABLE, 'callback' => [ $this, 'addon_action' ], 'permission_callback' => [ $this, 'can_manage' ], 'args' => [ 'action' => [ 'required' => true, 'type' => 'string', 'enum' => [ 'install', 'activate', 'deactivate' ], ], 'addonId' => [ 'required' => true, 'type' => 'string', 'enum' => Addons::known_addon_ids(), ], 'licenseKey' => $license_key, ], ] ); register_rest_route( Constants::REST_BASE, '/licenses/autoupdate', [ 'methods' => WP_REST_Server::CREATABLE, 'callback' => [ $this, 'set_autoupdate' ], 'permission_callback' => [ $this, 'can_manage' ], 'args' => [ 'addonId' => [ 'required' => true, 'type' => 'string', 'enum' => array_merge( [ Auto_Update::MAIN_ADDON_KEY ], Addons::known_addon_ids() ), ], 'state' => [ 'required' => true, 'type' => 'string', 'enum' => [ Auto_Update::STATE_ON, Auto_Update::STATE_OFF ], ], ], ] ); } /** * Permission callback - local capability only (never derived from shop error codes). * * @return bool */ public function can_manage(): bool { return Conditional::user_can( 'advanced_ads_manage_options' ); } /** * GET /licenses * * @return WP_REST_Response */ public function get_licenses(): WP_REST_Response { return rest_ensure_response( array_map( [ $this, 'license_card' ], License::get_instance()->get_licenses() ) ); } /** * Shape one stored license row for the license card on the License screen. * * @param array $row Stored license row. * @return array */ private function license_card( array $row ): array { $name = (string) ( $row['name'] ?? __( 'License', 'advanced-ads' ) ); $sites_total = (int) ( $row['availableSites'] ?? 0 ); $is_all_access = License::get_instance()->is_all_access( $row ); $status = strtolower( (string) ( $row['status'] ?? '' ) ); // The shop's `active` means active on any site; the card shows this site, except an expiry, which applies everywhere. if ( 'expired' !== $status ) { $status = License::get_instance()->is_license_active( $row ) ? 'active' : 'inactive'; } [ $auto_updates, $scope, $auto_update_toggles ] = $this->auto_updates( $name, $is_all_access ); return [ 'licenseKey' => (string) ( $row['licenseKey'] ?? '' ), 'licenseId' => (int) ( $row['licenseId'] ?? 0 ), 'planId' => $this->plan_id( $name, $is_all_access, $sites_total ), 'canRenew' => $this->can_renew( $status, (string) ( $row['expiryDate'] ?? '' ) ), 'type' => $sites_total > 1 /* translators: 1: License name, 2: Number of sites in the license. */ ? sprintf( __( '%1$s / %2$d sites', 'advanced-ads' ), $name, $sites_total ) : $name, 'status' => $status, 'sitesUsed' => (int) ( $row['activationCount'] ?? 0 ), 'sitesTotal' => $sites_total, 'autoUpdates' => $auto_updates, 'autoUpdatesScope' => $scope, 'autoUpdateToggles' => $auto_update_toggles, 'canEditAutoUpdates' => $this->can_edit_auto_updates(), 'purchaseDate' => $this->format_license_date( (string) ( $row['purchaseDate'] ?? '' ) ), 'expiryDate' => $this->format_license_date( (string) ( $row['expiryDate'] ?? '' ) ), 'autoRenew' => (bool) ( $row['autoRenew'] ?? false ), 'isAllAccess' => $is_all_access, 'addons' => $this->addon_states( $row, $is_all_access ), ]; } /** * Auto-update label (On, Off or Mixed) and what it covers, for one license. * * @param string $name License name from the shop. * @param bool $is_all_access Whether the license is an All Access bundle. * @return array{0: string, 1: string, 2: list} Label, scope and one toggle per plugin. */ private function auto_updates( string $name, bool $is_all_access ): array { if ( $is_all_access ) { $addon_ids = array_values( array_filter( array_keys( Addons::ADDONS ), [ Addons::class, 'is_all_access_addon' ] ) ); $scope = __( 'All add-ons', 'advanced-ads' ); } else { // Single-product licenses carry the shop product name (e.g. "Tracking"); no match ('') means the main plugin. $addon_id = (string) array_search( strtolower( $name ), array_map( 'strtolower', wp_list_pluck( Addons::ADDONS, 'name' ) ), true ); $addon_ids = [ '' !== $addon_id ? $addon_id : Auto_Update::MAIN_ADDON_KEY ]; $scope = '' !== $addon_id ? Addons::product_name( $addon_id ) : __( 'Advanced Ads', 'advanced-ads' ); } $toggles = array_map( static fn( $id ) => [ 'id' => $id, 'enabled' => Auto_Update::STATE_ON === Auto_Update::get_state( $id ), ], $addon_ids ); $enabled = array_unique( array_column( $toggles, 'enabled' ) ); if ( count( $enabled ) > 1 ) { $label = __( 'Mixed', 'advanced-ads' ); } else { $label = reset( $enabled ) ? __( 'On', 'advanced-ads' ) : __( 'Off', 'advanced-ads' ); } return [ $label, $scope, $toggles ]; } /** * Add-ons in a license with their state on this site. * * @param array $row Stored license row. * @param bool $is_all_access Whether the license is an All Access bundle. * @return list State is active, installed or missing. */ private function addon_states( array $row, bool $is_all_access ): array { // The shop sends no add-on list for All Access; it covers every All Access add-on in the catalog. $ids = $is_all_access ? array_filter( array_keys( Addons::ADDONS ), [ Addons::class, 'is_all_access_addon' ] ) : array_map( static fn( $addon ) => sanitize_key( (string) ( $addon['name'] ?? '' ) ), (array) ( $row['addons'] ?? [] ) ); $addons = []; foreach ( $ids as $id ) { if ( ! Addons::is_known_addon( $id ) ) { continue; } $file = Addons::resolve_installed_plugin_file( $id ); $state = null === $file ? 'missing' : 'installed'; if ( null !== $file && is_plugin_active( $file ) ) { $state = 'active'; } $addons[] = [ 'id' => $id, 'state' => $state, ]; } return $addons; } /** * Turn a shop date (d-m-Y) into the site's date format. * * @param string $date Date from the shop. * @return string Formatted date, the raw value when it can't be parsed, or "—" when empty. */ private function format_license_date( string $date ): string { if ( '' === $date ) { return '—'; } $parsed = \DateTimeImmutable::createFromFormat( '!d-m-Y', $date, wp_timezone() ); return $parsed ? wp_date( get_option( 'date_format' ), $parsed->getTimestamp() ) : $date; } /** * Pricing table plan the license matches, so the upgrade modal can rule out it and lower plans. * * @param string $name License name from the shop. * @param bool $is_all_access Whether the license is an All Access bundle. * @param int $sites_total Sites the license allows. * @return string `pro`, `all-access-single`, `all-access-five`, or '' for other products. */ private function plan_id( string $name, bool $is_all_access, int $sites_total ): string { if ( $is_all_access ) { return $sites_total > 1 ? 'all-access-five' : 'all-access-single'; } return 'pro' === strtolower( trim( $name ) ) ? 'pro' : ''; } /** * Whether to offer a renewal: expired, or expiring within 30 days. Lifetime licenses never expire. * * @param string $status Card status. * @param string $expiry Shop expiry date (d-m-Y), empty for lifetime. * @return bool */ private function can_renew( string $status, string $expiry ): bool { $date = '' !== $expiry ? \DateTimeImmutable::createFromFormat( '!d-m-Y', $expiry, wp_timezone() ) : false; if ( ! $date ) { return false; } return 'expired' === $status || $date->getTimestamp() - time() <= 30 * DAY_IN_SECONDS; } /** * POST /licenses/disconnect - free this site's shop slots, then clear the local license data. * * @return array{} The now-empty license list, same shape as GET /licenses. */ public function disconnect_account(): array { License::get_instance()->disconnect(); return []; } /** * POST /licenses/sync - refresh the stored licenses from the shop. * * @return WP_REST_Response|WP_Error The synced list, same shape as GET /licenses. */ public function sync_licenses() { $result = License::get_instance()->sync(); if ( ! is_wp_error( $result ) ) { return $this->get_licenses(); } if ( 'network' === $result->get_error_code() ) { return new WP_Error( 'advanced_ads_license_sync_network', __( 'Could not reach the license server. Check your connection and try again.', 'advanced-ads' ), [ 'status' => 502 ] ); } return new WP_Error( 'advanced_ads_license_sync_rejected', __( 'The license server did not recognize the licenses on this site. Connect your account again.', 'advanced-ads' ), [ 'status' => 422 ] ); } /** * POST /licenses/activate - activate a license for this site. * * @param WP_REST_Request $request Request with `licenseKey`. * @return WP_REST_Response|WP_Error The fresh list, same shape as GET /licenses. */ public function activate_license( WP_REST_Request $request ) { $result = License::get_instance()->activate( (string) $request->get_param( 'licenseKey' ) ); return is_wp_error( $result ) ? $this->activation_error( $result ) : $this->get_licenses(); } /** * POST /licenses/deactivate - free this site's slot on a license. * * @param WP_REST_Request $request Request with `licenseKey`. * @return WP_REST_Response|WP_Error The fresh list, same shape as GET /licenses. */ public function deactivate_license( WP_REST_Request $request ) { $result = License::get_instance()->deactivate( (string) $request->get_param( 'licenseKey' ) ); return is_wp_error( $result ) ? $this->activation_error( $result ) : $this->get_licenses(); } /** * Turn an activate/deactivate error code into a REST error the License screen can show. * * @param WP_Error $error Error from License::activate() or License::deactivate(). * @return WP_Error */ private function activation_error( WP_Error $error ): WP_Error { $code = $error->get_error_code(); if ( 'network' === $code ) { return new WP_Error( 'advanced_ads_license_network', __( 'Could not reach the license server. Check your connection and try again.', 'advanced-ads' ), [ 'status' => 502 ] ); } $messages = [ 'missing' => __( 'This license is not on this site. Sync your licenses and try again.', 'advanced-ads' ), 'no_activations_left' => __( 'This license has no sites left. Deactivate it on another site or upgrade your plan.', 'advanced-ads' ), 'expired' => __( 'This license has expired. Renew it to activate it.', 'advanced-ads' ), 'disabled' => __( 'This license has been disabled.', 'advanced-ads' ), 'license_not_activable' => __( 'This license is a bundle and cannot be activated on its own.', 'advanced-ads' ), 'failed' => __( 'The license could not be deactivated on this site.', 'advanced-ads' ), 'license_inactive' => __( 'Activate the license on this site first.', 'advanced-ads' ), 'no_package' => __( 'The license server offers no download of this add-on for this license.', 'advanced-ads' ), ]; return new WP_Error( 'advanced_ads_license_' . $code, $messages[ $code ] ?? __( 'The license server refused the request. Sync your licenses and try again.', 'advanced-ads' ), [ 'status' => 422 ] ); } /** * POST /licenses/addons - install, activate or deactivate an add-on on this site. * * Install downloads the package the license allows and unzips it; activation is a separate call * so the License screen can show each step. * * @param WP_REST_Request $request Request with `action`, `addonId` and `licenseKey`. * @return WP_REST_Response|WP_Error The fresh list, same shape as GET /licenses. */ public function addon_action( WP_REST_Request $request ) { $action = (string) $request->get_param( 'action' ); $addon_id = (string) $request->get_param( 'addonId' ); if ( 'install' === $action ) { $package = License::get_instance()->addon_package( (string) $request->get_param( 'licenseKey' ), $addon_id ); if ( is_wp_error( $package ) ) { return $this->activation_error( $package ); } $result = Installer::install_from_url( $package ); if ( true !== $result ) { return $this->addon_error( $result, __( 'The add-on could not be installed.', 'advanced-ads' ) ); } Addons::get_plugins( true ); return $this->get_licenses(); } if ( ! current_user_can( 'activate_plugins' ) ) { return new WP_Error( 'advanced_ads_addon_forbidden', __( 'You are not allowed to activate plugins on this site.', 'advanced-ads' ), [ 'status' => 403 ] ); } $file = Addons::resolve_installed_plugin_file( $addon_id ); if ( null === $file ) { return new WP_Error( 'advanced_ads_addon_missing', __( 'The add-on is not installed.', 'advanced-ads' ), [ 'status' => 404 ] ); } if ( 'activate' === $action ) { $result = activate_plugin( $file ); if ( is_wp_error( $result ) ) { return $this->addon_error( $result, __( 'The add-on could not be activated.', 'advanced-ads' ) ); } } else { deactivate_plugins( $file ); } return $this->get_licenses(); } /** * REST error for a failed add-on install or activation, keeping WordPress's reason when it gives one. * * @param mixed $result Upgrader or activation result. * @param string $fallback Message when there is no reason. * @return WP_Error */ private function addon_error( $result, string $fallback ): WP_Error { $message = $fallback; if ( is_wp_error( $result ) ) { // The add-on updater puts the shop's refusal (e.g. an expired license) in the error data. $reason = $result->get_error_data(); $message = is_string( $reason ) && '' !== $reason ? $result->get_error_message() . ' ' . wp_strip_all_tags( $reason ) : $result->get_error_message(); } return new WP_Error( 'advanced_ads_addon_failed', $message, [ 'status' => 500 ] ); } /** * POST /licenses/autoupdate - turn WordPress auto-updates on or off for the main plugin or an add-on. * * @param WP_REST_Request $request Request with `addonId` and `state`. * @return WP_REST_Response|WP_Error The fresh license list, or the error. */ public function set_autoupdate( WP_REST_Request $request ) { if ( ! $this->can_edit_auto_updates() ) { return new WP_Error( 'advanced_ads_autoupdate_forbidden', __( 'You are not allowed to change plugin auto-updates on this site.', 'advanced-ads' ), [ 'status' => 403 ] ); } $result = Auto_Update::set_state( (string) $request->get_param( 'addonId' ), (string) $request->get_param( 'state' ) ); if ( is_wp_error( $result ) ) { return new WP_Error( 'advanced_ads_autoupdate_' . $result->get_error_code(), $result->get_error_message(), [ 'status' => 400 ] ); } return $this->get_licenses(); } /** * Whether the current user may change plugin auto-updates, and WordPress allows them for plugins at all. * * @return bool */ private function can_edit_auto_updates(): bool { require_once ABSPATH . 'wp-admin/includes/update.php'; return current_user_can( 'update_plugins' ) && wp_is_auto_update_enabled_for_type( 'plugin' ); } }