<?PHP
#
#   FILE:  EmailFullRecord.php
#
#   Part of the Collection Workflow Integration System (CWIS)
#   Copyright 2015 Edward Almasy and Internet Scout Research Group
#   http://scout.wisc.edu/cwis/
#

# ----- MAIN -----------------------------------------------------------------

/**
* Function used to delay the execution of the page to minimize problems stemming
* from calling session_write_close(). This could cause errors if there are any
* unbuffered callbacks registered with $AF that require write access to session
* variables. Currently, there are none. session_write_close() is used because
* PHP sessions normally cause AJAX calls to block, forcing them to be
* synchronous, which can cause considerable latency.
* Sends a recommendation email using the MailIt plugin functionality if the
* page is requested with Ajax.
* Renders errors directly to the page with $JsonHelper
*/
function DelayCallAjax()
{
    $GLOBALS["AF"]->SuppressHTMLOutput();

    # how long until the cached results become stale
    $MaxAgeInSeconds = 30;

    # set headers to control caching
    header("Expires: ".gmdate("D, d M Y H:i:s \G\M\T", time()+$MaxAgeInSeconds));
    header("Cache-Control: private, max-age=".$MaxAgeInSeconds);
    header("Pragma:");

    # PHP sessions cause AJAX calls to block, so make the session readonly from
    # this point on to avoid latency
    session_write_close();

    # create the object to help deal with returning JSON
    $JsonHelper = new JsonHelper();

    # get the mailit plugin
    $Plugin = $GLOBALS["G_PluginManager"]->GetPluginForCurrentPage();

    # extract some parameters
    $Resource = new Resource(GetArrayValue($_GET, "ID"));
    $emails =  explode(",", $_POST['email']);

    foreach($emails as $email)
    {

      #Filter the email
      $email = trim($email);
      $email = filter_var($email, FILTER_VALIDATE_EMAIL);

      # the resource parameter is required
      if (is_null($Resource))
      {
          $JsonHelper->Error("The \"Resource\" parameter is necessary.");
          return;
      }

      # make sure the resource is valid
      if ($Resource->Status() == -1)
      {
          $JsonHelper->Error("The resource you are trying to send is not valid.");
          return;
      }

      # don't allow unauthorized access
      if (!$Plugin->EmailCanBeSent($Resource))
      {
          $JsonHelper->Error("You can only send resources that are OK for viewing.");
          return;
      }

      #empty error return string
      $return = "";

      #If it is valid, send the email
      if($email)
      {
        $return = SendEmail($Resource, $email);
      }
      else
      {
          $JsonHelper->Error("The email you entered (".$email.") does not appear to be valid.");
          return;
      }


      if($return === "SENT")
      {
        //continue
      }
      else
      {
        $JsonHelper->Error($return);
        return;
      }
    }
    $JsonHelper->Success();
}


/**
* Sends a recommendation email using the MailIt plugin functionality
* if the page was not requested with ajax. Passes error messages back
* to either the Confirm page or the FullRecord page depending upon
* error message type.
*/
function SendMailNoAjax()
{
    # get the mailit plugin
    $Plugin = $GLOBALS["G_PluginManager"]->GetPluginForCurrentPage();

    # extract some parameters
    $Resource = new Resource(GetArrayValue($_GET, "ID"));
    $emails=  explode(",", $_POST['email']);

    foreach ($emails as $email)
    {
      # go back to the full record page at the end
      $GLOBALS["AF"]->SetJumpToPage("index.php?P=FullRecord&ID=" . $Resource->Id());

      #Filter the email
      $email = trim($email);
      $email = filter_var($email, FILTER_VALIDATE_EMAIL);

      #Empty Errors variable.
      $errors = "";

      # the resource parameter is required
      if (is_null($Resource))
      {
          $errors = 0;
          $GLOBALS["AF"]->SetJumpToPage("index.php?P=FullRecord&ID=" . $Resource->Id()."&ER=".$errors);
          return;
      }

      # make sure the resource is valid
      if ($Resource->Status() == -1)
      {
          $errors = 1;
          $GLOBALS["AF"]->SetJumpToPage("index.php?P=FullRecord&ID=" . $Resource->Id()."&ER=".$errors);
          return;
      }

      # don't allow unauthorized access
      if (!$Plugin->EmailCanBeSent($Resource))
      {
          $errors = 2;
          $GLOBALS["AF"]->SetJumpToPage("index.php?P=FullRecord&ID=" . $Resource->Id()."&ER=".$errors);
          return;
      }

      #empty error return string
      $return = "";

      #If it is valid, send the email
      if(strlen($email)>0)
      {
        $return = SendEmail($Resource, $email);
        if($return == "SENT")
        {
          $GLOBALS["AF"]->SetJumpToPage("index.php?P=FullRecord&ID=" . $Resource->Id()."&SC=TRUE");
        }
        else
        {
          $errors = 4;
          $GLOBALS["AF"]->SetJumpToPage("index.php?P=FullRecord&ID=" . $Resource->Id()."&ER=".$errors);
        }
      }
      else
      {
          $errors = 3;
          $GLOBALS["AF"]->SetJumpToPage("index.php?P=P_MailIt_ConfirmMailIt&ID=" . $Resource->Id()."&ER=".$errors);
          return;
      }
    }
}

/**
* Function to check if the request is an AJAX request
* @return boolean value of page requested with Ajax
*/
function IsAjax() {
  return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}

/**
* Sends a recommendation email using the MailIt plugin functionality.
* @param Resource $Resource
* @param String $EmailAddress
* @return Integer error number
*/
function SendEmail($Resource, $EmailAddress)
{
    # get the mailit plugin
    $Plugin = $GLOBALS["G_PluginManager"]->GetPluginForCurrentPage();
    return $Plugin->SendFullRecordEmail($Resource, $EmailAddress);
}

PageTitle("Mail It - Email Full Record");


if (IsAjax()) {
  DelayCallAjax();
}
else {
  SendMailNoAjax();
}
