<?php

require_once dirname(__FILE__).'/../../lib/phoneprovisioning.php';
require_once __DIR__."/ergophone.php";
require_once __DIR__.'/lib/ErgophoneXml.php';

function _get_response_headers_as_string()
{
	global $_SERVER;
	if (! function_exists('headers_list')) {
		//gs_log( GS_LOG_DEBUG, 'Can\'t get response headers (PHP < 5)' );
		return false;
	}
	$ret = '';
	$ret.= $_SERVER['SERVER_PROTOCOL'] .' 200 OK'. "\r\n";
	$headers = headers_list();
	foreach ($headers as $header) {
		$ret .= $header ."\r\n";
	}
	$ret .= "\r\n";
	return $ret;
}

function _get_request_headers_as_string()
{
	global $_SERVER, $orig_url;
	$ret = '';
	$ret.= $_SERVER['REQUEST_METHOD'] .' '. $orig_url .' '. $_SERVER['SERVER_PROTOCOL'] ."\r\n";
	foreach ($_SERVER as $k => $v) {
		if (subStr($k,0,5) === 'HTTP_') {
			$k = str_replace(' ','-',ucWords(str_replace('_',' ',strToLower( subStr($k,5) ))));
			$ret .= $k .': '. $v ."\r\n";
		}
	}
	$ret .= "\r\n";
	return $ret;
}


function siemens_prov_error_handler( $type, $msg, $file, $line )
{
	Log::e("error", "ergotest");
	Log::e($type." ".$msg." ".$file.":".$line, "ergotest");
}
set_error_handler('siemens_prov_error_handler');



class ErgophonePhoneProvisioning extends VirtualPhoneProvisioningController {

	private $answer = null;
	private $filesToDeploy = array();
	private $filesAreDeployed = array();

	public function registerErgophone($relevantData) {
        
        $model = $this->getPhoneModelForDeviceName('ergoS501');
        if ($model == null) {
            return false;
        }
        
        $this->setCurrentPhoneModel($model);
        $this->checkMacAddress($relevantData['mac_addr']);
        $this->setCurrentFirmwareVersion($this->normalizeFirmwareVersion($relevantData['firmware']));
        
        $this->getPhoneModel();
        
        $sipAccount = SipAccounts::model()->findbyAttributes(array('authname'=>$relevantData['voipId']));
        if ($sipAccount) {
            $this->mCurrentRealPhoneModelInstance->sip_account_id = $sipAccount->id;
            $this->mCurrentRealPhoneModelInstance->ipv4_address = $relevantData['ipv4_address'];
            $this->mCurrentRealPhoneModelInstance->save();
        }
	}
	
	protected function getProvURL($mac=null) {
		return "https://".cfg('PROV_HOST').":18443";
	}

	protected function checkMacAddress($mac) {

		$mac = str_replace(":","", $mac); // remove :
		return parent::checkMacAddress($mac);
	}

	protected function checkUserAgent($ua) {
		return true;
	}

	protected function outputMessage(DLSMessage $dlsmessage) {

		ob_start();
		echo $dlsmessage->xml()."\n\n";
		header( 'X-Powered-By: Phonalisa DLS' );
		header( 'Content-Type: text/xml');
		header( 'Content-Length: '. (int)@ob_get_length() );
		Log::v("[".Yii::app()->session["mac-addr"]."] outputMessage: "._get_response_headers_as_string()."\n". $dlsmessage->xml(), "ergotest");
		@ob_flush();

	}

	private function getSecureDownloadHost() {
		$ports = cfg('PROV_PORT_SECURE');
		if ($ports == "" || $ports == "443") {
			return cfg('PROV_HOST');
		} else {
                        return cfg('PROV_HOST').":".$ports;
		}
	}

	private function readWorkPointMessagePost() {
		$raw_post = file_get_contents('php://input');
		if (trim($raw_post) == '') {
			Log::e("No post data!", "ergotest");
			Yii:app()->end();
		}
//  	Log::d("Phone Says: "._get_request_headers_as_string()."\n".$raw_post, "ergotest");
		$message = ErgophoneXml::xmlToArray($raw_post);
		
		return $message;
	}

	private function getPhoneModelForDeviceName($name) {
		foreach($this->_getSupportedPhoneModels() as $model) {
			//if ($model->getUserAgent() == Yii::app()->session["device-type"]) { // FIXME 
			if ($model->getUserAgent() == 'ergoS501') {
				Log::d("[".Yii::app()->session["mac-addr"]."] found model class for: ".Yii::app()->session["device-type"], "ergotest");
				return $model;
			}
		}
		Log::e("[".Yii::app()->session["mac-addr"]."] no Phone Model class found for: ".Yii::app()->session["device-type"], "ergotest");
		return NULL;
	}

	private function normalizeFirmwareVersion($version) {

        // FIXME : 
        return "1.05 14.11.13 12:38";
        return $version;
// 		$normalized = "";
// 		$m = array();
// 		if (preg_match("/^V?(\d+)(?:\s*|\.)R?(\d+)\.(\d+)\.(\d+)/i", $version, $parts)) {
// 			$normalized .= str_pad($parts[1], 2, '0', STR_PAD_LEFT) .'.'.
// 					str_pad($parts[2], 2, '0', STR_PAD_LEFT) .'.'.
// 					str_pad($parts[3], 2, '0', STR_PAD_LEFT) .'.'.
// 					str_pad($parts[4], 2, '0', STR_PAD_LEFT) ;
// 		}
// 
// 		return $normalized;
	}

	private function psetting($key, $value="", $index=null) {

		$configItem = new ConfigItem();
		$configItem->name = $key;
		$configItem->value = $value;
		$configItem->index = $index;
		$this->answer->addItem($configItem);

	}

	private function awnserRequest($msg) {

        $awnser = array();
        switch($msg['function'])
        {
        case 2:
        
            $awnser['led_action']['led'] = "emergency_led";
            $awnser['led_action']['ledmode'] = "2";
            $awnser['text'] = "Notruf ausgelöst";
            break;
//         case 3:
//             $awnser['function'] = $msg['function'];
//             $awnser['led_action']['led'] = "disp_led";
//             $awnser['led_action']['ledmode'] = "0";
//             $awnser['text'] = "Gute Nacht";
//             break; 
        }

        $request = new ErgophoneXml('PhonalisaResponse',null,false);
        $request->addItems($awnser);
        $request->writeXmlFile();
	}
	
	
	
	public function run($controller)
	{
        Log::d("ergophone/provisioning.php run() start","ergotest");
        
        
        //try
        //$model = $this->getPhoneModelForDeviceName(Yii::app()->session["device-type"]);
        
        $msg = $this->readWorkPointMessagePost();
        
//DEBUG 
//         foreach ($msg as $key => $value) {
//             if (is_array($value)) {
//                 foreach ($value as $valueKey => $valueValue) {
//                     Log::d("msg[$key][$valueKey] = $valueValue","ergotest");
//                 } 
//             } else {
//                 Log::d("msg[$key] = $value","ergotest");
//             }
//         }

//         $this->checkMacAddress($msg['macaddress']);
//         $model = $this->getPhoneModelForDeviceName('ergoS501');
//         if ($model == null) {
//             return;
//         }
//         $this->checkIfRequesterIsAllowedInNetwork();
//         $this->setCurrentPhoneModel($model);
        
//         //FIXME  : get firmware version //         
//         //FIXME  : normalizeFirmwareVersion();
//         $firmware = "1234";
//         $this->setCurrentFirmwareVersion($this->normalizeFirmwareVersion($firmware));
//         $this->getPhoneModel();
        
        /*
        $this->setProvisioningJobStarted();
        
        if ($this->mCurrentProvisioningJob != NULL) { // save job id into session
            Yii::app()->session["prov-job-id"] = $this->mCurrentProvisioningJob->id;
        }
        $this->loadConfigValues();
        */
        
        
        
        if (isset ( $msg['function'] ) &&  $msg['function'] != null) {
            $this->awnserRequest($msg);
        }
        Log::d("ergophone/provisioning.php run() ende ","ergotest");
	}

	private function checkFilesToDelete($nonce) {

		// check files on phone, and check if they are belong to us:
		$filesOnPhone = Yii::app()->session["file-deployment-name"];
		$filesOnPhoneWhichAreDeleted = Yii::app()->session["file-deployment-action"];
		$filesOnPhoneTypes = Yii::app()->session["file-deployment-type"];
		$filesToBeDeleted = array();

		Log::v("[".Yii::app()->session["mac-addr"]."] Files on Phone: ".print_r($filesOnPhone,true), "ergotest");
		Log::v("[".Yii::app()->session["mac-addr"]."] Files on Phone which are deleted: ".print_r($filesOnPhoneWhichAreDeleted,true), "ergotest");

		foreach ($filesOnPhone as $key => $fileOnPhone) {
			if (!array_key_exists($fileOnPhone, $this->filesToDeploy) && !array_key_exists($fileOnPhone, $this->filesAreDeployed)) {

				if ($filesOnPhoneWhichAreDeleted[$key] != "delete") {
					Log::v("[".Yii::app()->session["mac-addr"]."] File: ".$fileOnPhone." does not belongs to this phone and will be deleted from memory.", "ergotest");
					$definition = array();
					$definition["type"] = $filesOnPhoneTypes[$key];
					$definition["name"] = $filesOnPhone[$key];
					$filesToBeDeleted[$key] = $definition;
				}
			}
		}

		if (count($filesToBeDeleted) == 0) {
			return false;
		}

		$this->answer = new DLSMessage($nonce);
		$this->answer->setAction(DLSMessage::ActionFileDeployment);
		$index = 1;
		foreach($filesToBeDeleted as $fileToBeDeleted) {
			Log::v("[".Yii::app()->session["mac-addr"]."] Now deleting file: ".$fileToBeDeleted["name"] ,"ergotest");
			$this->psetting("file-name", $fileToBeDeleted["name"], $index);
			$this->psetting("file-type", $fileToBeDeleted["type"], $index);
			$this->psetting("file-action", "delete", $index);
			//$deleteMsg->addItem($item)
			++$index;
		}

		return $this->answer;
	}

	private function deployFile($name, $type) {

		$deployedFiles = Yii::app()->session["file-deployment-name"];
		Log::v("[".Yii::app()->session["mac-addr"]."] TEST: ".print_r($deployedFiles,true), "ergotest");

		if (is_array($deployedFiles) && in_array($name, $deployedFiles)) {
			Log::v("[".Yii::app()->session["mac-addr"]."] File: ".$name." is currently deployed.", "ergotest");
			$this->filesAreDeployed[$name] = $name;
			return;
		}

		Log::v("[".Yii::app()->session["mac-addr"]."] File: ".$name." is marked to deploy.", "ergotest");
		// add files to the todo list...
		$upload = array();
		$upload["type"] = $type;
		$upload["name"] = $name;
		$this->filesToDeploy[$name] = $upload;

	}

	protected function checkFirmwareUpdates($nonce) {

		// get current firmware version
		if ($this->mCurrentFirmwareVersion == "") {
			Log::w("[".Yii::app()->session["mac-addr"]."] Could not check Firmware Version (Phone has not reported one!).", "ergotest");
			return false;
		}

		$Phone = $this->getPhoneModel();
		$firmware = NULL;
		if ($Phone->firmware_update_key != null && $Phone->firmware_update_key != "") {
			//load firmware
			$firmware = Firmware::model()->findByPk($Phone->firmware_update_key);
			if ($firmware != NULL) {
				if ($firmware->version == $this->mCurrentFirmwareVersion) {
					Log::v("[".Yii::app()->session["mac-addr"]."] Firmware on Phone (".$this->mCurrentFirmwareVersion." is the same as the manual selected Firmware (".$firmware->version.").", "ergotest");
					return false;
				}
			} else {
				Log::v("[".Yii::app()->session["mac-addr"]."] Firmware was set Manually for Phone but the firmware file seams to does not exists any more, fallback to default firmware.", "ergotest");
			}
		}

		if ($firmware == NULL) { // no manual update was found

			$attributes = array();
			$attributes["phoneType"] = $this->mCurrentPhoneModel->getPhoneModelName();
			$attributes["standard"] = "1";

			$firmwares = Firmware::model()->findAllByAttributes($attributes,1);
			if (count($firmwares) == 0) {
				Log::v("[".Yii::app()->session["mac-addr"]."] No Firmware-file is available and set to standard for Phone.", "ergotest");
				return false;
			}
			$firmware = $firmwares[0];
			if ($firmware->version == $this->mCurrentFirmwareVersion) {
				Log::v("[".Yii::app()->session["mac-addr"]."] Firmware on Phone (".$this->mCurrentFirmwareVersion." is the same as the standard Firmware (".$firmware->version.").", "ergotest");
				return false;
			}

			Log::v("[".Yii::app()->session["mac-addr"]."] Firmware on Phone (".$this->mCurrentFirmwareVersion." differs from default Firmware (".$firmware->version."). Scheduling an update...", "ergotest");
		} else {
			Log::v("[".Yii::app()->session["mac-addr"]."] Firmware on Phone (".$this->mCurrentFirmwareVersion." differs from manuel set Firmware (".$firmware->version."). Scheduling an update...", "ergotest");
		}

		//OS_60_SIP_V3_R1_41_0.img
		$this->answer = new DLSMessage($nonce);
		$this->answer->setAction(DLSMessage::ActionSoftwareDeployment);

		Log::v("[".Yii::app()->session["mac-addr"]."] Updating Firmware to: ".$firmware->version." (".$firmware->fileName.")","ergotest");
		$this->psetting("file-type", "APP");
		$this->psetting("file-https-base-url", "https://".$this->getSecureDownloadHost()."/firmware/".$firmware->fileName); //FIXME URL!
		$this->psetting("file-sw-type", "Siemens SIP");
		$this->psetting("file-sw-version", $firmware->version);
		$this->psetting("file-priority", "normal");

		return $this->answer;

	}

	protected function loadConfigValues($mac=null) {

		$Phone = $this->getPhoneModel();
		Log::v("[".Yii::app()->session["mac-addr"]."] phone: ".print_r($Phone, true),"ergotest");
		$SipAccount = $Phone->getSipAccount();
		Log::v("[".Yii::app()->session["mac-addr"]."] phone: ".print_r($SipAccount, true),"ergotest");
		$User = $SipAccount->getUser();

		//$SipAccount
		// set registrar authname and password
		$this->psetting('e164'       , $SipAccount->authname);
		$this->psetting('sip-user-id', $SipAccount->authname);

		$this->psetting('sip-pwd', $SipAccount->secret);
		$this->psetting('sip-name', $SipAccount->getLabel());
		$this->psetting('register-by-name', 'false');

		$this->psetting('reg-addr', $SipAccount->getSIPRegistrar());
		$this->psetting('reg-port', "5060");

		$this->psetting('registrar-addr', $SipAccount->getSIPRegistrar());
		$this->psetting('registrar-port', '5060');

		// TLS
		if (cfg("INTERNAL_SSL_ENABLE") == "1") {
			$this->psetting('voip-server-validation', 'false');
			$this->psetting('sip-transport-user', '2');
			$this->psetting('reg-port', "5061");
			$this->psetting('registrar-port', '5061');
		} else {
			$this->psetting('sip-transport-user', '0');
		}
		//Yii::app()->session["deployFiles"] = true;
		
		
		
		
		$this->psetting('realm', 'phonalisa.local');

		$this->psetting('uaCSTA-enabled', 'true'); // Yes! We're supporting uaCSTA!
		$this->psetting('auto-answer', 'true'); // Yes! We're supporting uaCSTA!
		$this->psetting('beep-on-auto-answer', 'true'); // Yes! We're supporting uaCSTA!

		
		
		$this->psetting('moh-enabled', 'false');
		$this->psetting('voice-mail-e164', 'voicemail');

		$this->psetting('server-type', '0');

		// Call recording
		$this->psetting('call-record-auto-start', 'false');
		$this->psetting('call-record-all-calls', 'false');
		$this->psetting('feature-availability', 'true', '24');
		$this->psetting('call-record-phone-number', 'callrecorder');
		

		
		
		// Display stuff
		$this->psetting('display-id-unicode', $SipAccount->getShortLabel());
		$this->psetting('use-display-id', "true");

		if ($this->mCurrentPhoneModel->supportsLogoDeployment()) {
		
			if ($SipAccount->user_id == null || $SipAccount->user_id == "") {
				$this->psetting('display-skin', "1");
				$this->deployFile("logo_os60_default_dark.png", "LOGO");
			} else {
				$this->psetting('display-skin', "0");
				$this->deployFile("logo_os60_default_light.png", "LOGO");
			}
		}
		if ($this->mCurrentPhoneModel->supportsScreenSaverDeployment()) {
			$this->deployFile("screensaver_os60.png", "SCREENSAVER");
			$this->psetting("screensaver-enabled", "true");
		}
		
		if ($User) {
			$this->psetting('ldap-transport' , '0');
			$this->psetting('ldap-server-port' , '12389');
			$this->psetting('ldap-server-address', $SipAccount->getSIPRegistrar());
			$this->psetting('ldap-authentication', '1');
			$this->psetting('ldap-user', 'cn='.$User->name.",dc=default");
			$this->psetting('ldap-pwd', '439rz9f4uifh8vsfdpugh4');
		}
		$this->deployFile("ldap.txt", "LDAP");
		
		// Country and Language
		$language = cfg("GUI_LANGS");
		if ($User && $User->user_language != "") {
			$language = $User->user_language;
		}
		$language_iso = $this->phonalisaLanguageToSiemensLanguage($language);
		$this->psetting('language-iso' , $language_iso );
		$this->psetting('country-iso'  , strtoupper($language_iso));
		
		$language = cfg("GUI_LANGS");
		if ($User && $User->user_language != "") {
			$language = $User->user_language;
		}
			
		$dateformat = cfg("USER_DATE_FORMAT");
		if ($User && $User->user_date_format != "") {
			$dateformat = $User->user_date_format;
		}
		
		if ($dateformat == "dd.MM.yyyy") {
			$dateformat = "0";
		} else if ($dateformat == "yyyy-MM-dd") {
			$dateformat = "1";
		} else if ($dateformat == "MM/dd/yyyy") {
			$dateformat = "2";
		} else {
			$dateformat = "0";
		}
		$this->psetting('date-format'  , $dateformat );  // DD.MM.YYYY //FIXME get standard Date format with best match

		//codec negotation
		$this->psetting('allow-hd-icon-display', 'true');
		$this->psetting('codec-type', '2', '3'); // G729
		$this->psetting('codec-type', '1', '2'); // G722
		$this->psetting('codec-type', '0', '1'); // G711

		// disallow allow G729
		$this->psetting('codec-allowed', 'false', '3'); // G729

		// allow allow G711 and G722
		$this->psetting('codec-allowed', 'true', '2'); // G722
		$this->psetting('codec-allowed', 'true', '1'); // G711

		// set ranking of G722 to first position
		$this->psetting('codec-rank', '1', '2'); // G722
		$this->psetting('codec-rank', '2', '1'); // G711

		// SRTP
		$this->psetting('srtp-key-negotiation-method', '1');
		$this->psetting('secure-call-payload-options', '0');
		$this->psetting('srtp-encryption-allowed', 'true', '1');
		$this->psetting('voip-payload-security-allowed', 'true');



		// Date and Time
		$this->psetting('auto-daylight-save', 'true');
		$this->psetting('daylight-save', 'true');
		$this->psetting('daylight-save-minutes', '60');
		$this->psetting('daylight-save-zone-id', '9');

		//disable FPK Long press:
		$this->psetting('fpk-long-press-timer', '0');

		// Set BLF code
		$this->psetting('blf-code', cfg("DP_PICKUP_PREFIX"));

		// Callwaiting on/off
		if ($User && $User->call_waiting) {
			$this->psetting('call-waiting-enabled', 'true');
		} else {
			$this->psetting('call-waiting-enabled', 'false');
		}

		if ($User && $User->key_tone) {
			$this->psetting('click-keys', '1');
			$this->psetting('key-click-volume', '2');
		} else {
			$this->psetting('click-keys', '0');
			$this->psetting('key-click-volume', '0');
		}

		// set timezone settings
		$this->psetting("auto-daylight-save", "true");
		$this->psetting("conference-factory-uri", "");
		$this->psetting("daylight-save-minutes", "60");
		
		$tz = cfg("TIMEZONE");
		if ($User && $User->user_timezone != "") {
			$tz = $User->user_timezone;
		}
		$tz_offset = get_timezone_offset("UTC", $tz, true);
		$this->psetting("sntp-tz-offset", $tz_offset*60);
		$this->psetting("sntp-addr", cfg("NTP_HOST"));

		$time_format = cfg("USER_TIME_FORMAT"); 
		if ($User && $User->user_time_format != "") {
			$time_format = $User->user_time_format;
		}
		
		if ($time_format == "24") {
			$this->psetting('time-format', "0" );
		} else {
			$this->psetting('time-format', "1" );
		}
		
		for ($tone=1; $tone<9;$tone++) {
			$this->psetting('alert', "ringtone-".$tone."^".$tone."^2^60^".$tone , $tone);
		}
		
		$this->psetting('alert', "mute^0^2^60^0" , 9);
		
		
		// check ringtones
		if ($User && $User->ringtone_int != null && $User->ringtone_int != "" && $User->ringtone_int != "mute" && !startsWith($User->ringtone_int, "ringtone") ) {
			$this->deployFile($User->ringtone_int, "RINGTONE");
			$this->psetting('alert', "alert-internal^7^2^60^".$User->ringtone_int , 10);
		}
		
		if ($User && $User->ringtone_ext != null && $User->ringtone_ext != "" && $User->ringtone_ext != "mute" && !startsWith($User->ringtone_ext, "ringtone") ) {
			$this->deployFile($User->ringtone_ext , "RINGTONE");
			$this->psetting('alert', "alert-external^7^2^60^".$User->ringtone_ext , 11);
		}
		
		if ($User && $User->ringtone_queue != null && $User->ringtone_queue != "" && $User->ringtone_queue != "mute" && !startsWith($User->ringtone_queue, "ringtone") ) {
			$this->deployFile($User->ringtone_queue , "RINGTONE");
			$this->psetting('alert', "alert-queue^7^2^60^".$User->ringtone_queue , 12);
		}
		
		// Check XML Apps

		// Check Keys
		$this->processSoftkeys();

		// Get prov params out of the group!
		
		return true;

	}

	protected function processSoftkeys() {
			
		$Phone = $this->getPhoneModel();
		$SipAccount = $Phone->getSipAccount();
		$User       = $SipAccount->getUser();

		$levels = array("fpk", "shift", "ext1", "ext1-shift");
		foreach ($levels as $level) {
			$softKeys = array();
			// $Phone->getCurrentPhoneKeys($User, $level);
			ob_start();
			$softKeys = $Phone->getCurrentPhoneKeys($User, $level);
			$output = ob_get_clean();
			foreach ($softKeys as $softKey) {
				$this->processSoftKey($softKey);
			}
		}
	}

	protected function processSoftKey(PhoneKey $key) {
			
		if ($key->function == "") {
			$key->function = "0";
		}
		$this->psetting("function-key-def",  $key->function,    $key->name);
		$this->psetting("key-label-unicode", $key->label, $key->name);

		if ($key->function == "1") {
			$this->psetting('select-dial', $key->number_data,    $key->name);
		} else if ($key->function == "59") {
			$this->psetting('stimulus-led-control-uri',  $key->number_data,    $key->name);
			$this->psetting('blf-popup', 'true',    $key->name);
		} else if ($key->function == "58") { // Feature toggle
			
			$parts = explode('|',$key->number_data);
			if (count($parts) == 3) {
				$this->psetting('stimulus-feature-code', $parts[0] ,  $key->name);
				$this->psetting('stimulus-led-control-uri', $parts[1] ,  $key->name);
				$this->psetting('stimulus-DTMF-sequence', $parts[2] ,  $key->name);
			}
						
		} else if ($key->function == "X01") { // Feature toggle
					
			$this->psetting("function-key-def",  "58",    $key->name);
			$this->psetting('stimulus-feature-code', "*89*".$key->number_data ,  $key->name);
			$this->psetting('stimulus-led-control-uri', "*89*".$key->number_data ,  $key->name);
			$this->psetting('stimulus-DTMF-sequence', "*89*".$key->number_data ,  $key->name);
			
		} else if ($key->function == "X02") { // Feature toggle
					
			$Phone = $this->getPhoneModel();
			$SipAccount = $Phone->getSipAccount();
			$User       = $SipAccount->getUser();
			
			$this->psetting("function-key-def",  "58",    $key->name);
			$this->psetting('stimulus-feature-code', cfg("DP_FWD_ON_PREFIX").$key->number_data."*".$User->extension ,  $key->name);
			$this->psetting('stimulus-led-control-uri', cfg("DP_FWD_ON_PREFIX").$key->number_data."*".$User->extension ,  $key->name);
			$this->psetting('stimulus-DTMF-sequence', cfg("DP_FWD_ON_PREFIX").$key->number_data."*".$User->extension ,  $key->name);
			
		}
				

		


		//Log::v("[".Yii::app()->session["mac-addr"]."] key: ".print_r($key, true),"ergotest");


		/*$this->psetting($key->name.'|DKtype', $key->function);
		 $this->psetting($key->name.'|Line', "0");
		$this->psetting($key->name.'|Value', $key->number_data);
		*/
			
		/*if ($key->function == 16 ) {
			$this->psetting($key->name.'|type', "blf");
		if ( substr($key->number_data,0,3) == "*8*" ) {
		$this->psetting($key->name.'|PickupValue', $key->number_data);
		} else {
		$this->psetting($key->name.'|PickupValue', '*81*'.$key->number_data);
		}
		} else if ($key->function == 14 ) {
		$this->psetting($key->name.'|Value', "*85*".$key->number_data);
		}*/
			
	}

	protected function _getSupportedPhoneModels() {
		return Ergophone::getSupportedPhoneModels();
	}

	private function getTemplate() {
		$filename = dirname(__FILE__)."/templates/".$this->mCurrentPhoneModel->getPhoneModelName().".xml";

		$data = file_get_contents($filename);
		$xml = new SimpleXMLElement($data);
			
		foreach ($xml as $section => $element) {
			foreach ($element as $key => $value) {
				$attributes = (array)$value->attributes();
				$this->setting($section, $key, strval($value),"RW",null, @$attributes["@attributes"]);
			}
		}

		return $this->mCurrentSettings;
	}
	
	private function phonalisaLanguageToSiemensLanguage($lang) {
		return substr($lang, 0, 2);	
	}
	
}














