#!/usr/bin/php
<?php
#
# Usage: create-yealink-cfg add <station.extension>
#        create-yealink-cfg add-reboot <station.extension>
#        create-yealink-cfg delete <station.extension> <station.mac_address>
#
# This script creates/deletes a MAC based provisioning file for the specified
# Yealink phone.
#
# (C) Copyright 2017-2025, Bogen Communications LLC. All rights reserved.
#
require '/usr/local/bin/db_credentials' ;

$debug = FALSE;

error_reporting(0);

#
# Commenting out the following code since we no longer restrict C4000 from
# using the NQ-T1100.
#
# Get product type

#exec("/usr/local/bin/licinfo -p", $out, $ret);

#$isC4000 = ($out[0] == "nq-c4000") ? TRUE : FALSE;

$tftp_dir = "/srv/tftp/";

if (PHP_SAPI == "cli")
{
	$command    = $argv[1];
	$stationId  = $argv[2];
}
else
{
	$command    = $_GET['argument1'];
	$stationId  = $_GET['argument2'];
}

$reboot = 0;

if ($command == "add-reboot")
{
	$command = "add";
	$reboot = 1;
}

if ($command == "delete")
{
	if (PHP_SAPI == "cli")
	{
		$stationId  = $argv[2];
		$deviceMac = strtolower($argv[3]);
	}
	else
	{
		$stationId = strtolower($_GET['argument2']);
		$deviceMac = strtolower($_GET['argument3']);
	}

	if ($deviceMac == "" || strlen($deviceMac) != 12)
	{
		die("Invalid MAC address\n");
	} 

	$cfgfilename = $tftp_dir.$deviceMac.".cfg";

	unlink($cfgfilename);

	exec("/usr/local/bin/sync-yealink-phones -reboot $stationId");
	exec("/usr/local/bin/sync-yealink-phones");

	exit(0);
}

#
# Create configuration file for station:
#

#
# Get Timezone offset for setting Yealink timezone field
#
$time_zone = file_get_contents("/etc/timezone");
if ($time_zone != NULL)
{
	$time_zone = trim($time_zone);
	date_default_timezone_set($time_zone);
}
$offset = timezone_offset_get(new DateTimeZone(date_default_timezone_get()),
                              new DateTime());
$timeZone = sprintf("%s%d", ($offset >= 0) ? '+' : '-', abs($offset/3600));

$db = new mysqli($server, $user, $pass, $database);

if ($db->connect_errno > 0) {
	die('Unable to connect to database ['.$db->connect_error.']');
}

if ($debug == FALSE) {
	mysqli_report(MYSQLI_REPORT_OFF);
}

########################################################
# Get the Multicast IP Address to use, from system table
########################################################

$sql = "SELECT ip_multicast_rtp,ip_multicast_port,allcall_multicast_ip,allcall_multicast_port,audiodist_multicast_ip,audiodist_multicast_port,server_ipaddr,stunaddr FROM system";

if (!$result = $db->query($sql)) {
	die('Query error ['.$db->error.']');
}

$row = $result->fetch_assoc();
$multicast_ipaddr = long2ip($row['ip_multicast_rtp']);
$multicast_port = $row['ip_multicast_port'];
$allcall_multicast_ipaddr = long2ip($row['allcall_multicast_ip']);
$allcall_multicast_port = $row['allcall_multicast_port'];
$audiodist_multicast_ipaddr = long2ip($row['audiodist_multicast_ip']);
$audiodist_multicast_port = $row['audiodist_multicast_port'];
$server_ipaddr = long2ip($row['server_ipaddr']);

# Setup STUN configuration

$stun_addr = $row['stunaddr'];

if ($stun_addr != "") {
	if (preg_match("/(.*):(.*)/", $stun_addr, $parts)) {
		$stun_conf = "sip.nat_stun.enable = 1\n";
		$stun_conf.= "sip.nat_stun.server = $parts[1]\n";
		$stun_conf.= "sip.nat_stun.port = $parts[2]";
	} else {
		$stun_conf = "sip.nat_stun.enable = 1\n";
		$stun_conf.= "sip.nat_stun.server = $stun_addr\n";
		$stun_conf.= "sip.nat_stun.port = 3478";
	}
} else {
	$stun_conf = "sip.nat_stun.enable = 0\n";
}

############################################
# Get station's password from ps_auths table
############################################

$sql = "SELECT password FROM ps_auths WHERE id='$stationId'";

if (!$result = $db->query($sql)) {
	die('Query error ['.$db->error.']');
}

$row = $result->fetch_assoc();
$auth = $row['password'];

$sql = "UPDATE ps_endpoints SET message_context='messages' WHERE id='$stationId'";

$db->query($sql);

#############################################
# Get station's parameters from station table
#############################################

$sql = "SELECT mac_address, type, device_type, day_cos, has_paging,
	       has_multicast_audio, vlan_config, vlan_id, priority_802_1p,
	       schools_sites, use_uploaded_background_image
	FROM station WHERE extension='$stationId'";

if (!$result = $db->query($sql)) {
	die('Query error ['.$db->error.']');
}

$row = $result->fetch_assoc();
$deviceMac = strtolower($row['mac_address']);
$deviceTypeId = $row['device_type'];
$stationType = $row['type'];
$cos = $row['day_cos'];
$hasPaging = $row['has_paging'];
$hasMulticastAudio = $row['has_multicast_audio'];
$vlan_config = $row['vlan_config'];
$vlan_id = $row['vlan_id'];
$priority_802_1p = $row['priority_802_1p'];
$schoolsSites = $row['schools_sites'];
$useUploadedBackgroundImage = $row['use_uploaded_background_image'];

$result->free();

if ($deviceMac == "" || strlen($deviceMac) != 12)
{
	die("Invalid MAC address\n");
} 

$sql = "SELECT has_call_anystation, has_activate_alarms,
	       has_manual_activate_tone, has_zone_paging,
	       has_call_forwarding, has_program_distribution,
               has_multiserver_paging, has_all_call_page,
               has_emergency_all_call, has_execute_routines
	FROM cos INNER JOIN station ON cos.id=station.day_cos
	WHERE station.extension=$stationId";

if (!$result = $db->query($sql)) {
	die('Query error ['.$db->error.']');
}

$row = $result->fetch_assoc();
$hasAllCall = $row['has_all_call_page'];
$hasEAllCall = $row['has_emergency_all_call'];
$callAnyStation = $row['has_call_anystation'];
$activateAlarms = $row['has_activate_alarms'];
$activateTones = $row['has_manual_activate_tone'];
$zonePaging = $row['has_zone_paging'];
$callForwarding = $row['has_call_forwarding'];
$hasProgDist = $row['has_program_distribution'];
$multiServerPage = $row['has_multiserver_paging'];
$hasRoutines = $row['has_execute_routines'];

#######################################
# Get the "Zone" label for this product
#######################################

$sql = "SELECT label_plural FROM product_feature WHERE name='zone'";

if (!$result = $db->query($sql)) {
	die('Query error ['.$db->error.']');
}

$row = $result->fetch_assoc();

$zonePlural = $row['label_plural'];

if (strcmp($zonePlural, "Paging Groups") == 0)
{
	$zoneChar = "G";
	$zoneLabel = "Group";
}
else
{
	$zoneChar = "Z";
	$zoneLabel = "Zone";
}

#
# Fetch Paging Zones for placement on Zone keys (keytype = 0)
#
$sql = "SELECT zone_number,name
	FROM pagingzones
	WHERE type IN ('1','3','5','6')
	ORDER BY name";

if (!$zones_result = $db->query($sql)) {
        die('Query error ['.$db->error.']');
}

#
# Create linekey definitions for linekeys 1 - 29
#
# linekeys  1 - 11 are displayed on left and right of touch display
# linekeys 12 - 29 are displayed on middle of touch display after pressing "+ More" button.
#
$line_keys = "";

for ($key = 1; $key < 30; $key++)
{
	$keytype  = "type_$key";
	$keyline  = "line_$key";
	$keyvalue = "value_$key";
	$keylabel = "label_$key";
	$keycos   = "cos_$key";

	$sql = "SELECT $keytype, $keyline, $keyvalue, $keylabel, $keycos
		FROM yealink_linekey
		WHERE extension='$stationId'";

	if (!$result = $db->query($sql)) {
		continue;
	}

	if ($result->num_rows == 0) continue;

	$row = $result->fetch_assoc();

	$key_type  = $row[$keytype];
	$key_line  = $row[$keyline];
	$key_value = $row[$keyvalue];
	$key_label = $row[$keylabel];
	$key_cos   = $row[$keycos];

	if ($debug) echo "Key $key: Type: $key_type, Line: $key_line, Value: $key_value, Label: $key_label, Cos: $key_cos\n";

	#
	# If this is a reserved linekey, don't touch it, continue to next linekey.
	#
	if ($key_type == "Reserved") continue;

	#
	# Key type 'Zone' is reserved for Zone paging keys, placed in alphabetical order by name.
	#
	if ($key_type == "Zone")
	{
		#
		# If station does not have Zone paging permission, make the linekey blank.
		#
		if (!$zonePaging)
		{
			$line_keys.= "linekey.$key.type = %NULL%\nlinekey.$key.line = %NULL%\nlinekey.$key.value = %NULL%\nlinekey.$key.label = %NULL%\n";

			continue;
		}

		#
		# Fetch the next Zone from pagingzones table.
		#
		if (($zone_row = $zones_result->fetch_assoc()) != NULL)
		{
			$zone = $zone_row['zone_number'];
			$name = $zone_row['name'];

			if ($debug) echo "Zone: $zone, Name: $name, Key_label: $key_label\n";

			#
			# If key_label is blank, use default label format, else use custom label format.
			#
			if ($key_label == "")
			{
				$zoneKeyLabel = sprintf("%s%s: %s", $zoneChar, $zone, $name);
			}
			else
			{
				$zoneKeyLabel = str_replace('$name',   $name, $key_label);
				$zoneKeyLabel = str_replace('$number', $zone, $zoneKeyLabel);
			}

			$line_keys.= "linekey.$key.type = 13\nlinekey.$key.line = $key_line\nlinekey.$key.value = #$zone\nlinekey.$key.label = $zoneKeyLabel\n";
		}
		else
		{
			$line_keys.= "linekey.$key.type = %NULL%\nlinekey.$key.line = %NULL%\nlinekey.$key.value = %NULL%\nlinekey.$key.label = %NULL%\n";
		}

		continue;
	}

	if ($key_type == "Empty")
	{
		$line_keys.="linekey.$key.type = %NULL%
linekey.$key.line = %NULL%
linekey.$key.value = %NULL%
linekey.$key.label = %NULL%
linekey.$key.xml_phonebook = %NULL%\n";

		continue;
	}

	#
	# Check to make sure station has permission to use the feature related to the linekey.
	#

	$hasKeyPermission = FALSE;

	$cos_checks = explode('|',trim($key_cos));

	foreach ($cos_checks as $cos_check)
	{
		switch ($cos_check)
		{
			case 'has_all_call_page':
				if ($hasAllCall) $hasKeyPermission = TRUE;
				break;

			case 'has_execute_routines':
				if ($hasRoutines) $hasKeyPermission = TRUE;
				break;

			case 'has_emergency_all_call':
				if ($hasEAllCall) $hasKeyPermission = TRUE;
				break;

			case 'has_multiserver_paging':
				if ($multiServerPage) $hasKeyPermission = TRUE;
				break;

			case 'has_program_distribution':
				if ($hasProgDist) $hasKeyPermission = TRUE;
				break;

			case 'has_zone_paging':
				if ($zonePaging) $hasKeyPermission = TRUE;
				break;

			case 'schools_sites':
				if ($schoolsSites != "") $hasKeyPermission = TRUE;
				break;
			default:
				$hasKeyPermission = TRUE;
				break;
		}
	}

	if ($debug) echo "hasKeyPermission = $hasKeyPermission\n";

	if ($hasKeyPermission)
	{
		$key_value = str_replace('$server_ipaddr',$server_ipaddr,$key_value);
		$key_value = str_replace('$deviceMac',$deviceMac,$key_value);

		$line_keys.= "linekey.$key.type = $key_type
linekey.$key.line = $key_line
linekey.$key.value = $key_value
linekey.$key.label = $key_label
linekey.$key.xml_phonebook = %NULL%\n";
	} else {
		$line_keys.= "linekey.$key.type = 13
linekey.$key.line = $key_line
linekey.$key.value = Access Denied
linekey.$key.label = $key_label
linekey.$key.xml_phonebook = %NULL%\n";
	}
}

if ($debug) echo "Line Keys:\n$line_keys\n";

$remotePhonebook = "remote_phonebook.displayname = Directory";

#
# Build up the directory based on day_cos permissions
#
#if ($activateAlarms == 1 && !$isC4000)
if ($activateAlarms == 1)
{
$remotePhonebook.= "
remote_phonebook.data.1.url = tftp://$server_ipaddr/Alarms.xml
remote_phonebook.data.1.name = Alarms";
}
else
{
$remotePhonebook.= "
remote_phonebook.data.1.url = %NULL%
remote_phonebook.data.1.name = %NULL%";
}

if ($stationType == 1)
{
$remotePhonebook.= "
remote_phonebook.data.2.url = tftp://$server_ipaddr/Features.xml
remote_phonebook.data.2.name = Features";
}
else
{
$remotePhonebook.= "
remote_phonebook.data.2.url = %NULL%
remote_phonebook.data.2.name = %NULL%";
}

if ($zonePaging == 1)
{
$remotePhonebook.= "
remote_phonebook.data.3.url = tftp://$server_ipaddr/Zones.xml
remote_phonebook.data.3.name = Paging";
}
else
{
$remotePhonebook.= "
remote_phonebook.data.3.url = %NULL%
remote_phonebook.data.3.name = %NULL%";
}

#if ($callAnyStation == 1 && !$isC4000)
if ($callAnyStation == 1)
{
$remotePhonebook.= "
remote_phonebook.data.4.url = tftp://$server_ipaddr/Stations.xml
remote_phonebook.data.4.name = Stations";
}
else
{
$remotePhonebook.= "
remote_phonebook.data.4.url = %NULL%
remote_phonebook.data.4.name = %NULL%";
}

#if ($activateTones == 1 && !$isC4000)
if ($activateTones == 1)
{
$remotePhonebook.= "
remote_phonebook.data.5.url = tftp://$server_ipaddr/Tones.xml
remote_phonebook.data.5.name = Tones";
}
else
{
$remotePhonebook.= "
remote_phonebook.data.5.url = %NULL%
remote_phonebook.data.5.name = %NULL%";
}

switch ($vlan_config)
{
	case "disabled": // VLAN Disabled, set values to blank
		$vlan_enabled = 0;
		$vlan_id = 0;
		$priority_802_1p = 0;
		$dhcp_enable = 0;
		$dhcp_option = 132;
		break;

	case "server":	// Server-based Configuration
		$vlan_enabled = 1;
		$dhcp_enable = 0;
		break;

	case "network":	// Network-based Configuration
		$vlan_enabled = 0;
		$dhcp_enable = 1;
		$dhcp_option = 132;
		break;
	default:
		$vlan_enabled = 0;
		$dhcp_enable = 1;
		$dhcp_option = 132;
		break;
}

###################
# Check device type
###################

if (in_array($deviceTypeId, array(5,6,7,8,32,33)) == FALSE)
{
	die("$deviceTypeId device type not supported");
}

######################################################
# Determine if this device is on paging exclusion list
######################################################

$sql = "SELECT extension FROM paging_exclusion WHERE extension='$stationId'";

if (!$result = $db->query($sql)) {
        die('Query error ['.$db->error.']');
}

$row = $result->fetch_assoc();
$ext = $row['extension'];

if ($ext != "") {
        $excludePaging = TRUE;
} else {
        $excludePaging = FALSE;
}

#
# Adjust exclusion settings for Admin Phone and IP Phones (Staff Phone)
#
if (($stationType == 5) || ($stationType == 1))
{
	if ($hasPaging)
	{
		$excludeEAllCall = FALSE;
		$excludeAllCall  = FALSE;
		if ($excludePaging)
		{
			$excludeAllCall = TRUE;
		}
	}
	else
	{
		$excludeEAllCall = TRUE;
		$excludeAllCall  = TRUE;
		$excludePaging   = TRUE;
	}
}

$mcast_str = "";
$idx = 1;

################################
# Get RTP Multicast IP Addresses
################################

if ($excludeEAllCall == FALSE)
{
	$mcast_str.= "multicast.listen_address.$idx.ip_address = "
		.$multicast_ipaddr.":".$multicast_port.PHP_EOL;
	$mcast_str.= "multicast.listen_address.$idx.label = EACall".PHP_EOL;
	$idx++;
}

if ($excludeAllCall == FALSE)
{
	$mcast_str.= "multicast.listen_address.$idx.ip_address = "
		.$allcall_multicast_ipaddr.":".$allcall_multicast_port.PHP_EOL;
	$mcast_str.= "multicast.listen_address.$idx.label = ACall".PHP_EOL;
	$idx++;
}

#
# Get paging zones for this station and create multicast entries (max idx 20):
#
$sql = "SELECT multicast_rtp.id, multicast_ip_address, multicast_ip_port
	FROM multicast_rtp
	LEFT JOIN pagingzones ON multicast_rtp.zone_id=pagingzones.id
	LEFT JOIN zone_sublist ON zone_sublist.zone_number=pagingzones.zone_number
	WHERE zone_sublist.station='$stationId'";

if ($excludePaging == FALSE)
{
   if (!$result = $db->query($sql)) {
      die('Zone query error ['.$db->error.']');
   }

   while ($row = $result->fetch_assoc())
   {
	$mcast_str.= "multicast.listen_address.".$idx
		.".ip_address = ".long2ip($row['multicast_ip_address']).
		":".$row['multicast_ip_port'].PHP_EOL;
	$mcast_str.= "multicast.listen_address.".$idx.".label = Zone\n";
	$idx++;

	if ($idx == 21) break;
   }
}

#
# Clear remaining entries, just in case they used to have values:
#
if ($idx < 21)
{
	for ($empty_idx = $idx; $empty_idx < 21; $empty_idx++)
	{
		$mcast_str.= "multicast.listen_address.".$empty_idx.".ip_address = %NULL%\n";
		$mcast_str.= "multicast.listen_address.".$empty_idx.".label = %NULL%\n";
	}
}

#
# Add backup multicast paging feature for Admin phones.
#
$backup_paging="";

if ((!file_exists("/srv/tftp/no_backup_paging")) && (!file_exists("/srv/tftp/custom_paging"))) {
	$doBackupPaging = true;
} else {
	$doBackupPaging = false;
}

if ($doBackupPaging && ($stationType == 1))
{
	if ($hasEAllCall) {
		$backup_paging.= "multicast.paging_address.1.ip_address = $multicast_ipaddr:$multicast_port\n";
		$backup_paging.= "multicast.paging_address.1.label = Emergency-All-Call\n";
	} else {
		$backup_paging.= "multicast.paging_address.1.ip_address = %NULL%\n";
		$backup_paging.= "multicast.paging_address.1.label = %NULL%\n";
	}

	if ($hasAllCall) {
		$backup_paging.= "multicast.paging_address.2.ip_address = $allcall_multicast_ipaddr:$allcall_multicast_port\n";
		$backup_paging.= "multicast.paging_address.2.label = All-Call\n";
	} else {
		$backup_paging.= "multicast.paging_address.2.ip_address = %NULL%\n";
		$backup_paging.= "multicast.paging_address.2.label = %NULL%\n";
	}
}
else if (!file_exists("/srv/tftp/custom_paging"))
{
	# Clear out paging if not using custom paging
	$idx = 0;
	while ($idx++ < 32)
	{
		$backup_paging.= "multicast.paging_address.$idx.ip_address = %NULL%\n";
		$backup_paging.= "multicast.paging_address.$idx.label = %NULL%\n";
	}
}
else
{
	$backup_paging.= "multicast.paging_address.1.ip_address = %NULL%\n";
	$backup_paging.= "multicast.paging_address.1.label = %NULL%\n";
	$backup_paging.= "multicast.paging_address.2.ip_address = %NULL%\n";
	$backup_paging.= "multicast.paging_address.2.label = %NULL%\n";
}
#
# Fetch Paging Zones for backup paging
#
if ($doBackupPaging && ($stationType == 1) && $zonePaging)
{
	$sql = "SELECT m.multicast_ip_address, m.multicast_ip_port, p.zone_number, p.name
		FROM multicast_rtp AS m
		LEFT JOIN pagingzones AS p ON m.zone_id=p.id
		WHERE p.type IN ('1','3','5','6')
		ORDER BY p.name";

	if (!$zones_result = $db->query($sql)) {
	        die('Query error ['.$db->error.']');
	}

	$idx = 3;

	while ($row = $zones_result->fetch_assoc())
	{
		$backup_paging.= "multicast.paging_address.".$idx
			.".ip_address = ".long2ip($row['multicast_ip_address']).
			":".$row['multicast_ip_port'].PHP_EOL;
		$backup_paging.= "multicast.paging_address.".$idx
			.".label = $zoneLabel: ".$row['name']." (".$row['zone_number'].")".PHP_EOL;

		$idx++;

		if ($idx == 32) break;
	}

	$zones_result->free();

	if ($idx < 32)
	{
		while ($idx < 32)
		{
			$backup_paging.= "multicast.paging_address.$idx.ip_address = %NULL%\n";
			$backup_paging.= "multicast.paging_address.$idx.label = %NULL%\n";

			$idx++;
		}
	}
}
else
{
	$idx = 3;
	while ($idx < 32)
	{
		$backup_paging.= "multicast.paging_address.$idx.ip_address = %NULL%\n";
		$backup_paging.= "multicast.paging_address.$idx.label = %NULL%\n";

		$idx++;
	}
}

#
# Audio Distribution is disabled on Yealink phones
#
#if (($excludePaging == FALSE) && ($hasMulticastAudio != 0))
#{
#   $sql = "SELECT multicast_ip_port FROM multicast_rtp WHERE id='1'";
#
#   if (!$result = $db->query($sql)) {
#	die('There was an error running the query ['.$db->error.']');
#   }
#
#   $row = $result->fetch_assoc();
#
#   $mcast_str.= "multicast.listen_address.10.ip_address = "
#	.$audiodist_multicast_ipaddr.":".$row['multicast_ip_port'].PHP_EOL;
#   $mcast_str.= "multicast.listen_address.10.label = Audio".PHP_EOL;
#}
#else
#{
#   $mcast_str.= "multicast.listen_address.10.ip_address = %NULL%\n";
#   $mcast_str.= "multicast.listen_address.10.label = %NULL%\n";
#}

if (!$useUploadedBackgroundImage) {
	$backgroundImage = "phone_setting.backgrounds = Config:Nyquist_T48G_Screen_Image.png";
} else {
	$backgroundImage = "";
}


#############################################################
# Create MAC specific provisioning file for specified station
#############################################################

#
# Setup TLS for SIP
#
if (in_array($deviceTypeId, array(5,6,32,33)) == true) {
	$transport = "account.1.sip_server.1.transport_type = 2
account.1.srtp_encryption = 1
security.trust_certificates = 0
security.ca_cert = 2
security.cn_validation = 0
security.dev_cert = 1
trusted_certificates.url = http://$server_ipaddr/ssl/bogenCA.crt";

   $sql = "UPDATE ps_endpoints SET transport='transport-tls' WHERE id='$stationId'";
   $db->query($sql);
   $sql = "UPDATE ps_endpoints SET media_encryption='sdes',media_encryption_optimistic='yes' WHERE id='$stationId'";
   $db->query($sql);
} else {
	$transport = "account.1.sip_server.1.transport_type = 0
security.trust_certificates = 0";

   $sql = "UPDATE ps_endpoints SET transport='transport-udp' WHERE id='$stationId'";
   $db->query($sql);
}

$db->close();

$txt = <<<END
#!version:1.0.0.1

account.1.enable = 1
account.1.label = $stationId
account.1.display_name = $stationId
account.1.auth_name = $stationId
account.1.user_name = $stationId
account.1.password = $auth
account.1.reregister_enable = 1
account.1.codec.pcmu.priority = 3
account.1.codec.opus.enable = 1
account.1.codec.opus.priority = 1
account.1.codec.pcma.priority = 4
account.1.codec.g729.priority = 5
account.1.codec.g722.priority = 2
account.1.sip_server.1.address = $server_ipaddr
account.1.sip_server.1.port = 5060
account.1.sip_server.1.expires = 120
account.1.sip_server.1.retry_count = 20
account.1.subscribe_mwi = 1
account.1.display_mwi.enable = 1
account.1.nat.udp_update_enable = 2
account.1.nat.udp_update_time = 60
account.1.sip_server_type = 0
account.1.earlymedia = 1
$transport
voice_mail.number.1 = $stationId
voice.tns.enable = 0
local_time.time_zone = $timeZone
local_time.summer_time = 0
local_time.ntp_server1 = $server_ipaddr
local_time.time_format = 0
phone_setting.ringing_timeout = 3600
phone_setting.ringback_timeout = 3600
wallpaper_upload.url = tftp://$server_ipaddr/Nyquist_T48G_Screen_Image.png
$backgroundImage
phone_setting.contact_photo_display.enable = 2
network.vlan.internet_port_enable = $vlan_enabled
network.vlan.internet_port_vid = $vlan_id
network.vlan.internet_port_priority = $priority_802_1p
network.vlan.dhcp_enable = $dhcp_enable
network.vlan.dhcp_option = $dhcp_option
network.lldp.enable = 0
push_xml.sip_notify = 1
action_url.registered = https://$server_ipaddr/update_idle_screens
$remotePhonebook
features.missed_call_popup.enable = 0
features.remote_phonebook.enable= 0
features.remote_phonebook.flash_time = 21600
features.power_saving.enable = 0
features.dnd.allow = 0
features.config_dsskey_length=1
features.send_pound_key = 1
programablekey.2.type = 47
programablekey.2.line =
programablekey.2.value =
programablekey.2.label = Directory
programablekey.2.extension =
programablekey.2.xml_phonebook =
programablekey.2.pickup_value =
programablekey.3.type = 27
programablekey.3.line =
programablekey.3.value = tftp://$server_ipaddr/Alerts.xml
programablekey.3.label = NWS Alerts
programablekey.3.extension =
programablekey.3.xml_phonebook =
programablekey.3.pickup_value =
transfer.dsskey_deal_type = 0
$line_keys
multicast.receive_priority.priority = 0
$stun_conf
$mcast_str
$backup_paging

END;

$reload_pjsip = FALSE;

$cfgfilename = $tftp_dir.$deviceMac.".cfg";

if (!file_exists($cfgfilename)) $reload_pjsip = TRUE;

$htmfd = fopen($cfgfilename, "w") or die("Unable to open htm file!");

fwrite($htmfd, $txt);
fclose($htmfd);
chmod($cfgfilename, 0664);

if ($reboot == 1)
{
	exec("/usr/local/bin/sync-yealink-phones -reboot $stationId");
}

if ($reload_pjsip)
{
	exec("/usr/local/bin/reload-pjsip >/dev/null 2>&1 &");
}

?>
