<?PHP

/*
 *	W-AGORA 4.0
 *	-----------
 *	$Id: mail.php,v 1.73 2006/07/11 21:35:52 mdruilhe Exp $
 *	Usage:		send message to users
 *	Author:		Marc Druilhe <mdruilhe@w-agora.net>
 *
 */

# set $mail_debug = 1 for debugging mode
# -------------------------------------
$mail_debug = 0;

// Main value could be defined in globals.inc
if (!defined('MAIL_MIME_CRLF')) {
	define('MAIL_MIME_CRLF', "\n");
}

if (!defined('_GLOBALS')) {
	die('Hacking attempt');
}

include("$inc_dir/htmlMimeMail/htmlMimeMail.$ext");

/**
 * Send the mail using the mail() PHP function.
 *
 * @param	string	$to			receiver (Multiple recipients can be specified by putting a comma between each address)
 * @param	string	$subject	subject
 * @param	string	$body		message to send
 * @param	array	$headers	additional headers (eg. Bcc:, From: ...) 
 *								can be an associate array or a (properly formated header) string
 * @param	integer $html		1 : send an html_mime_mail ; 0 : only text mail
 * @param	array	$att_names	names of the files to attach to the mail
 * @param	array	$att_files	complete paths of the files to attach
 * @param	array	$file_types mime types of the fiels to attach
 */
function send_mail($to, $subject, $text_body, $headers, $html_body="", $att_names="", $att_files="", $file_types="") {
	global $bn_return_path, $mb_encoding;

	if (defined('MB_STRING') && extension_loaded('mbstring') ) {
		$mb_string = true;
	} else {
		$mb_string = false;
	}

	if (is_array($headers)) {
		if ( $GLOBALS['winbox'] && !minimum_phpversion('4.3') ) {
			// The windows implementation of PHP < 4.3 only support the Cc: header element !!
			if (!empty($headers['Bcc']) ) {
				if (empty($headers['Cc']) ) {
					$headers['Cc'] = $headers['Bcc'];
				} else {
				    $headers['Cc'] .= ', '. $headers['Bcc'];
				}
				unset($headers['Bcc']);
			}
		}
	} elseif (!empty($headers) ) {
		$headers = explode("\n", $headers);
	}

	// Set fully-compliant RFC 822 date
	$headers['Date'] = rfcDate();

	// add X-mailer
	$headers['X-Mailer']='HTML Mime mail class (http://www.phpguru.org) PHP '.phpversion().'/'.wa_version();

	// add the "Errors-To" header
	if (!empty($bn_return_path)) $headers['Errors-To']="<$bn_return_path>";

	if ($mb_string) {
		$m_headers = '';
		reset($headers);
		if (!empty($bn_return_path)) {
			$headers['Return-Path'] = "<$bn_return_path>";
			$safe_mode = (function_exists('ini_get')) ? ini_get('safe_mode') : get_cfg_var('safe_mode');
			if (minimum_phpversion('4.0.5') && !$safe_mode && !$GLOBALS['winbox']) {
				$m_param = "-f " . $bn_return_path;
			}
		}

		while (list($k, $v) = each($headers) ) {
			if (!empty($v)) {
				$m_headers .= "$k: ".str_replace("\n", '', $v). MAIL_MIME_CRLF;
			}
	    }

		$m_headers .= "MIME-Version: 1.0". MAIL_MIME_CRLF;
		// $m_headers .= "X-Priority: 1" . MAIL_MIME_CRLF;
		// $m_headers .= "X-MSMail-Priority: High" . MAIL_MIME_CRLF;
	
		// code conversion for japanese multibyte code mail
		if (mb_detect_encoding($text_body) == mb_internal_encoding()) {
			if ($GLOBALS["debug"] || $GLOBALS["mail_debug"]) {
				printf ("<br><b>mb_convert_encoding body form:</b><tt>%s<br></tt>", nl2br($text_body) );
			}
			$text_body = mb_convert_encoding($text_body, $mb_encoding);
		}
		// mime encode for japanese multibyte subject
		if (mb_detect_encoding($subject) == mb_internal_encoding()) {
			if ($GLOBALS["debug"] || $GLOBALS["mail_debug"]) {
				printf ("<br><b>mb_encode_mimeheader Subject form:</b><tt>%s<br></tt>", nl2br($subject) );
			}
			$subject = mb_encode_mimeheader($subject);
		}

		if ($GLOBALS["debug"] || $GLOBALS["mail_debug"]) {
			printf ("<br><b>sending mail:</b><br><tt>%s<br>Extra-parameters: %s<br><br>To: %s<br>Subject: %s<br><br>%s<br></tt>", nl2br(htmlspecialchars($m_headers)), $m_param, $to, $subject, nl2br($text_body) );
		} else {
			// use mb_send_mail() for multibyte content.
			if (empty($m_param)) {
				return mb_send_mail ($to, $subject, $text_body, $m_headers);
			} else {
				return mb_send_mail ($to, $subject, $text_body, $m_headers, $m_param);
			}
		}
	} else {
		// Create the mail object.
		$mail = new htmlMimeMail();

		// Set CRLF
		$mail->setCrlf(MAIL_MIME_CRLF);
		// Set the subject
		$mail->setSubject($subject);
		
		// Add the text, html and embedded images.
		if (!empty($html_body)) {
			$mail->setHtml($html_body, $text_body,"./");
		} else {
			$mail->setText($text_body);
		}
		// Can be used to add a background to the mail
		//$mail->addHtmlImage($background, 'background.gif', 'image/gif');
	
		// Add Content-Type (set in globals.inc)
		if (!empty($GLOBALS['bn_charset']) ) {
			$mail->setTextCharset($GLOBALS['bn_charset']);
			$mail->setHTMLCharset($GLOBALS['bn_charset']);
		}
	
		// Add attachments to the mail
		if (is_array($att_names)) {
			for( $i=0; $i < sizeof( $att_names); $i++ ) {
				$attachment = $mail->getFile($att_files[$i]);
				$mail->addAttachment($attachment, $att_names[$i], $file_types[$i]);
			}
		}

		// Set the return path of the message
		if (!empty($bn_return_path)) {
			$mail->setReturnPath($bn_return_path);
		}

		// Set headers of the mail
		if (is_array($headers)) {
			foreach ($headers as $k=>$v) {
				if (!empty($v)) {
					$m_headers .= "$k: ".str_replace("\n", '', $v). MAIL_MIME_CRLF;
					$mail->setHeader($k, $v);
				}
			}
		}

		// Send the mail
		if (!is_array($to)) {
			$to = array($to);
		}
		if ($GLOBALS["debug"] || $GLOBALS["mail_debug"]) {
			printf ("<br><b>sending mail:</b><br><tt>%s<br><br>To: %s<br>Subject: %s<br><br>%s<br></tt>", nl2br(htmlspecialchars($m_headers)), implode(',', $to), $subject, nl2br($text_body) );
			return ($mail->send($to, 'mail'));
		} else {
			return (@ $mail->send($to, 'mail'));
		}
	}
} // end func

function mail_note (&$note, $moderators=null) {
	global $ext, $bn_dir, $bn_dir_default, $bn_mail_template;
	global $site, $bn, $bn_title, $bn_base_url, $main_page, $db;
	global $bn_mail, $bn_user_mail, $bn_action, $owneraddress;
	global $bn_return_path,$bn_mail_attachment,$bn_db;
	global $bn_style, $bn_body,$bn_use_smileys,$bn_auto_url,$bn_allow_html;
	global $mail_update;
	
	if (empty($bn_mail_template) ) {
		include ("$bn_dir_default/mail_template.$ext");
	} else {
		include "$bn_dir/$bn_mail_template";
	}

# export all variables in the current scope
# -----------------------------------------
	reset ($note);
	while ( list( $var, $val ) = each( $note)) {
		if (is_string ($var)) {
			$$var=$val;
		}
	}

	if (!empty($bn_before_mail)) {
		eval ($bn_before_mail);
	}

	$att = $db->getAttachments ($bn_db, $cle);
	if (is_array($att)) {
		if ($bn_mail_attachment) {
			$att_count = count($att);
			for ($i=0; $i<$att_count; $i++) {
				$att_names[$i] = $att[$i]["att_name"];
				$info_att.="\n".$att_names[$i];
				$att_types[$i] = $att[$i]["att_type"];
				$att_ids[$i]=$att[$i]["att_id"];
				$att_paths[$i] = $att[$i]["att_path"]."/"."$att_ids[$i].".$att_names[$i];
			}
			$att_name=$att_names[0];
			$attachment=$att_name;
		} else {
			$info_att="\n---\n".LABEL_INFO_ATT_MAIL;
		}
	}

# Set the subject properly
# ------------------------
	if (empty($subject)) {
		$tpl = str_replace('"', '\"', $mail_no_subject);
		eval ("\$m_subject = \"$tpl\";");
	} else {
		$subject=html2plaintext($subject);
		$re = FALSE;
		if (eregi ("^re: *", $subject) ) {
			// Strip "Re: " from subject in order to append it later in front of subject
			$subject = eregi_replace ("^re: *", "", $subject);
			$re = TRUE;
		}
		$tpl = str_replace('"', '\"', $mail_subject);
		eval ("\$m_subject = \"$tpl\";");
		if ($re) {
			$m_subject = "Re: " . $m_subject;
		}
	}

# Set the URL to reply to this email (can be used in template)
# ------------------------------------------------------------
	$list_url      = "$bn_base_url/$main_page?bn=$bn&action=list";
	$reply_url     = "$bn_base_url/$main_page?bn=$bn&action=view&key=$cle";
	$reply_thread_url = "$bn_base_url/$main_page?bn=$bn&action=view&key=$thread";
	$moderate_url  = "$bn_base_url/moderate_notes.$ext?site=$site&bn=$bn";
	$subscribe_url = "$bn_base_url/subscribe.$ext?bn=$bn";

# Initialize the headers
# ----------------------
	// Set the priority
	$headers['X-priority'] = (empty($priority)) ? "3" : $priority;

	// set Message-Id and reference : (will be used to handle posts via email)
	if (!empty($_SERVER['HTTP_HOST'])) {
		$host = $_SERVER['HTTP_HOST'];
	} elseif (!empty($_SERVER['SERVER_NAME'])) {
		$host = $_SERVER['SERVER_NAME'];
	} else {
		$parsed_url = parse_url($bn_base_url);
		$host = $parsed_url["host"];
	}
	
	if ($mod_date>$unixdate) {
		$msgid = "$bn.$cle.$mod_date@$host";
	} else {
		$msgid = "$bn.$cle@$host";
	}

	$headers['Message-ID'] = "<$msgid>";

	if ($parent>0) {
		$headers['References'] = "<$bn.$parent@$host>";
		$headers['In-Reply-To'] = "<$bn.$parent@$host>";
	} elseif ($mod_date>$unixdate) {
		$headers['References'] = "<$bn.$cle@$host>";
	}

	// track IP of initial poster (take IP address from the note)
	$headers['X-Originating-IP'] = $ip;

	// username code conversion for japanese mail in From header
	if (!empty($username)) {
		if ($mb_string) {
			$headerusername = mb_encode_mimeheader(mb_convert_encoding($username, $mb_encoding));
		} else {
			$headerusername = stripSlashes($username);
		}
	}

# First send the mail to the main moderator of this forum
# -------------------------------------------------------
	if ( ($bn_mail || $hidden) && ($bn_action!='moderate_note') ) {
		// Always set the "From:" header to the original sender for moderator
		if (!empty($useraddress) ) {
			$headers['From'] = (empty($username)) ? $useraddress : "\"$headerusername\" <$useraddress>";
		} else {
			$bn_mail_from = str_replace('"', '\\"', $bn_mail_from);
			eval ("\$headers['From'] = \"$bn_mail_from\";");
		}

		// set the "Reply-To" header
		if (!empty($bn_reply_to)) {
			$bn_reply_to = str_replace('"', '\\"', $bn_reply_to);
			eval ("\$headers['Reply-To'] = \"$bn_reply_to\";");
		}
		
		if ($hidden) {
			$tpl = str_replace('"', '\"', $mail_approve_body);
		} elseif ($bn_action=="update") {
			$tpl = str_replace('"', '\"', $mail_update_body);
		} else {
			$tpl = str_replace('"', '\"', $mail_newpost_body);
		}
		eval ("\$m_body = \"$tpl\";");
		$m_body.=$info_att;

		if ($bn_allow_html) {
			# Prepare the HTML layout, build the message
			# -------------------------------------------
			if (!empty($bn_style) && file_exists ("$bn_dir/$bn_style")) {
			  $css = "$bn_dir/$bn_style";
			} elseif (file_exists ("$bn_dir_default/style.$ext") ) {
			  $css = "$bn_dir_default/style.$ext";
			}
			$html_header = "<html><head><title>$m_subject</title>";
			if (!empty($css) ) {
				$html_header .= join(' ', file($css)); // need space for the header to work ??
			}
			$html_header .= "</head><body $bn_body>";
			$html_footer = "</body></html>";
			$m_body=nl2br($m_body);
			if ($bn_use_smileys) $m_body=add_smileys ($m_body);
			if ($bn_auto_url) $m_body=checkURL ($m_body);

			$html_body = $html_header.$m_body.$html_footer;
		}

		$txt_body = html2plaintext($m_body);

		// $bn_mail=1 : send to main moderator
		$m_to = $owneraddress;

		if ($bn_mail>1) {
			// $bn_mail=2 => send email to all moderators
			$moderators = $db->getModerators ($site, $bn);
			if (is_array($moderators) ) {
				foreach ($moderators as $mod) {
					$email = $mod['useraddress'];
					if (!preg_match ("/$email/i", $m_to)) {
						$m_to .= ','. $email;
					}
				}
			}
		}

		if ($bn_mail>2) {
			// $bn_mail=3 => send also to all administrators
			$admins = $db->getAdministrators ($site);
			if (is_array($admins) ) {
				foreach ($admins as $adm) {
					$email = $adm['useraddress'];
					if (!preg_match ("/$email/i", $m_to)) {
						$m_to .= ','. $email;
					}
				}
			}
		}
	
		$rc = send_mail ($m_to, $m_subject, $txt_body, $headers, $html_body, $att_names, $att_paths, $att_types);
	}

	// set the "From:" header according to the configuration for the user subscribers
	if ( ($bn_send_user_address==1) && !empty($useraddress) ) {
		$headers['From'] = (empty($username)) ? $useraddress : "\"$headerusername\" <$useraddress>";
	} else {
		$bn_mail_from = str_replace('"', '\\"', $bn_mail_from);
		eval ("\$headers['From'] = \"$bn_mail_from\";");
	}
	// set the "Reply-To" header
	if (!empty($bn_reply_to)) {
		$bn_reply_to = str_replace('"', '\\"', $bn_reply_to);
		eval ("\$headers['Reply-To'] = \"$bn_reply_to\";");
	}

# send the mail to all users that subscribed to this forum/thread (only if not moderated)
# ---------------------------------------------------------------------------------------
	if ( $bn_user_mail && ($hidden!=1) && ($bn_action!="update" || $mail_update)) {

		if ($parent > 0) {
			// if it is a reply get all thread subscribers
			$users = $db->getSubscribedUsers ($site, $bn, $thread);
		} else {
			// new message get only forum subscribers
			$users = $db->getSubscribedUsers ($site, $bn, 0);
		}

		if (is_array ($users)) {
			reset ($users);
			$user_list = implode (",", $users);

			// fix from Grégoire Dessard <g.dessard@anthelie.com>
			$user_list =  ',' . $user_list . ',';

			// don't send twice to moderator
			if (!empty($owneraddress)) {
				$user_list = eregi_replace (",$owneraddress,", ',', $user_list);
			}

			// don't send to original sender (Should be optional ??? )
			if (!empty($useraddress)) {
				$user_list = eregi_replace (",$useraddress,", ',', $user_list);
			}
			// now strip extra commas
			$user_list = substr ($user_list, 1, -1);

			if ($bn_action=="update") {
				$tpl = str_replace('"', '\"', $mail_update_body);
			} else {
				$tpl = str_replace('"', '\"', $mail_newpost_body);
			}
			eval ("\$m_body = \"$tpl\";");
			$m_body.=$info_att;

			if ($bn_allow_html) {
				# Prepare the HTML layout, build the message
				# -------------------------------------------
				$m_body=nl2br($m_body);
				if ($bn_use_smileys) $m_body=add_smileys ($m_body);
				if ($bn_auto_url) $m_body=checkURL ($m_body);

				$html_body = $html_header.$m_body.$html_footer;
			}

			$txt_body = html2plaintext($m_body);
	
			$headers['Precedence'] = 'bulk';

			if (!empty($bn_mail_to)) {
				$m_to = $bn_mail_to;
				$headers['Bcc'] = $user_list;
			} else {
				$m_to = $user_list;
			}
			$rc = send_mail ($m_to, $m_subject, $txt_body, $headers, $html_body, $att_names, $att_paths, $att_types);
		}
	}
}

function mail_password ($userid, $password, $useraddress ) {
	global $ext, $bn_dir, $bn_dir_default, $bn_mail_template;
	global $site, $bn, $bn_title, $bn_base_url, $main_page, $db;
	global $bn_mail, $bn_user_mail, $bn_action;

	if (empty($bn_mail_template) ) {
		include ("$bn_dir_default/mail_template.$ext");
	} else {
		include "$bn_dir/$bn_mail_template";
	}

	$ip = get_remote_ip();

	$change_password_url = "$bn_base_url/change_password.$ext?site=$site&userid=$userid";
	$login_url = "$bn_base_url/login.$ext?site=$site";

	$tpl = str_replace('"', '\"', $mail_password_subject);
	eval ("\$m_subject = \"$tpl\";");

	$tpl = str_replace('"', '\"', $mail_password_body);
	eval ("\$m_body = \"$tpl\";");

	// set the "From" and "Reply-To" header
	$bn_mail_from = str_replace('"', '\\"', $bn_mail_from);
	eval ("\$headers['From'] = \"$bn_mail_from\";");
	if (!empty($bn_reply_to)) {
		$bn_reply_to = str_replace('"', '\\"', $bn_reply_to);
		eval ("\$headers['Reply-To'] = \"$bn_reply_to\";");
	}

	$rc = send_mail($useraddress, $m_subject, $m_body, $headers );

}

function mail_profile ($userid, $password, &$user_fields, &$moderators) {
	global $ext, $bn_dir, $bn_dir_default, $bn_mail_template;
	global $site, $bn, $bn_title, $bn_base_url, $main_page, $db;
	global $bn_mail, $bn_user_mail, $bn_action;
	global $registered_forums;

	$forums_list = $registered_forums;	// backward compatibility

	if (empty($bn_mail_template) ) {
		include ("$bn_dir_default/mail_template.$ext");
	} else {
		include "$bn_dir/$bn_mail_template";
	}

# export all variables in the current scope
# -----------------------------------------
	reset ($user_fields);
	while ( list( $var, $val ) = each( $user_fields)) {
		if (is_string ($var)) {
			if ($var != "password") {	// do not override with crypted password
				$$var = stripSlashes(my_br2nl($val));
			}
		}
	}

	$change_password_url = "$bn_base_url/change_password.$ext?site=$site&bn=$bn&userid=".urlencode($userid);
	$login_url = "$bn_base_url/login.$ext?site=$site&bn=$bn&loginuser=".urlencode($userid);
	$edit_user_url = "$bn_base_url/admin_user.$ext?site=$site&action=edit&userid=".urlencode($userid);

# Send email to the user
# ----------------------
	if ($bn_action=="register") {
		$tpl = str_replace('"', '\"', $mail_register_subject);
		eval ("\$m_subject = \"$tpl\";");

		$tpl = str_replace('"', '\"', $mail_register_body);
		eval ("\$m_body = \"$tpl\";");

		// set the "From" and "Reply-To" header
		$bn_mail_from = str_replace('"', '\\"', $bn_mail_from);
		eval ("\$headers['From'] = \"$bn_mail_from\";");
		if (!empty($bn_reply_to)) {
			$bn_reply_to = str_replace('"', '\\"', $bn_reply_to);
			eval ("\$headers['Reply-To'] = \"$bn_reply_to\";");
		}

		$rc = send_mail($useraddress, $m_subject, $m_body, $headers );
	}

# Send email to the moderator(s)
# ------------------------------
	if (is_array($moderators) ) {
		if (count($moderators)>1) {
			reset ($moderators);
			$recipients = implode (",", $moderators);
		} elseif (count($moderators) == 1) {
			$recipients = $moderators[0];
		} else {
			// No recipient specified 
			return;
		}
	} elseif (is_string($moderators) && !empty($moderators)) {
		$recipients = $moderators;
	} else {
		// No recipient specified 
		return;
	}

	if ( ($bn_action=="register") || ($bn_action=="create_user") ) {
		$mail_subject = str_replace('"', '\"', $mail_approve_user_subject);
		$mail_body = str_replace('"', '\"', $mail_approve_user_body);
	} else {
		$mail_subject = str_replace('"', '\"', $mail_change_profile_subject);
		$mail_body = str_replace('"', '\"', $mail_change_profile_body);
	}

	$headers['From'] = $useraddress;

	eval ("\$m_subject = \"$mail_subject\";");
	eval ("\$m_body = \"$mail_body\";");

	$rc = send_mail ($recipients, $m_subject, $m_body, $headers);

}

function mail_users ($users, $subject, $body, $from="", $reply_to="", $priority="") {
	global $ext, $bn_dir, $bn_dir_default, $bn_mail_template;
	global $site, $bn, $bn_title, $bn_base_url, $main_page, $db;
	global $bn_mail, $bn_user_mail, $bn_action;

	$multiple = false;

	if (is_array($users) ) {
		if (count($users)>1) {
			$multiple = true;
		} elseif (count($users)==1) {
			$users=$users[0];
		} else {
			return false;
		}
	} elseif (empty($users)) {
	    return FALSE;
	}

	if (empty($bn_mail_template) ) {
		include ("$bn_dir_default/mail_template.$ext");
	} else {
		include "$bn_dir/$bn_mail_template";
	}

	// set the "From:" and "Reply-To:" header
	if(!empty($from)) {
		$headers['From'] = $from;
	} else {
		$bn_mail_from = str_replace('"', '\\"', $bn_mail_from);
		eval ("\$headers['From'] = \"$bn_mail_from\";");	
	}
	if (!empty($reply_to)) {
		$headers['Reply-To'] = $reply_to;
	} elseif (!empty($bn_reply_to)) {
		$bn_reply_to = str_replace('"', '\\"', $bn_reply_to);
		eval ("\$headers['Reply-To'] = \"$bn_reply_to\";");
	}

	// set recipients : "To: " and "Bcc: " headers	
	if ($multiple) {
		reset ($users);
		if (!empty($bn_mail_to)) {
			$m_to = $bn_mail_to;
			$headers['Bcc'] = implode (',', $users);
		} else {
			$m_to = implode (',', $users);
		}
	} else {
		$m_to = $users;
	}	

	if (!empty($priority)) {
		$headers['X-Priority'] = $priority;
	}

	$m_subject = stripslashes($subject);
	$m_body = stripslashes($body);

	return send_mail ($m_to, $m_subject, $m_body, $headers);
}

?>
