<?php

$debug = FALSE;
/////////////////////////////////////////////////////////////
function hex2bin($str)
    {
    $bin = "";
    $i = 0;
    do{
       $bin .= chr(hexdec($str{$i}.$str{($i + 1)}));
       $i += 2;
        }while ($i < strlen($str));
    return $bin;
    }
    
function computeUnlockCode($imei_string)
    {
    $unlockcode = NULL;
    $strpos = -1; //process from the end of string
    $uc_codecount = 0;
    $md5_char;
    global $debug;
    
    $imei_first_13_digits = substr($imei_string,0,13);
    $imei_last_13_digits = substr($imei_string,-13);
    $step1 = $imei_first_13_digits.$imei_last_13_digits;
  
    if($debug)
        {
        echo $step1."\n";
        }

    $step2 = md5($step1);
    if($debug)
        {
        echo $step2."\n";
        }
    while ($uc_codecount<8)
        {
        $md5_char = substr($step2,$strpos--,1);
        if(ctype_digit($md5_char))
            {
            $unlockcode = $md5_char . $unlockcode;
            $uc_codecount++;
            }

        if($strpos == -32)
            break;
        }
    
    // Supposed $unlockcode is still < 8 chars, append with zeros to make it 8 chars
    if ($uc_codecount<8)
        {
        while ($uc_codecount<8)
            {
            $unlockcode = "0" . $unlockcode;
            $uc_codecount++;
            }  
        }
    return $unlockcode; 
    }
    
function SendEmail($license_string,$unlockkey_string,$email_string,$imei_string)
    {
    global $debug;        
    $to = $email_string;
    $to_copy = "custsvc@bak2u.com,sales@mobivation.com.sg"; 
    
    //define the headers we want passed. Note that they are separated with \r\n
    $headers = 'MIME-Version: 1.0' . "\r\n" . 'Content-type: text/plain; charset=UTF-8' . "\r\n";
    $headers .= "From: noreply@lost-located.de";
    $headers_copy = "From: noreply@lost-located.de";
    
    if($debug)
        {
        $headers .= "\r\nBcc: thomasleets@hotmail.com,support@mobivation.com.sg";
        }
    else
        {
        $headers .= "\r\nBcc: licenses@1step-gmbh.de,support@lost-located.de";
        }
   
    //define the subject of the email
    $subject_english = 'LLService - Activation';
    $message_english = "Dear customer,"; 
    $message_english .= "\n\n";
    $message_english .= "You just started the activation for LLService.";
    $message_english .= "\n\n";        
    $message_english .= "Please find your activation information below:"; 
    $message_english .= "\n\n";        
    $message_english .= "Pin number (or IMEI): ";
    $message_english .= $imei_string; 
    $message_english .= "\n";
    $message_english .= "Activation PIN: "; 
    $message_english .= $license_string;
    $message_english .= "\n";
    $message_english .= "Unlock key: ";
    $message_english .= $unlockkey_string;
    $message_english .= "\n\n";        
    $message_english .= "Keep the unlock key for future reference!";
    $message_english .= "\n\n";         
    $message_english .= "For program-activation, please enter the unlock-key (see above) into the program on your device.";
    $message_english .= "\n\n";         
    $message_english .= "Manuals can be found at http://www.lost-located.de";
    $message_english .= "\n\n";        
    $message_english .= "Best regards,";
    $message_english .= "\n";        
    $message_english .= "Security-Team 1Step GmbH";
    $message_english .= "\n";  
    $message_english .= "--";
    $message_english .= "\n";          
    $message_english .= "1Step GmbH";
    $message_english .= "\n";
    $message_english .= "Hartweg 27";
    $message_english .= "\n";
    $message_english .= "D-52525 Waldfeucht";
    $message_english .= "\n";        
    $message_english .= "GERMANY";
    $message_english .= "\n\n";        
    $message_english .= "Managing directors:";
    $message_english .= "\n";        
    $message_english .= "Dirk Hockerts, Torsten Koch";
    $message_english .= "\n\n";        
    $message_english .= "Registration court: AG Aachen";
    $message_english .= "\n";        
    $message_english .= "Registration number:  HRB 16034"; 
    $message_english .= "\n\n";        
    $message_english .= "VAT-ID: DE247689428";

    $subject_german = 'Willkommen bei lost & located!';            
    $message_german = "Hallo,"; 
    $message_german .= "\n\n";
    $message_german .= "wir danken dir für den Kauf von lost & located.";
    $message_german .= "\n\n"; 
    $message_german .= "Mit dieser E-Mail erhälst du deinen Freischalt-Code, den du für die Aktivierung der Software auf deinem Handy brauchst."; 
    $message_german .= "\n";        
    $message_german .= "Wie es genau funktioniert erfährst du unter: www.lost-located.de/setup";
    $message_german .= "\n";
    $message_german .= "Dein Freischalt-Code, für deine lost & located Lizenz ";
    $message_german .= $license_string;
    $message_german .= "  ist:     ";
    $message_german .= $unlockkey_string;    
    $message_german .= "\n\n";
    $message_german .= "Bitte hebe diese E-Mail gut auf. Bei Problemen stehen wir dir gerne unter support@lost-located.de  zur Verfügung.";
    $message_german .= "\n";
    $message_german .= "Für alle anderen Fragen steht unser Team unter info@lost-located.de für dich Bereit.";
    $message_german .= "\n\n";
    $message_german .= "Mit freundlichen Grüßen";
    $message_german .= "\n\n";      
    $message_german .= "Dein lost & located Team";
    $message_german .= "\n\n\n\n";   
    $message_german .= "lost & located ist ein Produkt der AppAttack GmbH (www.appattack.de)";
    
    //send the email
    $mail_sent = @mail( $to, $subject_german, $message_german, $headers );
    //Always send english to bak2u and mobivation
    $mail_sent = @mail( $to_copy, $subject_english, $message_english, $headers_copy );
    //if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" 
    //echo $mail_sent ? "Mail sent" : "Mail failed";
    }    
    
/////////////////////////////////////////////////////////////
$name = trim($_POST['name']);
$msisdn = trim($_POST['msisdn']);
$email = trim($_POST['email']);
$imei = trim($_POST['imei']);
$license = trim($_POST['license']);

include "mysql_connect.php";
include "mysql_select_db.php";

$query = "SELECT * from mobileback where license=".$license;
$result = mysql_query($query); 

if (!$result) //invalid query (should not occur at all!)
    {
    die('Invalid query: ' . mysql_error());
    }
else
    {
    $numrows = mysql_num_rows($result);
    if ($numrows>0) //License is found
        {
        //Check imei valid
        if(strlen($imei) < 15 || strlen($imei) > 20)
            {
            mysql_close();
            echo "-2 Invalid imei.";
            return "-2";
            }
            
        for($j = 0; $j < strlen($imei); $j++)
            {
            if(!ctype_digit($imei[$j]))
                {
                mysql_close();
                echo "-2 Invalid imei.";
                return "-2";
                }
            }
        
        $retrieved_numberofrequests = mysql_result($result,0,"numberofrequests");
        $retrieved_testenable = mysql_result($result,0,"testenable");
        $retrieved_imei = mysql_result($result,0,"imei");
        $retrieved_license_enable = mysql_result($result,0,"license_enable");
        
        if(!$retrieved_license_enable)
            {
            mysql_close();
            echo "-4 License disabled.";
            return "-4";
            }                
            
        if($retrieved_numberofrequests > 0 && $retrieved_testenable == 0)
            {
            if($retrieved_imei == $imei)
                {
                $unlockkey = computeUnlockCode($imei);
                mysql_close();
                echo "Ihr Freischalt-Code lautet: . $unlockkey. Dieser wird in wenigen Minuten auch an Ihrer eMail-Adresse gesendet.";
                echo "\n\n";
                echo "Your Unlock-Key is: . $unlockkey. You will also get it by eMail in a few minutes.";
                
                //echo "Unlock code -> " . $unlockkey . "</br>";
                SendEmail($license,$unlockkey,$email,$imei);
                return "1 " . $unlockkey;
                }
            else
                {
                mysql_close();
                echo "-3 License already consumed.";
                return "-3";
                }
            }
        else
            {
            // update IMEI to database
            $query = "UPDATE mobileback SET imei ='" . $imei . "' WHERE license = '" . $license . "'";
            mysql_query($query); 

            if ($retrieved_numberofrequests == 0 || ($retrieved_imei != $imei && $retrieved_testenable == 1)) 
                { // increment numberoftries $retrieved_numberofrequests++; 
                $query = "UPDATE mobileback SET numberofrequests ='" . ++$retrieved_numberofrequests . "' WHERE license = '" . $license . "'"; 
                mysql_query($query); 
                $query = "INSERT INTO testrecords(license,imei) VALUES (" . $license . "," . $imei . ")"; 
                mysql_query($query);
                
                if($retrieved_testenable == 1)
                    {
                    $myFile = "test_imeis.txt";
                    $fh = fopen($myFile, 'a') or die("can't open file");
                    fwrite($fh, $license.",".$imei."\n");
                    fclose($fh);
                    }
                }
            }
 
        // Compute MD5 for IMEI + Phone Number
        //$md5_str = md5($imei . $gatewaynumber);
        $unlockkey = computeUnlockCode($imei);
        
        $query = "UPDATE mobileback SET name ='" . $name . "' WHERE license = '" . $license . "'";
        mysql_query($query); 
        $query = "UPDATE mobileback SET msisdn ='" . $msisdn . "' WHERE license = '" . $license . "'";
        mysql_query($query); 
        $query = "UPDATE mobileback SET email ='" . $email . "' WHERE license = '" . $license . "'";
        mysql_query($query);             
        $query = "UPDATE mobileback SET distributor ='LLService' WHERE license = '" . $license . "'";
        mysql_query($query); 
                            
        mysql_close();
        echo "Ihr Freischalt-Code lautet: . $unlockkey. Dieser wird in wenigen Minuten auch an Ihrer eMail-Adresse gesendet.";
        echo "</br></br>";
        echo "Your Unlock-Key is: . $unlockkey. You will also get it by eMail in a few minutes.";
        
        //echo "Unlock code -> " . $unlockkey . "</br>";
        SendEmail($license,$unlockkey,$email,$imei);        
        return "1 " . $unlockkey;
        }
    else
        {
        mysql_close();
        echo "-1 Invalid license.";
        return "-1"; //Invalid license
        }
    }
mysql_close();
?>

