7 * DAY_IN_SECONDS, 'display' => __( 'Once Weekly', 'ai-search' ), ]; } return $schedules; } /** * Idempotent: schedules the next weekly tick if the digest is enabled * and logging is on; unschedules otherwise. Safe to call on every * plugins_loaded. */ public static function ensure_scheduled() { $enabled = (bool) get_option( self::OPT_ENABLED, true ); $logging = (bool) get_option( 'ai_search_logging_enabled', true ); if ( ! $enabled || ! $logging ) { $existing = wp_next_scheduled( self::CRON_HOOK ); if ( $existing ) { wp_unschedule_event( $existing, self::CRON_HOOK ); } return; } if ( ! wp_next_scheduled( self::CRON_HOOK ) ) { // Fire next Monday around 09:00 site-local, then every 7 days. $first = self::next_monday_9am(); wp_schedule_event( $first, self::SCHEDULE, self::CRON_HOOK ); } } /** * Compute the next Monday 09:00 in the site's timezone, as a UTC * timestamp for wp_schedule_event(). * * @return int */ private static function next_monday_9am() { try { $tz = wp_timezone(); $now = new DateTime( 'now', $tz ); $target = new DateTime( 'now', $tz ); $target->setTime( 9, 0, 0 ); // Days until next Monday (0 = already Monday 09:00+). $day_of_week = (int) $target->format( 'N' ); // 1 = Mon, 7 = Sun if ( $day_of_week === 1 && $target > $now ) { $add = 0; } else { $add = ( 8 - $day_of_week ) % 7; if ( $add === 0 ) { $add = 7; } } $target->modify( "+{$add} days" ); return $target->getTimestamp(); } catch ( Exception $e ) { return time() + ( 7 * DAY_IN_SECONDS ); } } /** * Cron callback: build the digest and send it to admin_email. * Skips sending when logging is off or when no searches were recorded * in the window — never spams empty digests. */ public static function send_digest() { if ( ! (bool) get_option( self::OPT_ENABLED, true ) ) return; if ( ! (bool) get_option( 'ai_search_logging_enabled', true ) ) return; $to = sanitize_email( get_option( 'admin_email' ) ); if ( ! is_email( $to ) ) return; $payload = self::build_payload(); if ( empty( $payload['summary']['total'] ) ) { // No activity this week — stay quiet. return; } self::dispatch( $to, $payload ); update_option( self::OPT_LAST, time(), false ); } /** * Send one real email right now, triggered manually from the Insights * tab's "Send me a test" button. Bypasses the activity guard so the * admin always gets something. * * @param string|null $to Target email, defaults to admin_email. * @return true|WP_Error */ public static function send_test( $to = null ) { $to = $to ? sanitize_email( $to ) : sanitize_email( get_option( 'admin_email' ) ); if ( ! is_email( $to ) ) { return new WP_Error( 'invalid_email', __( 'The admin email is not valid.', 'ai-search' ) ); } $payload = self::build_payload(); $payload['is_test'] = true; return self::dispatch( $to, $payload ) ? true : new WP_Error( 'send_failed', __( 'wp_mail returned false.', 'ai-search' ) ); } /** * Build the data used by both the HTML and text templates. * * Shape: * [ * 'window_days' => 7, * 'summary' => ['total'=>..., 'rescued'=>..., 'no_results'=>...], * 'top_searches' => [{query, hits, last_seen}, ...], * 'top_missing' => [{query, hits, last_seen}, ...], * 'plan_key' => 'free'|'standard'|'pro', * 'is_free' => bool, * 'site_url' => 'https://example.com', * 'site_name' => 'Example', * 'insights_url' => 'https://.../admin.php?page=ai-search-insights', * 'upgrade_url' => 'https://.../admin.php?page=ai-search-upgrade', * 'is_test' => false, * ] * * @return array */ public static function build_payload() { $summary = AI_Search::logs_summary( 7 ); $top_searches = AI_Search::top_searches_since( 7, 5 ); $top_missing = AI_Search::top_no_results_since( 7, 5 ); $plan_key = 'free'; $quota = get_transient( 'ai_search_quota_data' ); if ( is_array( $quota ) && isset( $quota['plan']['key'] ) ) { $plan_key = (string) $quota['plan']['key']; } return [ 'window_days' => 7, 'summary' => $summary, 'top_searches' => $top_searches, 'top_missing' => $top_missing, 'plan_key' => $plan_key, 'is_free' => 'free' === $plan_key, 'site_url' => home_url(), 'site_name' => wp_specialchars_decode( (string) get_bloginfo( 'name' ), ENT_QUOTES ), 'insights_url' => admin_url( 'admin.php?page=ai-search-insights' ), 'upgrade_url' => admin_url( 'admin.php?page=ai-search-upgrade' ), 'unsub_url' => admin_url( 'admin.php?page=ai-search-insights#weekly-digest' ), 'is_test' => false, ]; } /** * Render and send. Returns the wp_mail boolean. * * @param string $to Recipient. * @param array $payload Template data from build_payload(). * @return bool */ private static function dispatch( $to, array $payload ) { $subject = sprintf( /* translators: %s: site name */ __( '[AI Search] Weekly search summary for %s', 'ai-search' ), $payload['site_name'] ); if ( ! empty( $payload['is_test'] ) ) { $subject = '[Test] ' . $subject; } $html = self::render_html( $payload ); $text = self::render_text( $payload ); $boundary = 'ai-search-mime-' . wp_generate_password( 12, false ); $headers = [ 'Content-Type: multipart/alternative; boundary="' . $boundary . '"', ]; $body = "--{$boundary}\r\n"; $body .= "Content-Type: text/plain; charset=UTF-8\r\n\r\n"; $body .= $text . "\r\n\r\n"; $body .= "--{$boundary}\r\n"; $body .= "Content-Type: text/html; charset=UTF-8\r\n\r\n"; $body .= $html . "\r\n\r\n"; $body .= "--{$boundary}--"; return (bool) wp_mail( $to, $subject, $body, $headers ); } public static function render_html( array $payload ) { ob_start(); $data = $payload; // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable include AI_SEARCH_PATH . 'includes/views/email-weekly-digest.php'; return (string) ob_get_clean(); } public static function render_text( array $payload ) { ob_start(); $data = $payload; // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable include AI_SEARCH_PATH . 'includes/views/email-weekly-digest.txt.php'; return (string) ob_get_clean(); } }