<?php
// ------------------------------------------------------------------------- //
//                XOOPS - PHP Content Management System                      //
//                       <http://www.xoops.org/>                             //
// ------------------------------------------------------------------------- //
//  This program 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 2 of the License, or        //
//  (at your option) any later version.                                      //
//                                                                           //
//  This program is distributed in the hope that it 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 this program; if not, write to the Free Software              //
//  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA //
// ------------------------------------------------------------------------- //
// Author of File: 							     //
// Kazumi Ono (http://www.mywebaddons.com/ , http://www.myweb.ne.jp/)        //
// ------------------------------------------------------------------------- //
include_once(XOOPS_ROOT_PATH."/class/xoopspm.php");

class XoopsMailer{

	// sender email address
	// private
	var $fromEmail;

	// sender name
	// private
	var $fromName;

	// array of user class objects
	// private
	var $toUsers;

	// array of email addresses
	// private
	var $toEmails;

	// custom headers
	// private
	var $addHeaders;

	// subjet of mail
	// private
	var $subject;

	// body of mail
	// private
	var $body;

	// error messages
	// private
	var $errors;

	// messages upon success
	// private
	var $success;

	// private
	var $isMail;

	// private
	var $isPM;

	// private
	var $assignedTags;

	// private
	var $template;

	// private
	var $templatedir;

	function XoopsMailer(){
		$this->reset();
	}

	// public
	// reset all properties to default
	function reset(){
		$this->fromEmail = "";
		$this->fromName = "";
		$this->toUsers = array();
		$this->toEmails = array();
		$this->headers = array();
		$this->subject = "";
		$this->body = "";
		$this->errors = array();
		$this->success = array();
		$this->isMail = false;
		$this->isPM = false;
		$this->assignedTags = array();
		$this->template = "";
		$this->templatedir = "";
		// Change below to \r\n if you have problem sending mail
		$this->LE ="\n";
	}

	// public
	function setTemplateDir($value){
		if ( substr($value, -1, 1) != "/" ) {
			$value .= "/";
		}
		$this->templatedir = $value;
	}

	// public
	function setTemplate($value){
		$this->template = $value;
	}

	// pupblic
	function setFromEmail($value){
		$this->fromEmail = trim($value);
	}

	// public
	function setFromName($value){
		$this->fromName = trim($value);
	}

	// public
	function setSubject($value){
		$this->subject = trim($value);
	}

	// public
	function setBody($value){
		$this->body = trim($value);
	}

	// public
	function useMail(){
		$this->isMail = true;
	}

	// public
	function usePM(){
		$this->isPM = true;
	}

	// public
	function send(){
		global $xoopsConfig;
		if ( $this->body == "" && $this->template == "" ) {
			$this->errors[] = _AM_MSGBODY;
			return false;
		} elseif ( $this->template != "" ) {
			$path = ( $this->templatedir != "" ) ? $this->templatedir."".$this->template : (XOOPS_ROOT_PATH."/language/".$xoopsConfig['language']."/mail_template/".$this->template);
			if ( !($fd = @fopen($path, 'r')) ) {
				$this->errors[] = _AM_FAILOPTPL;
            			return false;
        		}
			$this->setBody(fread($fd, filesize($path)));
		}

		// for sending mail only
		if ( $this->isMail  || !empty($this->toEmails) ) {
			if ( empty($this->fromName) ) {
				$this->errors[] = _AM_FNAMENG;
				return false;
			}
			$from = $this->encodeFromName($this->fromName);
			//if ( $this->fromEmail == "" ) {
			//	$this->errors[] = _AM_FEMAILNG;
			//	return false;
			//}
			$this->headers[] = "From: ".$from." <".$this->fromEmail.">".$this->LE;
			$this->headers[] = "X-Mailer: PHP/".phpversion().$this->LE;
			$this->headers[] = "Return-Path: ".$this->fromEmail;
			//foreach ($this->addHeaders as $ah) {
			//	$headers .= $ah.$this->LE;
			//}
			$headers = join("", $this->headers);
		}

		// replace tags with actual values
		foreach ( $this->assignedTags as $k => $v ) {
			$this->body = str_replace("{".$k."}", $v, $this->body);
		}
		$this->body = str_replace("\r\n", "\n", $this->body);
		$this->body = str_replace("\r", "\n", $this->body);
		$this->body = str_replace("\n", $this->LE, $this->body);

		// send mail to specified mail addresses, if any
		foreach ( $this->toEmails as $mailaddr ) {
			if ( !$this->sendMail($mailaddr, $this->subject, $this->body, $headers) ) {
				$this->errors[] = sprintf(_AM_SENDMAILNG, $mailaddr);
			} else {
				$this->success[] = sprintf(_AM_MAILGOOD, $mailaddr);
			}
		}

		// send message to specified users, if any
		foreach ( $this->toUsers as $user ) {
			// set some user specific variables
			$subject = str_replace("{X_UNAME}", $user->getVar("uname"), $this->subject );
			$text = str_replace("{X_UID}", $user->getVar("uid"), $this->body );
			$text = str_replace("{X_UEMAIL}", $user->getVar("email"), $text );
			$text = str_replace("{X_UNAME}", $user->getVar("uname"), $text );
			$text = str_replace("{X_UACTLINK}", XOOPS_URL."/user.php?op=actv&id=".$user->getVar("uid")."&key=".$user->getVar("actkey")."", $text );
			//echo $subject."<br>".$text."<br>".$headers."";
			// send mail
			if ( $this->isMail ) {
				if ( !$this->sendMail($user->getVar("email"), $subject, $text, $headers) ) {
					$this->errors[] = sprintf(_AM_SENDMAILNG, $user->getVar("uname"));
				} else {
					$this->success[] = sprintf(_AM_MAILGOOD, $user->getVar("uname"));
				}
			}
			// send private message
			if ( $this->isPM ) {
				if ( !$this->sendPM($user->getVar("uid"), $subject, $text) ) {
					$this->errors[] = sprintf(_AM_SENDPMNG, $user->getVar("uname"));
				} else {
					$this->success[] = sprintf(_AM_PMGOOD, $user->getVar("uname"));
				}
			}
			flush();
		}
		if ( count($this->errors) > 0 ) {
			return false;
		}
		return true;
	}

	// private
	function sendPM($uid, $subject, $body){
		global $xoopsUser;
		$pm = new XoopsPM();
		$pm->setVar("subject", $subject);
		$pm->setVar("from_userid", $xoopsUser->getVar("uid"));
		$pm->setVar("msg_text", $body);
		$pm->setVar("to_userid", $uid);
		if ( !$pm->store() ) {
			return false;
		}
		return true;
	}

	// private
	function sendMail($email, $subject, $body, $headers){
		$subject = $this->encodeSubject($subject);
		$this->encodeBody($body);
		if ( !mail($email, $subject, $body, $headers) ) {
			return false;
		}
		return true;
	}


	// public
	function getErrors($ashtml = true){
		if ( !$ashtml ) {
			return $this->errors;
		} else {
			if ( !empty($this->errors) ) {
				$ret = "<h4>"._ERRORS."</h4>";
				foreach ( $this->errors as $error ) {
					$ret .= $error."<br />";
				}
			} else {
				$ret = "";
			}
			return $ret;
		}
	}

	// public
	function getSuccess($ashtml = true){
		if ( !$ashtml ) {
			return $this->success;
		} else {
			$ret = "";
			if ( !empty($this->success) ) {
				foreach ( $this->success as $suc ) {
					$ret .= $suc."<br />";
				}
			}
			return $ret;
		}
	}

	// public
	function assign($tag, $value=NULL) {
		if ( is_array($tag) ) {
			foreach ( $tag as $k => $v ) {
				$this->assign($k, $v);
			}
		} else {
			if ( !empty($tag) && isset($value) ) {
				$tag = strtoupper(trim($tag));
				if ( substr($tag, 0, 2) != "X_" ) {
					$this->assignedTags[$tag] = $value;
				}
			}
		}
	}

	// public
	function addHeaders($value){
		$this->headers[] = trim($value).$this->LE;
	}

	// public
	function setToEmails($email){
		if ( !is_array($email) ) {
			if (eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+([\.][a-z0-9-]+)+$",$email) ) {
				array_push($this->toEmails, $email);
			}
		} else {
			foreach ( $email as $e) {
				$this->setToEmails($e);
			}
		}
	}

	// public
	function setToUsers($user){
		if ( !is_array($user) ) {
			if ( get_class($user) == "xoopsuser" ) {
				array_push($this->toUsers, $user);
			}
		} else {
			foreach ( $user as $u) {
				$this->setToUsers($u);
			}
		}
	}

	// public
	function setToGroups($group){
		if ( !is_array($group) ) {
			if ( get_class($group) == "xoopsgroup" ) {
				$users = $group->getMembers(true);
				$this->setToUsers($users);
			}
		} else {
			foreach ( $group as $g) {
				$this->setToGroups($g);
			}
		}
	}


	// abstract
	// to be overidden by lang specific mail class, if needed
	function encodeFromName($text){
		return $text;
	}

	// abstract
	// to be overidden by lang specific mail class, if needed
	function encodeSubject($text){
		return $text;
	}

	// abstract
	// to be overidden by lang specific mail class, if needed
	function encodeBody(&$text){
	}
}
?>