<?php
// 33F190D04D71-0B067FFC03A6-1810FA8DBECA
/**
 * SiteGuarding Website Antivirus - standalone scanner
 *
 * Website: https://www.siteguarding.com/
 * Email: support@siteguarding.com
 *
 * @version 2.0.3
 * @date 12 Oct 2026
 * @package SiteGuarding Antivirus Scanner (standalone)
 *
 * One self-contained file for websites where our plugin is not installed. Upload it to the website root
 * and open it in a browser: it installs the antivirus agent, scans the website and shows the report.
 *
 * Works on PHP 5.6 - 8.5. No external libraries; the only thing loaded from outside is our logo.
 *
 * The GUID in the first comment marks our temporary tools: the cleanup of SiteGuarding removes them by it.
 *
 * Without a password (the owner pressed "Skip") the scanner is open to anyone and removes itself on the
 * first request that comes 3 hours after the file appeared on the server (filectime).
 *
 * What is different from 1.4.4:
 *   - the page can be protected by a password that the owner sets at the first opening;
 *   - the access key of the website never reaches the browser (every call to the agent is made by this
 *     script on the server side);
 *   - everything downloaded from SiteGuarding comes over HTTPS with the certificate checked, and is
 *     verified before it is written;
 *   - Semantic UI, jQuery and the remote assets are gone: the interface is in this file;
 *   - the scanner can remove itself (and the agent) when the work is done.
 */

define('SG_VERSION', '2.0.3');
define('SG_SERVER', 'https://www.siteguarding.com/');
define('SG_API', SG_SERVER.'ext/antivirus/index.php');
define('SG_WORK_DIR', 'webanalyze');
define('SG_LOGO', SG_SERVER.'templates/security/images/logo_siteguarding.svg');
define('SG_SERVER_TZ', 'Europe/Minsk');  // time zone of the SiteGuarding server: its "day" for the free plan

// Without a password the scanner lives this long after the file appeared on the server (filectime,
// seconds); the first request after that deletes the file. A file forgotten on a website cannot be used
// by strangers for long. With a password set there is no time limit.
define('SG_NO_PASSWORD_TTL', 10800);
define('SG_SESSION_TTL', 7200);          // a login lasts 2 hours
define('SG_LOGIN_MAX_TRIES', 5);         // then the login is blocked
define('SG_LOGIN_BLOCK', 900);           // for 15 minutes
define('SG_PASSWORD_MIN', 10);

@ini_set('display_errors', '0');
@ini_set('log_errors', '1');
error_reporting(E_ALL);
@set_time_limit(300);
@ignore_user_abort(true);

SG::Dispatch(SG::Request('task'));
exit;


class SG
{
    public static $error = '';     // message shown at the top of the page
    public static $notice = '';
    private static $state = null;

    /**
     * Pages and actions
     */
    public static function Dispatch($task)
    {
        // The answers of the two polling endpoints are JSON, with no page around them
        $is_json = ($task === 'progress' || $task === 'blacklist_check');

        $state = self::StateLoad();

        // 0. No password and older than SG_NO_PASSWORD_TTL: the scanner removes itself, whatever was asked
        if (!self::HasPassword($state) && time() > self::ExpiresAt()) { self::SelfDestruct($is_json); return; }

        // Nothing works before the work folder exists and is writable
        if (!self::WorkDirReady())
        {
            if ($is_json) { self::Json(array('error' => 'The folder '.SG_WORK_DIR.'/ is not writable.')); return; }
            self::PageEnv(self::EnvCheck(), true);
            return;
        }

        if (!self::HasPassword($state))
        {
            // 1. No password: set one, or skip it - then the scanner is open to anyone until it removes itself
            if ($task === 'setup') { self::ActionSetup(); return; }
            if ($task === 'skip')  { self::ActionSkip(); return; }
            if ($task === 'protect' || empty($state['skipped']))
            {
                if ($is_json) { self::Json(array('error' => 'The scanner is not set up yet.')); return; }
                self::PageSetup();
                return;
            }
        }
        else
        {
            // 2. Password set: login
            if ($task === 'login') { self::ActionLogin(); return; }
            if (!self::IsLoggedIn())
            {
                if ($is_json) { self::Json(array('error' => 'Your session has expired. Please sign in again.')); return; }
                self::PageLogin();
                return;
            }
            if ($task === 'logout') { self::ActionLogout(); return; }
        }

        // 3. Actions of the owner (signed in, or the scanner runs without a password)
        switch ($task)
        {
            case 'install':         self::ActionInstall(); return;
            case 'scan_start':      self::ActionScanStart(); return;
            case 'scan':            self::PageScan(); return;
            case 'progress':        self::AnswerProgress(); return;
            case 'blacklist':       self::PageBlacklist(); return;
            case 'blacklist_check': self::AnswerBlacklistCheck(); return;
            case 'tools':           self::ActionInstallTools(); return;
            case 'remove':          self::ActionRemove(); return;
            case 'env':             self::PageEnv(self::EnvCheck(), false); return;
            default:                self::PageDashboard(); return;
        }
    }

    // ---- the first opening: the owner sets a password or skips it

    private static function PageSetup()
    {
        $state = self::StateLoad();
        $skipped = !empty($state['skipped']);
        self::Head('Set a password');
        echo '<div class="sg-narrow">';
        echo self::Card('Protect the scanner',
            '<p>This page can scan your website and install the antivirus, so only you should be able to open it. '
            .'Set a password - you will need it every time you open the scanner.</p>'
            .'<form method="post" autocomplete="off">'
            .self::Hidden('task', 'setup')
            .'<label class="sg-label" for="p1">Password (at least '.SG_PASSWORD_MIN.' characters)</label>'
            .'<input class="sg-input" type="password" id="p1" name="password" autocomplete="new-password" required>'
            .'<label class="sg-label" for="p2">Repeat the password</label>'
            .'<input class="sg-input" type="password" id="p2" name="password2" autocomplete="new-password" required>'
            .'<button class="sg-btn sg-btn-primary sg-btn-block" type="submit">Set the password</button>'
            .'</form>'
            .($skipped
                ? '<p class="sg-mt"><a class="sg-btn sg-btn-ghost sg-btn-block" href="?">Back to the scanner</a></p>'
                : '<form method="post" class="sg-mt">'.self::Hidden('task', 'skip')
                  .'<button class="sg-btn sg-btn-ghost sg-btn-block" type="submit">Skip</button></form>')
            .'<p class="sg-muted sg-mt">Without a password the scanner is open to anyone who knows its address, and it '
            .'<b>removes itself automatically</b> 3 hours after it was uploaded - in about '.self::H(self::TimeLeft()).'. '
            .'With a password it stays until you remove it.</p>');
        echo '</div>';
        self::Foot();
    }

    private static function ActionSetup()
    {
        $state = self::StateLoad();
        if (self::HasPassword($state)) { self::Redirect(''); return; }

        $p1 = (string)self::Request('password');
        $p2 = (string)self::Request('password2');
        if (strlen($p1) < SG_PASSWORD_MIN) self::$error = 'The password is too short: at least '.SG_PASSWORD_MIN.' characters.';
        else if ($p1 !== $p2)             self::$error = 'The two passwords are different.';
        if (self::$error !== '') { self::PageSetup(); return; }

        $state['password'] = self::HashPassword($p1);
        $state['secret'] = self::RandomHex(32);
        $state['created'] = time();
        unset($state['skipped']);
        if (!self::StateSave($state)) { self::$error = 'Cannot write the settings into '.SG_WORK_DIR.'/. Please check the permissions of the folder.'; self::PageSetup(); return; }

        self::SessionStart();
        self::Redirect('');
    }

    /** "Skip": the scanner works without a password and removes itself SG_NO_PASSWORD_TTL after the upload */
    private static function ActionSkip()
    {
        $state = self::StateLoad();
        if (self::HasPassword($state)) { self::Redirect(''); return; }
        $state['skipped'] = 1;
        if (!isset($state['secret']) || $state['secret'] === '') $state['secret'] = self::RandomHex(32);
        if (!isset($state['created'])) $state['created'] = time();
        if (!self::StateSave($state)) { self::$error = 'Cannot write the settings into '.SG_WORK_DIR.'/. Please check the permissions of the folder.'; self::PageSetup(); return; }
        self::Redirect('');
    }

    /**
     * No password and the file is older than SG_NO_PASSWORD_TTL: delete the scanner and its settings.
     * If the file cannot be deleted, the scanner still refuses to work.
     */
    private static function SelfDestruct($is_json)
    {
        @unlink(self::StateFile());
        $gone = @unlink(__FILE__);
        if (!headers_sent()) header('HTTP/1.1 410 Gone', true, 410);
        $msg = $gone
            ? 'The scanner has removed itself: it was not protected by a password and was uploaded more than 3 hours ago.'
            : 'The scanner is switched off: it was not protected by a password and was uploaded more than 3 hours ago. Please delete '.self::SelfName().' from the website.';
        if ($is_json) { self::Json(array('error' => $msg)); return; }
        self::Head('Removed', false);
        echo '<div class="sg-narrow">'.self::Card('The scanner is no longer here',
            '<p>'.self::H($msg).'</p><p class="sg-muted">To scan the website again, upload '.self::H(self::SelfName()).' once more.</p>').'</div>';
        self::Foot();
    }

    // ---- login

    private static function PageLogin()
    {
        $left = self::LoginBlockedFor();
        self::Head('Sign in');
        echo '<div class="sg-narrow">';
        if ($left > 0)
        {
            echo self::Card('Sign in', '<p>Too many wrong passwords. Please try again in '.ceil($left / 60).' min.</p>');
        }
        else
        {
            echo self::Card('Sign in',
                '<form method="post" autocomplete="off">'
                .self::Hidden('task', 'login')
                .'<label class="sg-label" for="p">Scanner password</label>'
                .'<input class="sg-input" type="password" id="p" name="password" autocomplete="current-password" autofocus required>'
                .'<button class="sg-btn sg-btn-primary sg-btn-block" type="submit">Sign in</button>'
                .'</form>'
                .'<p class="sg-muted sg-mt">Lost the password? Delete <code>'.self::H(SG_WORK_DIR).'/sg_scanner_state.php</code> on the server '
                .'and upload the scanner again - then you can set a new one.</p>');
        }
        echo '</div>';
        self::Foot();
    }

    private static function ActionLogin()
    {
        if (self::LoginBlockedFor() > 0) { self::PageLogin(); return; }
        $state = self::StateLoad();
        $password = (string)self::Request('password');

        if (self::VerifyPassword($password, isset($state['password']) ? $state['password'] : ''))
        {
            $state['login_fails'] = 0; $state['login_blocked'] = 0;
            self::StateSave($state);
            self::SessionStart();
            self::Redirect('');
            return;
        }

        $fails = isset($state['login_fails']) ? intval($state['login_fails']) + 1 : 1;
        $state['login_fails'] = $fails;
        if ($fails >= SG_LOGIN_MAX_TRIES) { $state['login_blocked'] = time() + SG_LOGIN_BLOCK; $state['login_fails'] = 0; }
        self::StateSave($state);
        self::$error = 'Wrong password.';
        self::PageLogin();
    }

    private static function ActionLogout()
    {
        self::SetCookie('');
        self::Redirect('');
    }

    // ---- dashboard

    private static function PageDashboard()
    {
        $installed = self::AgentInstalled();
        $key = self::AccessKey();
        $license = ($key === '') ? null : self::LicenseInfo($key);
        $state = self::StateLoad();
        $bl = isset($state['blacklist']) && is_array($state['blacklist']) ? $state['blacklist'] : null;

        self::Head('Website Antivirus');

        // Status of the website
        $rows = '';
        $rows .= self::Row('Website', self::H(self::Host()));
        if (!$installed)
        {
            $rows .= self::Row('Antivirus agent', self::Badge('Not installed', 'red'));
        }
        else if ($license === null)
        {
            $rows .= self::Row('Antivirus agent', self::Badge('Installed', 'green').' <span class="sg-muted">no answer from SiteGuarding yet</span>');
        }
        else
        {
            $rows .= self::Row('Antivirus agent', self::Badge('Installed', 'green'));
            $plan = isset($license['membership']) ? ucwords((string)$license['membership']) : 'Trial';
            $exp = isset($license['exp_date']) ? (string)$license['exp_date'] : '';
            $expired = ($exp !== '' && $exp < date('Y-m-d'));
            $plan_html = self::Badge($plan, $expired ? 'grey' : 'green');
            if ($exp !== '') $plan_html .= ' <span class="sg-muted">valid till '.self::H($exp).'</span>';
            if ($expired) $plan_html .= ' '.self::Badge('Expired', 'red')
                .' <a class="sg-link" target="_blank" rel="noopener" href="'.self::H(SG_SERVER.'en/buy-service/antivirus-site-protection?domain='.urlencode(self::Host())).'">Renew</a>';
            $rows .= self::Row('Subscription', $plan_html);

            $g = isset($license['blacklist']['google']) ? (string)$license['blacklist']['google'] : 'ok';
            $rows .= self::Row('Google Safe Browsing', ($g === 'ok')
                ? self::Badge('Clean', 'green')
                : self::Badge('Blacklisted', 'red').' <a class="sg-link" target="_blank" rel="noopener" href="'.self::H(SG_SERVER.'en/services/malware-removal-service').'">Get it removed</a>');

            $fm = isset($license['filemonitoring']['status']) ? intval($license['filemonitoring']['status']) : 0;
            $rows .= self::Row('File change monitoring', $fm
                ? self::Badge('Enabled', 'green')
                : self::Badge('Disabled', 'grey').' <a class="sg-link" target="_blank" rel="noopener" href="'.self::H(SG_SERVER.'en/protect-your-website').'">Enable</a>');

            $rows .= self::Row('Last scan', self::ScanVerdict($license));
        }
        $rows .= self::Row('Blacklist check', ($bl === null)
            ? self::Badge('Never checked', 'grey').' <a class="sg-link" href="?task=blacklist">Check now</a>'
            : (count(isset($bl['blacklisted']) && is_array($bl['blacklisted']) ? $bl['blacklisted'] : array()) > 0
                ? self::Badge('Listed', 'red').' <a class="sg-link" href="?task=blacklist">Details</a>'
                : self::Badge('Not listed', 'green').' <a class="sg-link" href="?task=blacklist">Check again</a>'));

        echo self::Card('Your website', '<div class="sg-rows">'.$rows.'</div>');

        // Install or scan
        if (!$installed)
        {
            echo self::Card('Install the antivirus agent',
                '<p>The scanner needs our agent on the website: it collects the files and sends them to SiteGuarding for analysis. '
                .'Installation is free and takes a few seconds.</p>'
                .'<form method="post" class="sg-form-inline">'
                .self::Hidden('task', 'install')
                .'<input class="sg-input" type="email" name="email" placeholder="your@email.com" value="'.self::H((string)self::Request('email')).'" required>'
                .'<button class="sg-btn sg-btn-primary" type="submit">Install the agent</button>'
                .'</form>'
                .'<p class="sg-muted sg-mt">We send the scan reports to this address. The website is registered on '
                .'<a class="sg-link" target="_blank" rel="noopener" href="'.self::H(SG_SERVER).'">siteguarding.com</a>.</p>');
        }
        else
        {
            // Free plan: the server analyzes one scan a day for a website; a second scan of the same day gets the
            // report of that day again (server, since 11.10.2026). Warn before the start: no new report will come.
            $plan_html = '';
            $confirm = '';
            if ($license !== null && !self::IsPaid($license))
            {
                $today = self::FreeScanToday($license);
                if ($today !== null)
                {
                    $plan_html = '<div class="sg-msg sg-msg-warn"><b>This website was already scanned today.</b> The free plan allows one scan '
                        .'a day, so a scan started now will show today\'s report again. A new scan is possible tomorrow.'
                        .(isset($today['report_link']) ? ' <a class="sg-link" target="_blank" rel="noopener" href="'.self::H((string)$today['report_link'].'&showtrial=1').'">Open today\'s report</a>' : '')
                        .'</div>';
                    $confirm = ' onsubmit="return confirm(\'This website was already scanned today. On the free plan this scan will show the same report again. Start it anyway?\');"';
                }
                else
                {
                    $plan_html = '<p class="sg-muted">Free plan: one scan a day for each website. '
                        .'<a class="sg-link" target="_blank" rel="noopener" href="'.self::H(SG_SERVER.'en/buy-service/antivirus-site-protection?domain='.urlencode(self::Host())).'">See the paid plans</a></p>';
                }
            }

            echo self::Card('Scan the website',
                '<p>The scan collects the code of your website and analyzes it on our servers. It usually takes 2 to 10 minutes, '
                .'depending on the size of the website and the speed of the server.</p>'
                .$plan_html
                .'<form method="post" class="sg-choice"'.$confirm.'>'
                .self::Hidden('task', 'scan_start')
                .'<label class="sg-radio"><input type="radio" name="mode" value="quick" checked>'
                .'<span><b>Quick scan</b><em>Recommended. Takes every PHP file and every other server script, by file name.</em></span></label>'
                .'<label class="sg-radio"><input type="radio" name="mode" value="deep">'
                .'<span><b>Deep scan</b><em>Also reads images, templates and other files to find PHP code hidden inside them. Slower.</em></span></label>'
                .'<button class="sg-btn sg-btn-primary sg-btn-lg" type="submit">Start the scan</button>'
                .'</form>');

            if ($license !== null && isset($license['reports']) && is_array($license['reports']) && count($license['reports']))
            {
                $list = '';
                foreach ($license['reports'] as $r)
                {
                    if (!is_array($r) || !isset($r['report_link'])) continue;
                    $list .= '<li><a class="sg-link" target="_blank" rel="noopener" href="'.self::H((string)$r['report_link'].'&showtrial=1').'">Report of '
                        .self::H(isset($r['date']) ? (string)$r['date'] : '').'</a></li>';
                }
                if ($list !== '') echo self::Card('Earlier reports', '<ul class="sg-list">'.$list.'</ul>');
            }
        }

        // Finish
        $tools = file_exists(self::Root().'/siteguarding_tools.php');
        echo self::Card('When you are done',
            '<p>The scanner is a temporary tool. Remove it when you have the report - a page like this should not stay on a live website.</p>'
            .'<form method="post" onsubmit="return confirm(\'Remove the scanner from the website?\');">'
            .self::Hidden('task', 'remove')
            .'<label class="sg-check"><input type="checkbox" name="with_agent" value="1"> <span>Remove the antivirus agent as well '
            .'(the website stops being scanned by SiteGuarding)</span></label>'
            .'<button class="sg-btn sg-btn-danger" type="submit">Remove the scanner</button>'
            .'</form>'
            .'<p class="sg-muted sg-mt">Support tool <code>siteguarding_tools.php</code>: '
            .($tools ? 'installed in the website root.' : 'not installed. <a class="sg-link" href="?task=tools&amp;csrf='.self::H(self::Csrf()).'">Install it</a> if our support asked for it.')
            .'<br>Server check: <a class="sg-link" href="?task=env">PHP, extensions, permissions, connection</a>.</p>');

        self::Foot();
    }

    private static function ScanVerdict($license)
    {
        if (!isset($license['reports']) || !is_array($license['reports']) || !count($license['reports'])) return self::Badge('Never scanned', 'grey');
        $c = isset($license['last_scan_files_counters']) && is_array($license['last_scan_files_counters']) ? $license['last_scan_files_counters'] : array();
        $main = isset($c['main']) ? intval($c['main']) : 0;
        $heur = isset($c['heuristic']) ? intval($c['heuristic']) : 0;
        if ($main > 0) return self::Badge('Infected', 'red').' <a class="sg-link" target="_blank" rel="noopener" href="'.self::H(SG_SERVER.'en/services/malware-removal-service').'">Clean my website</a>';
        if ($heur > 0) return self::Badge('Needs a review', 'amber').' <a class="sg-link" target="_blank" rel="noopener" href="'.self::H(SG_SERVER.'en/services/malware-removal-service').'">Ask us to review</a>';
        return self::Badge('Clean', 'green');
    }

    /** A paid plan has scans on the server; without them (free, trial, expired) a website gets one scan a day */
    private static function IsPaid($license)
    {
        return is_array($license) && isset($license['scans']) && intval($license['scans']) > 0;
    }

    /**
     * The report of today, if there is one: the server counts the day in its own time zone (SG_SERVER_TZ),
     * so "today" is taken there, not on this website. null if the website was not scanned today.
     */
    private static function FreeScanToday($license)
    {
        if (!isset($license['reports']) || !is_array($license['reports'])) return null;
        $today = self::ServerToday();
        foreach ($license['reports'] as $r)
        {
            if (is_array($r) && isset($r['date']) && strncmp((string)$r['date'], $today, 10) === 0) return $r;
        }
        return null;
    }

    private static function ServerToday()
    {
        try { $d = new DateTime('now', new DateTimeZone(SG_SERVER_TZ)); return $d->format('Y-m-d'); }
        catch (Exception $e) { return gmdate('Y-m-d'); }
    }

    // ---- installation of the agent

    private static function ActionInstall()
    {
        self::CsrfCheck();
        $email = trim((string)self::Request('email'));
        if ($email === '' || !preg_match('/^[^@\s]+@[^@\s.]+\.[^@\s]{2,}$/', $email)) { self::$error = 'Please enter a valid email address.'; self::PageDashboard(); return; }

        $host = self::Host();
        // The server registers the website and calls webanalyze/antivirus_installer.php back with the key
        $answer = self::ApiGet('register', array(
            'domain' => 'http://'.$host,
            'email' => $email,
            'access_key' => '',
            'errors' => '',
            'call_back' => 1,
        ), false);

        $state = self::StateLoad(); $state['email'] = $email; self::StateSave($state);

        if (self::AgentInstalled()) { self::RemoveInstaller(); self::$notice = 'The antivirus agent is installed. You can scan the website now.'; self::PageDashboard(); return; }

        // The call back did not reach us (a firewall, or the website is already registered). Ask the
        // server for the key of this website by proving that we own it, and install the agent ourselves.
        $result = self::RecoverKeyAndInstall();
        if ($result === true) { self::RemoveInstaller(); self::$notice = 'The antivirus agent is installed. You can scan the website now.'; self::PageDashboard(); return; }

        $answer = trim((string)$answer);
        if ($answer !== '' && stripos($answer, 'installation_ok') === false && strlen($answer) < 400) self::$error = 'SiteGuarding: '.self::H($answer).' '.$result;
        else self::$error = $result;
        self::PageDashboard();
    }

    /**
     * Gets the access key of this website from the server (it answers only after we have proved that the
     * website is ours) and installs the agent. true, or a message why it did not work.
     */
    private static function RecoverKeyAndInstall()
    {
        $code = strtoupper(self::RandomHex(16));
        $proof = self::Work().'/antivirus_verification_'.$code.'.txt';
        if (@file_put_contents($proof, md5($code)) === false) return 'Cannot write into '.SG_WORK_DIR.'/ - please check the permissions of the folder.';

        $key = trim((string)self::ApiGet('register', array(
            'domain' => 'http://'.self::Host(),
            'domain_verification' => $code,
            'call_back' => 0,
        ), false));
        @unlink($proof);

        if (!preg_match('/^[0-9a-fA-F]{32}$/', $key))
        {
            if (stripos($key, 'verification') !== false) return 'SiteGuarding could not read the file we created for the check. If the website is behind a firewall or a password, please open it for siteguarding.com and try again.';
            return 'SiteGuarding did not confirm the registration of this website. Please contact our support.';
        }

        $agent = self::Download(SG_SERVER.'_get_file.php?file=antivirus&time='.time());
        if ($agent === false) return 'Cannot download the antivirus from SiteGuarding ('.self::H(self::$http_error).').';
        if (!self::LooksLikeAgent($agent)) return 'The downloaded antivirus file is damaged ('.strlen($agent).' bytes). Please try again.';

        if (!self::WriteFile(self::Work().'/antivirus_config.php', "<?php\ndefine(\"ACCESS_KEY\", ".var_export($key, true).");\n?>\n")) return 'Cannot write '.SG_WORK_DIR.'/antivirus_config.php.';
        if (!self::WriteFile(self::Work().'/antivirus.php', $agent)) return 'Cannot write '.SG_WORK_DIR.'/antivirus.php.';
        if (!file_exists(self::Work().'/index.html')) @file_put_contents(self::Work().'/index.html', '<html><body></body></html>');
        return true;
    }

    /**
     * The installer from the ZIP package is needed only until the agent is there. It removes itself after a
     * call of the server; when the agent came another way (the check of the domain), it would stay behind.
     */
    private static function RemoveInstaller()
    {
        $f = self::Work().'/antivirus_installer.php';
        if (file_exists($f)) @unlink($f);
    }

    private static function LooksLikeAgent($code)
    {
        return (strlen($code) > 50000 && substr($code, 0, 5) === '<?php'
            && strpos($code, "define('SCRIPT_VERSION'") !== false
            && strpos($code, 'Dont delete this line 95D5C9AB68C2') !== false);
    }

    // ---- the scan

    private static function ActionScanStart()
    {
        self::CsrfCheck();
        $key = self::AccessKey();
        if ($key === '') { self::$error = 'The antivirus agent is not installed yet.'; self::PageDashboard(); return; }

        $deep = (self::Request('mode') === 'deep');
        $state = self::StateLoad();
        $session_report_key = md5(self::RandomHex(16));
        $state['scan'] = array('key' => $session_report_key, 'started' => time(), 'deep' => $deep ? 1 : 0);
        self::StateSave($state);

        // The agent is told to work by a request to our own website. It keeps running after the request
        // is cut off (ignore_user_abort), so a few seconds are enough to start it.
        $fields = array(
            'task' => 'scan',
            'access_key' => $key,
            'session_report_key' => $session_report_key,
            'email' => isset($state['email']) ? $state['email'] : '',
            'no_html' => '1',
        );
        if ($deep) $fields['content_scan'] = '1';

        @unlink(self::Work().'/flag_terminated.tmp');
        @unlink(self::Work().'/antivirus_error.log');
        $started = self::SelfPost(SG_WORK_DIR.'/antivirus.php', $fields);
        if ($started !== true) { self::$error = 'Cannot start the antivirus on this website: '.self::H((string)$started); self::PageDashboard(); return; }

        self::Redirect('?task=scan');
    }

    private static function PageScan()
    {
        $state = self::StateLoad();
        $scan = isset($state['scan']) && is_array($state['scan']) ? $state['scan'] : null;
        if ($scan === null) { self::Redirect(''); return; }
        $report = SG_SERVER.'antivirus/viewreport?report_id='.urlencode($scan['key']).'&showtrial=1';

        self::Head('Scanning');
        echo self::Card('Scanning your website',
            '<div class="sg-progress"><div class="sg-progress-bar" id="sg-bar" style="width:2%"></div></div>'
            .'<p class="sg-progress-txt" id="sg-txt">Starting...</p>'
            .'<p class="sg-muted">You can leave this page open. '.($scan['deep'] ? 'A deep scan' : 'A scan').' usually takes 2 to 10 minutes.</p>'
            .'<p id="sg-done" class="sg-hidden"><a class="sg-btn sg-btn-primary" target="_blank" rel="noopener" href="'.self::H($report).'">Open the report</a> '
            .'<a class="sg-btn sg-btn-ghost" href="?">Back to the scanner</a></p>'
            .'<p class="sg-muted sg-mt">If the page stops moving, the report will still be here: '
            .'<a class="sg-link" target="_blank" rel="noopener" href="'.self::H($report).'">open it directly</a>.</p>');
        ?>
<script>
(function () {
    var bar = document.getElementById('sg-bar'), txt = document.getElementById('sg-txt'), done = document.getElementById('sg-done');
    var fails = 0;
    function poll() {
        var r = new XMLHttpRequest();
        r.open('GET', '?task=progress&cache=' + Date.now(), true);
        r.onload = function () {
            var d;
            try { d = JSON.parse(r.responseText); } catch (e) { return retry(); }
            fails = 0;
            if (d.error) { txt.className = 'sg-progress-txt sg-red'; txt.textContent = d.error; return; }
            var p = Math.max(2, Math.min(100, d.percent || 0));
            bar.style.width = p + '%';
            txt.textContent = p + '% - ' + (d.text || '');
            if (d.done) { bar.style.width = '100%'; txt.textContent = 'The analysis is ready.'; done.className = ''; return; }
            setTimeout(poll, 3000);
        };
        r.onerror = retry;
        r.send();
    }
    function retry() { if (++fails > 10) { txt.textContent = 'No answer from the server. Open the report by the link below.'; return; } setTimeout(poll, 5000); }
    poll();
})();
</script>
        <?php
        self::Foot();
    }

    /** Progress of the scan: read from the files of the agent, no access key is needed for that */
    private static function AnswerProgress()
    {
        self::Json(self::ProgressData());
    }

    private static function ProgressData()
    {
        $work = self::Work();
        if (file_exists($work.'/antivirus_error.log'))
        {
            $msg = trim((string)@file_get_contents($work.'/antivirus_error.log'));
            if ($msg !== '') return array('error' => self::Cut($msg, 300));
        }
        if (file_exists($work.'/flag_terminated.tmp')) return array('done' => true, 'percent' => 100, 'text' => 'Ready');

        $percent = 2; $text = 'Working...';
        $log = @file_get_contents($work.'/antivirus_last_action.log');
        if ($log !== false)
        {
            $a = json_decode($log, true);
            if (is_array($a))
            {
                if (isset($a['progress'])) $percent = (float)$a['progress'];
                if (isset($a['txt'])) $text = trim((string)$a['txt']);
            }
        }
        $state = self::StateLoad();
        $started = (isset($state['scan']['started'])) ? intval($state['scan']['started']) : 0;
        if ($percent < 2 && $started > 0 && time() - $started > 1500) return array('error' => 'The scan did not finish in time. Please start it again, or contact our support.');
        return array('done' => false, 'percent' => $percent, 'text' => $text);
    }

    // ---- blacklists

    private static function PageBlacklist()
    {
        $state = self::StateLoad();
        $bl = isset($state['blacklist']) && is_array($state['blacklist']) ? $state['blacklist'] : null;
        self::Head('Blacklists');

        echo self::Card('Blacklist check',
            '<p>We check your website and its server against 100+ blacklists, including the spam ones. '
            .'A listed website loses most of its visitors, and its email is treated as spam.</p>'
            .'<p><button class="sg-btn sg-btn-primary" id="sg-bl-start" type="button">'.($bl === null ? 'Check the blacklists' : 'Check again').'</button> '
            .'<a class="sg-btn sg-btn-ghost" href="?">Back</a></p>'
            .'<p id="sg-bl-msg" class="sg-progress-txt sg-hidden">Checking, it takes up to a minute...</p>');

        if ($bl !== null)
        {
            $listed = isset($bl['blacklisted']) && is_array($bl['blacklisted']) ? $bl['blacklisted'] : array();
            $clean = isset($bl['clean']) && is_array($bl['clean']) ? $bl['clean'] : array();
            $when = isset($state['blacklist_date']) ? date('Y-m-d H:i', intval($state['blacklist_date'])) : '';

            if (count($listed))
            {
                $rows = '';
                foreach ($listed as $r)
                {
                    if (!is_array($r)) continue;
                    $url = isset($r['delist_url']) ? (string)$r['delist_url'] : '';
                    $rows .= '<tr><td>'.self::H(isset($r['name']) ? strip_tags((string)$r['name']) : '').'</td>'
                        .'<td>'.($url === '' ? '' : '<a class="sg-link" target="_blank" rel="noopener nofollow" href="'.self::H($url).'">Delisting form</a>').'</td>'
                        .'<td class="sg-right">'.self::Badge('Listed', 'red').'</td></tr>';
                }
                echo self::Card('Your website is on '.count($listed).' blacklist'.(count($listed) > 1 ? 's' : ''),
                    '<table class="sg-table">'.$rows.'</table>'
                    .'<p class="sg-mt"><a class="sg-btn sg-btn-danger" target="_blank" rel="noopener" href="'.self::H(SG_SERVER.'en/website-blacklist-removal-service').'">Get my website delisted</a></p>');
            }
            else
            {
                echo self::Card('Not listed', '<p>'.self::Badge('Clean', 'green').' Your website was not found on any of the checked blacklists.'
                    .($when === '' ? '' : ' <span class="sg-muted">Checked '.self::H($when).'.</span>').'</p>');
            }

            if (count($clean))
            {
                $rows = '';
                foreach ($clean as $r) { if (is_array($r) && isset($r['name'])) $rows .= '<tr><td>'.self::H(strip_tags((string)$r['name'])).'</td><td class="sg-right">'.self::Badge('OK', 'green').'</td></tr>'; }
                echo self::Card('Checked and clean ('.count($clean).')', '<table class="sg-table sg-table-compact">'.$rows.'</table>');
            }
        }
        ?>
<script>
document.getElementById('sg-bl-start').onclick = function () {
    var b = this, m = document.getElementById('sg-bl-msg');
    b.disabled = true; m.className = 'sg-progress-txt';
    var r = new XMLHttpRequest();
    r.open('POST', '?', true);
    r.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    r.onload = function () {
        var d = null;
        try { d = JSON.parse(r.responseText); } catch (e) {}
        if (d && d.ok) { location.href = '?task=blacklist'; return; }
        m.className = 'sg-progress-txt sg-red';
        m.textContent = (d && d.error) ? d.error : 'The check did not work. Please try again later.';
        b.disabled = false;
    };
    r.onerror = function () { m.className = 'sg-progress-txt sg-red'; m.textContent = 'No answer from the server.'; b.disabled = false; };
    r.send('task=blacklist_check&csrf=<?php echo self::H(self::Csrf()); ?>');
};
</script>
        <?php
        self::Foot();
    }

    private static function AnswerBlacklistCheck()
    {
        if (!self::IsLoggedIn() || !self::CsrfValid()) { self::Json(array('error' => 'Please sign in again.')); return; }
        $answer = self::HttpPost(SG_SERVER.'index.php', array(
            'option' => 'com_securapp',
            'task' => 'API_mail_blacklist',
            'website_url' => self::SiteUrl(),
        ));
        if ($answer === false) { self::Json(array('error' => 'No answer from SiteGuarding ('.self::$http_error.').')); return; }
        $json = json_decode($answer, true);
        $report = (is_array($json) && isset($json['report'])) ? json_decode((string)$json['report'], true) : null;
        if (!is_array($report)) { self::Json(array('error' => 'SiteGuarding returned an unexpected answer.')); return; }

        $state = self::StateLoad();
        $state['blacklist'] = array(
            'blacklisted' => isset($report['blacklisted']) && is_array($report['blacklisted']) ? $report['blacklisted'] : array(),
            'clean' => isset($report['clean']) && is_array($report['clean']) ? $report['clean'] : array(),
        );
        $state['blacklist_date'] = time();
        self::StateSave($state);
        self::Json(array('ok' => true));
    }

    // ---- support tool, server check, removal

    private static function ActionInstallTools()
    {
        if (!self::CsrfValid()) { self::$error = 'The page has expired, please try again.'; self::PageDashboard(); return; }
        $expected = trim((string)self::Download(SG_SERVER.'_get_file.php?task=md5&file=siteguarding_tools.php'));
        $code = self::Download(SG_SERVER.'_get_file.php?file=siteguarding_tools.php&time='.time());
        if ($code === false) { self::$error = 'Cannot download the support tool ('.self::H(self::$http_error).').'; self::PageDashboard(); return; }
        if (!preg_match('/^[0-9a-f]{32}$/i', $expected) || md5($code) !== strtolower($expected)) { self::$error = 'The downloaded support tool did not pass the check. Nothing was written.'; self::PageDashboard(); return; }
        if (substr($code, 0, 5) !== '<?php') { self::$error = 'The downloaded support tool is damaged. Nothing was written.'; self::PageDashboard(); return; }
        if (!self::WriteFile(self::Root().'/siteguarding_tools.php', $code)) { self::$error = 'Cannot write siteguarding_tools.php into the website root.'; self::PageDashboard(); return; }
        self::$notice = 'The support tool is installed. Remove it together with the scanner when the work is done.';
        self::PageDashboard();
    }

    private static function PageEnv($env, $blocking)
    {
        self::Head('Server check');
        $rows = '';
        foreach ($env as $e)
        {
            $rows .= self::Row(self::H($e['label']),
                ($e['ok'] ? self::Badge('OK', 'green') : self::Badge($e['required'] ? 'Problem' : 'Attention', $e['required'] ? 'red' : 'amber'))
                .' <span class="sg-muted">'.$e['note'].'</span>');
        }
        $extra = $blocking
            ? '<p class="sg-mt"><b>The scanner cannot work until this is fixed.</b> Give the folder <code>'.self::H(SG_WORK_DIR)
              .'</code> in the website root permission to write (0755, or 0777 on some servers), then reload this page.</p>'
            : '<p class="sg-mt"><a class="sg-btn sg-btn-ghost" href="?">Back to the scanner</a></p>';
        echo self::Card('Your server', '<div class="sg-rows">'.$rows.'</div>'.$extra);
        self::Foot();
    }

    /** Creates webanalyze/ if it is not there yet; no network, so it is cheap enough for every request */
    private static function WorkDirReady()
    {
        $work = self::Work();
        if (!file_exists($work)) @mkdir($work, 0755);
        return (file_exists($work) && is_writable($work));
    }

    private static function EnvCheck()
    {
        $writable = self::WorkDirReady();
        $php_ok = (PHP_VERSION_ID >= 50600);
        $curl = function_exists('curl_init');
        $out = ($curl ? (self::Download(SG_SERVER.'_get_file.php?task=md5&file=siteguarding_tools.php') !== false) : false);
        $free = @disk_free_space(self::Root());

        return array(
            'php' => array('label' => 'PHP version', 'ok' => $php_ok, 'required' => true,
                'note' => self::H(PHP_VERSION).($php_ok ? '' : ' - the scanner needs PHP 5.6 or newer')),
            'work_dir' => array('label' => 'Folder '.SG_WORK_DIR.'/', 'ok' => $writable, 'required' => true,
                'note' => $writable ? 'exists and is writable' : 'cannot be created or written'),
            'curl' => array('label' => 'cURL extension', 'ok' => $curl, 'required' => true,
                'note' => $curl ? 'installed' : 'missing - please ask your hosting provider to enable it'),
            'openssl' => array('label' => 'OpenSSL extension', 'ok' => extension_loaded('openssl'), 'required' => false,
                'note' => extension_loaded('openssl') ? 'installed' : 'missing - HTTPS connections may fail'),
            'outgoing' => array('label' => 'Connection to siteguarding.com', 'ok' => $out, 'required' => true,
                'note' => $out ? 'works over HTTPS' : 'no answer: '.self::H(self::$http_error === '' ? 'blocked by the server' : self::$http_error)),
            'exec' => array('label' => 'Packing of the files', 'ok' => (function_exists('exec') || class_exists('ZipArchive')), 'required' => false,
                'note' => function_exists('exec') ? 'tar is available' : (class_exists('ZipArchive') ? 'ZipArchive is available' : 'neither exec() nor ZipArchive - the agent will use its own slower packer')),
            'disk' => array('label' => 'Free disk space', 'ok' => ($free === false || $free > 50 * 1024 * 1024), 'required' => false,
                'note' => ($free === false) ? 'unknown' : self::Size($free).' free'),
        );
    }

    private static function ActionRemove()
    {
        self::CsrfCheck();
        $with_agent = (self::Request('with_agent') === '1');
        $removed = array();
        $left = array();

        $work = self::Work();
        if ($with_agent)
        {
            foreach (array('antivirus.php', 'antivirus_config.php', 'antivirus_last_action.log',
                'antivirus_scan.lock', 'antivirus_sql.lock', 'antivirus_error.log', 'antivirus.debug.log', 'flag_terminated.tmp',
                'scan_run.json', 'content_scan_off.flag', 'index.html') as $f)
            {
                if (file_exists($work.'/'.$f)) { if (@unlink($work.'/'.$f)) $removed[] = SG_WORK_DIR.'/'.$f; else $left[] = SG_WORK_DIR.'/'.$f; }
            }
            foreach (array('debug_*.log', 'filelist_*.txt', 'report_*.php', 'pack_*.tar', 'pack_*.zip', 'check_*.zip') as $mask)
            {
                $files = @glob($work.'/'.$mask);
                if (is_array($files)) foreach ($files as $f) { if (@unlink($f)) $removed[] = SG_WORK_DIR.'/'.basename($f); else $left[] = SG_WORK_DIR.'/'.basename($f); }
            }
        }
        // the installer belongs to the package of the scanner, not to the agent: it goes with the scanner
        if (file_exists($work.'/antivirus_installer.php')) { if (@unlink($work.'/antivirus_installer.php')) $removed[] = SG_WORK_DIR.'/antivirus_installer.php'; else $left[] = SG_WORK_DIR.'/antivirus_installer.php'; }
        if (file_exists(self::Root().'/siteguarding_tools.php')) { if (@unlink(self::Root().'/siteguarding_tools.php')) $removed[] = 'siteguarding_tools.php'; else $left[] = 'siteguarding_tools.php'; }
        if (file_exists(self::StateFile())) { if (@unlink(self::StateFile())) $removed[] = SG_WORK_DIR.'/sg_scanner_state.php'; else $left[] = SG_WORK_DIR.'/sg_scanner_state.php'; }
        if ($with_agent) @rmdir($work);     // only if it is empty

        $self = self::SelfName();
        $self_gone = @unlink(__FILE__);
        if ($self_gone) $removed[] = $self; else $left[] = $self;
        self::SetCookie('');

        self::Head('Removed', false);
        $html = '<p>'.($self_gone
            ? 'The scanner is removed from your website. This page is already gone from the server - closing it is all that is left.'
            : '<b>The scanner could not delete itself.</b> Please delete <code>'.self::H($self).'</code> from the website root with your file manager or FTP.').'</p>';
        if (count($removed)) $html .= '<p class="sg-muted">Removed: '.self::H(implode(', ', $removed)).'</p>';
        if (count($left)) $html .= '<p class="sg-red">Please remove by hand: '.self::H(implode(', ', $left)).'</p>';
        if (!$with_agent) $html .= '<p class="sg-muted">The antivirus agent stays in <code>'.self::H(SG_WORK_DIR).'/</code> and keeps protecting the website.</p>';
        $html .= '<p class="sg-mt">Thank you for using <a class="sg-link" target="_blank" rel="noopener" href="'.self::H(SG_SERVER).'">SiteGuarding</a>.</p>';
        echo self::Card('The scanner is removed', $html);
        self::Foot();
    }

    /**
     * Requests to SiteGuarding
     */
    public static $http_error = '';

    private static function ApiGet($action, $data, $parse_json = true)
    {
        $url = SG_API.'?action='.urlencode($action).'&type=json&data='.urlencode(base64_encode(json_encode($data)));
        $body = self::Download($url);
        if ($body === false) return $parse_json ? null : false;
        if (!$parse_json) return $body;
        $json = json_decode($body, true);
        return is_array($json) ? $json : null;
    }

    private static function LicenseInfo($key)
    {
        return self::ApiGet('licenseinfo', array(
            'domain' => 'http://'.self::Host(),
            'access_key' => $key,
            'product_type' => 'any',
            'version' => 'standalone-'.SG_VERSION,
        ));
    }

    /** GET over HTTPS, certificate checked, no redirects. The body, or false */
    private static function Download($url)
    {
        self::$http_error = '';
        if (!function_exists('curl_init')) { self::$http_error = 'the cURL extension is missing'; return false; }
        if (stripos($url, 'https://') !== 0) { self::$http_error = 'only HTTPS is allowed'; return false; }

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
        if (defined('CURLOPT_PROTOCOLS') && defined('CURLPROTO_HTTPS')) curl_setopt($ch, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
        curl_setopt($ch, CURLOPT_TIMEOUT, 120);
        curl_setopt($ch, CURLOPT_USERAGENT, 'SiteGuarding-Scanner/'.SG_VERSION);
        $body = curl_exec($ch);
        $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($body === false) self::$http_error = curl_error($ch);
        else if ($code !== 200) self::$http_error = 'HTTP '.$code;
        if (PHP_VERSION_ID < 80000) curl_close($ch);
        if ($body === false || $code !== 200) return false;
        return $body;
    }

    private static function HttpPost($url, $fields)
    {
        self::$http_error = '';
        if (!function_exists('curl_init')) { self::$http_error = 'the cURL extension is missing'; return false; }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
        curl_setopt($ch, CURLOPT_TIMEOUT, 180);
        curl_setopt($ch, CURLOPT_USERAGENT, 'SiteGuarding-Scanner/'.SG_VERSION);
        $body = curl_exec($ch);
        $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($body === false) self::$http_error = curl_error($ch);
        else if ($code !== 200) self::$http_error = 'HTTP '.$code;
        if (PHP_VERSION_ID < 80000) curl_close($ch);
        if ($body === false || $code !== 200) return false;
        return $body;
    }

    /**
     * Starts a script of this same website (the agent) and does not wait for it to finish. The access key
     * travels in the POST body of a request that stays on this server: first HTTPS to ourselves with the
     * certificate checked, then - if the certificate of the website is not valid - the same request to
     * 127.0.0.1 so that it never leaves the machine. true, or the reason why it did not start.
     */
    private static function SelfPost($path, $fields)
    {
        if (!function_exists('curl_init')) return 'the cURL extension is missing';
        $host = self::Host();
        $base = self::SiteUrl();                                    // https://host/path/ or http://host/path/
        $https = (stripos($base, 'https://') === 0);
        // 1. the normal way: the website by its own address (an https certificate must be valid);
        // 2 and 3. the same request to 127.0.0.1, so that it never leaves this machine.
        $attempts = array(array('url' => $base.$path, 'resolve' => '', 'verify' => $https));
        $attempts[] = array('url' => 'https://'.$host.self::SelfDir().$path, 'resolve' => $host.':443:127.0.0.1', 'verify' => false);
        $attempts[] = array('url' => 'http://'.$host.self::SelfDir().$path, 'resolve' => $host.':80:127.0.0.1', 'verify' => false);

        $last = '';
        foreach ($attempts as $a)
        {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $a['url']);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $a['verify']);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, $a['verify'] ? 2 : 0);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
            curl_setopt($ch, CURLOPT_TIMEOUT, 5);               // we only need the agent to start
            curl_setopt($ch, CURLOPT_USERAGENT, 'SiteGuarding-Scanner/'.SG_VERSION);
            if ($a['resolve'] !== '' && defined('CURLOPT_RESOLVE')) curl_setopt($ch, CURLOPT_RESOLVE, array($a['resolve']));
            $body = curl_exec($ch);
            $errno = curl_errno($ch);
            $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $err = curl_error($ch);
            if (PHP_VERSION_ID < 80000) curl_close($ch);

            // A timeout is the normal case: the agent got the request and keeps scanning
            if ($errno === 28 || ($body !== false && $code === 200)) return true;
            if ($body !== false && $code === 404) { $last = 'the agent was not found on the website (HTTP 404)'; continue; }
            $last = ($err !== '') ? $err : ('HTTP '.$code);
        }
        return $last === '' ? 'no answer from the website itself' : $last;
    }

    /**
     * State of the scanner (webanalyze/sg_scanner_state.php, not readable over HTTP)
     */
    private static function StateFile() { return self::Work().'/sg_scanner_state.php'; }

    private static function StateLoad()
    {
        if (self::$state !== null) return self::$state;
        self::$state = array();
        $raw = @file_get_contents(self::StateFile());
        if ($raw !== false)
        {
            $pos = strpos($raw, "\n");
            $json = ($pos === false) ? '' : substr($raw, $pos + 1);
            $a = json_decode($json, true);
            if (is_array($a)) self::$state = $a;
        }
        return self::$state;
    }

    private static function StateSave($state)
    {
        self::$state = $state;
        $ok = self::WriteFile(self::StateFile(), "<?php exit; ?>\n".json_encode($state));
        if ($ok) @chmod(self::StateFile(), 0600);
        return $ok;
    }

    /**
     * Password, login session, CSRF
     */
    private static function HashPassword($password)
    {
        if (function_exists('password_hash'))
        {
            $h = password_hash($password, PASSWORD_DEFAULT);
            if (is_string($h) && $h !== '') return $h;
        }
        $salt = self::RandomHex(16);
        return 'sg1$'.$salt.'$'.self::SlowHash($password, $salt);
    }

    private static function VerifyPassword($password, $hash)
    {
        if ($password === '' || $hash === '') return false;
        if (substr($hash, 0, 4) === 'sg1$')
        {
            $parts = explode('$', $hash);
            if (count($parts) !== 3) return false;
            return self::Equals(self::SlowHash($password, $parts[1]), $parts[2]);
        }
        if (function_exists('password_verify')) return password_verify($password, $hash);
        return false;
    }

    private static function SlowHash($password, $salt)
    {
        $h = $salt.$password;
        for ($i = 0; $i < 100000; $i++) $h = hash('sha256', $h.$salt, true);
        return bin2hex($h);
    }

    private static function SessionStart()
    {
        $state = self::StateLoad();
        $sid = self::RandomHex(16);
        $state['session'] = array('sid' => $sid, 'exp' => time() + SG_SESSION_TTL);
        self::StateSave($state);
        self::SetCookie($sid.'.'.self::Sign($sid));
    }

    public static function IsLoggedIn()
    {
        if (self::OpenMode()) return true;          // "Skip": no password, the page is open
        $state = self::StateLoad();
        if (!self::HasPassword($state)) return false;
        if (!isset($state['session']['sid']) || intval($state['session']['exp']) < time()) return false;
        $cookie = isset($_COOKIE['sgav_session']) ? (string)$_COOKIE['sgav_session'] : '';
        $parts = explode('.', $cookie);
        if (count($parts) !== 2) return false;
        if (!self::Equals($parts[0], (string)$state['session']['sid'])) return false;
        return self::Equals($parts[1], self::Sign($parts[0]));
    }

    public static function Csrf()
    {
        $state = self::StateLoad();
        $sid = isset($state['session']['sid']) ? (string)$state['session']['sid'] : '';
        return self::Sign('csrf.'.$sid);
    }

    private static function CsrfValid()
    {
        $sent = (string)self::Request('csrf');
        return ($sent !== '' && self::Equals($sent, self::Csrf()));
    }

    private static function CsrfCheck()
    {
        if (self::CsrfValid()) return;
        self::$error = 'The page has expired. Please try again.';
        self::PageDashboard();
        exit;
    }

    private static function Sign($data)
    {
        $state = self::StateLoad();
        $secret = isset($state['secret']) ? (string)$state['secret'] : '';
        if ($secret === '') return '';
        return hash_hmac('sha256', $data, $secret);
    }

    private static function Equals($a, $b)
    {
        if (function_exists('hash_equals')) return hash_equals((string)$b, (string)$a);
        $a = (string)$a; $b = (string)$b;
        if (strlen($a) !== strlen($b)) return false;
        $r = 0;
        for ($i = 0; $i < strlen($a); $i++) $r |= ord($a[$i]) ^ ord($b[$i]);
        return ($r === 0);
    }

    private static function LoginBlockedFor()
    {
        $state = self::StateLoad();
        $until = isset($state['login_blocked']) ? intval($state['login_blocked']) : 0;
        return ($until > time()) ? ($until - time()) : 0;
    }

    private static function SetCookie($value)
    {
        $https = self::IsHttps();
        $parts = array('sgav_session='.rawurlencode($value));
        $parts[] = 'Path='.self::SelfDir();
        $parts[] = ($value === '') ? 'Max-Age=0' : 'Max-Age='.SG_SESSION_TTL;
        $parts[] = 'HttpOnly';
        $parts[] = 'SameSite=Lax';
        if ($https) $parts[] = 'Secure';
        if (!headers_sent()) header('Set-Cookie: '.implode('; ', $parts), false);
    }

    /**
     * Small helpers
     */
    public static function Request($name)
    {
        if (isset($_POST[$name]) && is_string($_POST[$name])) return trim($_POST[$name]);
        if (isset($_GET[$name]) && is_string($_GET[$name])) return trim($_GET[$name]);
        return '';
    }

    private static function RandomHex($bytes)
    {
        if (function_exists('random_bytes')) { $b = @random_bytes($bytes); if ($b !== false && $b !== null) return bin2hex($b); }
        if (function_exists('openssl_random_pseudo_bytes')) { $b = @openssl_random_pseudo_bytes($bytes); if ($b !== false) return bin2hex($b); }
        $s = '';
        for ($i = 0; $i < $bytes; $i++) $s .= chr(mt_rand(0, 255));
        return bin2hex(hash('sha256', $s.uniqid('', true).getmypid(), true));
    }

    public static function Root() { return rtrim(str_replace('\\', '/', dirname(__FILE__)), '/'); }
    public static function Work() { return self::Root().'/'.SG_WORK_DIR; }
    private static function SelfName() { return basename(__FILE__); }
    /** When the file appeared on the server: filectime (unzip and FTP keep the old mtime), else mtime */
    private static function SelfTime()
    {
        clearstatcache();
        $t = @filectime(__FILE__);
        if ($t === false) $t = @filemtime(__FILE__);
        return ($t === false) ? 0 : $t;
    }

    private static function ExpiresAt() { return self::SelfTime() + SG_NO_PASSWORD_TTL; }

    private static function TimeLeft()
    {
        $s = self::ExpiresAt() - time();
        if ($s < 60) return 'less than a minute';
        $h = (int)floor($s / 3600);
        $m = (int)floor(($s % 3600) / 60);
        return ($h > 0 ? $h.' h ' : '').$m.' min';
    }

    private static function HasPassword($state) { return (isset($state['password']) && $state['password'] !== ''); }

    /** The owner pressed "Skip": no password, the scanner is open until it removes itself */
    public static function OpenMode()
    {
        $state = self::StateLoad();
        return (!self::HasPassword($state) && !empty($state['skipped']));
    }

    /** Folder of this script as seen from the browser, with a slash at both ends */
    private static function SelfDir()
    {
        $script = isset($_SERVER['SCRIPT_NAME']) ? (string)$_SERVER['SCRIPT_NAME'] : '/';
        $dir = str_replace('\\', '/', dirname($script));
        if ($dir === '' || $dir === '.') $dir = '/';
        if (substr($dir, -1) !== '/') $dir .= '/';
        return $dir;
    }

    private static function IsHttps()
    {
        if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== '' && strtolower((string)$_SERVER['HTTPS']) !== 'off') return true;
        if (isset($_SERVER['SERVER_PORT']) && (int)$_SERVER['SERVER_PORT'] === 443) return true;
        return false;
    }

    /** Host of the website from the request, checked to be a plain domain name */
    public static function Host()
    {
        $host = isset($_SERVER['HTTP_HOST']) ? (string)$_SERVER['HTTP_HOST'] : '';
        if ($host === '' && isset($_SERVER['SERVER_NAME'])) $host = (string)$_SERVER['SERVER_NAME'];
        $host = strtolower(trim($host));
        $host = preg_replace('/:\d+$/', '', $host);
        if (!preg_match('/^[a-z0-9]([a-z0-9\-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9\-]*[a-z0-9])?)*$/', $host)) return '';
        return $host;
    }

    public static function SiteUrl()
    {
        $port = isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 0;
        $suffix = ($port && $port !== 80 && $port !== 443) ? ':'.$port : '';
        return (self::IsHttps() ? 'https://' : 'http://').self::Host().$suffix.self::SelfDir();
    }

    /** The access key of the website, read from the config of the agent (never printed on the page) */
    private static function AccessKey()
    {
        $raw = @file_get_contents(self::Work().'/antivirus_config.php');
        if ($raw === false) return '';
        if (!preg_match('/ACCESS_KEY["\']?\s*,\s*["\']([0-9a-fA-F]{32})["\']/', $raw, $m)) return '';
        return $m[1];
    }

    private static function AgentInstalled()
    {
        return (file_exists(self::Work().'/antivirus.php') && self::AccessKey() !== '');
    }

    private static function WriteFile($filename, $content)
    {
        $tmp = $filename.'.'.substr(md5(uniqid('', true).mt_rand()), 0, 12).'.tmp';
        if (@file_put_contents($tmp, $content) !== strlen($content)) { @unlink($tmp); return false; }
        if (!@rename($tmp, $filename)) { @unlink($tmp); return false; }
        return true;
    }

    private static function Redirect($query)
    {
        if (!headers_sent()) { header('Location: '.self::SelfName().($query === '' ? '' : $query), true, 302); exit; }
        echo '<script>location.href='.json_encode(self::SelfName().$query).';</script>';
        exit;
    }

    private static function Json($data)
    {
        if (!headers_sent())
        {
            header('Content-Type: application/json; charset=utf-8');
            header('Cache-Control: no-store');
        }
        echo json_encode($data);
    }

    private static function Size($bytes)
    {
        $u = array('B', 'KB', 'MB', 'GB', 'TB');
        $i = 0;
        while ($bytes >= 1024 && $i < 4) { $bytes /= 1024; $i++; }
        return round($bytes, ($i > 1) ? 1 : 0).' '.$u[$i];
    }

    public static function H($text) { return htmlspecialchars((string)$text, ENT_QUOTES, 'UTF-8'); }

    private static function Cut($text, $length)
    {
        if (function_exists('mb_substr')) return mb_substr($text, 0, $length, 'UTF-8');
        return substr($text, 0, $length);
    }

    private static function Hidden($name, $value)
    {
        $html = '<input type="hidden" name="'.self::H($name).'" value="'.self::H($value).'">';
        if ($name === 'task') $html .= '<input type="hidden" name="csrf" value="'.self::H(self::Csrf()).'">';
        return $html;
    }

    private static function Card($title, $body) { return '<section class="sg-card"><h2>'.$title.'</h2>'.$body.'</section>'; }
    private static function Row($label, $value) { return '<div class="sg-row"><div class="sg-row-l">'.$label.'</div><div class="sg-row-v">'.$value.'</div></div>'; }
    private static function Badge($text, $color) { return '<span class="sg-badge sg-'.$color.'">'.self::H($text).'</span>'; }

    /**
     * Layout
     */
    private static function Head($title, $with_menu = true)
    {
        if (!headers_sent())
        {
            header('Content-Type: text/html; charset=utf-8');
            header('X-Robots-Tag: noindex, nofollow');
            header('Referrer-Policy: no-referrer');
            header('X-Frame-Options: SAMEORIGIN');
            header('X-Content-Type-Options: nosniff');
            header('Cache-Control: no-store, no-cache, must-revalidate');
        }
        ?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
<title><?php echo self::H($title); ?> - Website Antivirus by SiteGuarding</title>
<style>
:root{--g:#50b948;--g-d:#3d9438;--g-l:#6ed465;--r:#dc2626;--r-d:#b91c1c;--a:#d97706;--g50:#f0fdf4;--r50:#fef2f2;--a50:#fffbeb;
--c0:#ffffff;--c1:#f9fafb;--c2:#f3f4f6;--c3:#e5e7eb;--c5:#6b7280;--c7:#374151;--c9:#111827;
--sh:0 1px 3px 0 rgba(0,0,0,.08),0 1px 2px -1px rgba(0,0,0,.08);--sh-l:0 10px 15px -3px rgba(0,0,0,.08),0 4px 6px -4px rgba(0,0,0,.06);--rad:12px}
*{box-sizing:border-box}
body{margin:0;background:var(--c1);color:var(--c9);font:16px/1.6 Inter,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;-webkit-font-smoothing:antialiased}
a{color:var(--g-d)}
.sg-top{background:var(--c0);border-bottom:1px solid var(--c3);position:sticky;top:0;z-index:5}
.sg-top-in{max-width:880px;margin:0 auto;padding:10px 16px;display:flex;align-items:center;gap:16px;flex-wrap:wrap}
.sg-logo{display:flex;align-items:center;text-decoration:none;color:var(--c9);font-weight:700;font-size:18px}
.sg-logo img{display:block;height:46px;width:auto}
.sg-top-nav{margin-left:auto;display:flex;gap:18px;align-items:center;font-size:14px}
.sg-top-nav a{color:var(--c5);text-decoration:none}
.sg-top-nav a:hover{color:var(--g-d)}
.sg-wrap{max-width:880px;margin:0 auto;padding:28px 16px 64px}
.sg-narrow{max-width:460px;margin:6vh auto 0}
h1{font-size:24px;margin:0 0 6px;letter-spacing:-.02em}
.sg-sub{color:var(--c5);margin:0 0 22px;font-size:15px}
.sg-card{background:var(--c0);border:1px solid var(--c3);border-radius:var(--rad);box-shadow:var(--sh);padding:22px;margin:0 0 18px}
.sg-card h2{font-size:17px;margin:0 0 14px;letter-spacing:-.01em}
.sg-card p{margin:0 0 12px}
.sg-card p:last-child{margin-bottom:0}
.sg-rows{border-top:1px solid var(--c2)}
.sg-row{display:flex;gap:14px;padding:11px 0;border-bottom:1px solid var(--c2);align-items:baseline;flex-wrap:wrap}
.sg-row-l{flex:0 0 190px;color:var(--c5);font-size:14px}
.sg-row-v{flex:1 1 220px;min-width:0}
.sg-badge{display:inline-block;padding:2px 10px;border-radius:999px;font-size:13px;font-weight:600;line-height:1.5}
.sg-green{background:var(--g50);color:var(--g-d)}
.sg-red{background:var(--r50);color:var(--r-d)}
.sg-amber{background:var(--a50);color:var(--a)}
.sg-grey{background:var(--c2);color:var(--c5)}
.sg-muted{color:var(--c5);font-size:14px}
p.sg-red{color:var(--r-d);background:none;font-size:14px}
.sg-mt{margin-top:14px}
.sg-link{color:var(--g-d);text-decoration:none;border-bottom:1px solid rgba(61,148,56,.3)}
.sg-link:hover{border-bottom-color:var(--g-d)}
.sg-btn{display:inline-block;border:1px solid transparent;border-radius:9px;padding:10px 18px;font:inherit;font-size:15px;font-weight:600;cursor:pointer;text-decoration:none;transition:background .15s,box-shadow .15s}
.sg-btn-primary{background:var(--g);color:#fff;box-shadow:0 1px 2px rgba(80,185,72,.4)}
.sg-btn-primary:hover{background:var(--g-d)}
.sg-btn-danger{background:var(--c0);color:var(--r-d);border-color:#fecaca}
.sg-btn-danger:hover{background:var(--r50)}
.sg-btn-ghost{background:var(--c0);color:var(--c7);border-color:var(--c3)}
.sg-btn-ghost:hover{background:var(--c1)}
.sg-btn-lg{padding:13px 26px;font-size:16px}
.sg-btn-block{display:block;width:100%;margin-top:18px}
.sg-btn[disabled]{opacity:.6;cursor:default}
.sg-label{display:block;margin:14px 0 6px;font-size:14px;font-weight:600}
.sg-input{width:100%;padding:11px 13px;border:1px solid var(--c3);border-radius:9px;font:inherit;background:var(--c0);color:var(--c9)}
.sg-input:focus{outline:none;border-color:var(--g);box-shadow:0 0 0 3px rgba(80,185,72,.15)}
.sg-form-inline{display:flex;gap:10px;flex-wrap:wrap}
.sg-form-inline .sg-input{flex:1 1 220px;width:auto}
.sg-choice{display:block}
.sg-radio,.sg-check{display:flex;gap:11px;align-items:flex-start;padding:13px;border:1px solid var(--c3);border-radius:10px;margin-bottom:10px;cursor:pointer}
.sg-radio:hover,.sg-check:hover{border-color:var(--g-l);background:var(--g50)}
.sg-radio input,.sg-check input{margin:4px 0 0;accent-color:var(--g)}
.sg-radio em,.sg-check span{font-style:normal}
.sg-radio em{display:block;color:var(--c5);font-size:14px;margin-top:2px}
.sg-check span{font-size:14px}
.sg-list{margin:0;padding-left:20px}
.sg-list li{margin-bottom:6px}
.sg-table{width:100%;border-collapse:collapse;font-size:14px}
.sg-table td{padding:9px 8px;border-bottom:1px solid var(--c2)}
.sg-table-compact td{padding:5px 8px}
.sg-right{text-align:right}
.sg-progress{height:12px;background:var(--c2);border-radius:999px;overflow:hidden;margin:6px 0 12px}
.sg-progress-bar{height:100%;width:2%;border-radius:999px;background:linear-gradient(90deg,var(--g),var(--g-l));transition:width .6s ease}
.sg-progress-txt{font-variant-numeric:tabular-nums;font-weight:600;margin:0 0 10px}
.sg-hidden{display:none}
.sg-msg{border-radius:10px;padding:13px 16px;margin:0 0 18px;font-size:15px;border:1px solid}
.sg-msg-err{background:var(--r50);border-color:#fecaca;color:var(--r-d)}
.sg-msg-ok{background:var(--g50);border-color:#bbf7d0;color:var(--g-d)}
.sg-msg-warn{background:var(--a50);border-color:#fde68a;color:#92400e}
.sg-foot{max-width:880px;margin:0 auto;padding:0 16px 40px;color:var(--c5);font-size:13px;text-align:center}
.sg-foot a{color:var(--c5)}
@media(max-width:620px){.sg-row-l{flex-basis:100%}.sg-wrap{padding-top:20px}.sg-card{padding:18px}.sg-top-nav a.sg-promo{display:none}.sg-top-nav{gap:14px}.sg-logo img{height:38px}}
</style>
</head>
<body>
<header class="sg-top"><div class="sg-top-in">
<a class="sg-logo" href="<?php echo self::H(SG_SERVER); ?>" target="_blank" rel="noopener">
<img src="<?php echo self::H(SG_LOGO); ?>" alt="SiteGuarding" width="199" height="46"></a>
<?php if ($with_menu && self::IsLoggedIn()) { ?>
<nav class="sg-top-nav">
<a href="?">Scanner</a>
<a href="?task=blacklist">Blacklists</a>
<a class="sg-promo" href="<?php echo self::H(SG_SERVER.'en/protect-your-website'); ?>" target="_blank" rel="noopener">Protect my website</a>
<?php if (!self::OpenMode()) { ?><a href="?task=logout">Sign out</a><?php } ?>
</nav>
<?php } ?>
</div></header>
<div class="sg-wrap">
<h1>Website Antivirus</h1>
<p class="sg-sub">Standalone scanner <?php echo self::H(SG_VERSION); ?> for <?php echo self::H(self::Host()); ?></p>
<?php
        if ($with_menu && self::OpenMode())
        {
            echo '<div class="sg-msg sg-msg-warn"><b>This scanner is not protected by a password.</b> Anyone who knows its address can '
                .'use it, so it removes itself automatically in about '.self::H(self::TimeLeft()).'. '
                .'<a class="sg-link" href="?task=protect">Set a password</a> to keep it.</div>';
        }
        if (self::$error !== '')  echo '<div class="sg-msg sg-msg-err">'.self::$error.'</div>';
        if (self::$notice !== '') echo '<div class="sg-msg sg-msg-ok">'.self::H(self::$notice).'</div>';
    }

    private static function Foot()
    {
        ?>
</div>
<div class="sg-foot">
<p>Website security by <a href="<?php echo self::H(SG_SERVER); ?>" target="_blank" rel="noopener">SiteGuarding.com</a>.
Questions? <a href="<?php echo self::H(SG_SERVER.'en/contacts'); ?>" target="_blank" rel="noopener">Contact our support</a>.</p>
<p>&copy; 2008 - <?php echo date('Y'); ?> SiteGuarding.com</p>
</div>
</body>
</html>
        <?php
    }
}
