<?php
// MEETING OVER - UNCOMMENT REDIRECT
//header('Location:http://www.borealis.gi');

$page_title = 'Online Proxy Password Request';

// SET YEAR, PATHS

//require('/home/default/borealis.gi/user/htdocs/proxy'.$year.'/common/definitions.php');
$year = '2025';

$path = realpath(dirname(__FILE__));
require($path.'/common/definitions.php');
//require($path.'/common/definitions.php');

$message = '';

$voting = 0;
$success = 0;

session_name("PROXY".$year);
session_start();

$_SESSION['year'] = $year;
$_SESSION['user'] = '';
$_SESSION['user_id'] = '';
$_SESSION['company'] = '';
$_SESSION['logon'] = '';
$_SESSION['auth_level'] = 0;


if (isset($_POST['submit'])) {
    // SANITIZE LOGON
    foreach ($_POST as $key => $value) {
       $eviltext = '[#|:~!()&%$^?<>`*\;\[\]\{\}\/\\\\]';

       $value = trim($value);
    
       if (eregi($eviltext, $value)) {
          //$value = ereg_replace($eviltext,'',$value);
       }
       
       if (strlen($value) > 60) {
          $value = substr($value, 0, 60);
       }
      
       $value = mysql_real_escape_string ($value);
 
       $_POST[$key] = $value;

	//echo "\r\n<!-- POST $key : $value -->\r\n";
    }

    $_POST['refcode'] = substr($_POST['refcode'], 0, 5);
    $_POST['zip'] = substr($_POST['zip'], 0, 5);

    

    // GRAB IP, SET TIME RANGE FOR LOGONS
    if (getenv("HTTP_CLIENT_IP")) {
       $ip = getenv("HTTP_CLIENT_IP");
    } else if(getenv("HTTP_X_FORWARDED_FOR")) {
       $ip = getenv("HTTP_X_FORWARDED_FOR");
    } else if(getenv("REMOTE_ADDR")) {
       $ip = getenv("REMOTE_ADDR");
    } else {
       $ip = "UNKNOWN";
    }
   
    $date = date("Y-m-d");
    require_once ($db_path.'/access.php'); // Connect to the db.
    
    
    // VALIDATE EMAIL
    $email_invalid = 0;

    $email1 = $_POST['email_address'];
    $email2 = $_POST['email_confirm'];

    //echo "\r\n<!-- EMAIL: $email1 $email2 --> \r\n";
    
    if (empty($email1) || empty($email2)) {
        $message = '<font face="Arial" size="4" color="#993333">Please provide an email addresses</font>';
	$message .= "\r\n<!-- $email1 $email2 -->\r\n";
        $email_invalid = 1;

    } else if ($email1 != $email2) {
        $message = '<font face="Arial" size="4" color="#993333">Email addresses do not match</font>';
        $email_invalid = 1;

    } else if (!filter_var($email1, FILTER_VALIDATE_EMAIL) || 
               !filter_var($email2, FILTER_VALIDATE_EMAIL)) {

        $message = '<font face="Arial" size="4" color="#993333">Email address is invalid</font>';
        $email_invalid = 1;
    }
            
    if ($email_invalid != 1) {
        // CHECK THE BANNED IP LIST
        $query = 'SELECT ip FROM events WHERE ip="'.$ip.'" '.
                 'AND timestamp LIKE "'.$date.'%" AND event_type="99"';
        $result = @mysql_query ($query); // Run the query.
        $count = mysql_num_rows($result);
       
        // CHECK FOR ADMIN OVERRIDE
        $query2 = 'SELECT ip FROM events WHERE ip="'.$ip.'" '.
                  'AND timestamp LIKE "'.$date.'%" AND event_type="98"';
        $result2 = @mysql_query ($query2); // Run the query.
        $count2 = mysql_num_rows($result2);
       
        if (($count > 0) && ($count2 == 0)) {
                      
             $message = '<font face="Arial" size="4" color="#993333">TOO MANY FAILURES - LOGON DISABLED</font>';
       
             // LOG THE FAILED ATTEMPT
             $querykeys = 'event_type, user, ip, timestamp';
             $queryvalues = '"3", "'.$ref.'", "'.$ip.'", NOW()';
        
             $log_query = "INSERT INTO events ($querykeys) VALUES ($queryvalues)"; 
             $log_result = @mysql_query ($log_query); // Run the query.
       
        } else {
            $zip = substr($_POST['zip'], 0, 3);
            $ref = $_POST['refcode'];
       
            $queryx = "SELECT user, password_clear as pass, email FROM users WHERE reference_code = '$ref' ".
                      "AND zip LIKE '{$zip}%' AND user_year = $year";
            $resultx = @mysql_query ($queryx); // Run the query.
            $countx  = @mysql_num_rows($resultx);

            //echo "\r\n<!-- $queryx -->\r\n";

            if ($countx == 0) {
                $message = '<font face="Arial" size="4" color="#993333">Invalid Reference Code or ZIP Code</font>';
          
                // LOG THE FAILED ATTEMPT
                $querykeys = 'event_type, user, ip, timestamp';
                $queryvalues = '"2", "'.$ref.'", "'.$ip.'", NOW()';
        
                $log_query = "INSERT INTO events ($querykeys) VALUES ($queryvalues)"; 
                $log_result = @mysql_query ($log_query); // Run the query.
          
                // CHECK FOR MULTIPLE FAILED ATTEMPTS
                $check_query = 'SELECT ip FROM events WHERE ip="'.$ip.'" AND '.
                            'timestamp LIKE "'.$date.'%" AND event_type="2"';
                $check_result = @mysql_query ($check_query); // Run the query.
                $check_count  = @mysql_num_rows($check_result);
            
                if ($check_count > 10) {
                    // BLOCK IP
                    $querykeys = 'event_type, user, ip, timestamp';
                    $queryvalues = '"99", "'.$ref.'", "'.$ip.'", NOW()';
        
                    $log_query = "INSERT INTO events ($querykeys) VALUES ($queryvalues)"; 
                    $log_result = @mysql_query ($log_query); // Run the query.
          
                    //$disable_query = 'UPDATE users SET disabled=1 where user="'.$u.'"';
                    //$result = @mysql_query ($disable_query); // Run the query.
                }
            }
        
       
            if ($countx == 1) {
                while ($row = mysql_fetch_array ($resultx, MYSQL_ASSOC)) {
                    if ($row['disabled'] == 1) {
                        $message = '<font face="Arial" size="4" color="#993333">Account Disabled</font>';
                   
                        // LOG THE FAILED ATTEMPT
                        $querykeys = 'event_type, user, ip, timestamp';
                        $queryvalues = '"3", "'.$ref.'", "'.$ip.'", NOW()';
       
                        $log_query = "INSERT INTO events ($querykeys) VALUES ($queryvalues)"; 
                        $log_result = @mysql_query ($log_query); // Run the query.

                    } else {
                        
                        $success = 1;

                        // LOG THE EVENT
                        $querykeys = 'event_type, user, user_id, ip, timestamp';
                        $queryvalues = '"11", "'.$ref.'", "'.$row['user_id'].'", "'.$ip.'", NOW()';
       
                        $log_query = "INSERT INTO events ($querykeys) VALUES ($queryvalues)"; 
                        $log_result = @mysql_query ($log_query); // Run the query.

                        if ($email1 != $row['email']) {
                            $query1  = "INSERT INTO user_updates (user, email, update_year, date_updated) ".
                                       "VALUES ('".$row['user']."','".$email1."', '$year', NOW() )";
                            $result1 = @mysql_query ($query1); // Run the query.

                            //echo "\r\n<!-- $query1 -->\r\n";
                        }

                        // PREPARE EMAIL                        
                        $mail_to = $email1;
                        //$mail_to = "jmagdych@borealis.gi";
                        
                        $mail_from = 'Borealis Proxy Voting <proxy@borealis.gi>';
                        
                        $subject   = '[BOREALIS ONLINE PROXY] - Logon Information';
                        
                        $emessage .= "--------------------------------------------------\r\n";
                        
                        $emessage .= "USERNAME: ".$row['user']."\r\n";
                        $emessage .= "PASSWORD: ".$row['pass']."\r\n";

                        $emessage .= "--------------------------------------------------\r\n";

                        $emessage .= "You may log on to vote your proxy now at:\r\n";
                        $emessage .= "https://www.borealis.gi/proxy".$year."/ \r\n";
                        
                        
                        
                        mail($mail_to, $subject, $emessage, "From:$mail_from\n");
//Cc:jmagdych@borealis.gi\n");
                    }
                }
            }
       } 
      
       @mysql_close(); // Close the database connection.      

    }
}

$_SESSION['year'] = $year;
$_SESSION['user'] = '';
$_SESSION['user_id'] = '';
$_SESSION['company'] = '';
$_SESSION['logon'] = '';
$_SESSION['auth_level'] = 0;

echo '<html><head>
<meta http-equiv="Content-Language" content="en-us">
<title>'.$page_title.'</title>
</head>
<body bgcolor="#EFEFE3" topmargin=4 onload="document.logon.username.focus()">
<!-- '.$year.' -->    
<form method="POST" action="request_password.php" name="request" ID="request">
<center>
<img src="images/spacer.gif" border=0 height=100 width=1><BR>
<table border="4" cellspacing="1" cellpadding="0" bordercolor="#000066" width="400" height="200" bgcolor="#FFFFFF">
  <tr><td valign="top">
    <table border=0 cellspacing="4" cellpadding="2" width="100%">
    <tr>
        <td colspan=2 align="center"><img src="images/spacer.gif" height=10><BR>
    <font face="Arial, Helvetica" size=5>Online Proxy - Password Request</font><BR>
    <img src="images/spacer.gif" height=10></td>
    </tr>
    ';

if ($success == 1) {
    echo '
    <tr>
    <td valign="middle" align="center" colspan="2"><span style="font-family: Arial, Helvetica">
    <b>Thank You!</b><BR><BR>
    Your proxy account information has been sent to '.$email1.'.  <BR><BR>
    Once it has arrived, you may <a href="logon.php">log on to vote</a>.
    </span>
    </td>
    </tr>
    ';

} else {

echo '
    <tr>
    <td align="left"><b><font face="Arial" color="#000066">Reference Code</font></b></td>
    <td align="right">
    <input type="text" name="refcode" size="28" style="width:200px" value="'.$_POST['refcode'].'">
    </td>
    </tr>

    <tr>
    <td align="left"><b><font face="Arial" color="#000066">ZIP Code <i>(as written on post card)</i></font></b></td>
    <td align="right">
    <input type="text" name="zip" size="28" style="width:200px" value="'.$_POST['zip'].'">
    </td>
    </tr>

    <tr>
    <td align="left"><b><font face="Arial" color="#000066">Email Address</font></b></td>
    <td align="right">
    <input type="text" name="email_address" size="28"  style="width:200px" value="'.$_POST['email1'].'">
    </td>
    </tr>

    <tr>
    <td align="left"><b><font face="Arial" color="#000066">Confirm Email</font></b></td>
    <td align="right">
    <input type="text" name="email_confirm" size="28"  style="width:200px" value="'.$_POST['email2'].'">
    </td>
    </tr>

    <tr>
        <td colspan="2" align="right" valign="bottom" height="*">
    <input type="submit" name="submit" value="Submit"></td>
    </tr>
';

echo '
    <tr>
    <td valign="bottom" align="center" colspan="2">'.$message.'&nbsp;</td>
    </tr>
';

}

echo '
    </table><BR>
</td></tr></table>
</form>
';

if ($success != 1) {
echo '
<span style="font size:14px;font-family:Arial, Helvetica;font-weight:bold;color:#CC0000">
<BR>
NOTE: Username and Password information will be sent via email.  <BR><BR>

<BR>
If require assistance, please contact <a href="mailto:proxy@borealis.gi">proxy@borealis.gi</a>.

</span>
';
}

echo'
</center>
</body>
</html>';

exit();
?>

