4 * HOUR_IN_SECONDS, 'display' => 'Every 4 hours (GuardPress)', ); } return $schedules; } public static function ensure_schedule() { $s = class_exists( 'GuardPress_Settings' ) ? GuardPress_Settings::get() : array(); $enabled = isset( $s['scheduled_enabled'] ) ? (int) $s['scheduled_enabled'] : 0; if ( ! $enabled ) { self::unschedule_all(); delete_option( 'guardpress_cron_applied' ); return; } $freq = isset( $s['schedule_frequency'] ) ? (string) $s['schedule_frequency'] : 'twicedaily'; $time = isset( $s['schedule_time'] ) ? (string) $s['schedule_time'] : '03:00'; $recurrence = self::map_frequency_to_recurrence( $freq ); // Reschedule when nothing is scheduled, when the recurrence changed, OR when the // chosen frequency/time changed since we last applied it (v1.0.13 time picker). $next = wp_next_scheduled( self::HOOK ); $current = self::get_current_recurrence(); $applied = (string) get_option( 'guardpress_cron_applied', '' ); $desired = $freq . '|' . $time; if ( ! $next || ( $current && $current !== $recurrence ) || $applied !== $desired ) { self::unschedule_all(); wp_schedule_event( self::compute_start( $freq, $time ), $recurrence, self::HOOK ); update_option( 'guardpress_cron_applied', $desired, false ); } } /** * First-run timestamp. For daily / twice-daily we anchor to the next occurrence of the * chosen HH:MM in the SITE timezone (so the scan lands at the user's quiet hour). For * hourly / every-4-hours the time-of-day is not meaningful, so we start shortly from * now. NOTE: WP-cron fires on the first request AFTER this time, so it runs "around" * the chosen hour, not on an exact server clock (exact scheduling is a PRO feature). */ private static function compute_start( $freq, $time ) { if ( in_array( $freq, array( 'daily', 'twicedaily' ), true ) && preg_match( '/^([01]\d|2[0-3]):[0-5]\d$/', $time ) ) { try { $tz = function_exists( 'wp_timezone' ) ? wp_timezone() : new DateTimeZone( 'UTC' ); $now = new DateTime( 'now', $tz ); $target = new DateTime( $now->format( 'Y-m-d' ) . ' ' . $time . ':00', $tz ); if ( $target <= $now ) { $target->modify( '+1 day' ); } return $target->getTimestamp(); } catch ( Exception $e ) { // fall through to the default below } } return time() + 5 * MINUTE_IN_SECONDS; } private static function map_frequency_to_recurrence( $freq ) { switch ( $freq ) { case 'hourly': return 'hourly'; case '4hours': case 'every4hours': return 'guardpress_4hours'; case 'daily': return 'daily'; case 'twicedaily': default: return 'twicedaily'; } } private static function get_current_recurrence() { // WordPress does not provide a direct API for this; we infer it from the cron array. $cron = _get_cron_array(); if ( ! is_array( $cron ) ) { return ''; } foreach ( $cron as $timestamp => $hooks ) { if ( empty( $hooks[ self::HOOK ] ) ) { continue; } foreach ( $hooks[ self::HOOK ] as $sig => $event ) { if ( isset( $event['schedule'] ) ) { return (string) $event['schedule']; } } } return ''; } public static function run_scheduled_scan() { $settings = class_exists( 'GuardPress_Settings' ) ? GuardPress_Settings::get() : array(); // Respect setting. if ( empty( $settings['scheduled_enabled'] ) ) { return; } // FIX (audit 2026-06-10): guard against overlap. A scheduled scan walks // and sha256-hashes all of ABSPATH; without a lock an overrunning cron // tick (or a concurrent manual scan) could start a SECOND full walk, // doubling I/O/CPU and racing on the same baseline/state files. Acquire // the integrity scan lock and skip this run if a scan is already going. $have_lock = false; $lock_owner = null; // ACG-047-003: thread the scan_id so the release below is owner-bound if ( class_exists( 'GuardPress_Scan_Lock' ) ) { $lk = GuardPress_Scan_Lock::acquire( 'integrity' ); if ( empty( $lk['acquired'] ) ) { return; // another scan is in progress — skip this tick } $have_lock = true; $lock_owner = isset( $lk['scan_id'] ) ? $lk['scan_id'] : null; } try { $mode = isset( $settings['schedule_mode'] ) ? (string) $settings['schedule_mode'] : 'regular'; if ( class_exists( 'GuardPress_FS_Helpers' ) ) { GuardPress_FS_Helpers::set_full_scan( $mode === 'full' ); } $report = class_exists( 'GuardPress_Scan_Runner' ) ? GuardPress_Scan_Runner::run() : array(); // Save scan metadata so dashboard shows when cron last ran // FIX H-10 (audit 2026-05-25): autoload=false. Read only by the // dashboard widget (admin/index.php) and scanner page — not needed // in alloptions on every request. Mirror the batch-scanner sibling. // RC-118-05 (audit 2026-06-18): carry incomplete/skipped coverage into the meta // so the dashboard/banner/digest show amber, not green, after a scheduled scan // that could not read every file. // RC-119-05 (audit 2026-06-18): coverage is incomplete if ANY file was skipped — // unreadable/hash-fail ($report['skipped']) OR over the 50MB hash cap // ($report['skipped_large']). Counting only 'skipped' let a scheduled scan that // skipped a >50MB archive still report green. Fold both into the coverage gap. // ACG-137-B2 (self-review round 2): RC-119-05 folded skipped_large into "incomplete" HERE, and // that was the defect — not the manual path's omission. One ordinary >50 MB backup made every // scheduled scan permanently amber with "%d file could not be read ... re-run the scan once the // file is accessible" — false (it reads fine, it is just large) and unactionable (re-running // never clears it). It also contradicted this release's own changelog promise that "an ordinary // backup/media file never marks a healthy site 'incomplete'". // Both paths now ask the one definition: "incomplete" = a FAILURE to inspect; an over-cap file // is a BOUNDARY carried in its own key. FN-safe because the dangerous sub-case — a BASELINED // file that crosses the cap — is reported as CHANGED by ACG-137-B5. $cron_skipped = class_exists( 'GuardPress_FS_Helpers' ) ? GuardPress_FS_Helpers::coverage_gap_count( $report ) : ( is_array( $report ) ? (int) ( $report['skipped'] ?? 0 ) : 0 ); $cron_oversize = class_exists( 'GuardPress_FS_Helpers' ) ? GuardPress_FS_Helpers::oversize_count( $report ) : ( is_array( $report ) ? (int) ( $report['skipped_large'] ?? 0 ) : 0 ); update_option( 'guardpress_last_scan_meta', array( 'time' => time(), 'type' => ucfirst( $mode ) . ' (Scheduled)', 'skipped' => $cron_skipped, 'incomplete' => ( $cron_skipped > 0 ), ), false ); // Clear stale results from previous scan (match manual scan behavior) delete_option( 'guardpress_ai_last_analysis' ); delete_transient( 'guardpress_db_scan_results' ); delete_transient( 'guardpress_core_verify_results' ); // Always return to regular after a scheduled run to keep UI predictable. if ( class_exists( 'GuardPress_FS_Helpers' ) ) { GuardPress_FS_Helpers::set_full_scan( false ); } // ───────────────────────────────────────────────────────────────────────────────────────── // ACG-149-138 — MALWARE-SCAN THE FILES THIS SCAN FOUND CHANGED OR NEW. // // Until now the scheduled scan was integrity-only: it compared file hashes to the baseline and // could not look for malicious code at all. So a user who enabled "Scheduled Scans" and // "Email Alerts" — both of which this plugin recommends — got no automatic malware detection, // and a malware finding could never produce an email. // // WHY THIS SET OF FILES. Malware arriving on a site IS a new or changed file, so the rows this // scan just produced are exactly where an automatic check belongs. It is also normally a // handful of files, so the cost is negligible and no cron batching/resume machinery is needed — // a full scan cannot fit in one cron tick (measured ~4.6 ms/file, i.e. minutes for a real site, // against a typical 30 s max_execution_time), which is why the manual scan is batched. // // BOUNDARY, stated because the notifier repeats it to the user: this catches malware that // ARRIVES after a baseline exists. Pre-existing malware, and malware in a file that never // changes, is the full manual scan's job — which the scanner page now actively prompts for. $mal_result = null; if ( class_exists( 'GuardPress_Malware_Scanner' ) && method_exists( 'GuardPress_Malware_Scanner', 'scan_paths_for_malware' ) ) { // ACG-149-R36-D (pre-release audit 2026-07-27) — THE SCHEDULED SCAN WENT BLIND ON A // FILE IT HAD ALREADY CONFIRMED AS MALWARE. // // This scan inspects the files the integrity run reported as changed or new. Refreshing // the baseline makes an infected file match its reference, so it stops being reported as // changed — and from that tick on it was never handed to the malware scan again. Silence, // over a live webshell, with no counter and no sentence anywhere saying we had stopped // looking. The old `! empty( $report['details'] )` gate made it worse: a completely quiet // tick skipped the malware scan entirely, so nothing could ever revisit the finding. // // A file we have POSITIVELY IDENTIFIED as malware stays on the list until a scan sees it // clean, whatever the baseline says. The list is the scheduled record's own file list — // already bounded to 50 and already written after every scheduled scan — so this adds no // new state, and it self-clears: when the user cleans the file, the next scan records no // findings for it and it drops off. Cost on a healthy site is exactly zero, because that // list is empty. $mal_paths = self::malware_paths_from_report( $report ); // array() for an empty report $mal_watch = self::malware_watch_paths(); if ( ! empty( $mal_watch ) ) { $mal_paths = array_merge( $mal_paths, $mal_watch ); // scan_paths_for_malware() dedupes } if ( ! empty( $mal_paths ) ) { // Bounded so a mass update (WordPress core + 30 plugins at once) cannot turn one cron // tick into a multi-minute scan. The remainder is REPORTED in over_limit, never dropped // silently, and the notifier prints it. $mal_result = GuardPress_Malware_Scanner::scan_paths_for_malware( $mal_paths, 300 ); if ( is_array( $mal_result ) ) { $report['malware'] = $mal_result; // ACG-149-R36-E: PERSIST THE VERDICT. save_scheduled_findings() was added in the // previous round with no caller anywhere in the plugin — so the behaviour it was // written to fix was still live: a webshell this scan positively identified existed // only inside the email body, and `email_enabled` ships as 0, so on a default // install the identification was made and then thrown away. It also feeds // malware_watch_paths() above, which is why it must be written on EVERY scheduled // scan — including one that finds nothing, which is what retires a cleaned file. // ACG-149-R37-A: hand over WHICH files this run actually read. Without it the // record was rebuilt from this tick's findings alone, so a watched file the tick // never opened (chmod 000, symlink swap, past the 2 MB cap, or outside the // 300-file rotation window) was silently retired — one chmod deleted the alarm. if ( method_exists( 'GuardPress_Malware_Scanner', 'save_scheduled_findings' ) ) { GuardPress_Malware_Scanner::save_scheduled_findings( $mal_result, isset( $mal_result['inspected'] ) && is_array( $mal_result['inspected'] ) ? $mal_result['inspected'] : array() ); } } } elseif ( method_exists( 'GuardPress_Malware_Scanner', 'reconcile_scheduled_findings' ) ) { // ACG-149-R37-U: nothing to inspect this tick — but a file the user DELETED must // stop being recorded durably, not only in the read view. Without this the stale row // survives, and a CLEAN file later reinstalled at the same path re-lights the red // "confirmed threat" banner. Writes only if something actually vanished. GuardPress_Malware_Scanner::reconcile_scheduled_findings(); } } // Email notifications. $report may now carry ['malware']; maybe_send() treats a confirmed // malware finding as its own reason to send, folds it into the dedupe signature, and lets it // bypass the rate limit. if ( class_exists( 'GuardPress_Email_Notifier' ) ) { GuardPress_Email_Notifier::maybe_send( $report, $settings ); } } finally { if ( $have_lock ) { GuardPress_Scan_Lock::release( 'integrity', $lock_owner ); // ACG-047-003: owner-bound release } } } /** * ACG-149-138 — which files from an integrity report should be malware-scanned. * * PUBLIC AND SEPARATE ON PURPOSE, so the path handling is testable. The first version of this was * inline and did `ABSPATH . ltrim( $rel, '/' )`, which is WRONG: GuardPress_Scan_Runner::run() keys * $report['details'] with `wp_normalize_path( $fp )` — the ABSOLUTE path — so that produced * "C:/site/C:/site/wp-content/..." for every row. Nothing would have been scanned, no alert could ever * fire, and the coverage-gap counter would have reported every changed file as "could not be read". * The bug was invisible from the outside: the feature would simply have done nothing, quietly. * * Accepts either shape (absolute, or relative for any other producer / older stored report) and * refuses anything resolving outside the install. * * @param array $report An integrity report with a 'details' map. * @return array Absolute, normalized paths of files that exist and are worth inspecting. */ public static function malware_paths_from_report( $report ) { $out = array(); if ( ! is_array( $report ) || empty( $report['details'] ) || ! is_array( $report['details'] ) ) { return $out; } $root = rtrim( str_replace( '\\', '/', ABSPATH ), '/' ); foreach ( $report['details'] as $key => $row ) { $status = is_array( $row ) && isset( $row['status'] ) ? strtolower( (string) $row['status'] ) : ''; // Only files that EXIST now can be inspected. 'deleted' has nothing left to read; 'unchanged' // is already covered by the previous scan plus the verdict cache. if ( 'changed' !== $status && 'new' !== $status ) { continue; } $p = str_replace( '\\', '/', (string) $key ); if ( '' === $p ) { continue; } if ( 0 === strpos( $p, $root . '/' ) ) { $out[] = $p; // already absolute, inside the install } elseif ( preg_match( '#^([A-Za-z]:/|/|\\\\\\\\)#', $p ) ) { continue; // absolute but OUTSIDE the install — out of scope } else { $out[] = $root . '/' . ltrim( $p, '/' ); // relative to the install root } } return $out; } /** * ACG-149-R36-D — files the LAST scheduled scan confirmed as malware, re-offered for inspection * regardless of whether they still count as "changed". * * Reads the scheduled record written by save_scheduled_findings(), whose 'files' list is already * capped at 50 and already holds exactly the rows whose verdict was 'malware'. Paths are stored * relative to ABSPATH there, so they are resolved the same way malware_paths_from_report() resolves * a relative details key — including its refusal of anything landing outside the install. * * A path that no longer exists is dropped: the user deleted the file, which is the outcome we * wanted, and re-offering it would only spend a coverage_gap on it. * * @return array Absolute, normalized paths. */ public static function malware_watch_paths() { $out = array(); if ( ! class_exists( 'GuardPress_Malware_Scanner' ) || ! method_exists( 'GuardPress_Malware_Scanner', 'get_scheduled_findings' ) ) { return $out; } $rec = GuardPress_Malware_Scanner::get_scheduled_findings(); if ( ! is_array( $rec ) || empty( $rec['files'] ) || ! is_array( $rec['files'] ) ) { return $out; } $root = rtrim( str_replace( '\\', '/', ABSPATH ), '/' ); foreach ( $rec['files'] as $row ) { $p = is_array( $row ) ? str_replace( '\\', '/', (string) ( $row['path'] ?? '' ) ) : ''; if ( '' === $p ) { continue; } if ( 0 === strpos( $p, $root . '/' ) ) { $abs = $p; } elseif ( preg_match( '#^([A-Za-z]:/|/|\\\\\\\\)#', $p ) ) { continue; // absolute but OUTSIDE the install — out of scope } else { $abs = $root . '/' . ltrim( $p, '/' ); } if ( @is_file( $abs ) ) { $out[] = $abs; } } return $out; } public static function unschedule_all() { $next = wp_next_scheduled( self::HOOK ); while ( $next ) { wp_unschedule_event( $next, self::HOOK ); $next = wp_next_scheduled( self::HOOK ); } } }