<?php
include_once('includes/PHPMail_master/src/PHPMailer.php');
/*
	There are two different ways of sending e-mails
	1. Function send_mail() where you pass an array of data
	
	2. By dc_email class, that is set up in steps and is sent by calling dc_email->Send
*/


/*
$Mail = new dc_email("me@gmail.com","Test Subject");
$Mail->setTo("someone@gmail.com");
$Mail->setSubject("Hello from me");
$Mail->setBody("Hello! Image is below:<br>".$Mail->embedImage("php.gif")."Testing...<br>\n");
$Mail->setFrom("me@gmail.com"); // Optional
$Mail->Send();
*/

class dc_email {

	public $from = "";
	public $to = "";
	public $subject = "";
	public $body = "";

	public $boundaryRelated = "";
	public $boundaryMessageTypes = "";
	public $parts = array();

	public function __construct() {

		$this->boundaryRelated       = "==========RELATED".time()."==";

		$this->boundaryMessageTypes  = "==========MSGTYPES".time()."==";

		$from = getenv('EMAIL_FROM');
		
		$this->setFrom($from);
	}



	public function Send($return_command_as_string = false) {

		// Build $headers

		$headers = "";

		if($this->from) $headers .= "From: ".$this->from."\n";

		$headers .= "MIME-Version: 1.0\n";

		$headers .= "Content-Type: multipart/related;\n  boundary=\"".$this->boundaryRelated."\"\n";



		// Build structure

		$newbody = "This is a multi-part message in MIME format.\n";

		$newbody .= "--".$this->boundaryRelated . "\n";



		// Build HTML content

		$newbody .= "Content-Type: multipart/alternative;\n  boundary=\"".$this->boundaryMessageTypes."\"\n";

		$newbody .= "MIME-Version 1.0\n\n";

		$newbody .= "--".$this->boundaryMessageTypes."\n";

		$newbody .= $this->body[0] . "\n";

		$newbody .= "MIME-Version 1.0\n\n";

		$newbody .= $this->body[1] . "\n\n";

		$newbody .= "--".$this->boundaryMessageTypes."--\n";



		// Add images

		foreach($this->parts as $part) {

			$contentHeader = $part[0];

			$content = $part[1];

			$newbody .= "--".$this->boundaryRelated."\n";

			$newbody .= $contentHeader . "\n\n";

			$newbody .= $content . "\n\n";

		}

		$newbody .= "--".$this->boundaryRelated."--";

		mail($this->to,$this->subject,$newbody,$headers);

		if($return_command_as_string) {
			return "mail(\"".$this->to."\",\"".$this->subject."\",\"".$newbody."\",\"".$headers."\");\n";
		}
	}



	public function setTo($address) { $this->to = trim($address); }

	public function setFrom($address) { $this->from = trim($address); }

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

	public function setBody($content) { 

		$this->body = array("Content-Type: text/html; charset=\"UTF-8\"",trim($content));

	}



	public function embedImage($image,$cid = "",$style = "") { 

		$data = file_get_contents($image);

		$name = basename($image);

		if($cid == "") $cid = preg_replace("/[^a-zA-Z0-9]/","_",$name);

		if(strpos($cid,"@") == false) $cid .= "@gr8gonzosmailwrapper";

		$this->parts[] = array(

		  "Content-Type: ".mime_content_type($image)."; name=\"$name\"\n" . 

		  "Content-Transfer-Encoding: base64\n" . 

		  "Content-ID: <{$cid}>\n" . 

		  "Content-Disposition: attachment;\n" . 

		  " filename=\"$name\"", 

		  chunk_split( base64_encode($data), 68, "\n")); 

		return "<img src=\"cid:{$cid}\" style='{$style}'>"; 

	}

}


if(!function_exists('mime_content_type')) {

    function mime_content_type($filename) {
        $mime_types = array(
            'txt' => 'text/plain',
            'htm' => 'text/html',
            'html' => 'text/html',
            'php' => 'text/html',
            'css' => 'text/css',
            'js' => 'application/javascript',
            'json' => 'application/json',
            'xml' => 'application/xml',
            'swf' => 'application/x-shockwave-flash',
            'flv' => 'video/x-flv',

            // images
            'png' => 'image/png',
            'jpe' => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'jpg' => 'image/jpeg',
            'gif' => 'image/gif',
            'bmp' => 'image/bmp',
            'ico' => 'image/vnd.microsoft.icon',
            'tiff' => 'image/tiff',
            'tif' => 'image/tiff',
            'svg' => 'image/svg+xml',
            'svgz' => 'image/svg+xml',

            // archives
            'zip' => 'application/zip',
            'rar' => 'application/x-rar-compressed',
            'exe' => 'application/x-msdownload',
            'msi' => 'application/x-msdownload',
            'cab' => 'application/vnd.ms-cab-compressed',

            // audio/video
            'mp3' => 'audio/mpeg',
            'qt' => 'video/quicktime',
            'mov' => 'video/quicktime',

            // adobe
            'pdf' => 'application/pdf',
            'psd' => 'image/vnd.adobe.photoshop',
            'ai' => 'application/postscript',
            'eps' => 'application/postscript',
            'ps' => 'application/postscript',

            // ms office
            'doc' => 'application/msword',
            'rtf' => 'application/rtf',
            'xls' => 'application/vnd.ms-excel',
            'ppt' => 'application/vnd.ms-powerpoint',

            // open office
            'odt' => 'application/vnd.oasis.opendocument.text',
            'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
        );

        $ext = strtolower(array_pop(explode('.',$filename)));

        if (array_key_exists($ext, $mime_types)) {
            return $mime_types[$ext];
        } elseif (function_exists('finfo_open')) {

            $finfo = finfo_open(FILEINFO_MIME);

            $mimetype = finfo_file($finfo, $filename);

            finfo_close($finfo);

            return $mimetype;
        } else {
            return 'application/octet-stream';
        }
    }
}


function send_mail($variables) {
	/*
		$variables['to'] = array of recipients
		$variables['subject'] = subject of mail
		$variables['message'] = message to send
		$variables['html'] = true (default)/false 
		
		$variables['charset'] = true (default)/false 
		
	*/
	
	$to = $variables['to'];
	
	$subject = $variables['subject'];
	
	$message = $variables['message'];
	
	/*
	$message = "
	<html><head></head>
	<body>
	".$variables['message']."
	</body>
	</html>
	";
	*/
	
	$headers = array(
		'From' => 'projects@hfkf.fi',
		'X-Mailer' => 'PHP/'.phpversion()
	);
	
	if(isset($variables['html']) ? $variables['html'] : false) {
		// To send HTML mail, the Content-type header must be set
		$headers['MIME-Version'] = '1.0';
		
		// Next part should be upgraded to check for valid charsets as well
		if(isset($variables['charset'])) {
			$headers['Content-type'] = 'text/html; charset='.$variables['charset'];
		} else {
			$headers['Content-type'] = 'text/html; charset=utf-8';
		}
	} else {
		
	}
	
	if(isset($variables['html']) ? $variables['html'] : false) {
		$message = str_replace("\r\n", "<br>", $message);
		$returndata = mail($to, $subject, $message, $headers);
	} else {
		$returndata = mail($to, $subject, $message, $headers);
	}
	
	return $returndata;
}

function get_send_mail_settings() {
	$query = "SELECT * FROM system_settings WHERE system_setting_name='send_mail'";
	
	$result = run_query($query);
	
	if($result) {
		while($row = $result->fetch_assoc()) {
			$returndata  = array('from' => $row['system_setting_value_1']);
		}
	} else {
		$returndata = false;
	}
	
	return $returndata;
}

function send_test_mail() {

	$variables = array('to_get' => 'post');
	$form_values = get_url_variables($variables);

	$message = "<div style='width:100%;float:left;text-align:center;font-size:150%;font-weight:bold;'><h1>Test mail</h1></div>";
	$message = "<div style='width:100%;float:left;'>This is a test mail!</div>";
	
	$variables = array('to' => $form_values['to'], 'subject' => 'Test mail', 'message' => $message);
	$result = send_mail($variables);
	
	if($result) {
		$_SESSION['system']['popups']['que'][] = array('alerttype' => "alert-success", 'message' => 'Mail sent successfully!');
	} else {
		// Create error message
		$_SESSION['system']['popups']['que'][] = array('alerttype' => "alert-warning", 'message' => 'Could not send test mail!');
	}
}
