<?php
/************************************************************************/
/* ajax_get_messages.php                                                */
/*----------------------------------------------------------------------*/
/* Ajax handler for $mbox->GetMessages() which in turn calls            */
/* $mailserver->GetMessages() which in turn calls COM::GetMessages()    */
/*----------------------------------------------------------------------*/
/* Copyright (c) 2008-2009 Avaya Inc.                                   */
/************************************************************************/

// This script is stored out of the way in the ajax folder, but needs to
// act as if it were called from folder above (scripts) so that paths
// used in require_once files remain valid. Hence, chdir to the dir above.
chdir('..');

// Include mailserver module
require_once('inc/mailserver.php');

// Recreate $_SESSION variable
session_start();

// Record client's time for this request
$ajax_timestamp = 0;
if( isset( $_POST['timestamp'] ) )
{
  $l = strlen($_POST['timestamp']);
  if( $l > 3 )
  {
    $time_string = substr($_POST['timestamp'],0,$l-3);
    $ajax_timestamp = (int)$time_string;
  }
}

// Record page access (also writes session id)
GetEventLog()->LogAccess();

// Check that visitor should be here. Authenticate populates $user record.
$mailserver = null;
$user = null;
$reason = GetSessionHandler()->Authenticate( session_id(), $user );

if ( $reason != SessionHandler::AUTH_SUCCESS )
{
  $res = 'auth+++ajax_get_messages+++'. $reason;
  GetSessionHandler()->DestroySession();
  GetEventLog()->WriteError( gettext('Authentication failed:') . ' ' . GetSessionHandler()->ErrorText($reason) );
  header('Content-Type: text/plain; charset="utf-8"');
  header('Content-Length: ' . strlen($res));
  echo $res;
  exit;
}
else
{
  // Connect to mail server
  $mailserver = GetMailserver();
  if( !$mailserver )
  {
    $res = 'error+++ajax_get_messages+++' . gettext("Can't connect to mailserver.");
    GetEventLog()->WriteError( gettext("Can't connect to mailserver.") );
    header('Content-Type: text/plain; charset="utf-8"');
    header('Content-Length: ' . strlen($res));
    echo $res;
    exit;
  }
}

// Initialise script output
$res = 'error+++ajax_get_messages+++' . gettext('Unspecified error.');

// Get parameters from query string
if( !isset( $_POST['mbid'] )
 || !isset( $_POST['folderId'] )
 || !isset( $_POST['orderBy'] )
 || !isset( $_POST['sortDir'] )
 || !isset( $_POST['getAlways'] )
 || !isset( $_POST['offset'] )
 || !isset( $_POST['amount'] ) )
{
  $res = 'error+++ajax_get_messages+++Request is missing parameters.';
  GetEventLog()->WriteError( gettext("Request is missing parameters.")
  . " mbid=\"" . isset($_POST['mbid']) . "\""
  . " folderId=\"" . isset($_POST['folderId']) . "\""
  . " orderBy=\"" . isset($_POST['orderBy']) . "\""
  . " sortDir=\"" . isset($_POST['sortDir']) . "\""
  . " getAlways=\"" . isset($_POST['getAlways']) . "\""
  . " offset=\"" . isset($_POST['offset']) . "\""
  . " amount=\"" . isset($_POST['amount']) . "\"" );
}
else
{
  $mbId = Disinfect( $_POST['mbid'] );
  $folderId = Disinfect( $_POST['folderId'] );
  $orderBy = Disinfect( $_POST['orderBy'] );
  $sortDir = Disinfect( $_POST['sortDir'] );
  $getAlways = (int)$_POST['getAlways'];
  $offset = (int)$_POST['offset'];
  $amount = (int)$_POST['amount'];

  // Store current folder id
  GetSessionHandler()->SetSessionVar(SessionHandler::CURRENT_FOLDER_ID, $folderId);

	// Let server know that session is still alive (even though user may not be using the session)
  $mailserver->UpdateLastContact( session_id(), $user->id, 0 );

  // This is the async call:
  $msgCsv = $mailserver->GetMessages( session_id(), $mbId, $folderId, $orderBy, $sortDir, $getAlways, $offset, $amount );
  /* the return string $msgCsv is in the following format
  totalNumMessages|numMessagesUnread;
  msgGuid|caller id|called id|calling party name|date|private|priority|state|length|media location;
  ...
  msgGuid|caller id|called id|calling party name|date|private|priority|state|length|media location;
  ***************************************************************************************************/

  if( $msgCsv == 'error' )
  {
    $res = 'error+++ajax_get_messages+++' . gettext("Unable to retrieve messages.");
  }
  else
  {
    $res = $msgCsv;
  }
}

// Output to the stream the resulting HTML
header('Content-Type: text/plain; charset="utf-8"');
header('Content-Length: ' . strlen($res));
echo $res;

?>