generate_uuid(); update_option( self::$uuid_option, $uuid ); } return $uuid; } /** * Generate a random UUID v4. * * @return string UUID. */ private function generate_uuid() { $data = random_bytes( 16 ); $data[6] = chr( ord( $data[6] ) & 0x0f | 0x40 ); // Version 4 $data[8] = chr( ord( $data[8] ) & 0x3f | 0x80 ); // Variant return vsprintf( '%s%s-%s-%s-%s-%s%s%s', str_split( bin2hex( $data ), 4 ) ); } /** * Send telemetry event to endpoint. * * @param string $event Event type (activate, deactivate, uninstall, heartbeat). * @return bool Success status. */ private function send_event( $event ) { if ( $this->is_disabled() ) { return false; } $payload = array( 'event' => $event, 'site_id' => $this->get_site_uuid(), 'plugin_slug' => self::$slug, 'plugin_version' => self::$version, ); // Send non-blocking request $response = wp_remote_post( self::$endpoint, array( 'body' => wp_json_encode( $payload ), 'headers' => array( 'Content-Type' => 'application/json', ), 'timeout' => 5, 'blocking' => false, ) ); // Non-blocking request, so we can't check response directly // Error handling is done via WordPress error logging if needed return true; } /** * Handle plugin activation event. * * @return bool */ public function track_activation() { if ( $this->is_disabled() ) { return false; } // Ensure UUID exists $this->get_site_uuid(); // Schedule heartbeat cron if ( ! wp_next_scheduled( 'powerstack_telemetry_heartbeat' ) ) { wp_schedule_event( time(), 'daily', 'powerstack_telemetry_heartbeat' ); } return $this->send_event( 'activate' ); } /** * Handle plugin deactivation event. * * @return bool */ public function track_deactivation() { if ( $this->is_disabled() ) { return false; } // Clear heartbeat cron $timestamp = wp_next_scheduled( 'powerstack_telemetry_heartbeat' ); if ( $timestamp ) { wp_unschedule_event( $timestamp, 'powerstack_telemetry_heartbeat' ); } return $this->send_event( 'deactivate' ); } /** * Handle plugin uninstall event. * * @return bool */ public function track_uninstall() { if ( $this->is_disabled() ) { return false; } // Send uninstall event before deleting data $result = $this->send_event( 'uninstall' ); // Delete site UUID delete_option( self::$uuid_option ); return $result; } /** * Send daily heartbeat event. * * @return bool */ public function track_heartbeat() { if ( $this->is_disabled() ) { return false; } return $this->send_event( 'heartbeat' ); } /** * Initialize telemetry hooks. */ public function init() { // Register heartbeat cron callback add_action( 'powerstack_telemetry_heartbeat', array( $this, 'track_heartbeat' ) ); } }