<?php
/*****************************************************************************
 * Email.php
 * Contains key class Email.
 *
 * Kabuki CMS (C) 2013-2016, Aaron van Geffen
 *****************************************************************************/

class Email
{
	public static function send($address, $addressee, $subject, $body, $headers = '')
	{
		// Set a boundary.
		$boundary = uniqid('sr');

		if (empty($headers))
			$headers .= "From: " . SITE_TITLE . " <" . REPLY_TO_ADDRESS . ">\r\n";

		// Set up headers.
		$headers .= "MIME-Version: 1.0\r\n";
		$headers .= "Content-Type: multipart/alternative;boundary=$boundary\r\n";

		// Start the message with a plaintext version of the mail.
		$message = "This is a MIME encoded message.";
		$message .= "\r\n\r\n--$boundary\r\n";
		$message .= "Content-type: text/plain;charset=utf-8\r\n\r\n";
		$message .= self::wrapLines($body);

		// Autolink URLs and wrap lines.
		$html_body = preg_replace('~\b(?!")https?://[^"\s]+~', '<a href="$0">$0</a>', $body);
		$html_body = preg_replace('~(\s+)(www\..+\.[^"\s]+?)(\.|\s+)~', '$1<a href="https://$2">$2</a>$3', $html_body);
		$html_body = preg_replace('~={10,}~', '<hr>', $html_body);
		$html_body = self::wrapLines(str_replace("\r", "<br>\r", $html_body), 80, "\r\n");

		// Then, more excitingly, add an HTML version!
		$message .= "\r\n\r\n--" . $boundary . "\r\n";
		$message .= "Content-type: text/html;charset=utf-8\r\n\r\n";
		$message .= "<html>\r\n<head><style type=\"text/css\">\r\nbody { font: 13px Helvetica, Arial, sans-serif; }\r\n</style></head>\r\n<body><p>" .
			$html_body . "</p></body>\r\n</html>";

		// End off with a final boundary.
		$message .= "\r\n\r\n--" . $boundary . "--";

		if (DEBUG)
			return file_put_contents(BASEDIR . '/mail_dumps.txt', "To: \"$addressee\" <$address>\r\n$headers\r\nSubject: $subject\r\n" . self::wrapLines($message), FILE_APPEND);
		else
			return mail("\"$addressee\" <$address>", $subject, $message, $headers);
	}

	public static function wrapLines($body, $maxlength = 80, $break = "\r\n")
	{
		$lines = explode("\n", $body);
		$wrapped = "";
		foreach ($lines as $line)
			$wrapped .= wordwrap($line, $maxlength, $break) . $break;
		return $wrapped;
	}

	private static function parseTemplate($template, $replacements)
	{
		$replacement_keys = array_map(function($el) { return "%$el%"; }, array_keys($replacements));
		$subject = str_replace($replacement_keys, array_values($replacements), $template['subject']);
		$body = str_replace($replacement_keys, array_values($replacements), $template['body']);
		return [$subject, $body];
	}

	public static function resetMail($id_user)
	{
		$row = Registry::get('db')->queryAssoc('
			SELECT first_name, surname, emailaddress, reset_key
			FROM users
			WHERE id_user = {int:id_user}',
			[
				'id_user' => $id_user,
			]);

		if (empty($row))
			return false;


		list($subject, $body) = self::parseTemplate([
			'subject' => 'Information on how to reset your HashRU password',
			'body' => str_replace("\n", "\r\n", 'Dear %FIRST_NAME%,

You are receiving this email because a password reset request was issued on our website.

If you did not request a password reset, please disregard this email. Otherwise, please follow the link below.

%RESET_LINK%

The HashRU Pics team'),
		], [
			'FIRST_NAME' => $row['first_name'],
			'RESET_LINK' => BASEURL . '/resetpassword/?step=2&email=' . rawurlencode($row['emailaddress']) . '&key=' . $row['reset_key'],
		]);

		$addressee = trim($row['first_name'] . ' ' . $row['surname']);
		self::send($row['emailaddress'], $addressee, $subject, $body);
	}
}