<?php
if(!(is_readable(realpath(dirname(__FILE__)).'/log.inc'))) {
	die('Error - Could not open or read file '.realpath(dirname(__FILE__)).'/log.inc');
} else {
	include_once(realpath(dirname(__FILE__)).'/log.inc');
}
if (!function_exists('mb_str_replace')) {
	function mb_str_replace($search, $replace, $subject, &$count = 0) {
		if (!is_array($subject)) {
			$searches = is_array($search) ? array_values($search) : array($search);
			$replacements = is_array($replace) ? array_values($replace) : array($replace);
			$replacements = array_pad($replacements, count($searches), '');

			foreach ($searches as $key => $search) {
				$parts = mb_split(preg_quote($search), $subject);
				$count += count($parts) - 1;
				$subject = implode($replacements[$key], $parts);
			}
		} else {
			foreach ($subject as $key => $value) {
				$subject[$key] = mb_str_replace($search, $replace, $value, $count);
			}
		}

		return $subject;
	}
}

function logmailevent($msg){
	if (GetSetting('portal','log.sendemails',0) == 1 ) {
		logmessage($msg);
	}
}

if ( getSetting('smtp','username','') == '' || getSetting('smtp','password','') == '' ) {
	if(!(is_readable(realpath(dirname(__FILE__)).'/mail.anon.inc'))) {
		die('Error - Could not open or read file '.realpath(dirname(__FILE__)).'/mail.anon.inc');
	} else {
		include_once(realpath(dirname(__FILE__)).'/mail.anon.inc');
	}
} else if (mb_strtolower(mb_substr(getSetting('smtp','host',''), 0, 6)) == 'ssl://' ) {
	if(!(is_readable(realpath(dirname(__FILE__)).'/mail.ssl.inc'))) {
		die('Error - Could not open or read file '.realpath(dirname(__FILE__)).'/mail.ssl.inc');
	} else {
		include_once(realpath(dirname(__FILE__)).'/mail.ssl.inc');
	}
} else {
	if(!(is_readable(realpath(dirname(__FILE__)).'/mail.auth.inc'))) {
		die('Error - Could not open or read file '.realpath(dirname(__FILE__)).'/mail.auth.inc');
	} else {
		include_once(realpath(dirname(__FILE__)).'/mail.auth.inc');
	}
}

function getPortalMainLinkToSignature(){
	return '<a href="'.getSetting('portal','url',getCurPageURLWO()).'">'.GetSetting('company','portalname','BUSINESS STUDIO PORTAL').'</a>';
}

function defaultLangExt(){
	$cn = db_connect();
	$langf = db_getDefaultLangShortName($cn);
	if ($cn) {db_disconnect($cn);}
	return $langf;
}

function getTemplate($filename, $lang, &$file){
	$file = realpath(dirname(__FILE__).'/../').$filename.$lang;
  if (is_readable($file)) return true;
	$file = realpath(dirname(__FILE__).'/../').$filename.getLanguage();
  if (is_readable($file)) return true;
	logmessage('Error - not found template file for mail '.$filename);
	return false;
}

function replacePattern($inputString, $params){
  $search = array('portal:main', 'portal:logo');
  $replace = array(getPortalMainLinkToSignature(), src_picture());//encode64_picture
  foreach ($params as $key => $value){
    array_push($search, $key);
    array_push($replace, $value);
  }    
  return mb_str_replace($search, $replace, $inputString);
}

function addCustomMailCSSToBody($body){
	//61448
	$css = "";
	if((is_readable(realpath(dirname(__FILE__).'/../').'/css/mail.css'))) {
		$css = file_get_contents(realpath(dirname(__FILE__).'/../').'/css/mail.css');
	}
	return "<head><style>".$css."</style></head> ".mb_str_replace("<body>", "<body class='mail-css'> <style>".$css."</style>", $body);
}

function createMailUncompletedPoll($email, $subject, $pollname, $url, $lang, $username = '[not set]', $finishdate){
	$result = false;
  	if (getTemplate('/templates/mail/poll/pollUncompleted'.(isset($finishdate) && $finishdate !="" ? "WithDate" : "").'.', $lang, $file)){
    	$params = array('portal:url'=>$url, 'poll:name'=>$pollname, 'poll:main'=>'<a href="'.$url.'">'.$pollname.'</a>', 'poll:finishdate'=>$finishdate);
		$subject = replacePattern($subject, $params);
		$body = addCustomMailCSSToBody( replacePattern(file_get_contents($file),$params) );
		$idmaitype = 1000; // pollUncompleted
    	$cn = db_connect();
		$result = db_insertMailInQueue($cn, $idmaitype, $email, $username, $subject, $body); 
	}
	return $result;
}

function createMailNewPoll($email, $subject, $pollname, $url, $lang, $username = '[not set]', $finishdate){
	$result = false;
  	if (getTemplate('/templates/mail/poll/pollNew'.(isset($finishdate) && $finishdate !="" ? "WithDate" : "").'.', $lang, $file)){
    	$params = array('portal:url'=>$url, 'poll:name'=>$pollname, 'poll:main'=>'<a href="'.$url.'">'.$pollname.'</a>', 'poll:finishdate'=>$finishdate);
		$subject = replacePattern($subject, $params);
		$body = addCustomMailCSSToBody( replacePattern(file_get_contents($file),$params) );
		$idmaitype = 200; // pollNew
    	$cn = db_connect();
		$result = db_insertMailInQueue($cn, $idmaitype, $email, $username, $subject, $body); 
	}
	return $result;
}

function createMailDeletePoll($email, $subject, $pollname, $url, $lang, $username = '[not set]'){
	$result = false;
  if (getTemplate('/templates/mail/poll/pollDelete.', $lang, $file)){
    $params = array('portal:url'=>$url, 'poll:name'=>$pollname, 'poll:main'=>'<a href="'.$url.'">'.$pollname.'</a>');
		$subject = replacePattern($subject, $params);
		$body = addCustomMailCSSToBody( replacePattern(file_get_contents($file),$params) );
		$idmaitype = 600; // pollDelete
   	$cn = db_connect();
		$result = db_insertMailInQueue($cn, $idmaitype, $email, $username, $subject, $body); 
	}
	return $result;
}

function createMailStopPoll($email, $subject, $pollname, $url, $lang, $username = '[not set]'){
	$result = false;
  if (getTemplate('/templates/mail/poll/pollStop.', $lang, $file)){
    $params = array('portal:url'=>$url, 'poll:name'=>$pollname, 'poll:main'=>'<a href="'.$url.'">'.$pollname.'</a>');
		$subject = replacePattern($subject, $params);
		$body = addCustomMailCSSToBody( replacePattern(file_get_contents($file),$params) );
		$idmaitype = 700; // pollStop
   	$cn = db_connect();
		$result = db_insertMailInQueue($cn, $idmaitype, $email, $username, $subject, $body); 
	}
	return $result;
}

function createMailContinuePoll($email, $subject, $pollname, $url, $lang, $username = '[not set]', $finishdate){
	$result = false;
  	if (getTemplate('/templates/mail/poll/pollContinue'.(isset($finishdate) && $finishdate !="" ? "WithDate" : "").'.', $lang, $file)){
    	$params = array('portal:url'=>$url, 'poll:name'=>$pollname, 'poll:main'=>'<a href="'.$url.'">'.$pollname.'</a>', 'poll:finishdate'=>$finishdate);
		$subject = replacePattern($subject, $params);
		$body = addCustomMailCSSToBody( replacePattern(file_get_contents($file),$params) );
		$idmaitype = 800; // pollContinue
   		$cn = db_connect();
		$result = db_insertMailInQueue($cn, $idmaitype, $email, $username, $subject, $body); 
	}
	return $result;
}

function createMailHidePoll($email, $subject, $pollname, $url, $lang, $username = '[not set]'){
	$result = false;
  if (getTemplate('/templates/mail/poll/pollHide.', $lang, $file)){
    $params = array('portal:url'=>$url, 'poll:name'=>$pollname, 'poll:main'=>'<a href="'.$url.'">'.$pollname.'</a>');
		$subject = replacePattern($subject, $params);
		$body = addCustomMailCSSToBody( replacePattern(file_get_contents($file),$params) );
		$idmaitype = 900; // pollHide
    $cn = db_connect();
		$result = db_insertMailInQueue($cn, $idmaitype, $email, $username, $subject, $body); 
	}
	return $result;
}

function createMailNewPollAnalyst($email, $subject, $pollname, $url, $lang, $username = '[not set]'){

	$result = false;
  if (getTemplate('/templates/mail/poll/pollNewAnalyst.', $lang, $file)){
    $params = array('portal:url'=>$url, 'poll:name'=>$pollname, 'poll:main'=>'<a href="'.$url.'">'.$pollname.'</a>');
		$subject = replacePattern($subject, $params);
		$body = addCustomMailCSSToBody( replacePattern(file_get_contents($file),$params) );
		$idmaitype = 300; // pollNewAnalyst
    $cn = db_connect();
		$result = db_insertMailInQueue($cn, $idmaitype, $email, $username, $subject, $body); 
	}
	return $result;
}

function createMailPollContainsErrorsAnalyst($email, $subject, $pollname, $url, $lang, $username = '[not set]'){
	$result = false;
	if (getTemplate('/templates/mail/poll/pollContainsErrors.', $lang, $file)){
    $params = array('portal:url'=>$url, 'poll:name'=>$pollname, 'poll:main'=>'<a href="'.$url.'">'.$pollname.'</a>');
		$subject = replacePattern($subject, $params);
		$body = addCustomMailCSSToBody( replacePattern(file_get_contents($file),$params) );
		$idmaitype = 400; // pollContainsErrors
	  $cn = db_connect();
		$result = db_insertMailInQueue($cn, $idmaitype, $email, $username, $subject, $body); 
	}
	return $result;
}

function createMailPollContainsErrorsAnalystAdmin($email, $subject, $pollname, $url, $lang, $username = '[not set]'){
	$result = false;
  if (getTemplate('/templates/mail/poll/pollContainsErrorsAdmin.', $lang, $file)){
    $params = array('portal:url'=>$url, 'poll:name'=>$pollname, 'poll:main'=>'<a href="'.$url.'">'.$pollname.'</a>');
		$subject = replacePattern($subject, $params);
		$body = addCustomMailCSSToBody( replacePattern(file_get_contents($file),$params) );
		$idmaitype = 500; // pollContainsErrorsAdmin
    $cn = db_connect();
		$result = db_insertMailInQueue($cn, $idmaitype, $email, $username, $subject, $body); 
	}
	return $result;
}

function createMailNewPollAdmin($email, $subject, $pollname, $url, $lang, $username = '[not set]'){
	$result = false;
  if (getTemplate('/templates/mail/poll/pollNewAdmin.', $lang, $file)){
    $params = array('portal:url'=>$url, 'poll:name'=>$pollname, 'poll:main'=>'<a href="'.$url.'">'.$pollname.'</a>');
		$subject = replacePattern($subject, $params);
		$body = addCustomMailCSSToBody( replacePattern(file_get_contents($file),$params) );
		$idmaitype = 400; // pollNewAdmin
    $cn = db_connect();
		$result = db_insertMailInQueue($cn, $idmaitype, $email, $username, $subject, $body); 
	}
	return $result;
}

function sendNewForumMessage($email, $subject, $objname, $url, $lang, $username = '[not set]', $forummessagebody = '', $forummessageuser = '', $forummessagedate = ''){
	$result = false;
  if (getTemplate('/templates/mail/newforummessage.', $lang, $file)){
    $params = array('portal:url'=>$url, 'object:name'=>$objname, 'portal:forummessagebody'=>$forummessagebody, 'portal:forummessageuser'=>$forummessageuser, 'portal:forummessagedate'=>$forummessagedate);
		$subject = replacePattern($subject, $params);
		$body = addCustomMailCSSToBody( replacePattern(file_get_contents($file),$params) );
    $result = smtpmail($email, $subject, $body, $username);
	}
	return $result;
}

function sendNotificateMessage($email, $subject, $mailbody, $lang, $username = '[not set]'){
	$result = false;
  if (getTemplate('/templates/mail/newobject.', $lang, $file)){
    $params = array('portal:body'=>$mailbody);
		$subject = replacePattern($subject, $params);
		$body = addCustomMailCSSToBody( replacePattern(file_get_contents($file),$params) );
    $result = smtpmail($email, $subject, $body, $username);
	}
	return $result;
}

function sendReportUploadedMessage($email, $subject, $objname, $url, $lang, $username = '[not set]'){
	$result = false;
  if (getTemplate('/templates/mail/reportuploaded.', $lang, $file)){
    $params = array('portal:url'=>$url, 'object:name'=>$objname);
		$subject = replacePattern($subject, $params);
		$body = addCustomMailCSSToBody( replacePattern(file_get_contents($file),$params) );
    $result = smtpmail($email, $subject, $body, $username);
	}
	return $result;
}

function sendPortalStartMessage($email, $subject, $url, $lang, $username = '[not set]'){
	$result = false;
  logmessage(print_r($email, true));
  logmessage(print_r($subject, true));
  logmessage(print_r($url, true));
  logmessage(print_r($lang, true));
  logmessage(print_r($username, true));
  if (getTemplate('/templates/mail/portalstarted.', $lang, $file)){
    $params = array('portal:url'=>$url);
		$subject = replacePattern($subject, $params);
  logmessage(print_r($file, true));
  logmessage(print_r(file_get_contents($file), true));
		$body = addCustomMailCSSToBody( replacePattern(file_get_contents($file),$params) );
    $result = smtpmail($email, $subject, $body, $username);
	}
	return $result;
}

function sendPortalStopOnErrorMessage($email, $subject, $url, $lang, $username = '[not set]'){
	$result = false;
  if (getTemplate('/templates/mail/portalstoppedonerror.', $lang, $file)){
    $params = array('portal:url'=>$url);
		$subject = replacePattern($subject, $params);
		$body = addCustomMailCSSToBody( replacePattern(file_get_contents($file),$params) );
    $result = smtpmail($email, $subject, $body, $username);
	}
	return $result;
}

function sendTestEmail($email, $subject, $lang, $username = '[not set]'){
	$result = false;
	if (getTemplate('/templates/mail/portaltestmessage.', $lang, $file)){
		$params = array();
		$subject = replacePattern($subject, $params);
		$body = addCustomMailCSSToBody( replacePattern(file_get_contents($file),$params) );
        $result = smtpmail($email, $subject, $body, $username);		
	}else{
		logmessage('Error - not found template file for mail portaltestmessage');
	}
	return $result;
}


function src_picture(){
	return '<img src="'.getSetting('portal', 'url', $_SERVER['HTTP_HOST']).'/img/logo-bsp.png">';
}

function encode64_picture(){
	$file = realpath(dirname(__FILE__).'/../').'/img/logo-bsp.png';
    $extension = explode(".", $file);
    $extension = end($extension);
    $binary = fread(fopen($file, "r"), filesize($file));
	//'<img src="'.getSetting('portal', 'url', $_SERVER['HTTP_HOST']).'/img/logo-bsp.png">'
    return '<img src="data:image/'.$extension.';base64,'.base64_encode($binary).'"/>';
}

?>
