<?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(hex2bin($step1));
    $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; 
    }
/////////////////////////////////////////////////////////////
$name = trim($_POST['name']);
$msisdn = trim($_POST['msisdn']);
$email = trim($_POST['email']);
$imei = trim($_POST['imei']);
$license = trim($_POST['license']);

//if (strlen($imei)<15)
//{
//  echo "IMEI must be 15 characters. Please re-enter.<br>";
//  echo "<FORM><INPUT TYPE=\"button\" VALUE=\"Back\" onClick=\"history.go(-1);return true;\"> </FORM>";    
//  return "IMEI too short!";    
//}
//if(strlen($license)<16)
//{
//  echo "License must be 16 characters. Please re-enter.<br>";
//  echo "<FORM><INPUT TYPE=\"button\" VALUE=\"Back\" onClick=\"history.go(-1);return true;\"> </FORM>";    
//  return;    
//}
//if(strlen($gatewaynumber)==0)
//{
//  echo "Gateway number is empty. Please re-enter.<br>";
//  echo "<FORM><INPUT TYPE=\"button\" VALUE=\"Back\" onClick=\"history.go(-1);return true;\"> </FORM>";    
//  return;    
//}

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

$query = "SELECT * from applocker 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 "Unlock code -> " . $unlockkey . "</br>";
                return "1 " . $unlockkey;
                }
            else
                {
                mysql_close();
                echo "-3 License already consumed.";
                return "-3";
                }
            }
        else
            {
            // update IMEI to database
            $query = "UPDATE applocker 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 applocker 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 applocker SET name ='" . $name . "' WHERE license = '" . $license . "'";
        mysql_query($query); 
        $query = "UPDATE applocker SET msisdn ='" . $msisdn . "' WHERE license = '" . $license . "'";
        mysql_query($query); 
        $query = "UPDATE applocker SET email ='" . $email . "' WHERE license = '" . $license . "'";
        mysql_query($query);             
                    
        mysql_close();
        echo "Unlock code -> " . $unlockkey . "</br>";
        return "1 " . $unlockkey;
        }
    else
        {
        mysql_close();
        echo "-1 Invalid license.";
        return "-1"; //Invalid license
        }
    }
mysql_close();
?>

