<?php
/**
 * PHP Mailer
 *
 * @package SMF Zhen Mailer
 * @PHP Mailer version 6.03
 * @license https://www.gnu.org/licenses/lgpl.html
 */

if (!defined('SMF'))
	die('Hacking attempt...');

function ZhenMailer_admin_areas(&$admin_areas)
{
	global $txt;

	$admin_areas['maintenance']['areas']['mailqueue']['subsections'] += array(
		'zhenmailtemplates' => array($txt['ZhenMailer_templates'], 'admin_forum'),
		'zhenmailset' => array($txt['ZhenMail_settings'], 'admin_forum'),
		'phpconfig' => array($txt['ZhenMail_file_config'], 'admin_forum'),
	);
}

function ZhenMailer_actions(&$actionArray)
{
	global $modSettings;

	if (!empty($modSettings['ZhenMailer_cron_job_ajax']))
		$actionArray['zhenmailerschedule'] = array('ZhenMailerCron.php', 'ZhenMailerCronJobInit');

}

function ZhenMailer_init()
{
	// load necessary language files
	global $txt, $boarddir, $sourcedir, $context, $zhenMailModSettings;
	loadLanguage('ZhenMailer');
	require_once($sourcedir . '/ZhenMailerCron.php');
	require_once($boarddir . '/ZhenMailer/ZhenMailerFixUTF8.php');
	ZhenMailerCronJob();
}

function ZhenMailer_sendmail()
{
	global $boarddir, $zhenMailModSettings, $txt;

	require_once($boarddir . '/ZhenMailer/ZhenMailer.php');
	require_once($boarddir . '/ZhenMailer/ZhenMailerClass.php');
	loadZhenMailModSettings();
}

// Send an email via SMTP.
function ZhenMailer_smtp_mail($mail_to_array, $subject, $message, $headers)
{
	global $modSettings, $webmaster_email, $txt;

	$modSettings['smtp_host'] = trim($modSettings['smtp_host']);

	// Try to connect to the SMTP server... if it doesn't exist, only wait three seconds.
	if (!$socket = fsockopen($modSettings['smtp_host'], empty($modSettings['smtp_port']) ? 25 : $modSettings['smtp_port'], $errno, $errstr, 3))
	{
		// Maybe we can still save this?  The port might be wrong.
		if (substr($modSettings['smtp_host'], 0, 4) == 'ssl:' && (empty($modSettings['smtp_port']) || $modSettings['smtp_port'] == 25))
		{
			if ($socket = fsockopen($modSettings['smtp_host'], 587, $errno, $errstr, 3))
				log_error($txt['smtp_port_ssl']);
		}

		// Unable to connect!  Don't show any error message, but just log one and try to continue anyway.
		if (!$socket)
		{
			log_error($txt['smtp_no_connect'] . ': ' . $errno . ' : ' . $errstr);
			return false;
		}
	}

	// Wait for a response of 220, without "-" continuer.
	if (!server_parse(null, $socket, '220'))
		return false;

	if ($modSettings['mail_type'] == 2 && $modSettings['smtp_username'] != '' && $modSettings['smtp_password'] != '')
	{
		// !!! These should send the CURRENT server's name, not the mail server's!
		// EHLO could be understood to mean encrypted hello...
		if (server_parse('EHLO ' . $modSettings['smtp_host'], $socket, null) == '250')
		{
			//STARTTLS
			server_parse('STARTTLS', $socket, null);
			stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
			server_parse('EHLO ' . $modSettings['smtp_host'], $socket, null);

			if (!server_parse('AUTH LOGIN', $socket, '334'))
				return false;
			// Send the username and password, encoded.
			if (!server_parse(base64_encode($modSettings['smtp_username']), $socket, '334'))
				return false;
			// The password is already encoded ;)
			if (!server_parse($modSettings['smtp_password'], $socket, '235'))
				return false;
		}
		elseif (!server_parse('HELO ' . $modSettings['smtp_host'], $socket, '250'))
			return false;
	}
	else
	{
		// Just say "helo".
		if (!server_parse('HELO ' . $modSettings['smtp_host'], $socket, '250'))
			return false;
	}

	// Fix the message for any lines beginning with a period! (the first is ignored, you see.)
	$message = strtr($message, array("\r\n" . '.' => "\r\n" . '..'));

	// !! Theoretically, we should be able to just loop the RCPT TO.
	$mail_to_array = array_values($mail_to_array);
	foreach ($mail_to_array as $i => $mail_to)
	{
		// Reset the connection to send another email.
		if ($i != 0)
		{
			if (!server_parse('RSET', $socket, '250'))
				return false;
		}

		// From, to, and then start the data...
		if (!server_parse('MAIL FROM: <' . (empty($modSettings['mail_from']) ? $webmaster_email : $modSettings['mail_from']) . '>', $socket, '250'))
			return false;
		if (!server_parse('RCPT TO: <' . $mail_to . '>', $socket, '250'))
			return false;
		if (!server_parse('DATA', $socket, '354'))
			return false;
		fwrite($socket, 'Subject: ' . $subject . "\r\n");
		if (strlen($mail_to) > 0)
			fwrite($socket, 'To: <' . $mail_to . '>' . "\r\n");
		fwrite($socket, $headers . "\r\n\r\n");
		fwrite($socket, $message . "\r\n");

		// Send a ., or in other words "end of data".
		if (!server_parse('.', $socket, '250'))
			return false;

		// Almost done, almost done... don't stop me just yet!
		@set_time_limit(300);
		if (function_exists('apache_reset_timeout'))
			@apache_reset_timeout();
	}
	fwrite($socket, 'QUIT' . "\r\n");
	fclose($socket);

	return true;
}

function ZhenMailer_attachments(&$attachIDs, &$msgID)
{
	global $txt, $boarddir, $smcFunc, $context, $modSettings, $sourcedir;

	if (!empty($modSettings['ZhenMailer_attachments']))
	{
		// email a copy of the attachment
		require_once($sourcedir . '/ZhenMailerCron.php');
		list($attData, $filepaths, $topicId) = array(array(), array(), 0);
		$ext = version_compare((!empty($modSettings['smfVersion']) ? substr($modSettings['smfVersion'], 0, 3) : '2.0'), '2.1', '<') ? '' : '.dat';

		foreach ($attachIDs as $attachID)
		{
			$row = array();
			$result =  $smcFunc['db_query']('', '
				SELECT att.id_attach, att.filename, att.fileext, att.id_folder, att.file_hash, att.id_msg, msg.id_topic
				FROM {db_prefix}attachments AS att
				LEFT JOIN {db_prefix}messages AS msg ON (msg.id_msg = {int:msgid})
				WHERE id_attach = {int:idatt}
				LIMIT 1',
				array(
					'idatt' => $attachID,
					'msgid' => $msgID,
				)
			);
			while ($row = $smcFunc['db_fetch_assoc']($result))
			{
				if (strlen($row['filename']) > 5 && substr($row['filename'], -6) == '_thumb')
					continue;

				$attData[] = array(
					'id' => $row['id_attach'],
					'topic' => $row['id_topic'],
					'filename' => $row['filename'],
					'fileext' => $row['fileext'],
					'file_hash' => $row['file_hash'],
					'path' => $modSettings['attachmentUploadDir'][$row['id_folder']]
				);

				$topicId = empty($topicId) ? $row['id_topic'] : $topicId;
			}

			$smcFunc['db_free_result']($result);
		}

		if (!empty($attData))
		{
			$backupDir = $boarddir . '/ZhenMailer/' . uniqidNameZhenMailer();
			@mkdir($backupDir, 0775);
			@copy($boarddir . '/ZhenMailer/index.php', $backupDir . '/index.php');
			foreach ($attData as $data)
			{
				if (file_exists($data['path'] . '/' . strval($data['id']) . '_' . $data['file_hash'] . $ext))
				{
					$filename = preg_replace('/[^a-zA-Z0-9\-\._]/', '' , $data['filename']);
					@copy($data['path'] . '/' . strval($data['id']) . '_' . $data['file_hash'] . $ext, $backupDir . '/' . $filename);
				}

				if (!file_exists($backupDir . '/' . $filename) && !empty($modSettings['ZhenMailer_log_error']))
					log_error('[3]' . $txt['ZhenMailer_move_error'] . ' ~ ' . $filename);
				else
					$filepaths[] = array(
						'filename' => $backupDir . '/' . $filename,
						'id' => $data['id']
					);
			}

			if (!empty($filepaths))
				ZhenMailerEmailAttachment($backupDir, $filepaths, $msgID, $topicId);
		}
	}
}

function ZhenMailer_manage_mail(&$subActions)
{
	global $sourcedir, $context;

	require_once($sourcedir . '/ManageZhenMailer.php');
	$subActions += array(
		'zhenmailtemplates' => 'ZhenMailerTemplates',
		'zhenmailset' => 'ZhenMailerSettings',
		'phpconfig' => 'ZhenMailerFileCreation',
	);
}

function ZhenMailerUserInfo($id, $attribute)
{
	global $smcFunc, $context, $txt, $max_views, $modSettings, $scripturl;

	list($id, $email) = array(abs($id), '');
	$att[$id] = array(
		'id_member' => 0,
		'real_name' => '',
		$attribute => ''
	);

	$result =  $smcFunc['db_query']('', '
		SELECT {raw:attr}, real_name, id_member
		FROM {db_prefix}members
		WHERE id_member = {int:memid}
		LIMIT 1',
		array(
			'memid' => $id,
			'attr' => $attribute
		)
	);

	//$att[$id] = array();

	while ($row = $smcFunc['db_fetch_assoc']($result))
	{
		$email = $row[$attribute];
		$att[$id] = array(
			'id_member' => $row['id_member'],
			'real_name' => $row['real_name'],
			$attribute => $row[$attribute]
		);
	}

	$smcFunc['db_free_result']($result);

	return $att;
}

function ZhenMailerAttachmentId($ZhenFileHash)
{
	global $smcFunc;
	list($attId, $msgId) = array(0, 0);

	// first check if the attachment was already created
	if (!empty($ZhenFileHash))
	{
		$result =  $smcFunc['db_query']('', '
			SELECT id_attach, id_msg
			FROM {db_prefix}attachments
			WHERE file_hash = {string:fh}
			LIMIT 1',
			array(
				'fh' => $ZhenFileHash
			)
		);
		while ($row = $smcFunc['db_fetch_assoc']($result))
		{
			$attId = !empty($row['id_attach']) ? $row['id_attach'] : 0;
			$msgId = !empty($row['id_msg']) ? $row['id_msg'] : 0;
		}

		$smcFunc['db_free_result']($result);
	}

	// hash has not been created yet therefore figure out the last increment of attachment id
	if (empty($attId))
	{
		$result =  $smcFunc['db_query']('', '
			SELECT id_attach, id_msg
			FROM {db_prefix}attachments
			ORDER BY id_attach DESC
			LIMIT 1',
			array(
			)
		);
		while ($row = $smcFunc['db_fetch_assoc']($result))
		{
			$attId = !empty($row['id_attach']) ? $row['id_attach'] : 0;
			$msgId = !empty($row['id_msg']) ? $row['id_msg'] : 0;
		}

		$smcFunc['db_free_result']($result);
	}

	// message id has not been created yet therefore figure out the next increment
	if (empty($msgId))
	{
		$result =  $smcFunc['db_query']('', '
			SHOW TABLE STATUS LIKE "{db_prefix}messages"',
			array()
		);
		while ($row = $smcFunc['db_fetch_assoc']($result))
			$msgId = !empty($row['Auto_increment']) ? $row['Auto_increment'] : '';

		$smcFunc['db_free_result']($result);

		$msgId = (int)$msgId;
	}

	return array($attId, $msgId);
}

function ZhenMailerGetUserNames($emailAddrs = array())
{
	global $smcFunc;

	$emailAddrs = is_array($emailAddrs) ? $emailAddrs : array($emailAddrs);
	$realNames = array();
	$result =  $smcFunc['db_query']('', '
		SELECT member_name, real_name, email_address
		FROM {db_prefix}members
		WHERE email_address  IN ({array_string:emails})
		ORDER BY email_address ASC',
		array(
			'emails' => $emailAddrs
		)
	);
	while ($row = $smcFunc['db_fetch_assoc']($result))
	{
		$realNames[] = array(
			'email' => $row['email_address'],
			'realname' => !empty($row['real_name']) ? $row['real_name'] : $row['member_name'],
			'username' => $row['member_name']
		);
	}

	$smcFunc['db_free_result']($result);

	return $realNames;
}

function ZhenMailConvert($str, $sendhtml, $pm = false)
{
	global $modSettings, $zhenMailModSettings, $context, $boardurl, $scripturl, $mbname, $settings, $txt;

	if (empty($modSettings['ZhenMail_sendmail'])) {
		return $str;
	}

	$action = !empty($_REQUEST['action']) && is_string($_REQUEST['action']) ? strtolower($_REQUEST['action']) : '';
	$area = !empty($_REQUEST['area']) && is_string($_REQUEST['area']) ? strtolower($_REQUEST['area']) : '';
	$sa = !empty($_REQUEST['sa']) && is_string($_REQUEST['sa']) ? strtolower($_REQUEST['sa']) : '';

	if (stripos($str, '<div class="zhenmailersig">') !== FALSE && !empty($modSettings['ZhenMail_sendHTML']) && !empty($zhenMailModSettings['zhenmailer_msg_css'])) {
		$pos = stripos($str, '<div class="zhenmailersig">');
		if ($pos !== FALSE){
			$str = '<div style="' . $zhenMailModSettings['zhenmailer_msg_css'] . '">' . substr_replace($str, '</div><br><div class="zhenmailersig">', $pos, strlen('<div class="zhenmailersig">'));
		}
	}
	elseif ($action == 'admin' && $area == 'mailqueue' && $sa == 'test' && !empty($zhenMailModSettings['zhen_email_signature_body']) && allowedTo('admin_forum')) {
		$decodedSig = ZhenMailer_decode($zhenMailModSettings['zhen_email_signature_body']);
		$str .= empty($sendhtml) ? '\r\n' . strip_tags($decodedSig) : '<br><div class="zhenmailersig">' . $decodedSig . '</div>';
		$pos = stripos($str, '<div class="zhenmailersig">');
		if ($pos !== FALSE && !empty($sendhtml)) {
			$str = '<div style="' . $zhenMailModSettings['zhenmailer_msg_css'] . '">' . substr_replace($str, '</div><div class="zhenmailersig">', $pos, strlen('<div class="zhenmailersig">'));
		}
	}

	// custom filtering of email message body
	$precursoryBody = !empty($zhenMailModSettings['zhen_precursory_body']) ? ZhenMailer_decode($zhenMailModSettings['zhen_precursory_body']) : '';
	$precursoryBody = empty($sendhtml) ? strip_tags($precursoryBody) : $precursoryBody;
	$str = $precursoryBody . $str;

	if (!empty($sendhtml) && !empty($zhenMailModSettings['zhenmailer_css']) && !empty($sendhtml)) {
		$str = '<div style="' . ZhenMailer_decode($zhenMailModSettings['zhenmailer_css']) . '">' . $str .'</div>';
	}

	$str = str_replace(
		array('{BOARDURL}', '{SCRIPTURL}', '{FORUMNAME}', '{THEMEURL}', '{IMAGESURL}', '{DEFAULT_THEMEURL}'),
		array($boardurl, $scripturl, $context['forum_name'], $settings['theme_url'],  $settings['images_url'], $settings['default_theme_url']), $str);

	return $str;
}

function ZhenMailTemplates()
{
	global $modSettings, $zhenMailModSettings, $txtBirthdayEmails, $context, $txt;

	$modSettings['ZhenMail_sendmail'] = !empty($modSettings['ZhenMail_sendmail']) ? (int)$modSettings['ZhenMail_sendmail'] : 0;
	if ($modSettings['ZhenMail_sendmail'] < 1) {
		return;
	}

	$emailTxt = array('resend_activate_message', 'resend_pending_message', 'mc_group_approve', 'mc_group_reject', 'mc_group_reject_reason', 'admin_approve_accept', 'admin_approve_activation', 'admin_approve_reject', 'admin_approve_delete',
		'admin_approve_remind', 'admin_register_activate', 'admin_register_immediate', 'new_announcement', 'notify_boards_once_body', 'notify_boards_once', 'notify_boards_body', 'notify_boards', 'alert_unapproved_reply', 'unapproved_attachment',
		'alert_unapproved_post', 'alert_unapproved_topic', 'request_membership', 'paid_subscription_reminder', 'activate_reactivate', 'forgot_password', 'change_password', 'register_activate', 'register_coppa', 'register_immediate',
		'register_pending', 'notification_reply', 'notification_reply_body', 'notification_reply_once', 'notification_reply_body_once', 'new_pm_body', 'new_pm_tolist', 'new_pm_body_tolist', 'admin_notify', 'notification_sticky',
		'notification_lock', 'notification_unlock', 'notification_remove', 'notification_move', 'notification_merge', 'notification_split', 'admin_notify_approval', 'admin_attachments_full', 'paid_subscription_refund', 'paid_subscription_new',
		'paid_subscription_error', 'msg_quote', 'msg_mention'
	);

	// define empty values as default
	$txtBirthdayEmails['happy_birthday_subject'] = !empty($txtBirthdayEmails['happy_birthday_subject']) ? $txtBirthdayEmails['happy_birthday_subject'] : '';
	$txtBirthdayEmails['happy_birthday_body'] = !empty($txtBirthdayEmails['happy_birthday_body']) ? $txtBirthdayEmails['happy_birthday_body'] : '';
	$txt['regards_team'] = !empty($txt['regards_team']) ? $txt['regards_team'] : '';

	// the main email body is stripped of tags if HTML decoding is disabled
	foreach ($emailTxt as $email) {
		$txt[$email . '_subject'] = !empty($txt[$email . '_subject']) ? $txt[$email . '_subject'] : '';
		$txt[$email . '_body'] = !empty($txt[$email . '_body']) ? $txt[$email . '_body'] : '';

		if ($modSettings['ZhenMail_sendmail'] < 3 && !empty($modSettings['ZhenMail_sendHTML'])) {
			$txt[$email . '_subject'] = !empty($zhenMailModSettings['zhen_' . $email . '_subject']) ? ZhenMailer_decode($zhenMailModSettings['zhen_' . $email . '_subject']) : $txt[$email . '_subject'];
			$txt[$email . '_body'] = !empty($zhenMailModSettings['zhen_' . $email . '_body']) ? ZhenMailer_decode($zhenMailModSettings['zhen_' . $email . '_body']) : $txt[$email . '_body'];
		}
		elseif ($modSettings['ZhenMail_sendmail'] < 3) {
			$txt[$email . '_subject'] = !empty($zhenMailModSettings['zhen_' . $email . '_subject']) ? strip_tags(ZhenMailer_decode($zhenMailModSettings['zhen_' . $email . '_subject'])) : $txt[$email . '_subject'];
			$txt[$email . '_body'] = !empty($zhenMailModSettings['zhen_' . $email . '_body']) ? strip_tags(ZhenMailer_decode($zhenMailModSettings['zhen_' . $email . '_body'])) : $txt[$email . '_body'];
		}
		elseif ($modSettings['ZhenMail_sendmail'] == 3 && !empty($modSettings['ZhenMail_sendHTML'])) {
			$txt[$email . '_subject'] = ZhenMailer_decode($txt[$email . '_subject']);
			$txt[$email . '_body'] = ZhenMailer_decode($txt[$email . '_body']);
		}
		elseif ($modSettings['ZhenMail_sendmail'] == 3) {
			$txt[$email . '_subject'] = strip_tags(ZhenMailer_decode($txt[$email . '_subject']));
			$txt[$email . '_body'] = strip_tags(ZhenMailer_decode($txt[$email . '_body']));
		}
	}

	// birthday & signature
	if ($modSettings['ZhenMail_sendmail'] < 3 && !empty($modSettings['ZhenMail_sendHTML'])) {
		$txtBirthdayEmails['happy_birthday_subject'] = !empty($zhenMailModSettings['zhen_happy_birthday_subject']) ? ZhenMailer_decode($zhenMailModSettings['zhen_happy_birthday_subject']) : $txtBirthdayEmails['happy_birthday_subject'];
		$txtBirthdayEmails['happy_birthday_body'] = !empty($zhenMailModSettings['zhen_happy_birthday_body']) ? ZhenMailer_decode($zhenMailModSettings['zhen_happy_birthday_body']) : $txtBirthdayEmails['happy_birthday_body'];
		$decodedSig = !empty($zhenMailModSettings['zhen_email_signature_body']) ? '<div class="zhenmailersig">' . ZhenMailer_decode($zhenMailModSettings['zhen_email_signature_body']) . '</div>' : '';
	}
	elseif ($modSettings['ZhenMail_sendmail'] < 3 && empty($modSettings['ZhenMail_sendHTML'])) {
		$txtBirthdayEmails['happy_birthday_subject'] = !empty($zhenMailModSettings['zhen_happy_birthday_subject']) ? strip_tags(ZhenMailer_decode($zhenMailModSettings['zhen_happy_birthday_subject'])) : $txtBirthdayEmails['happy_birthday_subject'];
		$txtBirthdayEmails['happy_birthday_body'] = !empty($zhenMailModSettings['zhen_happy_birthday_body']) ? strip_tags(ZhenMailer_decode($zhenMailModSettings['zhen_happy_birthday_body'])) : $txtBirthdayEmails['happy_birthday_body'];
		$decodedSig = !empty($zhenMailModSettings['zhen_email_signature_body']) ? strip_tags(ZhenMailer_decode($zhenMailModSettings['zhen_email_signature_body'])) : '';
	}
	elseif ($modSettings['ZhenMail_sendmail'] == 3 && !empty($modSettings['ZhenMail_sendHTML'])) {
		$txtBirthdayEmails['happy_birthday_subject'] =ZhenMailer_decode($txtBirthdayEmails['happy_birthday_subject']);
		$txtBirthdayEmails['happy_birthday_body'] = ZhenMailer_decode($txtBirthdayEmails['happy_birthday_body']);
		$decodedSig = !empty($zhenMailModSettings['zhen_email_signature_body']) ? '<div class="zhenmailersig">' . ZhenMailer_decode($zhenMailModSettings['zhen_email_signature_body']) . '</div>' : '';
	}
	elseif ($modSettings['ZhenMail_sendmail'] == 3) {
		$txtBirthdayEmails['happy_birthday_subject'] = strip_tags($txtBirthdayEmails['happy_birthday_subject']);
		$txtBirthdayEmails['happy_birthday_body'] = strip_tags($txtBirthdayEmails['happy_birthday_body']);
		$decodedSig = !empty($zhenMailModSettings['zhen_email_signature_body']) ? strip_tags(ZhenMailer_decode($zhenMailModSettings['zhen_email_signature_body'])) : '';
	}

	// signature ~ add an argument at the end to be removed later
	$decodedSig = !empty($decodedSig) ? str_replace('{FORUMNAME}', $context['forum_name'], $decodedSig) : '';
	$txt['regards_team'] = !empty($decodedSig) ? str_ireplace(array('<br/>', '<br>', '<br />'), "\n", ltrim($decodedSig)) : (strpos($txt['regards_team'], '%1$s') !== FALSE ? sprintf($txt['regards_team'], $context['forum_name']) : $txt['regards_team']);
}

function updateZhenMailSettings($changeArray, $update = false)
{
	global $zhenMailModSettings, $smcFunc;

	if (empty($changeArray) || !is_array($changeArray))
		return;

	$toRemove = array();
	foreach ($changeArray as $k => $v)
		if ($v === null)
		{
			unset($changeArray[$k]);
			$toRemove[] = $k;
		}

	if (!empty($toRemove))
		$smcFunc['db_query']('', '
			DELETE FROM {db_prefix}zhenmail_modsettings
			WHERE variable IN ({array_string:remove})',
			array(
				'remove' => $toRemove,
			)
		);

	if ($update)
	{
		$existing = array();
		$request = $smcFunc['db_query']('', '
			SELECT variable
			FROM {db_prefix}zhenmail_modsettings
			WHERE variable IN ({array_string:vars})',
			array(
				'vars' => array_keys($changeArray),
			)
		);

		while ($row = $smcFunc['db_fetch_row']($request)) {
			if (!empty($row['variable']))
				$existing[] = $row['variable'];
		}
		$smcFunc['db_free_result']($request);
		foreach ($changeArray as $variable => $value)
		{
			if (!in_array($variable, $existing)) {
				$smcFunc['db_insert']('replace',
					'{db_prefix}zhenmail_modsettings',
					array('variable' => 'string-255', 'value' => 'string-65534'),
					array($variable, $value),
					array('variable')
				);
			}
			else {
				$smcFunc['db_query']('', '
					UPDATE {db_prefix}zhenmail_modsettings
					SET value = {' . ($value === false || $value === true ? 'raw' : 'string') . ':value}
					WHERE variable = {string:variable}',
					array(
						'value' => $value === true ? 'value + 1' : ($value === false ? 'value - 1' : $value),
						'variable' => $variable,
					)
				);
			}
			$zhenMailModSettings[$variable] = $value === true ? $zhenMailModSettings[$variable] + 1 : ($value === false ? $zhenMailModSettings[$variable] - 1 : $value);
		}

		return;
	}

	$replaceArray = array();
	foreach ($changeArray as $variable => $value)
	{
		if (isset($zhenMailModSettings[$variable]) && $zhenMailModSettings[$variable] == $value)
			continue;
		elseif (!isset($zhenMailModSettings[$variable]) && empty($value))
			continue;

		$replaceArray[] = array($variable, $value);

		$zhenMailModSettings[$variable] = $value;
	}

	if (empty($replaceArray))
		return;

	$smcFunc['db_insert']('replace',
		'{db_prefix}zhenmail_modsettings',
		array('variable' => 'string-255', 'value' => 'string-65534'),
		$replaceArray,
		array('variable')
	);
}

function loadZhenMailModSettings()
{
	global $zhenMailModSettings, $smcFunc;

	$request = $smcFunc['db_query']('', '
		SELECT variable, value
		FROM {db_prefix}zhenmail_modsettings',
		array(
		)
	);
	$zhenMailModSettings = array();
	if (!empty($request)) {
		foreach ($smcFunc['db_fetch_all']($request) as $row)
			$zhenMailModSettings[$row['variable']] = $row['value'];
	}
	$smcFunc['db_free_result']($request);
}

function ZhenMailer_digest_email(&$email, $types, $notify_types, $langtxt)
{
	global $txt, $mbname, $context, $zhenMailModSettings, $txtBirthdayEmails;

	if (strpos($txt['regards_team'], '%1$s') !== FALSE) {
		ZhenMailTemplates();
	}
}

function ZhenMailer_decode($str)
{
	global $context;

	$charset = !empty($context['character_set']) ? $context['character_set'] : 'UTF-8';
	$ret = html_entity_decode($str, ENT_COMPAT, $charset);
	$p2 = -1;
	for(;;)
	{
		$p = strpos($ret, '&#', $p2+1);
		if ($p === false)
		    break;
		$p2 = strpos($ret, ';', $p);
		if ($p2 === false)
		    break;

		if (substr($ret, $p+2, 1) == 'x')
		    $char = hexdec(substr($ret, $p+3, $p2-$p-3));
		else
		    $char = intval(substr($ret, $p+2, $p2-$p-2));

		$newchar = iconv(
			'UCS-4', 'UTF-8',
			chr(($char>>24)&0xFF).chr(($char>>16)&0xFF).chr(($char>>8)&0xFF).chr($char&0xFF)
		);

		$ret = substr_replace($ret, $newchar, $p, 1+$p2-$p);
		$p2 = $p + strlen($newchar);
	}

	$content = un_htmlspecialchars($ret);
	$content = preg_replace('/\xc2\xa0/', ' ', $content);
	return htmlspecialchars_decode($content, ENT_QUOTES|ENT_SUBSTITUTE|ENT_HTML5);
}

?>