<?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($language_string,$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@1step-security.de";
    $headers_copy = "From: noreply@1step-security.de";
    
    if($debug)
        {
        $headers .= "\r\nBcc: thomasleets@hotmail.com,support@mobivation.com.sg";
        }
    else
        {
        $headers .= "\r\nBcc: activation@1step-security.de";
        }
   
    //define the subject of the email
    $subject_english = 'MobileBack - Activation';
    $message_english = "Dear customer,"; 
    $message_english .= "\n\n";
    $message_english .= "You just started the activation for MobileBack.";
    $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.mobileback.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 = 'MobileBack -Aktivierung';            
    $message_german = "Sehr geehrter Kunde, sehr geehrte Kundin,"; 
    $message_german .= "\n\n";
    $message_german .= "Sie haben die Aktivierung für Ihr Programm MobileBack gestartet.";
    $message_german .= "\n\n";        
    $message_german .= "Nachfolgend finden Sie Ihre Aktivierungsdaten:"; 
    $message_german .= "\n\n";        
    $message_german .= "Geräte- oder IMEI-Nummer: ";
    $message_german .= $imei_string; 
    $message_german .= "\n";
    $message_german .= "Lizenz-Nr.: "; 
    $message_german .= $license_string;
    $message_german .= "\n";
    $message_german .= "Freischalt-Code: ";
    $message_german .= $unlockkey_string;
    $message_german .= "\n\n";        
    $message_german .= "Bitte bewahren Sie diese Daten an einem sicheren Ort auf!";
    $message_german .= "\n\n";         
    $message_german .= "Um Ihr Programm zu aktivieren, geben Sie den Freischalt-Code in das Programm auf Ihrem Mobiltelefon ein.";
    $message_german .= "\n\n";         
    $message_german .= "Anleitungen finden Sie auch unter http://www.mobileback.de";
    $message_german .= "\n\n";        
    $message_german .= "Mit freundlichen Grüßen,";
    $message_german .= "\n";        
    $message_german .= "Ihr Security-Team der 1Step GmbH";
    $message_german .= "\n";  
    $message_german .= "--";
    $message_german .= "\n";          
    $message_german .= "1Step GmbH";
    $message_german .= "\n";
    $message_german .= "Hartweg 27";
    $message_german .= "\n";
    $message_german .= "D-52525 Waldfeucht";
    $message_german .= "\n";        
    $message_german .= "GERMANY";
    $message_german .= "\n\n";        
    $message_german .= "Vertretungsberechtigte Geschäftsführer:";
    $message_german .= "\n";        
    $message_german .= "Dirk Hockerts, Torsten Koch";
    $message_german .= "\n\n";        
    $message_german .= "Registergericht: Amtsgericht Aachen";
    $message_german .= "\n";        
    $message_german .= "Registernummer: HRB 16034"; 
    $message_german .= "\n\n";        
    $message_german .= "Ust.-ID: DE247689428";            

    $subject_portuguese = 'MobileBack - Activação ';   
    $message_portuguese = "Caro cliente,";
    $message_portuguese .= "\n\n";    
    $message_portuguese .= "Começou agora mesmo a activação MobileBack"; 
    $message_portuguese .= "\n\n";
    $message_portuguese .= "Seguem abaixo informações sobre a sua activação";
    $message_portuguese .= "\n\n";
    $message_portuguese .= "Número de PIN (ou IMEI): ";
    $message_portuguese .= $imei_string;     
    $message_portuguese .= "\n\n";
    $message_portuguese .= "Activação do PIN: ";
    $message_portuguese .= $unlockkey_string;
    $message_portuguese .= "\n\n";
    $message_portuguese .= "Chave para desbloquear:";
    $message_portuguese .= "\n\n";
    $message_portuguese .= "Guarde a chave para desbloqueamento para futura referência!";
    $message_portuguese .= "\n\n";
    $message_portuguese .= "Para activação do programa, por favour insira a chave para desbloquear (acima) no programa do seu aparelho";
    $message_portuguese .= "\n\n";
    $message_portuguese .= "Os manuais podem ser encontrados em http://www.mobileback.de";
    $message_portuguese .= "\n\n";
    $message_portuguese .= "Melhores Cumprimentos,";
    $message_portuguese .= "\n";
    $message_portuguese .= "Security-Team 1Step GmbH"; 
    $message_portuguese .= "\n";
    $message_portuguese .= "1Step GmbH"; 
    $message_portuguese .= "\n";
    $message_portuguese .= "Hartweg 27";
    $message_portuguese .= "\n";     
    $message_portuguese .= "D-52525 Waldfeucht";
    $message_portuguese .= "\n";     
    $message_portuguese .= "GERMANY";
    $message_portuguese .= "\n\n";
    $message_portuguese .= "Directores administrativos:";
    $message_portuguese .= "\n";
    $message_portuguese .= "Dirk Hockerts, Torsten Koch";  
    $message_portuguese .= "\n\n";
    $message_portuguese .= "Registo Judicial: AG Aachen";
    $message_portuguese .= "\n";
    $message_portuguese .= "Número de registo: HRB 16034"; 
    $message_portuguese .= "\n\n";
    $message_portuguese .= "Número de Contribuinte: DE247689428";

    $subject_spanish = 'MobileBack - Activación';
    $message_spanish = "Estimado Cliente,";
    $message_spanish .= "\n\n";    
    $message_spanish .= "Ha empezado la activación de MobileBack."; 
    $message_spanish .= "\n\n"; 
    $message_spanish .= "Puede encontrar la información de activación abajo:"; 
    $message_spanish .= "\n\n";
    $message_spanish .= "PIN o número de IMEI: ";
    $message_spanish .= $imei_string;     
    $message_spanish .= "\n";    
    $message_spanish .= "PIN de Activación: ";
    $message_spanish .= $unlockkey_string;    
    $message_spanish .= "\n";
    $message_spanish .= "Clave de Desbloqueo:";
    $message_spanish .= "\n\n";
    $message_spanish .= "Guarda la clave para futuras consultas!";
    $message_spanish .= "\n\n";
    $message_spanish .= "Para activar el programa, por favor introduce la clave de desbloqueo (ver arriba) en la programa en tu dispositivo.";
    $message_spanish .= "\n\n";
    $message_spanish .= "Puedes encontrar instrucciones en http://www.mobileback.de";
    $message_spanish .= "\n\n"; 
    $message_spanish .= "Un saludo,";
    $message_spanish .= "\n";    
    $message_spanish .= "Equipo de Seguridasd 1Step GmbH"; 
    $message_spanish .= "\n";
    $message_spanish .= "--"; 
    $message_spanish .= "\n";
    $message_spanish .= "1Step GmbH"; 
    $message_spanish .= "\n";
    $message_spanish .= "Hartweg 27"; 
    $message_spanish .= "\n";
    $message_spanish .= "D-52525 Waldfeucht";
    $message_spanish .= "\n";    
    $message_spanish .= "GERMANY";
    $message_spanish .= "\n\n"; 
    $message_spanish .= "Directores de ejecutivo:"; 
    $message_spanish .= "\n";
    $message_spanish .= "Dirk Hockerts, Torsten Koch";  
    $message_spanish .= "\n\n";
    $message_spanish .= "Juzgado de inscripción: AG Aachen";
    $message_spanish .= "\n";
    $message_spanish .= "Número de inscripción:  HRB 16034";
    $message_spanish .= "\n\n";
    $message_spanish .= "ID de IVA: DE247689428";
 
    //send the email
    if($language_string == "English")
        {
        $mail_sent = @mail( $to, $subject_english, $message_english, $headers );
        }
    else if($language_string == "Portuguese")
        {
        $mail_sent = @mail( $to, $subject_portuguese, $message_portuguese, $headers );            
        }
    else if($language_string == "Spanish")
        {
        $mail_sent = @mail( $to, $subject_spanish, $message_spanish, $headers );            
        }
    else
        {
        $mail_sent = @mail( $to, $subject_german, $message_german, $headers );
        }

   $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']);
$language = trim($_POST['language']);

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($language,$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 ='MobileBack' WHERE license = '" . $license . "'";
        mysql_query($query); 
                            
        mysql_close();
        print "Ihr Freischalt-Code lautet: . $unlockkey. Dieser wird in wenigen Minuten auch an Ihrer eMail-Adresse gesendet.";
        print "</br></br>";
        print "Your Unlock-Key is: . $unlockkey. You will also get it by eMail in a few minutes.";

        //echo "Unlock code -> " . $unlockkey . "</br>";
        SendEmail($language,$license,$unlockkey,$email,$imei);        
        return "1 " . $unlockkey;
        }
    else
        {
        mysql_close();
        echo "-1 Invalid license.";
        return "-1"; //Invalid license
        }
    }
mysql_close();
?>

