<?php
	// All script inside these brackets (less than question mark and question mark greater than) is PHP script
	// all other script is VXML
    print "<?xml version=\"1.0\" ?>\n";
?>
<!DOCTYPE vxml PUBLIC "SpeechBrowser/2.0/DTD" "ignore" >
<vxml version="2.0">

<?php
// ************************************************
// This is a sample queue announcment script for Vision Call Centre
// ************************************************
	date_default_timezone_set('UTC');

	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");
	
	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];
		print "cmd=$cmd num=$num target=$target crguid=$crguid pos=$pos orignum=$orignum\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 = $row[0];
					$res->close();
				}
				$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_vxml.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 )
        {
?>
            <form id="soon">
                <block>
<?php
				if( $count == 0 )
				{
					if (strlen($welcome))
						print "<prompt>$welcome</prompt>\n";
					print "<prompt>You are currently held in a queue.</prompt>\n";
				}
?>
                <prompt>We estimate your call will be answered in.</prompt>
                <prompt>less than one minute</prompt>
                <prompt>Please continue to hold.</prompt>
                <disconnect/>
                </block>
            </form>
<?php
        }
        else
        {
?>
            <form id="later">
                <block>
<?php 
				if( ($count == 0) && strlen($welcome) ) {
					echo "<prompt>$welcome</prompt>";
				}
?>
                <prompt>You are currently held in a queue.</prompt>
                <prompt>We estimate your call will be answered in.</prompt>
<?php
                print "<prompt>$pos</prompt>\n";
?>
                <prompt>minutes.</prompt>
                <prompt>Please continue to hold.</prompt>
                <disconnect/>
                </block>
            </form>
<?php
        }
    }
    else if ($cmd == "pos")														
    {
        if( $pos <= 1 )
        {
?>
            <form id="soon">
                <block>
<?php
				if( $count == 0 )
				{
					if (strlen($welcome))
						print "<prompt>$welcome</prompt>\n";
					print "<prompt>You are currently held in a queue.</prompt>\n";
				}
?>
                <prompt>Your call will be answered shortly.</prompt>
                <prompt>Please continue to hold.</prompt>
                <disconnect/>
                </block>
            </form>
<?php
        }
        else
        {
?>
            <form id="later">
                <block>
<?php 
				if( ($count == 0) && strlen($welcome) ) {
					echo "<prompt>$welcome</prompt>";
				}
?>
                <prompt>You are currently held in a queue.</prompt>
<?php
				print "<prompt>You are currently at position</prompt>\n";
				print "<prompt>$pos</prompt>\n";
?>
                <prompt>Please continue to hold.</prompt>
                <disconnect/>
                </block>
            </form>
<?php
        }
    }
    
    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!="" )
    {
        print "<prompt>$name</prompt>\n";
    }
    else
    {
        print "<prompt>Number </prompt>\n";
        for ($i=0; $num[$i] != ""; $i++)
        {
            print "<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";
	}
    print "<prompt>$hour</prompt>\n";
    print "<prompt>$min</prompt>\n";
}

?>
