useAnalytics(); */ class Client { private const REST_NAMESPACE = 'packedge/v1'; /** * PackEdge public (product) key. * * @var string */ private $public_key; /** * Absolute path to the plugin main file. * * @var string */ private $plugin_file; /** * Plugin slug derived from the plugin file. * * @var string */ private $slug; /** * Whether analytics is enabled. * * @var bool */ private $analytics_enabled = false; /** * Whether deactivation feedback is enabled. * * @var bool */ private $deactivation_enabled = false; /** * Whether admin scripts have been hooked. * * @var bool */ private $scripts_hooked = false; /** * Singleton instances keyed by public key. * * @var array */ private static $instances = []; public static function create( string $public_key, string $plugin_file ): self { if ( ! isset(self::$instances[ $public_key ]) ) { self::$instances[ $public_key ] = new self($public_key, $plugin_file); } return self::$instances[ $public_key ]; } private function __construct( string $public_key, string $plugin_file ) { $this->public_key = $public_key; $this->plugin_file = $plugin_file; $this->slug = basename(dirname($plugin_file)); } /** * Enable analytics - registers consent endpoint and enqueues JS SDK. */ public function useAnalytics(): self { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid -- Public fluent SDK API name; renaming breaks the documented packedge()->useAnalytics() contract. if ( ! $this->analytics_enabled ) { $this->analytics_enabled = true; add_action('rest_api_init', [ $this, 'register_consent_route' ]); // Re-ask on every (re)install: clear stored consent on deactivation // so a fresh activation shows the banner again. register_deactivation_hook($this->plugin_file, [ $this, 'reset_consent' ]); $this->hook_scripts(); } return $this; } /** * Forget the diagnostic consent choice (fired on plugin deactivation). */ public function reset_consent(): void { delete_option($this->get_option_key()); } /** * Enable just the deactivation feedback modal (no consent notice). * Useful when the plugin shares a parent's consent surface but should * still ask why it's being deactivated. */ public function useDeactivationFeedback(): self { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid -- Public fluent SDK API name. $this->deactivation_enabled = true; $this->hook_scripts(); return $this; } /** * Enqueue the drop-in JS once, regardless of how many features are on. */ private function hook_scripts(): void { if ( ! $this->scripts_hooked ) { $this->scripts_hooked = true; add_action('admin_enqueue_scripts', [ $this, 'enqueue_scripts' ]); } } /** * Register REST route to save/get diagnostic consent. */ public function register_consent_route(): void { register_rest_route(self::REST_NAMESPACE, '/analytics/consent', [ 'methods' => 'POST', 'callback' => function ( \WP_REST_Request $request ): \WP_REST_Response { $consent = (bool) $request->get_param('consent'); update_option($this->get_option_key(), $consent); return new \WP_REST_Response([ 'success' => true, 'consent' => $consent, ]); }, 'permission_callback' => function () { return current_user_can('manage_options'); }, ]); register_rest_route(self::REST_NAMESPACE, '/analytics/consent', [ 'methods' => 'GET', 'callback' => function () { return new \WP_REST_Response([ 'consent' => $this->has_consent() ]); }, 'permission_callback' => function () { return current_user_can('manage_options'); }, ]); } /** * Enqueue analytics JS and localize consent + diagnostic data. */ public function enqueue_scripts(): void { $handle = 'packedge-' . $this->slug; $pkg_ver = @filemtime( plugin_dir_path( $this->plugin_file ) . 'assets/js/packedge.js' ); wp_enqueue_script( $handle, plugins_url('assets/js/packedge.js', $this->plugin_file), [], $pkg_ver ? $pkg_ver : null, true ); $plugin_data = get_plugin_data($this->plugin_file, false, false); $consent_raw = get_option($this->get_option_key(), 'unset'); $data = [ 'publicKey' => $this->public_key, 'slug' => $this->slug, 'pluginName' => ! empty( $plugin_data['Name'] ) ? $plugin_data['Name'] : $this->slug, 'site' => site_url(), 'consent' => 'unset' !== $consent_raw && (bool) $consent_raw, 'consentAsked' => 'unset' !== $consent_raw, 'restUrl' => rest_url(self::REST_NAMESPACE . '/analytics/consent'), 'nonce' => wp_create_nonce('wp_rest'), // Feature flags read by the IIFE bootstrap (wp-global.ts). 'analytics' => $this->analytics_enabled, 'deactivation' => $this->deactivation_enabled, ]; global $pagenow; if ( 'plugins.php' === $pagenow ) { $data['diagnostics'] = $this->get_diagnostics(); } wp_localize_script($handle, 'packedge_' . preg_replace('/[^a-zA-Z0-9]/', '_', $this->public_key), $data); } /** * Check if user has given diagnostic consent. */ public function has_consent(): bool { return (bool) get_option($this->get_option_key(), false); } /** * Diagnostics shipped to the deactivation modal on plugins.php. * * Mirrors the PHP lifecycle hook's env_snapshot() shape so * modal-fired uninstall events land in the dashboard's * environment breakdowns the same way hook-fired ones do. * Backend reads `payload->'env'->>'php'`, `…->>'wp'`, etc. * * @return array */ public function get_diagnostics(): array { global $wpdb; if ( ! function_exists('wp_get_theme') ) { return []; } $theme = wp_get_theme(); $active = (array) get_option('active_plugins', []); if ( is_multisite() ) { $active = array_merge($active, array_keys( (array) get_site_option('active_sitewide_plugins', []))); } $active = array_values(array_unique($active)); $plugins = array_map(static function ( $file ) { $dir = dirname($file); return ( '.' === $dir ) ? basename($file, '.php') : $dir; }, $active); return [ 'env' => [ 'php' => PHP_VERSION, 'wp' => get_bloginfo('version'), 'os' => strtolower(defined('PHP_OS_FAMILY') ? constant('PHP_OS_FAMILY') : PHP_OS), 'server' => isset( $_SERVER['SERVER_SOFTWARE'] ) ? sanitize_text_field( wp_unslash( $_SERVER['SERVER_SOFTWARE'] ) ) : '', 'mysql' => $wpdb->db_version(), 'memory_limit' => defined('WP_MEMORY_LIMIT') ? WP_MEMORY_LIMIT : ini_get('memory_limit'), 'locale' => get_locale(), 'multisite' => is_multisite(), 'theme' => [ 'name' => get_template(), 'version' => $theme ? $theme->get('Version') : '', ], ], 'plugins' => $plugins, // Extras kept on the event payload for raw inspection. 'site_url' => site_url(), 'site_title' => get_bloginfo('name'), 'admin_email' => get_option('admin_email'), 'timezone' => wp_timezone_string(), 'language' => get_bloginfo('language'), 'debug_mode' => defined('WP_DEBUG') && WP_DEBUG, ]; } public function get_public_key(): string { return $this->public_key; } public function get_slug(): string { return $this->slug; } private function get_option_key(): string { return 'packedge_analytics_consent_' . md5($this->public_key); } } } } // phpcs:ignore Universal.Namespaces.DisallowCurlyBraceSyntax.Forbidden, Universal.Namespaces.DisallowDeclarationWithoutName.Forbidden, Universal.Namespaces.OneDeclarationPerFile.MultipleFound -- Global-namespace block hosting the packedge() helper; braced multi-namespace layout is intentional (see note above). namespace { if ( ! function_exists('packedge') ) { function packedge( string $public_key, string $plugin_file ): \PackEdge\Client { return \PackEdge\Client::create($public_key, $plugin_file); } } }