Your IP : 216.73.216.249


Current Path : /home/jeromecohp/www/administrator/components/com_emailbeautifier/
Upload File :
Current File : /home/jeromecohp/www/administrator/components/com_emailbeautifier/helper.php

<?php
/**
 * @package     EmailBeautifier
 * @subpackage  com_emailbeautifier
 *
 * @author      Techjoomla <extensions@techjoomla.com>
 * @copyright   Copyright (C) 2009 - 2022 Techjoomla. All rights reserved.
 * @license     http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 */

// No direct access.
defined('_JEXEC') or die('Restricted access');

use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Factory;
use Joomla\CMS\Log\Log;
use Joomla\CMS\Log\LogEntry;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\CMS\Uri\Uri;

jimport('joomla.filesystem.file');

/**
 * EB beautify email helper class
 *
 * @package     EmailBeautifer
 * @subpackage  com_emailbeautifier
 * @since       1.0
 */
class BeautifyEmail
{
	/**
	 * Function to change email body
	 *
	 * @param   object  &$mailobj  Mail object
	 * @param   array   $to        Array of emails
	 *
	 * @return  boolean
	 */
	public function changeMail(&$mailobj, $to)
	{
		$content   = $mailobj->Body;
		$app       = Factory::getApplication();
		$lang      = Factory::getLanguage();
		$input     = $app->input;
		$option    = $input->get("option", '', 'cmd');
		$langTag   = $lang->getTag();
		$allParams = array();
		$userId    = $this->getuserID($to);

		// 1.1 Rare, but even after skipping loading EB for skipped extensions,
		// If execution reaches here, again recheck skipped list of components
		$comParams          = ComponentHelper::getParams('com_emailbeautifier');
		$skipComponentsList = $comParams->get('skip_list');

		// 1.2 Trim the whitespace from component names
		$skipComponentsList = array_map('trim', explode("\n", $skipComponentsList));

		// 1.3 Return if extension is skipped
		if (in_array($option, $skipComponentsList, true))
		{
			return false;
		}

		// 2. Try to get user language
		if (Factory::getApplication()->isClient('site'))
		{
			$langTag = ($userId) ? Factory::getUser($userId)->getParam('language', $langTag) : $langTag;
		}
		else
		{
			$langTag = ($userId) ? Factory::getUser($userId)->getParam('admin_language', $langTag) : $langTag;
		}

		// 3.1 - get all URL params used for URL conditions
		$urlParamsList           = array();
		$urlParamsList['option'] = $input->get("option", '', 'cmd');
		$urlParamsList['layout'] = $input->get("layout", '', 'string');
		$urlParamsList['view']   = $input->get("view", '', 'string');
		$urlParamsList['task']   = $input->get->get("task", '', 'cmd');
		$urlParamsList['action'] = $input->get->get("action", '', 'cmd');

		// 3.2 - remove blank URL parmas
		$urlParamsList           = array_filter($urlParamsList, "trim");

		// 4.1 - get all templates for current language
		$db    = Factory::getDbo();
		$query = $db->getQuery(true);
		$query->select(array('id', 'conditions', 'advance_condition'));
		$query->from($db->quoteName('#__eb_templates'));
		$query->where($db->quoteName('published') . "= 1 AND " . $db->quoteName('language') . " = " . $db->quote($langTag));
		$db->setQuery($query);
		$templates = $db->loadAssocList();

		// 4.2 - if lang. specific tempaltes not found, get all templates with lang = *
		if (empty($templates))
		{
			$query = $db->getQuery(true);
			$query->select(array('id', 'conditions', 'advance_condition'));
			$query->from($db->quoteName('#__eb_templates'));
			$query->where($db->quoteName('published') . "= 1 AND " . $db->quoteName('language') . " = " . $db->quote('*'));
			$db->setQuery($query);
			$templates = $db->loadAssocList();
		}

		// Recursive function
		if (!function_exists('currentCompReleted'))
		{
			/**
			 * Function to check condition if $option exists in current URL
			 * Eg. if current URI is for option=com_users, remove conditions for eg: com_content
			 *
			 * @param   object  $condition  array of condition
			 *
			 * @return  boolean
			 */
			function currentCompReleted($condition)
			{
				$input2  = Factory::getApplication()->input;
				$option2 = $input2->get("option", '', 'cmd');

				if (strpos($condition, $option2) !== false)
				{
					return true;
				}
				else
				{
					return false;
				}
			}
		}

		// Flag to indicate template is present or not for input conditions.
		$templateFound = 0;

		if (!empty($templates))
		{
			$rating = array();

			// 5 - Loop through all templates
			foreach ($templates as $templateId => $template)
			{
				// 5.1 - get conditions from template
				$conditionsArray = json_decode($template['conditions']);

				if (empty($conditionsArray))
				{
					$conditionsArray = array();
				}

				// 5.2 - remove unnecessary condition for other components
				$conditionsArray = array_filter($conditionsArray, "currentCompReleted");

				// Reset array index from 0
				$conditionsArray = array_values($conditionsArray);

				// 6.1 - validate current template to match URL conditions
				if ($template['advance_condition'] == 1)
				{
					foreach ($conditionsArray as $cArray)
					{
						$matchedParamCount = 0;

						// For all option from url
						// Eg: $key = 'option', $urlParam = 'com_users'
						foreach ($urlParamsList as $key => $urlParam)
						{
							// Eg: 'option=com_users'
							$search = $key . "=" . $urlParam;

							if (strpos($cArray, $search) !== false)
							{
								$matchedParamCount++;
							}
						}

						// To get id of template if template is made for particular condition
						if (count($urlParamsList) == $matchedParamCount)
						{
							$rating['id']  = $template['id'];
							$templateFound = 1;
						}
					}
				}
				// 6.2 - for components selected, check if $conditionsArray matches with $option
				// Here $conditionsArray will only have one component option left which will be current $option in current URL thanks to step 5.2
				else
				{
					if (!empty($conditionsArray) && ($option == $conditionsArray[0]))
					{
						$rating['id']  = $template['id'];
						$templateFound = 1;
					}
				}
			}
		}

		// 7.1 - Flag to check whether template is found or not
		if ($templateFound == 1)
		{
			$query = $db->getQuery(true);
			$query->select('id, template, template_css');
			$query->from($db->quotename('#__eb_templates'));
			$query->where($db->quoteName('id') . " = " . $rating['id']);
		}
		// 7.2 - Else apply default template
		else
		{
			$query = $db->getQuery(true);
			$query->select('id, template, template_css');
			$query->from($db->quotename('#__eb_templates'));
			$query->where($db->quoteName('isDefault') . " = 1 AND " . $db->quoteName('published') . " = 1");
		}

		$db->setQuery($query);
		$finalTemplate = $db->loadAssoc();

		// Check whether storelog option set for componente
		$comParams = ComponentHelper::getParams('com_emailbeautifier');
		$storelog  = $comParams->get('storelog');

		if (!empty($storelog))
		{
			$allParams           = $urlParamsList;
			$allParams['option'] = $option;

			// Getting current url  with options
			$uri        = Factory::getURI();
			$requestUrl = $uri->toString();

			$logData["url"]        = $requestUrl;
			$logData["parameters"] = $allParams;
			$logData["id"]         = (empty($finalTemplate['id'])) ? 0 : $finalTemplate['id'];

			$this->storeLog($logData);
		}

		// No template found
		if (empty($finalTemplate))
		{
			return false;
		}

		$messageBody    = $finalTemplate['template'];
		$templateCss    = $finalTemplate['template_css'];
		$messageBody    = stripslashes($messageBody);
		$messageSubject = $mailobj->Subject;

		// Collect content that will be replaced
		$fromMail = $app->get('mailfrom');
		$site     = $app->get('sitename');
		$siteLink = Uri::root();
		$today    = date('Y-m-d H:i:s');

		// Replace line breaks by br tags in case of a plain text email
		$isHTML = $this->isHTML($content);

		// Create links from plain text refer to Bug #9401
		if (!$isHTML)
		{
			$content = nl2br($content);

			$content = preg_replace_callback("#((http|https|ftp)://(\S*?\.\S*?))(\s|\;|\)|\]|\[|\{|\}|,|\"|'|:|\<|$|\.\s)#i",

				function ($match)
				{
					return "<a href=\"{$match[1]}\" target=\"_blank\">{$match[1]}</a>{$match[4]}";
				},
			$content
			);
		}

		// Set all emails as text/html emails, since we are putting HTML template around content
		$mailobj->isHtml(true);

		// Replace placeholders with values
		$find        = array('[SITENAME]', '[SITELINK]', '[CONTENT]', '[TIMESTAMP]');
		$findSubject = array('[SITENAME]', '[SITELINK]', '[TIMESTAMP]');

		// For Bug #9401
		$siteLink = '<a href="' . $siteLink . '" target="_blank" rel="noopener">' . $siteLink . '</a>';

		$replace        = array($site, $siteLink, $content, $today);
		$replaceSubject = array($site, $siteLink, $today);

		$messageBody    = str_replace($find, $replace, $messageBody);
		$messageSubject = str_replace($findSubject, $replaceSubject, $messageSubject);

		// Get css file and read

		// $cssfile = JPATH_SITE . "/components/com_emailbeautifier/assets/beautifier.css";
		// $cssdata = file_get_contents($cssfile);

		// Get the userid against the mail_id
		$userid     = $this->getuserID($to);
		$dispatcher = JDispatcher::getInstance();

		PluginHelper::importPlugin('emailbeautifier');
		$dispatcher->trigger('onPrepareEmailBody',    array(&$messageBody, $to, $userid));
		$dispatcher->trigger('onPrepareEmailSubject', array(&$messageSubject, $to, $userid));

		// START JMA PLUGIN SUPPORT CODE

		PluginHelper::importPlugin('system', 'plg_sys_jma_integration');
		$result = $dispatcher->trigger('onPrepareEmailJmaIntegration', array($messageBody, $templateCss, $userid));

		if (!empty($result))
		{
			$messageBody = $result[0]['message_body'];
			$templateCss = $result[0]['cssdata'];
		}

		// END JMA PLUGIN SUPPORT CODE

		// Call function and send HTML and CSS for body

		// $mailData = $this->getEmogrify($messageBody,$cssdata);
		// Use template css to emogrify

		$mailData         = $messageBody;
		$mailobj->Body    = $mailData;
		$mailobj->Subject = $messageSubject;

		return true;
	}

	/**
	 * Function to find if the email being sent contains HTML. @TODO: Use the mail
	 * objects ContentType to determine html/plain
	 *
	 * @param   string  $content  Email content string
	 *
	 * @return  boolean
	 */
	public function isHTML($content)
	{
		$l1 = strlen($content);
		$l2 = strlen(strip_tags($content));

		return ($l1 != $l2);
	}

	/**
	 * Function to find the user id based on the emails in the mail object
	 *
	 * @param   array  $to  Array of email addresses
	 *
	 * @return  integer  Integer or null
	 */
	public function getuserID($to)
	{
		// #TODO fetch email of recipent in joomla 1.7
		$email = $to[0][0];

		if (!empty($email))
		{
			$db    = Factory::getDbo();
			$query = $db->getQuery(true);
			$query->select('id');
			$query->from($db->quoteName('#__users'));
			$query->where($db->quoteName('email') . " = " . $db->quote($email));
			$db->setQuery($query);
			$result = $db->loadResult();

			if ($result)
			{
				return $result;
			}
			else
			{
				return null;
			}
		}
		else
		{
			return null;
		}
	}

	/**
	 * Function to get the inline css html code from the emogrifier
	 *
	 * @param   string  $html  Email html
	 * @param   string  $css   Email css
	 *
	 * @return  string
	 */
	public function getEmogrify($html, $css)
	{
		// $path = JPATH_ADMINISTRATOR . "/components/com_emailbeautifier/models/emogrifier.php";

		jimport('techjoomla.emogrifier.tjemogrifier');
		InitEmogrifier::initTjEmogrifier();

		$emogr     = new TJEmogrifier($html, $css);
		@$htmlCss = $emogr->emogrify();

		return $htmlCss;
	}

	/**
	 * Add Bcc from component options to BCC filed in mail object
	 *
	 * @param   array  $bcc  Array of bcc email ids
	 *
	 * @return array
	 */
	public function Bcc($bcc)
	{
		$comParams = ComponentHelper::getParams('com_emailbeautifier');
		$eConfig   = array('bcc' => $comParams->get('bcc_list'));

		if (is_array($bcc))
		{
			$bcc = array_merge((array) $eConfig, (array) $bcc);
		}

		return $eConfig;
	}

	/**
	 * Function to store the data in the generate log file
	 *
	 * @param   string  $logData  log data
	 *
	 * @return  string
	 */
	public function storeLog($logData)
	{
		jimport('joomla.error.log');

		$options = "{DATE}\t{TIME}\t{USER}\t{DESC}";
		$me      = Factory::getUser();

		$logArray = array(
			'text_file'         => 'com_emailbeautifier.log' . '.php',
			'text_entry_format' => $options
		);

		Log::addLogger($logArray, Log::INFO, 'com_emailbeautifier');

		$logEntry       = new LogEntry('Log added', Log::INFO, 'com_emailbeautifier');
		$logEntry->user = $me->id;
		$logEntry->desc = json_encode($logData);

		Log::add($logEntry);
	}
}