<?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/check_mailing.inc.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__)."/../private/mailing_functions.inc.php");
require_once(dirname(__FILE__)."/../common/Mail/pop3.php");

function check_mailing($name="",$xml=false,$requestName="",$current_path="",$firstNode="",$firstNodePath=""){
	mailing_log('check started');
	$moduleInfo = moduleInfo('mailing');
	if($moduleInfo->loaded){
		$moduleContactInfo = moduleInfo('contact');
		$db_conn = db_connect();
	
		global $slash;
	
		$steps=2;
	
		$server = $GLOBALS["PopServer"];

		$username = $GLOBALS["PopUsername"];
		$password = $GLOBALS["PopPassword"];
	
		$pop3 = new Net_POP3();
	
		if($pop3->connect($server)){
			if($pop3->login($username,$password)){
				mailing_log('Authenticated for check_mailing');
				//return generateMsgXML(1,"Problem with the Pop3 authentication.",0,'',$name);
			}else{
				mailing_log('Problem with authentication on check_mailing');
				return generateMsgXML(1,"Problem with the Pop3 connection : login or password is incorrect.",0,'',$name);
			}
		}else{
			return generateMsgXML(1,"Problem with the Pop3 connection : could not connect.",0,'',$name);
		}
	
		$noob = TRUE;
		$now = date("Y-m-d H:i:s");
		$now_timestamp = time();
		$query_result2.="<RESULTS>";
		$num = $pop3->numMsg();
		mailing_log('nb messages '.$num);
		for($i=1;$i<=$num;$i++){
			mailing_log('trying to get message');
			$get_msg = TRUE;
			$delete = FALSE;
			if(!$header = $pop3->getRawHeaders($i)){
				$get_msg = FALSE;
			}
			if($get_msg){
				if(!$message = $pop3->getMsg($i)){
					$delete = FALSE;
				}else{
					$delete = true;
					//mailing_log("analysing mail ".$message);
					$viewing_code = "";
					$found_info = false;
					$msg = '';
					$lines = explode("\n",$message);
					for($j=0;$j<count($lines);$j++){
						$line = $lines[$j];
						//mailing_log($line);
						// remove eol at end
						$line = str_replace(array("\r","\n"),"",$line);
						if(substr($line,-1)=='=')
							$line = substr($line,0,-1);// cut the = and the eol
						$regex_date = "^(Date:)";
						if (eregi($regex_date,$line)){
							$sending_date = $line;
							$timestamp = strtotime(substr($sending_date,6));
							if( ($timestamp+604800) < $now_timestamp){
								//mailing_log("message is too old ".date("Y-m-d",$timestamp));
								$delete = true;
							}
						}
						$msg.=$line;
						//mailing_log($line);
						unset($line);
					}
					//mailing_log("***".$msg."***");
					$spy_start = strpos($msg,'<mailing resident=3D"');//strpos($msg,'<mailing resident=3D"'.$GLOBALS['resident_name'].'"');
					if($spy_start!==false){
						//mailing_log("found a mailing tag");
						$resident_name_start = $spy_start+21;
						$resident_name_end = strpos($msg,'"',$resident_name_start);
					
						if($resident_name_end!==false){
							$resident_name = substr($msg,$resident_name_start,$resident_name_end-$resident_name_start);
							$spy_end = strpos($msg,'</mailing',$spy_start);
							if($spy_end===false)
								$spy_end = $spy_start+150;
							if($spy_end!==false){
								//mailing_log('found spy! '.$spy_end);
								$spy_str = substr($msg,$spy_start,$spy_end-$spy_start);
								$viewing_code_start = strpos($spy_str,' viewing_code=3D"');
								//mailing_log('spy is '.$spy_str.'*****');
								//mailing_log('msg is '.$msg);
								$ID_start = strpos($spy_str,' ID=3D"');
								if($viewing_code_start!==false && $ID_start!==false){
									$viewing_code_end = strpos($spy_str,'"',$viewing_code_start+18);
									//mailing_log("***".$spy_str."***");
									//mailing_log("viewing_code_start = ".$viewing_code_start);
									//mailing_log("viewing_code_end = ".$viewing_code_end);
									$ID_end = strpos($spy_str,'"',$ID_start+8);
									$viewing_code = substr($spy_str,$viewing_code_start+17,$viewing_code_end-$viewing_code_start-17);
									$mailingID = substr($spy_str,$ID_start+7,$ID_end-$ID_start-7);
									//mailing_log("viewing_code = ".$viewing_code);
									//$viewing_code = str_replace(array("\r","\n","="),"",$viewing_code);
									$found_info = true;
								}else{
									mailing_log("couldn't find ID or viewing_code ID?".$ID_start." viewing_code?".$viewing_code_start);
								}
							}else{
								mailing_log('found no closing mailing tag in '. substr($msg,$spy_start,'300'));
							}
						}
					}
					$regex2 = '(did not reach the following recipient)|(permanent fatal errors)|(Unable to deliver)|(Notification)|(Notice)|(Returned mail)|(Undeliverable)|(Delivery)|(Undelivered)|(Transcript of session)|(Failure notice)|(permanent error)';
					$is_error = eregi($regex2,$msg);
					if(!$is_error){
						mailing_log("It's not an error message");
					}
				
					if($is_error && $found_info && is_numeric($mailingID) && $viewing_code!=""){
						if(strlen($viewing_code)>32){
							$viewing_code = substr($viewing_code,0,32);
						}
						if($resident_name){
							$resident_sql = 'SELECT DbName FROM residents WHERE Denomination="'.$resident_name.'" AND Activity=1;';
							$resident = $db_conn->GetRow($resident_sql);
							$resident_dbname = $resident['DbName'].'.'; // the dot is for future sql query 
							$maildir = $GLOBALS["nectil_dir"].$slash.'Residents'.$slash.$resident_name.$slash.'Files'.$slash.'mailing'.$slash.$mailingID;
						}else{
							$resident_dbname = '';
							$maildir = $GLOBALS["directoryRoot"].$slash.'mailing'.$slash.$mailingID;
						}
						makeDir($maildir);
					
						$sql = 'SELECT * FROM '.$resident_dbname.'`mailing_recipients` WHERE `Status`="sent" AND `ViewingCode`="'.$viewing_code.'" AND `MailingID`='.$mailingID.';';
						$recipient = $db_conn->GetRow($sql);
						if($recipient){
							//mailing_log($sql);
						
							$info_sql = "SELECT * FROM ".$resident_dbname.$moduleInfo->tableName." WHERE ID=$mailingID;";
							//mailing_log($info_sql);
							$info = $db_conn->GetRow($info_sql);
							$email = $recipient['Email'];
							// must complete the infos in the xml
						
							$contact_sql = "SELECT * FROM ".$resident_dbname.$moduleContactInfo->tableName." WHERE ID=".$recipient['ContactID'].";";
							$contact = $db_conn->GetRow($contact_sql);
							//mailing_log($contact_sql);
							$compl_info = false;
							$regex_quota = '(quota exceeded)|(exceeded storage allocation)|(mailbox is full)|(over quota)';
							$is_over_quota = eregi($regex_quota,$msg);
							if($is_over_quota)
								$new_status = 'over_quota';
							else
								$new_status = 'erroneous';
						
							setMailingRecipientStatus($mailingID,$viewing_code,$new_status,false,$now,$steps,$compl_info,$msg,$resident_dbname);
							updateMailingCounts($mailingID,$resident_dbname);
							// must delete the message
							$delete = true;
						
							// must mark the email as incorrect (in db)
							if(!$is_over_quota){
								$update_sql = 'UPDATE '.$resident_dbname.'`'.$moduleContactInfo->tableName.'` SET `ModificationDate`="'.$GLOBALS["sushee_today"].'",`EmailInvalid`=`EmailInvalid`+1 WHERE `ID`=\''.$contact['ID'].'\' AND `Email1`="'.$email.'";';
								// the condition on the Email is to avoid discarding something that has been modified since sending
								$db_conn->Execute($update_sql);
							}
							//break;
							//mailing_log($maildir.$slash.$recipient['ViewingCode'].'.txt');
							saveInFile($msg,$maildir.$slash.$recipient['ViewingCode'].'.txt');
						}
					}
					if($delete == true)
						$pop3->deleteMsg($i);
				}
			
			}
			// Send Noob command !!
			if($noob){
				if(!$pop3->_cmdNoop()){
					$noob = FALSE;
				}
			}
		}
		$pop3->disconnect();
	}else
		debug_log('mailing module not available');
	$query_result = generateMsgXML(0,"The check was succesfully accomplished",0,'',$name);
	return $query_result;
}
?>
