| Current Path : /home/jeromecohp/www/administrator/components/com_emailbeautifier/models/ |
| Current File : /home/jeromecohp/www/administrator/components/com_emailbeautifier/models/template.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\Application\ApplicationHelper;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\Model\AdminModel;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\CMS\Table\Table;
use Joomla\CMS\Uri\Uri;
use Joomla\Registry\Registry;
jimport('joomla.application.component.modeladmin');
/**
* Item Model for an Template.
*
* @package EmailBeautifer
* @subpackage com_emailbeautifier
* @since 2.2
*/
class EmailbeautifierModelTemplate extends AdminModel
{
/**
* @var string The prefix to use with controller messages.
* @since 1.6
*/
protected $text_prefix = 'COM_EMAILBEAUTIFIER';
/**
* Constructor.
*
* @param array $config An optional associative array of configuration settings.
*
* @since 2.1.0
*/
public function __construct($config = array())
{
$config['event_after_delete'] = 'ebOnAfterTemplateDelete';
$config['event_change_state'] = 'ebOnAfterTemplateChangeState';
parent::__construct($config);
}
/**
* Returns a Table object, always creating it.
*
* @param string $type The table type to instantiate
* @param string $prefix A prefix for the table class name. Optional.
* @param array $config Configuration array for model. Optional.
*
* @return JTable|boolean JTable if found, boolean false on failure
*/
public function getTable($type = 'Template', $prefix = 'EmailBeautiferTable', $config = array())
{
return Table::getInstance($type, $prefix, $config);
}
/**
* Method to get the templateform.
*
* The base form is loaded from XML
*
* @param array $data An optional array of data for the form to interogate.
* @param boolean $loadData True if the form is to load its own data (default case), false if not.
*
* @return object | boolean on failure
*
* @since 2.2.0
*/
public function getForm($data = array(), $loadData = true)
{
// Get the form.
$form = $this->loadForm(
'com_emailbeautifier.template',
'template',
array (
'control' => 'jform',
'load_data' => $loadData,
)
);
if (empty($form))
{
return false;
}
return $form;
}
/**
* Method to get the data that should be injected in the form.
*
* @return mixed $data The data for the form.
*
* @since 1.6
*/
protected function loadFormData()
{
// Check the session for previously entered form data.
$data = Factory::getApplication()->getUserState('com_emailbeautifier.edit.template.data', array());
if (empty($data))
{
$data = $this->getItem();
}
return $data;
}
/**
* Method to get a single record.
*
* @param integer $pk The id of the primary key.
*
* @return mixed $item Object on success, false on failure.
*/
public function getItem($pk = null)
{
if ($item = parent::getItem($pk))
{
if ($item->advance_condition != 0)
{
$decoded_conditions = json_decode($item->conditions);
$textarea_conditions_data = implode("\n", $decoded_conditions);
$item->textarea_conditions = $textarea_conditions_data;
}
}
return $item;
}
/**
* Prepare and sanitise the table data prior to saving.
*
* @param Table $table A Table object.
*
* @return void
*
* @since 1.6
*/
protected function prepareTable($table)
{
jimport('joomla.filter.output');
if (empty($table->id))
{
// Set ordering to the last item if not set
if (@$table->ordering === '')
{
$db = Factory::getDbo();
$db->setQuery('SELECT MAX(ordering) FROM #__tj_template');
$max = $db->loadResult();
$table->ordering = $max + 1;
}
}
}
/**
* This function returns the plugin names under the email-alerts component
*
* @return array
*/
public function getPluginNames()
{
// FIRST GET THE EMAIL-ALERTS RELATED PLUGINS FRM THE `jos_plugins` TABLE
$this->_db->setQuery('SELECT element FROM #__extensions WHERE folder=\'emailalerts\' AND enabled = 1');
$email_alert_plugins_array = $this->_db->loadColumn();
return $email_alert_plugins_array;
}
/**
* Function to return description of the 'emailalert' plugins from the XML file
* Input: plugin_array which contains names of the 'emailalert' plugins
* This function is called only from the view.html.php file
*
* @return array
*/
public function getPluginDescriptionFromXML()
{
$plugin_array = $this->getPluginNames();
$plugin_description_array = array();
$i = 0;
if ($plugin_array)
{
foreach ($plugin_array as $emailalert_plugin)
{
// Get the description of the plugin from the XML file
$data = ApplicationHelper::parseXMLInstallFile(JPATH_SITE . '/plugins/emailalerts/' . $emailalert_plugin . '/' . $emailalert_plugin . '.xml');
// Store it in the array
$plugin_description_array[$i++] = $data['description'];
}
}
return $plugin_description_array;
}
/**
* This function change relative image path and relative href path to absolute path
*
* @param string $m_body STRING which contain template data
*
* @return string With absolute links
*/
public function getImageUrl($m_body)
{
if (!function_exists('makeRelativeUrl'))
{
function makeRelativeUrl($str)
{
// If string doesn't start with http
if (substr($str[0], 0, 4) != "http" && substr($str[0], 0, 6) != "mailto")
{
$str[0] = Uri::root() . $str[0];
}
return $str[0];
}
}
// MAKE href absolute path
$hrefpattern = "/(?<=href=(\"|'))[^\"']+(?=(\"|'))/";
$m_body = preg_replace_callback($hrefpattern, 'makeRelativeUrl', $m_body);
// MAKE <img src absolute path
$srcpattern = "/(?<=src=(\"|'))[^\"']+(?=(\"|'))/";
$m_body = preg_replace_callback($srcpattern, 'makeRelativeUrl', $m_body);
return $m_body;
}
/**
* Method to toggle the default setting for template
*
* @param array $pks The ids of the items to toggle.
*
* @return boolean True on success.
*/
public function toggleDefault($pks)
{
// Sanitize the ids.
$pks = (array) $pks;
JArrayHelper::toInteger($pks);
// Choose only first item, as there will be only 1 default template
$pk = $pks[0];
try
{
$db = $this->getDbo();
// Unset other previous templates from being default
$query = $db->getQuery(true)
->update($db->quoteName('#__eb_templates'))
->set('isDefault = 0')
->where('id != ' . $pk);
$db->setQuery($query);
$db->execute();
// Get current status for Unset previous template from being default
$query = $db->getQuery(true)
->select('isDefault')
->from($db->quoteName('#__eb_templates'))
->where('id = ' . $pk);
$db->setQuery($query);
$alreadyDefault = $db->loadResult();
if ($alreadyDefault)
{
// Set is default to 0 [unset]
$default = 0;
}
else
{
// Set default to 1 [set]
$default = 1;
}
// Set/unset template as default
$query = $db->getQuery(true)
->update($db->quoteName('#__eb_templates'))
->set('isDefault=' . (int) $default)
->where('id = ' . (int) $pk);
$db->setQuery($query);
$db->execute();
// Plugin trigger ebOnAfterTemplateToggleDefault
$dispatcher = JDispatcher::getInstance();
PluginHelper::importPlugin('emailbeautifier');
$dispatcher->trigger('ebOnAfterTemplateToggleDefault', array($templateId = $pk, $default));
}
catch (Exception $e)
{
$this->setError($e->getMessage());
return false;
}
return true;
}
/**
* Get sites default template
*
* @return json
*
* @since 1.5
*/
public function getSiteDefaultTemplate()
{
try
{
$db = $this->getDbo();
/* Get current status for Unset previous template from being default
For front end => client_id=0 */
$query = $db->getQuery(true)
->select('template')
->from($db->quoteName('#__template_styles'))
->where('client_id=0')
->where('home=1');
$db->setQuery($query);
return $db->loadResult();
}
catch (Exception $e)
{
$this->setError($e->getMessage());
return '';
}
}
/**
* Saves Template Details into database
*
* @param array $data Template form data
*
* @return boolean
*/
public function save($data)
{
// $data is accessed by reference in belo function call
$this->getConditionsData($data);
// $data is accessed by reference in belo function call
$isDuplicateTemplate = $this->validateDuplicateTemplate($data);
if (!empty($isDuplicateTemplate))
{
$this->setError(JText::_('COM_EMAILBEAUTIFIER_TEMPLATE_ERR_MSG_TEMPLATE_EXISTS'));
return false;
}
/* if ($data['params'])
{
$param_string = strval($data['params']);
$remove_space_param = preg_replace('/\s+/', '', $param_string );
$param_data = explode(',',$remove_space_param ,0);
$data['params'] = json_encode($param_data);
} */
if ($data['isDefault'] == '1')
{
$db = Factory::getDbo();
$query = $db->getQuery(true);
$query->select('id');
$query->from($db->quoteName('#__eb_templates'));
$query->where($db->quoteName('isDefault') . "=" . '1');
$db->setQuery($query);
$cid = $db->loadResult();
$def = new stdClass;
$def->id = $cid;
$def->isDefault = '0';
if (!$db->updateObject('#__eb_templates', $def, 'id'))
{
$this->setError($db->stderr());
return false;
}
}
$table = $this->getTable();
$id = (!empty($data['id'])) ? $data['id'] : (int) $this->getState('com_emailbeautifier.edit.template.id');
// $state = (!empty($data['published'])) ? 1 : 0;
$isNew = true;
// Remove backslashes
$data['template'] = stripslashes($data['template']);
if (empty($data['template']))
{
$this->setError(Text::_('COM_EMAILBEAUTIFIER_EMPTY_TMPLATE_BODY_IS_NOT_ALLOWED'));
return false;
}
// Relative image path and relative href path to absolute path
$msgbody = $this->getImageUrl($data['template']);
// Emogrify html and css
$BeautifyEmail = new BeautifyEmail;
$data['template'] = $BeautifyEmail->getEmogrify($msgbody, $data['template_css']);
// Allow an exception to be thrown.
try
{
// Load the row if saving an existing record.
if ($id > 0)
{
$table->load($id);
$isNew = false;
}
// Bind the data.
if (!$table->bind($data))
{
$this->setError($table->getError());
return false;
}
// Prepare the row for saving
$this->prepareTable($table);
// Check the data.
if (!$table->check())
{
$this->setError($table->getError());
return false;
}
// Store the data.
if (!$table->store())
{
$this->setError($table->getError());
return false;
}
}
catch (\Exception $e)
{
$this->setError($e->getMessage());
return false;
}
// IMPORTANT to set new id in state, it is fetched in controller later
if (isset($table->id))
{
$this->setState('com_emailbeautifier.edit.template.id', $table->id);
}
$this->setState('com_emailbeautifier.edit.template.new', $isNew);
// Plugin trigger onAfterLeaveChat
$dispatcher = JDispatcher::getInstance();
PluginHelper::importPlugin('emailbeautifier');
$dispatcher->trigger('ebOnAfterTemplateSave', array($templateDetails = $data, $isNew));
return true;
}
/** This function return result object with condtions dependion upon advance condition checkbox
*
* @param array &$data Template form data
*
* @return array
*/
protected function getConditionsData(&$data)
{
if (empty($data['conditions']))
{
$data['conditions'] = '';
}
// If User entered advanced conditions
if (!empty($data['advance_condition']))
{
$cond_list = $data['textarea_conditions'];
$textarea_data = explode("\r\n", $cond_list);
$data['conditions'] = json_encode($textarea_data);
$data['advance_condition'] = 1;
}
// Selected component list from component list
else
{
$data['conditions'] = json_encode($data['conditions']);
$data['advance_condition'] = 0;
}
}
/**
* Method to load new template HTML and CSS on ajax call for change template on temolate form.
*
* @return json
*
* @since 1.5
*/
public function loadTemplate()
{
$jinput = Factory::getApplication()->input;
$folder = $jinput->get("template_type");
jimport('techjoomla.emogrifier.tjemogrifier');
InitEmogrifier::initTjEmogrifier();
$path = JPATH_SITE . "/components/com_emailbeautifier/templates/" . $folder;
$defTemplate = $this->getSiteDefaultTemplate();
jimport('joomla.filesystem.folder');
$overidePath = JPATH_SITE . '/templates/' . $defTemplate . '/html/com_emailbeautifier/templates/' . $folder;
$data = array();
if (JFolder::exists($overidePath))
{
$path = $overidePath;
}
$htmlFile = $path . '/' . $folder . '.html';
if (JFile::exists($htmlFile))
{
$htmlData = file_get_contents($htmlFile);
// Condition to check if mbstring is enabled
if (!function_exists('mb_convert_encoding'))
{
echo Text::_("MB_EXT");
// $emorgdata = $emails_config['message_body'];
$emorgdata = $htmlData;
}
else
{
$cssFile = $path . '/' . $folder . '.css';
$cssdata = file_get_contents($cssFile);
$emogr = new TJEmogrifier($htmlData, $cssdata);
@$emorgdata = $emogr->emogrify();
$emorgdatanew = stripslashes($emorgdata);
$data['template'] = $emorgdatanew;
$data['css'] = $cssdata;
}
}
$result = (object) $data;
return $result;
}
/** This function return array with condtions dependion upon language and conditions
*
* @param array &$data Template form data
*
* @return array|boolean
*/
public function validateDuplicateTemplate(&$data)
{
// 1. Get conditions from form inputs
$lang = $data['language'];
// If User entered advanced conditions
if (!empty($data['advance_condition']))
{
$formConditions = explode("\r\n", $data['textarea_conditions']);
}
// Selected component list from component list
else
{
$formConditions = json_decode($data['conditions']);
}
// 2. Get existing conditions for current language selected and templates other than current template
$id = $data['id'];
$db = Factory::getDbo();
$query = $db->getQuery(true);
$query->select('`id`, `conditions`');
$query->from($db->quoteName('#__eb_templates'));
$query->where($db->quoteName('language') . "= '" . $lang . "' AND " . $db->quoteName('id') . " <> " . $id);
$db->setQuery($query);
$dbConditions = $db->loadObjectList();
// If nothing from database, this is not duplicate
if (empty($dbConditions))
{
return false;
}
$conditionsListArray = [];
if (empty($formConditions))
{
return $conditionsListArray;
}
// Foreach loop to check the input conditions from textarea OR list are equal to conditions fetched from database
foreach ($formConditions as $formKey => $formCondition)
{
// Foreach loop to access values from database
foreach ($dbConditions as $databaseKey => $dbCondition)
{
// To convert json string to array
$dbConditionsArray = json_decode($dbCondition->conditions);
if (empty($dbConditionsArray))
{
return $conditionsListArray;
}
// Foreach loop to access array of json string
foreach ($dbConditionsArray as $dbConditionsArrayElement)
{
/* If loop to check whether the value of conditions from
data['conditions'] equals to value from database if 'yes' the value from database will enter in array $conditionsListArray.*/
if ($formCondition == $dbConditionsArrayElement)
{
$conditionsListArray[] = $dbConditionsArrayElement;
}
}
}
}
return $conditionsListArray;
}
}