<?php
include ('gmatom/gmatom.php');
include("settings.php");
//Header("Content-Type: text/xml");


function push2phone($ip, $uri, $uid, $pwd, $pri)
{
$auth = base64_encode($uid.":".$pwd);
$xml  = "<CiscoIPPhoneExecute><ExecuteItem Priority=\"0\"URL=\"".$uri."\"/></CiscoIPPhoneExecute>";
$xml  = "XML=".urlencode($xml);

$post  = "POST /CGI/Execute HTTP/1.0\r\n";
$post .= "Host: $ip\r\n";
$post .= "Authorization: Basic $auth\r\n";
$post .= "Connection: close\r\n";
$post .= "Content-Type: application/x-www-form-urlencoded\r\n";
$post .= "Content-Length: ".strlen($xml)."\r\n\r\n";

$fp = fsockopen ( $ip, 80, $errno, $errstr, 10);
if(!$fp){ echo "$errstr ($errno)<br>\n"; }
else
{
 fputs($fp, $post.$xml);
 flush();
 while (!feof($fp))
 {
  $response .= fgets($fp, 128);
  flush();
 }
}

return $response;
}

$gMailStatusURL = "http://192.168.144.2/xmlservices/statusMsg.php?x=";

$g = new GmAtom ($gUser, $gPassword);

$msgCount = $g->check();
if (false === $msgCount) {
    die ('Error getting new mail count');
} else {
    if(file_exists("gMsgs-" . $gUser . ".txt")) {
        //read the number of messages in the inbox from the last gmail poll.
        $handle = fopen("gMsgs-" . $gUser . ".txt",r);
        while (!feof($handle)) {
            $prevCount .= fread($handle, 8192);
        }
        fclose($handle);
    } else {
        //if file doesn't exist - we've never checked before.
        $prevCount=0;
    }

    if($msgCount>$prevCount) {    
        //WE HAVE NEW MAIL.
        //play a chime iff the phone is idle:
        echo push2phone($ciscoip, "Play:" . $gSound, $ciscouid, $ciscopwd, 2);
        //load up the gmail phone status:
        echo push2phone($ciscoip, $gMailStatusURL . $msgCount, $ciscouid, $ciscopwd, 0);
    
    } else if($prevCount>$msgCount) {
        if($msgCount==0) {
            //ALL MESSAGES HAVE NOW BEEN READ- clear any Phone Status still present!
            echo push2phone($ciscoip,"Init:AppStatus",$ciscouid,$ciscopwd,0);
        } else {
            // The New Message Count has gone done but is still >0, lets update the number of messages, but not play the chime.
            echo push2phone($ciscoip, $gMailStatusURL . $msgCount, $ciscouid, $ciscopwd, 0);
        }
    }
    
    //UPDATE CURRENT MSG COUNT
    $handle = fopen("gMsgs-" . $gUser . ".txt",w);
    fwrite($handle, $msgCount);
    fclose($handle);
}

?>