<?php
/*
Officity - Web application platform - Version 6.0 - 2011-07-05

François Dispaux, Boris Verdeyen, Thomas Hermant,
Jérémie Roy, Grégory Meurice, Abdelila Harbi, 
Marc Mignonsin, Jonathan Sanchez, Julien Gonzalez, Pierre Fouchez

Sushee and Officity is © Copyright 2011 Nectil SA.

`/sushee-source/sushee/private/mailingQueue.php` is part of Officity.

Sushee is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Officity and Sushee are distributed in the hope that they will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Sushee. If not, see <http://www.gnu.org/licenses/>.
*/
require_once(dirname(__FILE__)."/../common/common_functions.inc.php");
require_once(dirname(__FILE__)."/../common/commandline.class.php");
require_once(dirname(__FILE__)."/../common/batch.class.php");
require_once(dirname(__FILE__)."/../common/cron.class.php");

error_reporting(E_ERROR | E_WARNING | E_PARSE);
// relaunching babeler if not running
$launcher = new babelerLauncher();
if(!$launcher->isRunning()){
	debug_log('relaunching babeler');
	$launcher->execute();
}

$eol = "\r\n";
set_time_limit(1200);
echo 'connecting'.$eol;
$db_conn = db_connect();
if($db_conn){
	echo 'connected'.$eol;
	$moduleInfo = moduleInfo('mailing');
	$sql = 'SELECT `ID`,`DbName`,`MailingMinInterval`,`MailingCurInterval`,`LastSendingDate`,`URL` FROM `residents` WHERE (`Activity`=1 AND `IsTemplate`!=1 AND (`ExpirationDate`="0000-00-00" OR `ExpirationDate` > "'.$GLOBALS["sushee_today"].'" OR `ExpirationDate`="0000-01-01")) OR `ID`=1 ORDER BY `LastSendingDate` ASC';
	;
	$rs = $db_conn->Execute($sql);
	echo 'executed sql instruction'.$eol;
	$mailerResidents = array();
	if($rs){
		while($row = $rs->FetchRow()){
			// MailingMinInterval = 0 
			// MailingCurrentInterval = 1
			// LastSendingDate = 0000-00-00 00:00:00
			if($row['ID']==1){
				$row['DbName']=$GLOBALS["generic_backoffice_db"];
				/*if($GLOBALS["NectilMasterURL"]=='bna-bbot.net')
				$row['URL']='http://localhost';
				else*/
				$row['URL']='http://'.$GLOBALS["NectilMasterURL"];
			}
			$mailerResidents[]=$row;
		}
		$nbResidents = sizeof($mailerResidents);
		if(isset($GLOBALS['MailingMinInterval']))
			$minInterval = $GLOBALS['MailingMinInterval'];
		else
			$minInterval = 15;
		$sent = false;
		for($i=0;$i<$nbResidents;$i++){
			$now = date("Y-m-d H:i:s");
			$resident = $mailerResidents[$i];
			if($resident['MailingMinInterval']!=0)
				$thisInterval = $resident['MailingMinInterval'];
			else
				$thisInterval = $minInterval;
			if($resident['MailingCurInterval']>=($thisInterval-1) && $sent===false){
				$sql = 'SELECT ID FROM `'.$resident['DbName'].'`.`'.$moduleInfo->tableName.'` WHERE ID!=1 AND Activity=1 AND (Status="pending" OR Status="sending") AND SendingDate <= "'.$now.'";';
				echo $resident['DbName'].' Mailing ? '.$eol;
				
				$row = $db_conn->GetRow($sql);
				if($row){
					// we found a resident which needs to send a mailing
					$url = $resident['URL'].'/Kernel/private/send_mailings.php';
					echo 'Mailing '.$resident['DbName'].' can send its mailings at '.$url.' '.$eol;
					$sql = 'UPDATE `residents` SET `LastSendingDate`="'.$now.'",`MailingCurInterval`=0,`MailingMinInterval`=66 WHERE `ID`=\''.$resident['ID'].'\'';
					$db_conn->Execute($sql);
					
					$fp = fopen($url,'r');
					if($fp){
						while (!feof ($fp)) {
							$buffer = fgets($fp, 64);
							echo $buffer;
						  }
						  fclose ($fp);
					}
					// if there was a corruption due to a brutal stop and the resident was left in a slow state, correct it
					if($resident['MailingMinInterval']==66)
						$resident['MailingMinInterval']=0;
					$sql = 'UPDATE `residents` SET `MailingMinInterval`='.$resident['MailingMinInterval'].' WHERE `ID`=\''.$resident['ID'].'\'';
					$db_conn->Execute($sql);
					
					$sent = true;
					
				}else{
					$sql = 'UPDATE `residents` SET `MailingCurInterval`=0 WHERE `ID`=\''.$resident['ID'].'\'';
					//echo $sql.''.$eol;
					$db_conn->Execute($sql);
				}
			}else if($resident['MailingCurInterval']!=66){
				$sql = 'UPDATE `residents` SET `MailingCurInterval`=`MailingCurInterval`+1 WHERE `ID`=\''.$resident['ID'].'\'';
				$db_conn->Execute($sql);
				//echo $sql.''.$eol;
			}
		}
	}else{
		echo 'Problem getting residents list'.$eol;
	}
}else{
	echo 'Problem connecting to database'.$eol;
}
$queue = new BatchQueue();
$queue->Execute();
$queue = new CronQueue();
$queue->Execute();

require_once(dirname(__FILE__).'/../common/kernel.class.php');
$kernel = new NectilKernel();
$kernel->launchResidentsBatches();
$kernel->launchResidentsCrons();

// deleting the session after usage, to keep the session directory clean
session_destroy();
?>
