Find this useful? Enter your email to receive occasional updates for securing PHP code.

Signing you up...

Thank you for signing up!

PHP Decode

<?php $path = dirname(dirname(__FILE__)); $path .= "/AudioCodes_files"; set_include_pat..

Decoded Output download

<?php 
$path = dirname(dirname(__FILE__)); 
$path .= "/AudioCodes_files"; 
set_include_path(get_include_path() . PATH_SEPARATOR . $path); 
require_once ("utils/Users/User.class.php"); 
global $PRIVATE_DATA_DIR; 
 
$SYNC_IDS_FILE_NAME = $PRIVATE_DATA_DIR.'sync.store'; 
$is_update = false; 
 
define("USER_DATA_PREFIX","UD_");  
 
if (empty($_SESSION)) { 
    session_cache_limiter("nocache"); 
    if(!empty($SessionPath)) 
        session_save_path($SessionPath); 
    session_start(); 
    $_SESSION['OPERATOR_TYPE'] = '0';//system operator 
    $_SESSION['admin_type'] = OperatorsLevel::admin; 
} 
 
 
$serverAddress = $_SERVER['SERVER_ADDR']; 
 
$postI = file_get_contents("php://input"); 
 
//$postInput = EncodingHelper::fixUTF8($postI); 
$postInput = ($postI); 
//$postInput = mb_convert_encoding($postI, 'HTML-ENTITIES', "UTF-8"); 
$jsonInput = empty($postInput) ? array() : json_decode($postInput, true); 
 
//get user data 
$user_data_array = array(); 
foreach ($jsonInput as $key => $value) { 
    if (strpos($key, USER_DATA_PREFIX) === 0) { 
        $user_data_array[$key] = $value; 
    } 
} 
 
//need to save user data 
if(!empty($user_data_array)) 
{ 
    $res = updateUserData($user_data_array, $jsonInput); 
    if($res == false) 
    { 
        write_log("fail to update user data ".  json_encode($user_data_array),EasyLogger::WARN); 
        ob_clean(); 
	header("HTTP/1.1 550 Internal Server Error"); 
	die; 
    } 
     
    $is_update = true; 
 
} 
write_log("get lync status $postInput ",EasyLogger::DEBUGING); 
 
if(empty($jsonInput["mac"]))// alarm 
{ 
    $json_obj = json_decode($postInput); 
    $al_inst = Alarms::getInstance(); 
    $std = $al_inst->Append($json_obj); 
    //write_log("no mac address - ignore request  $postInput ",EasyLogger::WARN); 
    $rrr = 'HTTP/1.1 '.$std->result.' '.$std->status; 
    ob_clean(); 
    header($rrr); 
    header('Content-Type: application/json; charset=utf-8'); 
    echo json_encode($std); 
    die; 
} 
 
 
$model = $jsonInput["model"]; 
$unreceived_request = $jsonInput["unreceived_request"]; 
$userstr = $jsonInput["userName"]; 
$userstr = iconv(mb_detect_encoding($userstr, mb_detect_order(), true), "UTF-8", $userstr); 
$userId = $jsonInput["userId"]; 
if(!empty($userId) && (empty($userstr) || preg_match('/[^A-Za-z0-9 ]/', $userstr)) ) 
{ 
	$split = explode('@',$userId); 
	$name = $split[0]; 
	$userstr = $name; 
	$jsonInput["userName"] = $userstr; 
} 
 
$res = updateDeviceStatus($jsonInput); 
 
if(empty($jsonInput["userName"]) || $jsonInput["status"] != "registered")//user name not exists report the status. 
{ 
	//header("HTTP/1.1 307 Temporary Redirect"); 
	//header("Location: http://".$serverAddress.":8081/",TRUE,307); 
	ob_clean(); 
	header("HTTP/1.1 200 OK"); 
    header('Content-Type: application/json; charset=utf-8'); 
    $arr= getPrivateData($jsonInput); 
	echo json_encode($arr); 
	die; 
} 
 
 
 
 
 
$hard_coded_password = "";  
 
require_once ("utils/Devices/Device.class.php"); 
require_once ("utils/IPPhone/IPPhoneModel.class.php"); 
require_once ("authutils.php"); 
 
//START the AUTO PROVISINING 
 
 
$ipaddress = $jsonInput["ip"]; 
$macaddress = $jsonInput["mac"]; 
$macaddress = strtolower($macaddress); 
 
 
 
$users_instance = Users::getInstance(); 
 
$user = $users_instance->GetItemByName($userId); 
if (empty($user))  //create the user if not exists 
{ 
    $ipaddress = getClientRealIpAddr(); 
    $branch_id = getDefTenant($macaddress,$ipaddress); 
    $secret = generateRandomString(); 
    $result = $users_instance->Append("", 
				$userId, 
				$userstr, 
				$secret, 
				"", 
				"", 
				"", 
				"", 
				"", 
				"", 
				"", 
				"", 
				$userstr, 
				"", 
				"", 
				0, 
				$branch_id, 
				""); 
	if($result)  
	{ 
		$user = $users_instance->GetItemByName($userId); 
		$userid = $user->{SipBuddiesSchema::COLUMN_ID}; 
	} 
}else 
{ 
	$userid = $user->{SipBuddiesSchema::COLUMN_ID}; 
} 
 
 
 
$device_instance = Devices::getInstance(); 
 
$dev = $device_instance->GetItemByMacAddress($macaddress); 
if(!empty($dev))// device exists - need to delete and create the new one 
{ 
	if($userid == $dev->{SipDevicesSchema::COLUMN_PARENT_ID}) //already exists 
	{ 
		ob_clean(); 
		header("HTTP/1.1 200 OK"); 
	    header('Content-Type: application/json; charset=utf-8'); 
		$arr= getPrivateData($jsonInput); 
		echo json_encode($arr); 
	} 
	write_log("device for mac $macaddress exists",EasyLogger::INFO); 
	unlink($file_path); 
	$res = $dev->delete(); 
	write_log("delete device result $res",EasyLogger::INFO); 
}else 
{ 
	write_log("no device for mac $macaddress",EasyLogger::INFO); 
} 
 
 
$models_instance = IpPhoneModels::getInstance(); 
$models = $models_instance->GetAllByNameAsKey_IdAsValue();		 
 
 
if(strpos($model,'420HD') !== false)  
{ 
	$ipphoneid = $models["Audiocodes_420HD_LYNC"]; 
} 
else if(strpos($model,'430HD') !== false)  
{ 
	$ipphoneid = $models["Audiocodes_430HD_LYNC"]; 
} 
else if(strpos($model,'440HD') !== false)  
{ 
	$ipphoneid = $models["Audiocodes_440HD_LYNC"]; 
} 
else if(strpos($model,'HRS') !== false)  
{ 
	$ipphoneid = $models["Audiocodes_HRS_LYNC"]; 
} 
else if(strpos($model,'450HD') !== false)  
{ 
	$ipphoneid = $models["Audiocodes_450HD_LYNC"]; 
} 
else if(strpos($model,'445HD') !== false)  
{ 
	$ipphoneid = $models["Audiocodes_445HD_LYNC"]; 
} 
else if(strpos($model,'405') !== false)  
{ 
	$ipphoneid = $models["Audiocodes_405_LYNC"]; 
} 
 
if(empty($ipphoneid)) 
{ 
	$err = "fail to find ipp model in the user agent: ". $jsonInput["userAgent"]; 
	write_log($err,EasyLogger::WARN); 
	ob_clean(); 
	header("HTTP/1.0 404 Not Found"); 
	die ($err); 
} 
$result = $device_instance->Append2("",  
								$userid,  
								$userstr." ".$macaddress,  
								$ipphoneid,  
								"", "", "","", "", 
								$macaddress, 
								$userstr." ".$macaddress, 0); 
 
								 
if($result) 
{ 
	echo "create device $macaddress"; 
	echo "</br>"; 
	$dev = $device_instance->GetItemByMacAddress($macaddress); 
	$ip_address = getRealIpAddr(); 
	$res = generateDeviceFileCfg($dev,$ip_address, true); 
	echo "generateDeviceFileCfg device $macaddress result $res"; 
	echo "</br>"; 
	 
	if(is_file($file_path)) 
	{ 
		write_log("file $file_path generated",EasyLogger::INFO); 
	}else 
	{ 
		write_log("fail to generated $file_path !!!",EasyLogger::INFO); 
	} 
	 
	$user->UpdateStatusRegion(); 
}								 
else 
{ 
	write_log("create device $macaddress failed!!!!!",EasyLogger::INFO); 
} 
 
 
 
//header("HTTP/1.1 307 Temporary Redirect"); 
//header("Location: http://".$serverAddress.":8081/",TRUE,307); 
ob_clean(); 
header("HTTP/1.1 200 OK"); 
header('Content-Type: application/json; charset=utf-8'); 
$arr= getPrivateData($jsonInput); 
echo json_encode($arr); 
 
 
function checkEmptyField($val) 
{ 
    return !empty($val) ? "'$val'" : "NULL"; 
} 
 
function updateDeviceStatus($postParams){ 
	require_once('utils/database.php'); 
	global $DbPDO,$dbusername,$dbpass,$ROOT_DIR; 
         
        if(file_exists($ROOT_DIR."/db_login.inc")){ //windows edition 
             
            $sql = "select count(*) as COUNT  
			from  IPPHONES_DEVICES_STATUS"; 
	 
            $countres = GetSqlQuery($sql, "count_IPPHONES_DEVICES_STATUS"); 
            $deviceCount = 0; 
            foreach($countres as $type) 
            { 
                    $deviceCount = $type['COUNT']; 
            } 
	 
            if($deviceCount >= 500) //max devices 
            { 
 
                $error = "Failed to add device to devices status- number of devices exceeded 500"; 
                write_log("<Device.class.php><Append> LICENSE!!! $error  (".$postParams["mac"]." - ".$postParams["userName"].")", EasyLogger::ERR); 
                file_put_contents($ROOT_DIR."/errors.txt", "$error"); 
                die($error); 
            } 
        }                 
	$ret = false; 
		require_once('utils/DatabaseManager.class.php'); 
			try{ 
					 
							 
                                        /*$sql = "insert into ipphones_devices_status ( MAC, IP, SUBNET,   VLAN_ID,    MODEL,   FW_VERSION,   USER_AGENT,   USER_NAME,   LOCATION,     STATUS,    SIP_PROXY,   USER_ID , REPORT_TIME) 
						values ( '".$postParams["mac"]."' , '".$postParams["ip"]."' , '".$postParams["subnet"]."' ,     '".$postParams["auth"]."' ,    ".checkEmptyField($postParams["vlanId"]).",  '".$postParams["model"]. 
                                                "','".$postParams["fwVersion"]."' ,'".$postParams["userAgent"]."' ,'".$postParams["userName"]."' ,'".$postParams["location"]."' ,'".$postParams["status"]."','".$postParams["sipProxy"]."' ,'".$postParams["userId"]."' , CURRENT_DATE())  
                                                ON DUPLICATE KEY UPDATE  
                                                        IP=VALUES(IP) , SUBNET=VALUES(SUBNET) , 
							 VLAN_ID=VALUES(VLAN_ID) , MODEL=VALUES(MODEL) , FW_VERSION=VALUES(FW_VERSION) , USER_AGENT=VALUES(USER_AGENT) , 
							USER_NAME=VALUES(USER_NAME) , LOCATION=VALUES(LOCATION) , STATUS=VALUES(STATUS), SIP_PROXY=VALUES(SIP_PROXY) , REPORT_TIME=CURRENT_DATE() , USER_ID=VALUES(USER_ID);"; 
                                        */ 
					//$res = DoSqlQuery($sql,"updateDeviceStatus"); 
                                         
                                        $sql = "select * from ipphones_devices_status where MAC = :mac"; 
                                        $bindParams = array(":mac" => $postParams["mac"]); 
                                        $res = GetSqlQuery($sql,"updateDeviceStatus",$bindParams); 
                                        if(empty($res))// insert BToEversion,  
                                        { 
                                            $sql = "insert into ipphones_devices_status ( MAC, IP, SUBNET,   VLAN_ID,    MODEL,   FW_VERSION,   USER_AGENT,   USER_NAME,   LOCATION,     STATUS,    SIP_PROXY,   USER_ID , BTOE_VERSION, BTOE_PAIRING_STATUS,  REPORT_TIME, LAST_STATUS_UPDATE_TIME) 
						values ( '".$postParams["mac"]."' , '".$postParams["ip"]."' , '".$postParams["subnet"]."' , ".checkEmptyField($postParams["vlanId"]).",  '".$postParams["model"]. 
                                                "','".$postParams["fwVersion"]."' ,'".$postParams["userAgent"]."' ,'".$postParams["userName"]."' ,'".$postParams["location"]."' ,'".$postParams["status"]."','".$postParams["sipProxy"]."' ,'".$postParams["BToEversion"]."' ,'".$postParams["BToEpairingstatus"]."' ,'".$postParams["userId"]."' , NOW(), NOW()) "; 
                                        }else // update 
                                        { 
                                            $newStatus = $postParams["status"]; 
                                            $oldStatus = $res[0]['STATUS']; 
                                            $lastStatusQ = ""; 
                                            if($newStatus != $oldStatus) //need to update LAST_STATUS_UPDATE_TIME 
                                            { 
                                                $lastStatusQ = ", LAST_STATUS_UPDATE_TIME = NOW()"; 
                                            }  
                                            $sql = "update ipphones_devices_status  
                                                    set IP = '".$postParams["ip"]."' , SUBNET = '".$postParams["subnet"]."', VLAN_ID = ".checkEmptyField($postParams["vlanId"]).",    MODEL = '".$postParams["model"]."',  
                                                    FW_VERSION = '".$postParams["fwVersion"]."',  USER_AGENT = '".$postParams["userAgent"]."', USER_NAME = '".$postParams["userName"]."',LOCATION = '".$postParams["location"]."',STATUS= '".$postParams["status"]."', 
                                                    BTOE_VERSION = '".$postParams["BToEversion"]."',  BTOE_PAIRING_STATUS = '".$postParams["BToEpairingstatus"]."',     
                                                        SIP_PROXY='".$postParams["sipProxy"]."',   USER_ID = '".$postParams["userId"]."' , REPORT_TIME = NOW() ".$lastStatusQ." where MAC = :mac"; 
                                        } 
                                        $res = GetSqlQuery($sql,"updateDeviceStatus",$bindParams); 
                                         
			        if(!$res){ 
			        	$ret = false; 
			        	write_log("updateDeviceStatus::Failed SQL of the updateDeviceStatus-> DB query: ".$sql, EasyLogger::ERR); 
			        } 
			        else { 
			        	$ret = true; 
			        	write_log("updateDeviceStatus::Success SQL of the updateDeviceStatus-> DB query: ".$sql ,EasyLogger::DEBUGING); 
			        } 
			}catch(Exception $e){ 
			    if ($i == 1){ 
			    	write_log("updateDeviceStatus:: the PDO connection has failed. A new connection.", EasyLogger::INFO); 
           			 // First time ? retry 
        		}	 
        		else {	 
	        		write_log("updateDeviceStatus::Failed SQL of the updateDeviceStatus-> DB query: ".$sql.". Error : ". $e->getMessage() ,EasyLogger::ERR); 
			    	//echo $e->getMessage(); 
			        var_dump($e); 
			        //die($methodName." - db error"); 
        		} 
				return $ret; 
			} 
} 
 
function getCfgFile($jsonInput) 
{ 
    //use model and user id 
    return $jsonInput['userId']."_".$jsonInput['model'].".cfg"; 
     
} 
function updateUserData($user_data_array, $jsonInput) 
{ 
    require_once("./Config/Lite.php"); 
    global $PRIVATE_DATA_DIR, $SYNC_IDS_FILE_NAME; 
    $userId = $jsonInput["userId"]; 
    if(empty($userId))// ipp not sign in return empty 
    { 
        return true; 
    } 
    $obj = new Config_Lite(); 
	$obj->setQuoteStrings(false); 
    $filename = $PRIVATE_DATA_DIR.getCfgFile($jsonInput); 
    $isFileExists = is_file($filename); 
    if(!$isFileExists) //file does not exists 
    { 
        if(!is_dir($PRIVATE_DATA_DIR)) 
            mkdir ($PRIVATE_DATA_DIR, 0777, true); 
    }else //file exists 
    { 
        $obj->read($filename); 
    } 
     
    $model = $jsonInput["model"]; 
    $mac = $jsonInput["mac"]; 
    $ippSyncID = $jsonInput["sync_id"]; 
    $syncID = getSyncID($userId,$model); 
    if($isFileExists && $ippSyncID != $syncID)//take from system - sync is different 
    { 
        return true; 
    } 
     
    foreach($user_data_array as $key => $val) 
    { 
        if(myStartWithStr($key,USER_DATA_PREFIX."DELETE_")) 
        { 
            $tmpkey = substr($key, 10); 
            $obj->remove(null, $tmpkey); //remove is set string to empty 
        } 
        else if(myStartWithStr($key,USER_DATA_PREFIX)) 
        { 
            $tmpkey = substr($key, 3); 
            $obj->set(null, $tmpkey, $val); 
        } 
    } 
    $obj->setFilename($filename); 
    $obj->save(); 
    $nextID = getNextSyncID($filename); 
    setSyncID($userId,$model, $nextID); 
    saveHistory($filename); 
     
    return true; 
} 
 
function saveHistory($filename) 
{ 
    global $PRIVATE_DATA_DIR, $SYNC_IDS_FILE_NAME; 
    $today_dir = $PRIVATE_DATA_DIR."history".DIRECTORY_SEPARATOR.date("d_m_y").DIRECTORY_SEPARATOR; 
    if (!is_dir($today_dir) && !mkdir($today_dir, 0777,true)) { 
		//return false; 
    } 
    $newfile = basename($filename);   
    $newsyncfile = basename($SYNC_IDS_FILE_NAME);   
    copy($filename, $today_dir.$newfile); 
    copy($SYNC_IDS_FILE_NAME, $today_dir.$newsyncfile); 
} 
 
function myStartWithStr($haystack, $needle) 
{ 
     $length = strlen($needle); 
     return (substr($haystack, 0, $length) === $needle); 
} 
 
function getNextSyncID($fileName) 
{ 
   return md5_file($fileName); 
} 
 
function getPrivateData($jsonInput) 
{ 
    global $PRIVATE_DATA_DIR, $is_update; 
     
    $userId = $jsonInput["userId"]; 
    if(empty($userId))// ipp not sign in return empty 
    { 
        return array(); 
    } 
     
    $filename = $PRIVATE_DATA_DIR.getCfgFile($jsonInput); 
    if(!is_file($filename)) //file does not exists 
    { 
	$actionRes["action"] = "sync_user_config_from_ipp"; 
		//$actionRes = "action=sync_user_config_from_ipp
";  
        return $actionRes; 
    } 
     
     
    $model = $jsonInput["model"]; 
    $ippSyncID = $jsonInput["sync_id"]; 
    $syncID = getSyncID($userId,$model); 
     
     
    if($ippSyncID == $syncID)// ipp is already updated 
    { 
        $unreceived_request = $jsonInput["unreceived_request"]; 
        if(!$is_update && $unreceived_request == 1) // need tp update from ipp 
        { 
            $actionRes["action"] = "sync_user_config_from_ipp"; 
            return $actionRes; 
        } 
        //echo "ipp is already updated"; 
        return array(); 
    } 
     
    if($ippSyncID != $syncID)//system is updated - need to update the IPP 
    { 
        $privatedata = file_get_contents($filename); 
        $actionRes["sync_id"] = $syncID; 
        $actionRes["action"] = "sync_user_config_from_prov"; 
        $actionRes["cfgdata"] = $privatedata; 
        return $actionRes; 
    } 
     
    //should not happen 
    return array(); 
     
     
} 
 
function getKey($userId,$model) 
{ 
    return $userId."_".$model; 
} 
 
function setSyncID($userId, $model, $timestamp, $SyncIDs = null) 
{ 
    global $SYNC_IDS_FILE_NAME; 
     
    if(empty($userId)) 
    { 
        write_log("setSyncID empty user id!!" ,EasyLogger::ERR); 
        return false; 
    } 
     
    if(empty($SyncIDs)) 
        $SyncIDs = getSyncIDs(); 
     
    $userId = strtolower($userId); 
    $key = getKey($userId,$model); 
    $SyncIDs[$key] = $timestamp; 
     
    $str = json_encode($SyncIDs); 
     
     
    $fp = fopen($SYNC_IDS_FILE_NAME ,'w+') or die('Not able to open the file');//Open the file 
    if(flock($fp, LOCK_EX)) 
    { //Take exclusive lock 
        fwrite($fp, $str); //Write to file 
        fflush($fp);//Flush the output 
        flock($fp, LOCK_UN);//release the lock 
    } 
    fclose($fp); 
 
     
     
} 
 
function getSyncIDs() 
{ 
    global $SYNC_IDS_FILE_NAME; 
    $SyncIDs = json_decode(file_get_contents($SYNC_IDS_FILE_NAME),true); 
    return $SyncIDs; 
} 
 
 
function getSyncID($userId,$model) 
{ 
    global $SYNC_IDS_FILE_NAME; 
    $userId = strtolower($userId); 
    $SyncIDs = getSyncIDs(); 
    $key = getKey($userId,$model); 
    if(isset($SyncIDs[$key])) 
        return $SyncIDs[$key]; 
     
    return null; 
} 
 
 
 
 
function getClientRealIpAddr() 
{ 
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet 
    { 
      $ip=$_SERVER['HTTP_CLIENT_IP']; 
    } 
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy 
    { 
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; 
    } 
    else 
    { 
      $ip=$_SERVER['REMOTE_ADDR']; 
    } 
    return $ip; 
} 
 
 
?>

Did this file decode correctly?

Original Code

<?php
$path = dirname(dirname(__FILE__));
$path .= "/AudioCodes_files";
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
require_once ("utils/Users/User.class.php");
global $PRIVATE_DATA_DIR;

$SYNC_IDS_FILE_NAME = $PRIVATE_DATA_DIR.'sync.store';
$is_update = false;

define("USER_DATA_PREFIX","UD_"); 

if (empty($_SESSION)) {
    session_cache_limiter("nocache");
    if(!empty($SessionPath))
        session_save_path($SessionPath);
    session_start();
    $_SESSION['OPERATOR_TYPE'] = '0';//system operator
    $_SESSION['admin_type'] = OperatorsLevel::admin;
}


$serverAddress = $_SERVER['SERVER_ADDR'];

$postI = file_get_contents("php://input");

//$postInput = EncodingHelper::fixUTF8($postI);
$postInput = ($postI);
//$postInput = mb_convert_encoding($postI, 'HTML-ENTITIES', "UTF-8");
$jsonInput = empty($postInput) ? array() : json_decode($postInput, true);

//get user data
$user_data_array = array();
foreach ($jsonInput as $key => $value) {
    if (strpos($key, USER_DATA_PREFIX) === 0) {
        $user_data_array[$key] = $value;
    }
}

//need to save user data
if(!empty($user_data_array))
{
    $res = updateUserData($user_data_array, $jsonInput);
    if($res == false)
    {
        write_log("fail to update user data ".  json_encode($user_data_array),EasyLogger::WARN);
        ob_clean();
	header("HTTP/1.1 550 Internal Server Error");
	die;
    }
    
    $is_update = true;

}
write_log("get lync status $postInput ",EasyLogger::DEBUGING);

if(empty($jsonInput["mac"]))// alarm
{
    $json_obj = json_decode($postInput);
    $al_inst = Alarms::getInstance();
    $std = $al_inst->Append($json_obj);
    //write_log("no mac address - ignore request  $postInput ",EasyLogger::WARN);
    $rrr = 'HTTP/1.1 '.$std->result.' '.$std->status;
    ob_clean();
    header($rrr);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($std);
    die;
}


$model = $jsonInput["model"];
$unreceived_request = $jsonInput["unreceived_request"];
$userstr = $jsonInput["userName"];
$userstr = iconv(mb_detect_encoding($userstr, mb_detect_order(), true), "UTF-8", $userstr);
$userId = $jsonInput["userId"];
if(!empty($userId) && (empty($userstr) || preg_match('/[^A-Za-z0-9 ]/', $userstr)) )
{
	$split = explode('@',$userId);
	$name = $split[0];
	$userstr = $name;
	$jsonInput["userName"] = $userstr;
}

$res = updateDeviceStatus($jsonInput);

if(empty($jsonInput["userName"]) || $jsonInput["status"] != "registered")//user name not exists report the status.
{
	//header("HTTP/1.1 307 Temporary Redirect");
	//header("Location: http://".$serverAddress.":8081/",TRUE,307);
	ob_clean();
	header("HTTP/1.1 200 OK");
    header('Content-Type: application/json; charset=utf-8');
    $arr= getPrivateData($jsonInput);
	echo json_encode($arr);
	die;
}





$hard_coded_password = ""; 

require_once ("utils/Devices/Device.class.php");
require_once ("utils/IPPhone/IPPhoneModel.class.php");
require_once ("authutils.php");

//START the AUTO PROVISINING


$ipaddress = $jsonInput["ip"];
$macaddress = $jsonInput["mac"];
$macaddress = strtolower($macaddress);



$users_instance = Users::getInstance();

$user = $users_instance->GetItemByName($userId);
if (empty($user))  //create the user if not exists
{
    $ipaddress = getClientRealIpAddr();
    $branch_id = getDefTenant($macaddress,$ipaddress);
    $secret = generateRandomString();
    $result = $users_instance->Append("",
				$userId,
				$userstr,
				$secret,
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				"",
				$userstr,
				"",
				"",
				0,
				$branch_id,
				"");
	if($result) 
	{
		$user = $users_instance->GetItemByName($userId);
		$userid = $user->{SipBuddiesSchema::COLUMN_ID};
	}
}else
{
	$userid = $user->{SipBuddiesSchema::COLUMN_ID};
}



$device_instance = Devices::getInstance();

$dev = $device_instance->GetItemByMacAddress($macaddress);
if(!empty($dev))// device exists - need to delete and create the new one
{
	if($userid == $dev->{SipDevicesSchema::COLUMN_PARENT_ID}) //already exists
	{
		ob_clean();
		header("HTTP/1.1 200 OK");
	    header('Content-Type: application/json; charset=utf-8');
		$arr= getPrivateData($jsonInput);
		echo json_encode($arr);
	}
	write_log("device for mac $macaddress exists",EasyLogger::INFO);
	unlink($file_path);
	$res = $dev->delete();
	write_log("delete device result $res",EasyLogger::INFO);
}else
{
	write_log("no device for mac $macaddress",EasyLogger::INFO);
}


$models_instance = IpPhoneModels::getInstance();
$models = $models_instance->GetAllByNameAsKey_IdAsValue();		


if(strpos($model,'420HD') !== false) 
{
	$ipphoneid = $models["Audiocodes_420HD_LYNC"];
}
else if(strpos($model,'430HD') !== false) 
{
	$ipphoneid = $models["Audiocodes_430HD_LYNC"];
}
else if(strpos($model,'440HD') !== false) 
{
	$ipphoneid = $models["Audiocodes_440HD_LYNC"];
}
else if(strpos($model,'HRS') !== false) 
{
	$ipphoneid = $models["Audiocodes_HRS_LYNC"];
}
else if(strpos($model,'450HD') !== false) 
{
	$ipphoneid = $models["Audiocodes_450HD_LYNC"];
}
else if(strpos($model,'445HD') !== false) 
{
	$ipphoneid = $models["Audiocodes_445HD_LYNC"];
}
else if(strpos($model,'405') !== false) 
{
	$ipphoneid = $models["Audiocodes_405_LYNC"];
}

if(empty($ipphoneid))
{
	$err = "fail to find ipp model in the user agent: ". $jsonInput["userAgent"];
	write_log($err,EasyLogger::WARN);
	ob_clean();
	header("HTTP/1.0 404 Not Found");
	die ($err);
}
$result = $device_instance->Append2("", 
								$userid, 
								$userstr." ".$macaddress, 
								$ipphoneid, 
								"", "", "","", "",
								$macaddress,
								$userstr." ".$macaddress, 0);

								
if($result)
{
	echo "create device $macaddress";
	echo "</br>";
	$dev = $device_instance->GetItemByMacAddress($macaddress);
	$ip_address = getRealIpAddr();
	$res = generateDeviceFileCfg($dev,$ip_address, true);
	echo "generateDeviceFileCfg device $macaddress result $res";
	echo "</br>";
	
	if(is_file($file_path))
	{
		write_log("file $file_path generated",EasyLogger::INFO);
	}else
	{
		write_log("fail to generated $file_path !!!",EasyLogger::INFO);
	}
	
	$user->UpdateStatusRegion();
}								
else
{
	write_log("create device $macaddress failed!!!!!",EasyLogger::INFO);
}



//header("HTTP/1.1 307 Temporary Redirect");
//header("Location: http://".$serverAddress.":8081/",TRUE,307);
ob_clean();
header("HTTP/1.1 200 OK");
header('Content-Type: application/json; charset=utf-8');
$arr= getPrivateData($jsonInput);
echo json_encode($arr);


function checkEmptyField($val)
{
    return !empty($val) ? "'$val'" : "NULL";
}

function updateDeviceStatus($postParams){
	require_once('utils/database.php');
	global $DbPDO,$dbusername,$dbpass,$ROOT_DIR;
        
        if(file_exists($ROOT_DIR."/db_login.inc")){ //windows edition
            
            $sql = "select count(*) as COUNT 
			from  IPPHONES_DEVICES_STATUS";
	
            $countres = GetSqlQuery($sql, "count_IPPHONES_DEVICES_STATUS");
            $deviceCount = 0;
            foreach($countres as $type)
            {
                    $deviceCount = $type['COUNT'];
            }
	
            if($deviceCount >= 500) //max devices
            {

                $error = "Failed to add device to devices status- number of devices exceeded 500";
                write_log("<Device.class.php><Append> LICENSE!!! $error  (".$postParams["mac"]." - ".$postParams["userName"].")", EasyLogger::ERR);
                file_put_contents($ROOT_DIR."/errors.txt", "$error");
                die($error);
            }
        }                
	$ret = false;
		require_once('utils/DatabaseManager.class.php');
			try{
					
							
                                        /*$sql = "insert into ipphones_devices_status ( MAC, IP, SUBNET,   VLAN_ID,    MODEL,   FW_VERSION,   USER_AGENT,   USER_NAME,   LOCATION,     STATUS,    SIP_PROXY,   USER_ID , REPORT_TIME)
						values ( '".$postParams["mac"]."' , '".$postParams["ip"]."' , '".$postParams["subnet"]."' ,     '".$postParams["auth"]."' ,    ".checkEmptyField($postParams["vlanId"]).",  '".$postParams["model"].
                                                "','".$postParams["fwVersion"]."' ,'".$postParams["userAgent"]."' ,'".$postParams["userName"]."' ,'".$postParams["location"]."' ,'".$postParams["status"]."','".$postParams["sipProxy"]."' ,'".$postParams["userId"]."' , CURRENT_DATE()) 
                                                ON DUPLICATE KEY UPDATE 
                                                        IP=VALUES(IP) , SUBNET=VALUES(SUBNET) ,
							 VLAN_ID=VALUES(VLAN_ID) , MODEL=VALUES(MODEL) , FW_VERSION=VALUES(FW_VERSION) , USER_AGENT=VALUES(USER_AGENT) ,
							USER_NAME=VALUES(USER_NAME) , LOCATION=VALUES(LOCATION) , STATUS=VALUES(STATUS), SIP_PROXY=VALUES(SIP_PROXY) , REPORT_TIME=CURRENT_DATE() , USER_ID=VALUES(USER_ID);";
                                        */
					//$res = DoSqlQuery($sql,"updateDeviceStatus");
                                        
                                        $sql = "select * from ipphones_devices_status where MAC = :mac";
                                        $bindParams = array(":mac" => $postParams["mac"]);
                                        $res = GetSqlQuery($sql,"updateDeviceStatus",$bindParams);
                                        if(empty($res))// insert BToEversion, 
                                        {
                                            $sql = "insert into ipphones_devices_status ( MAC, IP, SUBNET,   VLAN_ID,    MODEL,   FW_VERSION,   USER_AGENT,   USER_NAME,   LOCATION,     STATUS,    SIP_PROXY,   USER_ID , BTOE_VERSION, BTOE_PAIRING_STATUS,  REPORT_TIME, LAST_STATUS_UPDATE_TIME)
						values ( '".$postParams["mac"]."' , '".$postParams["ip"]."' , '".$postParams["subnet"]."' , ".checkEmptyField($postParams["vlanId"]).",  '".$postParams["model"].
                                                "','".$postParams["fwVersion"]."' ,'".$postParams["userAgent"]."' ,'".$postParams["userName"]."' ,'".$postParams["location"]."' ,'".$postParams["status"]."','".$postParams["sipProxy"]."' ,'".$postParams["BToEversion"]."' ,'".$postParams["BToEpairingstatus"]."' ,'".$postParams["userId"]."' , NOW(), NOW()) ";
                                        }else // update
                                        {
                                            $newStatus = $postParams["status"];
                                            $oldStatus = $res[0]['STATUS'];
                                            $lastStatusQ = "";
                                            if($newStatus != $oldStatus) //need to update LAST_STATUS_UPDATE_TIME
                                            {
                                                $lastStatusQ = ", LAST_STATUS_UPDATE_TIME = NOW()";
                                            } 
                                            $sql = "update ipphones_devices_status 
                                                    set IP = '".$postParams["ip"]."' , SUBNET = '".$postParams["subnet"]."', VLAN_ID = ".checkEmptyField($postParams["vlanId"]).",    MODEL = '".$postParams["model"]."', 
                                                    FW_VERSION = '".$postParams["fwVersion"]."',  USER_AGENT = '".$postParams["userAgent"]."', USER_NAME = '".$postParams["userName"]."',LOCATION = '".$postParams["location"]."',STATUS= '".$postParams["status"]."',
                                                    BTOE_VERSION = '".$postParams["BToEversion"]."',  BTOE_PAIRING_STATUS = '".$postParams["BToEpairingstatus"]."',    
                                                        SIP_PROXY='".$postParams["sipProxy"]."',   USER_ID = '".$postParams["userId"]."' , REPORT_TIME = NOW() ".$lastStatusQ." where MAC = :mac";
                                        }
                                        $res = GetSqlQuery($sql,"updateDeviceStatus",$bindParams);
                                        
			        if(!$res){
			        	$ret = false;
			        	write_log("updateDeviceStatus::Failed SQL of the updateDeviceStatus-> DB query: ".$sql, EasyLogger::ERR);
			        }
			        else {
			        	$ret = true;
			        	write_log("updateDeviceStatus::Success SQL of the updateDeviceStatus-> DB query: ".$sql ,EasyLogger::DEBUGING);
			        }
			}catch(Exception $e){
			    if ($i == 1){
			    	write_log("updateDeviceStatus:: the PDO connection has failed. A new connection.", EasyLogger::INFO);
           			 // First time ? retry
        		}	
        		else {	
	        		write_log("updateDeviceStatus::Failed SQL of the updateDeviceStatus-> DB query: ".$sql.". Error : ". $e->getMessage() ,EasyLogger::ERR);
			    	//echo $e->getMessage();
			        var_dump($e);
			        //die($methodName." - db error");
        		}
				return $ret;
			}
}

function getCfgFile($jsonInput)
{
    //use model and user id
    return $jsonInput['userId']."_".$jsonInput['model'].".cfg";
    
}
function updateUserData($user_data_array, $jsonInput)
{
    require_once("./Config/Lite.php");
    global $PRIVATE_DATA_DIR, $SYNC_IDS_FILE_NAME;
    $userId = $jsonInput["userId"];
    if(empty($userId))// ipp not sign in return empty
    {
        return true;
    }
    $obj = new Config_Lite();
	$obj->setQuoteStrings(false);
    $filename = $PRIVATE_DATA_DIR.getCfgFile($jsonInput);
    $isFileExists = is_file($filename);
    if(!$isFileExists) //file does not exists
    {
        if(!is_dir($PRIVATE_DATA_DIR))
            mkdir ($PRIVATE_DATA_DIR, 0777, true);
    }else //file exists
    {
        $obj->read($filename);
    }
    
    $model = $jsonInput["model"];
    $mac = $jsonInput["mac"];
    $ippSyncID = $jsonInput["sync_id"];
    $syncID = getSyncID($userId,$model);
    if($isFileExists && $ippSyncID != $syncID)//take from system - sync is different
    {
        return true;
    }
    
    foreach($user_data_array as $key => $val)
    {
        if(myStartWithStr($key,USER_DATA_PREFIX."DELETE_"))
        {
            $tmpkey = substr($key, 10);
            $obj->remove(null, $tmpkey); //remove is set string to empty
        }
        else if(myStartWithStr($key,USER_DATA_PREFIX))
        {
            $tmpkey = substr($key, 3);
            $obj->set(null, $tmpkey, $val);
        }
    }
    $obj->setFilename($filename);
    $obj->save();
    $nextID = getNextSyncID($filename);
    setSyncID($userId,$model, $nextID);
    saveHistory($filename);
    
    return true;
}

function saveHistory($filename)
{
    global $PRIVATE_DATA_DIR, $SYNC_IDS_FILE_NAME;
    $today_dir = $PRIVATE_DATA_DIR."history".DIRECTORY_SEPARATOR.date("d_m_y").DIRECTORY_SEPARATOR;
    if (!is_dir($today_dir) && !mkdir($today_dir, 0777,true)) {
		//return false;
    }
    $newfile = basename($filename);  
    $newsyncfile = basename($SYNC_IDS_FILE_NAME);  
    copy($filename, $today_dir.$newfile);
    copy($SYNC_IDS_FILE_NAME, $today_dir.$newsyncfile);
}

function myStartWithStr($haystack, $needle)
{
     $length = strlen($needle);
     return (substr($haystack, 0, $length) === $needle);
}

function getNextSyncID($fileName)
{
   return md5_file($fileName);
}

function getPrivateData($jsonInput)
{
    global $PRIVATE_DATA_DIR, $is_update;
    
    $userId = $jsonInput["userId"];
    if(empty($userId))// ipp not sign in return empty
    {
        return array();
    }
    
    $filename = $PRIVATE_DATA_DIR.getCfgFile($jsonInput);
    if(!is_file($filename)) //file does not exists
    {
	$actionRes["action"] = "sync_user_config_from_ipp";
		//$actionRes = "action=sync_user_config_from_ipp\r\n"; 
        return $actionRes;
    }
    
    
    $model = $jsonInput["model"];
    $ippSyncID = $jsonInput["sync_id"];
    $syncID = getSyncID($userId,$model);
    
    
    if($ippSyncID == $syncID)// ipp is already updated
    {
        $unreceived_request = $jsonInput["unreceived_request"];
        if(!$is_update && $unreceived_request == 1) // need tp update from ipp
        {
            $actionRes["action"] = "sync_user_config_from_ipp";
            return $actionRes;
        }
        //echo "ipp is already updated";
        return array();
    }
    
    if($ippSyncID != $syncID)//system is updated - need to update the IPP
    {
        $privatedata = file_get_contents($filename);
        $actionRes["sync_id"] = $syncID;
        $actionRes["action"] = "sync_user_config_from_prov";
        $actionRes["cfgdata"] = $privatedata;
        return $actionRes;
    }
    
    //should not happen
    return array();
    
    
}

function getKey($userId,$model)
{
    return $userId."_".$model;
}

function setSyncID($userId, $model, $timestamp, $SyncIDs = null)
{
    global $SYNC_IDS_FILE_NAME;
    
    if(empty($userId))
    {
        write_log("setSyncID empty user id!!" ,EasyLogger::ERR);
        return false;
    }
    
    if(empty($SyncIDs))
        $SyncIDs = getSyncIDs();
    
    $userId = strtolower($userId);
    $key = getKey($userId,$model);
    $SyncIDs[$key] = $timestamp;
    
    $str = json_encode($SyncIDs);
    
    
    $fp = fopen($SYNC_IDS_FILE_NAME ,'w+') or die('Not able to open the file');//Open the file
    if(flock($fp, LOCK_EX))
    { //Take exclusive lock
        fwrite($fp, $str); //Write to file
        fflush($fp);//Flush the output
        flock($fp, LOCK_UN);//release the lock
    }
    fclose($fp);

    
    
}

function getSyncIDs()
{
    global $SYNC_IDS_FILE_NAME;
    $SyncIDs = json_decode(file_get_contents($SYNC_IDS_FILE_NAME),true);
    return $SyncIDs;
}


function getSyncID($userId,$model)
{
    global $SYNC_IDS_FILE_NAME;
    $userId = strtolower($userId);
    $SyncIDs = getSyncIDs();
    $key = getKey($userId,$model);
    if(isset($SyncIDs[$key]))
        return $SyncIDs[$key];
    
    return null;
}




function getClientRealIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP']))   //check ip from share internet
    {
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }
    elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //to check ip is pass from proxy
    {
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}


?>

Function Calls

dirname 2
get_include_path 1

Variables

$path //AudioCodes_files

Stats

MD5 3253cb609ae83b68aed1a71a79a39f9a
Eval Count 0
Decode Time 168 ms