<?php
  // background-mailer.php - Command line script to send queued messages from the _outgoing_mail table
  // NOTE: If you update this file be sure to RENAME it *-custom.php so it doesn't get overwritten next time you upgrade the plugin!

  // Mail limits - If your server or host requires it, you can limit mail sending speed below
  $GLOBALS['BACKGROUND_SEND_MAX']   = 25;  // max messages to send in each batch, eg: If a cronjob runs the script every 10 min and this is set to 200, you'll send approx 1200 emails an hour
  $GLOBALS['BACKGROUND_SEND_DELAY'] = 0;  // second to wait after sending each message

  // load viewer library
  chdir( dirname(__FILE__) ); // change dir to the directory the script is in (so relative paths below work).
  $libraryPath = 'lib/viewer_functions.php';
  $dirsToCheck = array('','../','../../','../../../','../../../../','../../../../../');
  foreach ($dirsToCheck as $dir) { if (@include_once("$dir$libraryPath")) { break; }}
  if (!function_exists('getRecords')) { die("Couldn't load viewer library, check filepath in sourcecode."); }

  // send headers (for running through web)
  if (!inCLI()) {
    header("Content-type: text/plain");
    header("Content-Disposition: inline; filename='output.txt'"); // Force IE to display as text and not download file
    if (!@$CURRENT_USER['isAdmin']) { die("You must be logged in as Admin to run this script from the web!"); } // security check for web access - don't show cron filepaths unless logged in
  }

  // PHP Buffering: turn off _all_ PHP output-buffering, including user defined and internal PHP output buffering, see ob_get_status(true) for details
  // Web Server Buffering: turn off output compression which requires all output be buffered in advance before being compressed
  ob_implicit_flush(true);
  ini_set('zlib.output_compression', 0);
  if (function_exists('apache_setenv')) {
    apache_setenv('no-gzip', 1);
    apache_setenv('no-mod_gzip_on', 'No');
  }
  while (@ob_end_flush()); // turn off PHP buffering

  // Show cronjob instructions
  if (@$_REQUEST['i']) {
    $thisScriptPath = __FILE__;
    $thisScriptUrl  = preg_replace("/\?.*/", '', thisPageUrl());

    print "Cronjob Setup Instructions\n";
    print "-------------------------------------------------------------------------------\n";
    print "To automatically run this script from a cronjob or 'scheduled task' use the\n";
    print "following filepath or url:\n\n";
    print "Filepath: $thisScriptPath\n";
    print "URL: $thisScriptUrl\n\n\n";
  }

  // error checking
  if (@$GLOBALS['SETTINGS']['advanced']['outgoingMail'] == 'logOnly') {
    print "-------------------------------------------------------------------------------\n";
    print "Not sending - Outgoing Mail is currently configured as 'Log Only'.\n";
    print "To change outgoing mail setting go to: Admin > General Settings > Email Settings.\n";
    print "-------------------------------------------------------------------------------\n";
    exit;
  }

  // send mail
  print "Background Mailer - Sending Queued Messages\n";
  print "-------------------------------------------------------------------------------\n";

  $pendingMessages = mysql_count('_outgoing_mail', array('backgroundSend' => '1'));
  #if (!$pendingMessages) { die("No new emails to send!"); }
  print "Sending queued 'Background Send' emails, ($pendingMessages queued";
  if ($BACKGROUND_SEND_MAX)   { print ", sending max $BACKGROUND_SEND_MAX per batch"; }
  if ($BACKGROUND_SEND_DELAY) { print ", $BACKGROUND_SEND_DELAY second pause between sends"; }
  print ")\n\n";

  list($messagesSent, $sendErrors) = _sendQueuedEmails();
  $executeSeconds = showExecuteSeconds(true);

  if ($sendErrors) {
    print "\nErrors: $sendErrors\n";
  }

  print "\nDone, sent $messagesSent emails, total time: $executeSeconds seconds\n";
  exit;


// list($messagesSent, $sendErrors) = _sendQueuedEmails();
function _sendQueuedEmails() {
  $max        = $GLOBALS['BACKGROUND_SEND_MAX'];
  $count      = 0;
  $sendErrors = '';

  while (1) {
    if ($max && $count >= $max) { break; }

    // lock table
    if (!mysql_get_lock(__FUNCTION__)) { return array(0, 'Aborting, another mail process is still running'); } // if already locked, another process is still running so abort

    // load next message
    $record = mysql_get('_outgoing_mail', null, array('backgroundSend' => 1));
    if (!$record) { break; }

    // send message
    print "Sending message to {$record['to']}\n";
    $message            = array();
    $message['from']    = $record['from'];
    $message['to']      = $record['to'];
    $message['subject'] = $record['subject'];
    if   ($record['text']) { $message['text'] = $record['text']; } // send text if available
    if   ($record['html']) { $message['html'] = $record['html']; } // send html if available
    else                   { $message['text'] = $record['text']; } // or if no html, send text by default
    $message['logging'] = false; // disable logging (since we're already mailing messages from the log)
    $sendErrors .= sendMessage($message);
    if ($sendErrors) { mysql_release_lock(__FUNCTION__); break; }

    // update or delete message record
    $mode = @$GLOBALS['SETTINGS']['advanced']['outgoingMail'];
    if ($mode == 'sendOnly') { mysql_delete('_outgoing_mail', $record['num']); }
    else                     { mysql_update('_outgoing_mail', $record['num'], null, array('sent=' => 'NOW()', 'backgroundSend' => 0)); }

    // unlock table
    mysql_release_lock(__FUNCTION__);

    // pause after sending
    if ($GLOBALS['BACKGROUND_SEND_DELAY']) { sleep( $GLOBALS['BACKGROUND_SEND_DELAY'] ); }

    $count++;
  }

  //
  $messagesSent = $count;
  return array($messagesSent, $sendErrors);
}


?>
