<?php

	date_default_timezone_set('UTC');

echo "<?xml version=\"1.0\" ?>\n";

echo "<!DOCTYPE vxml PUBLIC 'SpeechBrowser/2.0/DTD' 'ignore' >";
echo "<vxml version='2.0'>";


// ************************************************
// This is a sample queue announcment script for Vision Call Centre Script - this allows testing on a CallServer.
// ************************************************
//
// SAMPLE DIAL PLAN CONFIGURATIONS
//
// ETA
// 1 MINUTE   !EA:http://127.0.0.1/cc_announce_vxml.php?cmd=eta&s=203&t=8000&g=203&q=2&o=203&a=5
// 4 MINUTES  !EA:http://127.0.0.1/cc_announce_vxml.php?cmd=eta&s=203&t=8000&g=203&q=200&o=203&a=5
// 10 MINUTES !EA:http://127.0.0.1/cc_announce_vxml.php?cmd=eta&s=203&t=8000&g=203&q=600&o=203&a=5
//
// POS
// POSITION 1  !EA:http://127.0.0.1/cc_announce_vxml.php?cmd=pos&s=203&t=8000&g=203&q=1&o=203&a=5
// POSITION 5  !EA:http://127.0.0.1/cc_announce_vxml.php?cmd=pos&s=203&t=8000&g=203&q=5&o=203&a=5
// POSITION 10 !EA:http://127.0.0.1/cc_announce_vxml.php?cmd=pos&s=203&t=8000&g=203&q=10&o=203&a=5
// ************************************************
// Change the following to match your CONFIGURATION
// ************************************************

	set_error_handler (function ($errno, $errstr, $errfile, $errline)
	{
		if ($errno != E_NOTICE)
		{
			$stderr = fopen('php://stderr', 'w');
			fprintf($stderr, "PHP error %d: %s at %s line %d\n", $errno, $errstr, $errfile, $errline);
			fclose($stderr);
		}
	});

	$welcome = '';
	$start_time = microtime(true);
	
	if (file_exists("debug"))
		$log = fopen("php://stderr", "w");
	
	// Now pickup the standard always present parameters (source number and command)
	
	if ($_SERVER['SERVER_PORT'])				// We are running from a web server
	{
    	$cmd = $_REQUEST['cmd'];
	    $num = $_REQUEST['s'];
	    $target = $_REQUEST['t'];
	    $crguid = $_REQUEST['g'];
	    $pos = $_REQUEST['q'];
	    $orignum = $_REQUEST['o'];
        $count = $_REQUEST['a'];
        if ($log)
        {
	    	fwrite($log, date("r"));  
			fwrite($log, "\ncmd=$cmd num=$num target=$target crguid=$crguid pos=$pos orignum=$orignum\n");
		}
	}
	else                                        // We are running from the command line for testing
	{
		$cmd = $argv[1];
		$num = $argv[2];
		$target = $argv[3];
		$crguid = $argv[4];
		$pos = $argv[5];
		$orignum = $argv[6];
        $count = $argv[7];
		print "cmd=$cmd num=$num target=$target crguid=$crguid pos=$pos orignum=$orignum count=$count\n";
    }
    $organiser = $target.$filename.$num;

    
    $cfg = fopen("/SpliceCom/config/Vision.cfg", "r");
    if ($cfg != FALSE)
    {
    	while (!feof($cfg))
    	{
    		$line = fgets($cfg,256);
    		
			if (strncmp($line,"serverAddress=", 14)==0)
				$svr = rtrim(substr($line, 14));
			else if (strncmp($line,"db=", 3)==0)
				$db = rtrim(substr($line, 3));
			else if (strncmp($line,"user=", 5)==0)
				$user = rtrim(substr($line, 5));
			else if (strncmp($line,"password=", 9)==0)
				$password = rtrim(substr($line, 9));
    	}
		fclose($cfg);
		
		if ($log)
			fwrite($log, "svr=$svr, user=$user, password=$password, db=$db\n");
		
		if (strlen($svr) && strlen($db) && strlen($user) && strlen($password))
		{
			$mysqli = new mysqli($svr, $user, $password, $db);
			if (!$mysqli->connect_errno)
			{
				$q = "SELECT welcomeAnnouncement FROM CallCentreQueue WHERE queueNumber='".$target."' AND announcementMode IN (1,2)";
					
				$res = $mysqli->query($q);
				if ($res)
				{
					$row = $res->fetch_row();
					$welcome = "wavs/welcome/".$row[0];
					$res->close();
					if (file_exists($welcome))
						$welcome = "wavs/welcome/".rawurlencode($row[0]);
					else
					{
						if ($log)
							fwrite($log, "welcome file ".$welcome." not found\n");
						$welcome = "";
					}
				}
				$mysqli->close();
			}
			else if ($log)
				fwrite("MySQL database not opened\n");
		}
	}
	else if ($log)
		fwrite($log, "Vision.cfg not opened for read\n");

	if ($log)
		fwrite($log, "cc_announce_vxml2.php: cmd=$cmd count=$count welcome=$welcome\n");
	
	$us = 1000000 - (microtime(true) - $start_time);
	if ($us > 0)
		usleep($us);	// give audio stream time to establish

	// Now interpet the specific command
    if ($cmd == "eta")													
    {
        $pos = ceil($pos / 60);
        if( $pos <= 1 )
        {
			echo "<form id='soon'><block>";

    		if( $count == 0 )
       		{
				if (strlen($welcome))
					echo "<prompt><audio src='${welcome}'/></prompt>";
				echo "<prompt><audio src='wavs/you_are_currently_held_in_a_queue.wav'/></prompt>";
       		}
	
			echo "<prompt><audio src='wavs/we_estimate_your_call_will_be_answered_in.wav'/></prompt>";
			echo "<prompt><audio src='wavs/digits/{$pos}.wav'/></prompt>";
			echo "<prompt><audio src='wavs/minutes.wav'/></prompt>";
			echo "<prompt><audio src='wavs/please_continue_to_hold.wav'/></prompt>";
			echo "<disconnect/></block></form>";
		}
		else
		{
			echo "<form id='later'><block>";
    		if ( ($count == 0) && strlen($welcome) )
				echo "<prompt><audio src='${welcome}'/></prompt>";

			echo "<prompt><audio src='wavs/you_are_currently_held_in_a_queue.wav'/></prompt>";
			echo "<prompt><audio src='wavs/we_estimate_your_call_will_be_answered_in.wav'/></prompt>";

			if (file_exists("wavs/digits/{$pos}.wav")) {
				echo "<prompt><audio src='wavs/digits/{$pos}.wav'/></prompt>";
				echo "<prompt><audio src='wavs/minutes.wav'/></prompt>";
			} else {
				echo "<prompt><audio src='wavs/more_than_twenty_minutes.wav'/></prompt>"; 
			}

			echo "<prompt><audio src='wavs/please_continue_to_hold.wav'/></prompt>";
			echo "<disconnect/></block></form>";
        }
    }
    else if ($cmd == "pos")														
    {
        if( $pos <= 1 )
        {
			echo "<form id='soon'><block>";

			if( $count == 0 )
			{
				if (strlen($welcome))
					echo "<prompt><audio src='${welcome}'/></prompt>";
				echo "<prompt><audio src='wavs/you_are_currently_held_in_a_queue.wav'/></prompt>";
			}

			echo "<prompt><audio src='wavs/your_call_will_be_answered_shortly.wav'/></prompt>";
			echo "<prompt><audio src='wavs/thankyou.wav'/></prompt>";
			echo "<disconnect/></block></form>";
		}
		else
		{
			echo "<form id='later'><block>";
    		if ( ($count == 0) && strlen($welcome) )
				echo "<prompt><audio src='${welcome}'/></prompt>";
			echo "<prompt><audio src='wavs/you_are_currently_held_in_a_queue.wav'/></prompt>";

			if (file_exists("wavs/digits/{$pos}.wav")) {
				echo "<prompt><audio src='wavs/you_are_at_position.wav'/></prompt>";
				echo "<prompt><audio src='wavs/digits/{$pos}.wav'/></prompt>";
			} else {
				echo "<prompt><audio src='wavs/there_are_currently_more_than_twenty_callers_ahead_of_you_in_the_queue.wav'/></prompt>";		
			}
			echo "<prompt><audio src='wavs/please_continue_to_hold.wav'/></prompt>";
			echo "<disconnect/></block></form>";
		}
    }
    
    if ($log)
    	fclose($log);
?>

</vxml>

<?php
// Helpful functions to make the above code easier
function LdapConnect($server,$user_login,$user_password)
{
    $ds=ldap_connect($server,4000);  // must be a valid LDAP server!
    if ($ds)
    {
        $r=ldap_bind($ds, $user_login, $user_password);
        if (!$r)
        {
            ldap_close($ds);
            $ds = 0;
        }
    }
    return $ds;
}

function LdapClose($ds)
{
    ldap_close($ds);
}

function LdapGetName($ds,$num)
{
	$name = "";
	if ($num != "" && $ds)
	{
		$sr=ldap_search($ds, "", "(GlobalTelephoneNumber=$num)",array("cn"),0,1); 	// Optimized special key search
		$o = ldap_get_entries($ds, $sr);
		if ($o['count'] != 0)					// If we have some answers
		{  
			$name = $o[0]['cn'][0];				// Extract the name (common name = cn) attribute
		}
	}
	return $name;
}

function LdapGetVmPort($ds,$vmportname,$vmportlocation)
{
    if( $vmportlocation )
    {
        $sr=ldap_read($ds, "cn=$vmportlocation,cn=Modules","(objectclass=Module)",array("guid","cn"),0,1); 
        $o = ldap_get_entries($ds, $sr);
        if ($o['count'] != 0)
        {
            $location = $o[0]['guid'][0];
        }
    }
    else
    {
        $location = "00000000-0000-0000-0000-000000000000";
    }
    
    if( $location )
    {
		$sr=ldap_list($ds, "cn=VoicemailPorts","(&(location=$location)(cn=$vmportname))",array("guid","cn"),0,0); 
		$o = ldap_get_entries($ds, $sr);
		if ($o['count'] != 0)
		{
			$vmport = $o[0]['guid'][0];
			return $vmport;
		}
	}
	return "notfound";
}

function SpeakName($name,$num)
{
	if( $name!="" )
    {
        echo "<prompt>$name</prompt>\n";
    }
    else
    {
        echo "<prompt>Number </prompt>\n";
        for ($i=0; $num[$i] != ""; $i++)
        {
            echo "<prompt>$num[$i]</prompt>\n";
        }
    }
}

function SpeakTime($t)
{
    if( strlen($t) == 3 )
    {
        $t="0".$t;
    }
    else if( strlen($t) == 2 )
    {
        $t="00".$t;
    }
	$hour = substr($t, -4, 2);
	$min = substr($t, -2, 2);
	if( $min == "00" )
	{
		$min = " hundred hours";
	}
    echo "<prompt>$hour</prompt>\n";
    echo "<prompt>$min</prompt>\n";
}

?>
