ElixirVault/www/system-brs-core/cms/cmsMailEngine/inc/cmsMailEngineController.php

1346 lines
48 KiB
PHP

<?php
namespace BRSystems\Core\Cms\cmsMailEngine\inc;
use BRSystems\Core\Cms\cmsClassificators\inc\cmsClassificatorsModule;
use BRSystems\Core\Library\cCore\cCore;
use BRSystems\Core\Library\cDb\cDb;
use BRSystems\Core\Library\cDbLog\cDbLogModule;
use BRSystems\Core\Library\cDefuseCrypto\cDefuseCrypto;
use BRSystems\Core\Library\cINI\cINI;
use BRSystems\Core\Library\cJSON\cJSON;
use BRSystems\Core\Library\cMail\cMail;
use BRSystems\Core\Library\cSession\cSession;
use BRSystems\Core\Library\cValidator\cValidator;
use BRSystems\Core\Sys\sysLanguages\inc\sysLanguagesModule;
/**
* cmsMailEngine Controller
*
* @category cmsMailEngine Controller
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @since Version 2.0
*/
class cmsMailEngineController extends cCore
{
public $dir;
public $name;
public $module;
public $history = false;
private $uriData = false;
private $mailS = false;
private $mimeTypes = array(
'pdf' => 'application/pdf',
'txt' => 'text/plain',
'html' => 'text/html',
'exe' => 'application/octet-stream',
'zip' => 'application/zip',
'doc' => 'application/msword',
'docx' => 'application/msword',
'xls' => 'application/vnd.ms-excel',
'xlsx' => 'application/vnd.ms-excel',
'ppt' => 'application/vnd.ms-powerpoint',
'gif' => 'image/gif',
'png' => 'image/png',
'jpeg' => 'image/jpg',
'jpg' => 'image/jpg',
'php' => 'text/plain'
);
const CUSTOM_TYPE_MAIL = 0;
const SENT_MAIL_TABLE = 'mod_mail_sent';
const OUTGOING_MAIL_TABLE = 'mod_mail_outgoing';
/**
* Class constructor
*/
public function __construct($uriData, $dir, $name) {
$this->dir = $dir;
$this->name = $name;
parent :: __construct($uriData);
$this->module = new cmsMailEngineModule();
$this->oView->setTemplateDir($this->dir . "/tmpl/");
if(!$this->oView->cacheUsed()){
$this->oView->setJs(getCurrentFolder($this->dir) . '/js/' . $this->name . '.js');
$this->oView->setCss(getCurrentFolder($this->dir) . '/css/' . $this->name . '.css');
}
// Set JS module init title
$this->oView->setAsJSON(cCore::JS_MOD, ucfirst($name));
$this->mailS = new cSession('mail-overview');
}
/**
* Function to show main form in the module
*
* @category cmsMailEngine Controller
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @returns bool true
*/
public function run($initEditMode = false)
{
$this->chkFileDownload();
$this->oView->TABLE = true;
$this->oView->setAsJSON('initEdit', $initEditMode);
$this->oView->setAsJSON('baseUrl', $this->gL());
$this->oView->setAsJSON('vcfg', $this->getValCfg());
$this->oView->setAsJSON('gM', $this->getTranslations());
$this->oView->display();
}
/**
* Function to create cms table & return for direct & ajax input
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cmsMailEngine Controller
* @param int $page - page to display
* @param string $filter_json - (optional) filter json string
* @param bool $headers - flag whether to send header data or not
* @return array of data
* @version 1.1
*/
public function createCmsTable($page = 1, $filter_json = '', $headers = false)
{
$pages = 0;
$filter = array();
if ($filter_json) {
$filter = cJSON::decode($filter_json, true);
}
if($this->history || !$this->chkP('CMS_MAILENGINE_ADD_NEW')) {
$this->oView->LIST_BTN = true;
}
$timerDiv = '';
if ($this->chkP('CMS_MAILENGINE_SHOW_5MIN_CRON_CALL_TIMEOUT')) {
$time = 0;
$timerDiv = '
<span class="nCall">
(<span id="' . $this->module->getNext5MinCronCall($time) . '"
data-cron-interval="' . cmsMailEngineModule::CRON_TIMER_INTERVAL * 60 . '">' . $time . '</span>)
</span>';
}
$this->oView->MODULE_TITLE = $this->gM("Outgoing mail overview") . $timerDiv;
if ($this->history) {
$this->oView->MODULE_TITLE = $this->gM("Sent mail overview");
}
if (!!$filter && is_array($filter)) {
$this->oView->DEFAULT_SEARCH_VALUES = prepForDisplayHtml($filter);
}
$this->oView->LIST_HEADER = reOrderTableFields(
$this->getTableFields(),
$this->oUser->oCfg->getTableProperty($this->name)
);
$this->oView->LIST_DATA = $this->getModuleData($page, $filter, $pages);
$this->oView->LIST_ACTIONS = $this->getTableActions();
$data = [
'data' => $this->oView->genHelperView('cmsc/table/data-table'),
'pcount' => $pages,
'rlimit' => $this->cmsTableRecordsPerPage
];
// Send data to client
if ($headers) {
$data['header'] = $this->oView->genHelperView('cmsc/table/data-table-search');
}
return $data;
}
/**
* Function to get module data
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cmsMailEngine Controller
* @param int $page
* @param array $filter
* @param int $pages
* @return array of data
* @version 1.1
*/
public function getModuleData($page = 1, $filter = array(), &$pages) {
$where = "AND 1";
if($this->history)
$sort = "mm.mail_sent DESC";
else
$sort = "mm.mail_priority, mm.mail_send_atempt, mm.mail_disabled, mm.id desc";
$offset = (($page?$page:1)-1) * $this->cmsTableRecordsPerPage;
$tFields = $this->getTableFields();
// Create sort by
if(getP('sortBy'))
$sort = $this->module->db->genOrderByQuery(getP('sortBy'), getP('sortWay'), $tFields);
// Create where clause
if(count($filter))
$where = $this->module->db->genSearchFieldQuery($filter, $tFields);
$subWhere = "";
/*if(isset($filter['field_search'])){
// Get keywords
$keyFilter = extractKeywords($filter['field_search'], array('mail:read' => 1, 'mail:unread' => 0, 'mail:custom' => 0, 'mail:disabled' => 1, 'mail:enabled' => 0));
$filter = array_merge($filter, $keyFilter);
$filter['field_search'] = $this->module->db->prepData($filter['field_search']);
$subWhere = "
AND (
mm.mail_owner LIKE '%{$filter['field_search']}%'
OR mm.mail_title LIKE '%{$filter['field_search']}%'
OR mm.mail_content LIKE '%{$filter['field_search']}%'
OR mc.cl_name LIKE '%{$filter['field_search']}%'
)"; */
/* // Base filter
if(isset($filter['date_from']) && $filter['date_from']){
$subWhere .= " AND mm.mail_inserted >= " . strtotime(str_replace('/','-',$filter['date_from']));
}
if(isset($filter['date_till']) && $filter['date_till']){
$subWhere .= " AND mm.mail_inserted <= " . strtotime('+1 day', strtotime(str_replace('/','-',$filter['date_till'])));
}
// Outgoing filter
if(isset($filter['mail:disabled']) && !$this->history){
$subWhere .= " AND mm.mail_disabled = '{$filter['mail:disabled']}'";
}
if(isset($filter['mail:enabled']) && !$this->history){
$subWhere .= " AND mm.mail_disabled = '{$filter['mail:enabled']}'";
}
// History filter
if(isset($filter['mail:read']) && $this->history){
$subWhere .= " AND mm.mail_read = '{$filter['mail:read']}'";
}
if(isset($filter['mail:unread']) && $this->history){
$subWhere .= " AND mm.mail_read = '{$filter['mail:unread']}'";
}
if(isset($filter['mail:custom'])){
$subWhere .= " AND mm.mail_template_id = '{$filter['mail:custom']}'";
}
unset($filter['field_search']);
}*/
// Fetch data
$data = $this->module->getModuleRecords($where . $subWhere, $sort, $offset, $this->cmsTableRecordsPerPage);
// Format data
if(!empty($data) && is_array($data)){
$link = $this->getFullLinkForID();
foreach($data as &$v){
$v['mail_attachment'] = ($v['mail_attachment']?"<a class='attachment' href='{$link}?dfile=" . base64_encode(urldecode($v['mail_attachment'])) . "'>&nbsp;</a>":"-");
$v['mail_send_atempt'] = ($v['mail_send_atempt']?$v['mail_send_atempt']:'-');
$v['mail_server_type'] = ($v['mail_server_type'] == '1'?'<img src="/img/pub/svg/sys_logo3.svg" style="height: 32px;" />':'<img src="/img/pub/Z18.png" style="height: 24px;margin-top: 4px;" />');
if($this->history){
if($v['mail_read']){
$v['mail_read'] = '&check;';
$v['sclass'] = 'bggreen';
}else
$v['mail_read'] = '-';
}else{
$v['sclass'] = ($v['mail_locked'] == '1' ?'bgred':'');
}
// $v['mail_inserted'] = date($this->CMSDateFormat . ' H:i', $v['mail_inserted']);
if(date('d-m-Y', $v['mail_inserted']) == date('d-m-Y')){
$v['mail_inserted'] = date('H:i', $v['mail_inserted']);
}else{
$v['mail_inserted'] = date($this->CMSDateFormat . ' H:i', $v['mail_inserted']);
}
if(date('d-m-Y', $v['mail_sent']) == date('d-m-Y')){
$v['mail_sent'] = date('H:i', $v['mail_sent']);
}else{
$v['mail_sent'] = date($this->CMSDateFormat . ' H:i', $v['mail_sent']);
}
//$v['mail_owner'] = "<a href='" . $this->getLinkForID($this->uri_data['id'], false, true, "action:qmail/id:{$v['id']}") . "' class='show-mail'>{$v['mail_owner']}</a>";
}
}
$this->oView->ROWS = $rows = $this->module->db->getSelectedRecordsCount();
$pages = floor($rows / $this->cmsTableRecordsPerPage) + ($rows%$this->cmsTableRecordsPerPage?1:0);
return $data;
}
/**
* Function to disable / enable enum records marked in table
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cmsMailEngine Controller
* @param array $baseField - basefield to handle
* @param string $rows - passed user ids in JSON string
* @return array of data
*/
public function changeEnumFields($baseField, $rows) {
if($baseField && $rows = cJSON::decode($rows, true)){
$baseField = substr($baseField, 2);
$fields = $this->getTableFields();
if(isset($fields[$baseField]['db_field'])){
if($this->module->changeRecordsStatus($this->module->db->prepData($rows), $fields[$baseField][cDb::TF_DB_FIELD ])){
return true;
}
}
}
cJSON::sendError();
}
/**
* Function to delete records marked in table
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cmsMailEngine Controller
* @param string $rows - passed user ids in JSON string
* @return array of data
*/
public function delete($rows) {
if($rows = cJSON::decode($rows, true)){
if($this->module->deleteRecords($this->module->db->prepData($rows))){
return true;
}else{
cJSON::sendError();
}
}
}
/**
* Function to stop all new outgoing messages
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cmsMailEngine Controller
* @return array of data
*/
public function stopAllNewEmails() {
if(!$this->history && $this->module->stopNewOutgoing()){
return array('msg' => $this->gM('All new messages have been disabled!'));
}
}
/**
* Function to stop all new outgoing messages
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cmsMailEngine Controller
* @return array of data
*/
public function resumeAllNewEmails() {
if(!$this->history && $this->module->resumeNewOutgoing()){
return array('msg' => $this->gM('All new messages have been enabled!'));
}
}
/**
* Function to get table record data for edit mode
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cmsMailEngine Controller
* @param int $id - record id
* @return array of data
*/
public function editCmsTableRecord($id) {
$readonly = false;
$oReturnData = array(
'show' => array('buttons_top' => false, 'buttons_bottom' => true),
'btn' => $this->getFormButtons(),
);
if($id){
$mail = $this->module->getRecordById($id);
if(date('d-m-Y', $mail['mail_inserted']) == date('d-m-Y')){
$mail['mail_inserted'] = date('H:i', $mail['mail_inserted']);
}else{
$mail['mail_inserted'] = date($this->CMSDateFormat, $mail['mail_inserted']);
}
if(date('d-m-Y', $mail['mail_modified']) == date('d-m-Y')){
$mail['mail_modified'] = date('H:i', $mail['mail_modified']);
}else{
$mail['mail_modified'] = date($this->CMSDateFormat, $mail['mail_modified']);
}
if(!$this->history && !$mail['mail_disabled']){
$this->module->saveRecordById($id, array(
'mail_disabled' => 1
));
}
$link = $this->getFullLinkForID();
$mail['mail_attachment'] = ($mail['mail_attachment']?"<a class='att' href='{$link}?dfile=" . base64_encode(urldecode($mail['mail_attachment'])) . "'>".$this->gM('Attachement')."</a>":"");
if($this->history || (!$this->chkP('CMS_MAILENGINE_ADD_NEW') && !$this->chkP('CMS_MAILENGINE_EDIT')))
$readonly = true;
$this->oView->MAIL = $mail;
// When new mail set - ability to choose template
}else{
// Load mail types
$vLanguages = new sysLanguagesModule();
$oClMod = new cmsClassificatorsModule();
$vDefLang = $vLanguages->getDefaultAppLang();
$this->oView->iDefaultLang = $oReturnData['iDefLang'] = $vDefLang['id'];
$this->oView->vMailTypes = $oClMod->getClTypes($oClMod::CT_TYPE_MAILS);
$oReturnData['vMailTypeData'] = $this->module->getMailTemplateDataByLanguage();
$this->oView->vLangs = $vLanguages->getLanguages();
}
$this->oView->readonly = $readonly;
// Generate template
$oReturnData['html'] = $this->oView->genTemplate('edit');
return $oReturnData;
}
/**
* Function to get form buttons
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cmsMailEngine Controller
* @return array of data
*/
public function getFormButtons(){
$buttons = array(
1 => array(
'id' => 'fsave',
'lbl' => $this->gM('Save')
),
2 => array(
'id' => 'fcancel',
'lbl' => $this->gM('Cancel')
)
);
if($this->history || (!$this->chkP('CMS_MAILENGINE_ADD_NEW') && !$this->chkP('CMS_MAILENGINE_EDIT')))
unset($buttons[1]);
return $buttons;
}
/**
* Function to get js validator cfg
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cmsMailEngine Controller
* @param array|bool $lng - language array
* @return array of data
*/
public function getValCfg($lng = false){
$fields = array();
$fields["to"] = array(
cValidator::P_TYPE => cValidator::TY_STR,
cValidator::P_COMP => 1,
cValidator::P_TEST => array(cValidator::CHK_EMAIL),
);
$fields["subject"] = array(
cValidator::P_TYPE => cValidator::TY_STR,
cValidator::P_COMP => 1,
cValidator::P_TEST => array(cValidator::CHK_STR),
);
return $fields;
}
/**
* Function to save Record data
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cmsShops Controller
* @param int $recordId - record id
* @param string $fields - param JSON string
* @return array of data
*/
public function saveRecordData($recordId, $fields) {
$oldId = 0;
if($this->history)
cJSON::sendError();
if($fields){
$fields = $this->getSubmittedDataAsArray($fields);
}
// Start save process
if($fields){
//---------------------------------------------------------
// Validate fields
//---------------------------------------------------------
$valid = new cValidator($this);
$errors = $valid->checkArray($fields, $this->getValCfg());
if($errors !== true){
cJSON::sendError(array('data' => $errors));
}
$base = $fields['base'];
//---------------------------------------------------------
// Translation data manipulation
//---------------------------------------------------------
if(isset($fields['translations']) && !!$fields['translations']){
$iDefLangKey = 0;
foreach($fields['translations'] as $k=>$v){
$iLang = intval(substr($k, 1));
if(!$iDefLangKey) $iDefLangKey = $iLang;
if($v["def-html-content-{$iLang}"]) $iDefLangKey = $iLang;
}
//---------------------------------------------------------
// Send to all newsletter users
//---------------------------------------------------------
$reloadList = false;
if(isset($base['newsletter_mails']) && $base['newsletter_mails']){
if(!$this->createMailsForAllNewsletterMails($fields['translations'], $base['selMailType'], $iDefLangKey))
cJSON::sendError();
}
//---------------------------------------------------------
// Send to all newsletter users
//---------------------------------------------------------
if(isset($base['system_mails']) && $base['system_mails']){
if(!$this->createSystemNoticeMailsForAllUsers($fields['translations'], $base['selMailType'], $iDefLangKey))
cJSON::sendError();
}
//---------------------------------------------------------
// Send to all user emails
//---------------------------------------------------------
if(isset($base['all_mails']) && $base['all_mails']){
/*if(!$this->module->createMailsForAllUserMails($update))
cJSON::sendError();
$reloadList = true;*/
}
// Default action - create one mail based on template
$base['subject'] = $fields['translations']["k{$iDefLangKey}"]["title-{$iDefLangKey}"];
$base['WYSIWYG'] = $fields['translations']["k{$iDefLangKey}"]["WYSIWYG-{$iDefLangKey}"];
}
//---------------------------------------------------------
// Update / Insert base data
//---------------------------------------------------------
$update = array(
'mail_owner' => @$base['to'],
'mail_title' => @$base['subject'],
'mail_content' => @$base['WYSIWYG'],
'mail_modified' => time(),
);
//pr($fields);
$dlang = getDefaultAppLang();
// Upon new e-mail insert
if(!$recordId){
$update['mail_sender'] = cMail::$SERVER_CFG[cMail::MAIL_SERVER_DEFAULT][cMail::SENDER];
$update['mail_inserted'] = time();
$update['mail_priority'] = 1;
$update['mail_send_atempt'] = 0;
$update['mail_disabled'] = 1;
$update['mail_locked'] = 0;
$update['mail_server_type'] = cMail::MAIL_SERVER_DEFAULT;
$update['mail_lang_id'] = @$dlang['id'];
$update['mail_template_id'] = self::CUSTOM_TYPE_MAIL;
}
// Update / Insert record data
if(!$reloadList){
$oldId = $recordId;
if(!($recordId = $this->module->saveRecordById($recordId, $update))){
cJSON::sendError();
}
}
// Add tracking code
/*if(@$base['insert_magic_pixel']){
$base['WYSIWYG'] .= '<img src="http://' . $_SERVER['HTTP_HOST'] . '/ajax/ac:track/m' . $recordId . '.png" alt="" />';
$this->module->saveRecordById($recordId, array('mail_content' => $base['WYSIWYG']));
}*/
cJSON::sendOk($oldId?"":array('newid' => $recordId, 'reloadList' => $reloadList));
}
}
/**
* Function to create mails for newsletter subscription list
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cmsMailEngine Controller
* @param array $vMailData - mail title and mail body
* @param int $iMailType - mail type
* @param int $iDefLangKey - default language key
* @return mixed
* @version 1.1
*/
public function createMailsForAllNewsletterMails($vMailData, $iMailType, $iDefLangKey){
// Check data
if(empty($vMailData) || !is_array($vMailData) || empty($iMailType) || empty($iDefLangKey))
cJSON::sendError(array('msg' => $this->gM('Mail data missing')));
// gather all newsletter subscription emails
$vEmails = $this->module->gatherAllNewsletterSubscriptionEmails();
if(!empty($vEmails) && is_array($vEmails)){
$mm = new cMail();
foreach($vEmails as $mail){
$mm->addMail(
$mail,
false,
cMail::MAIL_SERVER_DEFAULT,
cMail::MAIL_3_SUBSCRIPTION_MAIL,
$iDefLangKey,
array(
// '[%FULL USER NAME%]' => "{$vEmails[$uid]['user_name']} {$vEmails[$uid]['user_surname']}",
// '[%BUG_LINK_HERE%]' => '',
// '[%CONTENT_DATA%]' => $vMailData //$this->oView->genTemplate('helpers/mailBody.twig')
),
false
);
}
}
return true;
}
/**
* Function to create mails for newsletter subscription list
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cmsMailEngine Controller
* @param array $vMailData - mail title and mail body
* @param int $iMailType - mail type
* @param int $iDefLangKey - default language key
* @return mixed
* @version 1.1
*/
public function createSystemNoticeMailsForAllUsers($vMailData, $iMailType, $iDefLangKey){
// Check data
if(empty($vMailData) || !is_array($vMailData) || empty($iMailType) || empty($iDefLangKey))
cJSON::sendError(array('msg' => $this->gM('Mail data missing')));
// gather all newsletter subscription emails
$vUsers = $this->module->gatherAllSystemUsersEmails();
if(!empty($vUsers) && is_array($vUsers)){
$mm = new cMail();
foreach($vUsers as $v){
$mm->addMail(
$v['user_email'],
false,
cMail::MAIL_SERVER_DEFAULT,
cMail::MAIL_3_SUBSCRIPTION_MAIL,
(!empty($v['user_lang_id']) ? $v['user_lang_id'] : $iDefLangKey),
array(
// '[%FULL USER NAME%]' => "{$vEmails[$uid]['user_name']} {$vEmails[$uid]['user_surname']}",
// '[%BUG_LINK_HERE%]' => '',
// '[%CONTENT_DATA%]' => $vMailData //$this->oView->genTemplate('helpers/mailBody.twig')
),
false
);
}
}
return true;
}
/**
* Function to create table headers + search
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cmsMailEngine Controller
* @return array of data
* @version 1.1
*/
public function getTableFields() {
if(!(!$this->history && $this->oUser->chkPermission('CMS_MAILENGINE_OUT_SHOW_MANAGEMENT', false, false) || $this->history && $this->oUser->chkPermission('CMS_MAILENGINE_SENT_SHOW_MANAGEMENT', false, false))){
return false;
}
// $clTypes = array(''=> array(cDb::TF_TITLE => $this->gM("-- Select --"))) + $this->module->getClTypes();
$statusData = array(
'' => array(
cDb::TF_TITLE => $this->gM("Select")
),
0 => array(
cDb::TF_TITLE => $this->gM("Active")
),
1 => array(
cDb::TF_TITLE => $this->gM("Inactive")
)
);
$readStatusData = array(
'' => array(
cDb::TF_TITLE => $this->gM("Select")
),
1 => array(
cDb::TF_TITLE => $this->gM("Read")
),
0 => array(
cDb::TF_TITLE => $this->gM("Unread")
)
);
$srvStatusData = array(
'' => array(
cDb::TF_TITLE => $this->gM("Select")
),
1 => array(
cDb::TF_TITLE => $this->gM("Z18")
),
0 => array(
cDb::TF_TITLE => $this->gM("elixirvault.lv")
)
);
$tFields = array(
"checkbox" => array(
cDb::TF_SORT => false,
cDb::TF_TITLE => '',
cDb::TF_CLASS => 'w4 center rchk'
),
"id" => array(
cDb::TF_SORT => true,
cDb::TF_SEARCH => true,
cDb::TF_TITLE => $this->gM("ID"),
cDb::TF_CLASS => 'w6 center',
cDb::TF_DB_FIELD => 'mm.id',
cDb::TF_TYPE => cDb::TF_T_INPUT,
),
"mail_owner" => array(
cDb::TF_SORT => true,
cDb::TF_SEARCH => true,
cDb::TF_TITLE => $this->gM("Mail owner"),
cDb::TF_CLASS => 'w18',
cDb::TF_DB_FIELD => 'mm.mail_owner',
cDb::TF_TYPE => cDb::TF_T_INPUT,
),
"mail_owner_cc" => array(
cDb::TF_SORT => true,
cDb::TF_SEARCH => true,
cDb::TF_TITLE => $this->gM("CC owner"),
cDb::TF_CLASS => 'w18',
cDb::TF_DB_FIELD => 'mm.mail_owner_cc',
cDb::TF_TYPE => cDb::TF_T_INPUT,
),
"mail_title" => array(
cDb::TF_SORT => true,
cDb::TF_SEARCH => true,
cDb::TF_TITLE => $this->gM("Title"),
cDb::TF_CLASS => 'w12',
cDb::TF_DB_FIELD => 'mm.mail_title',
cDb::TF_TYPE => cDb::TF_T_INPUT,
),
"cl_name" => array(
cDb::TF_SORT => true,
cDb::TF_SEARCH => false,
cDb::TF_TITLE => $this->gM("Type"),
cDb::TF_CLASS => 'w7',
cDb::TF_DB_FIELD => 'mc.cl_name',
cDb::TF_TYPE => cDb::TF_T_INPUT,
),
"mail_inserted" => array(
cDb::TF_SORT => true,
cDb::TF_SEARCH => array (
cDb::TF_CTITLE => $this->gM("Date from"),
cDb::TF_DB_FIELD => 'mm.mail_inserted',
cDb::TF_S_TYPE => cDb::TF_ST_FROM_TILL,
cDb::TF_S_LINK_FIELD => 'mail_sent',
cDb::TF_S_OPTIONS => cDb::TF_SO_FROM,
),
cDb::TF_TITLE => $this->gM("Inserted"),
cDb::TF_CLASS => 'w12 date center',
cDb::TF_DB_FIELD => 'mm.mail_inserted',
cDb::TF_TYPE => cDb::TF_T_DATE,
),
"mail_sent" => array(
cDb::TF_SORT => true,
cDb::TF_SEARCH => array (
cDb::TF_CTITLE => $this->gM("Date till"),
cDb::TF_DB_FIELD => 'mm.mail_sent',
cDb::TF_S_TYPE => cDb::TF_ST_FROM_TILL,
cDb::TF_S_LINK_FIELD => 'mail_inserted',
cDb::TF_S_OPTIONS => cDb::TF_SO_TILL,
),
cDb::TF_TITLE => $this->gM("Sent"),
cDb::TF_CLASS => 'w12 date center' . ($this->history ? ' sortDesc sort':''),
cDb::TF_DB_FIELD => 'mm.mail_sent',
cDb::TF_TYPE => cDb::TF_T_DATE,
),
"mail_attachment" => array(
cDb::TF_SORT => false,
cDb::TF_SEARCH => false,
cDb::TF_TITLE => $this->gM("Att."),
cDb::TF_CLASS => 'w6 center',
cDb::TF_DB_FIELD => 'mm.mail_attachment',
cDb::TF_TYPE => cDb::TF_T_INPUT,
),
"mail_priority" => array(
cDb::TF_SORT => false,
cDb::TF_SEARCH => false,
cDb::TF_TITLE => $this->gM("Priority"),
cDb::TF_CLASS => 'w8 center',
cDb::TF_DB_FIELD => 'mm.mail_priority',
cDb::TF_TYPE => cDb::TF_T_INPUT,
),
"mail_send_atempt" => array(
cDb::TF_SORT => true,
cDb::TF_SEARCH => false,
cDb::TF_TITLE => $this->gM("Attempts"),
cDb::TF_CLASS => 'w8 center',
cDb::TF_DB_FIELD => 'mm.mail_send_atempt',
cDb::TF_TYPE => cDb::TF_T_INPUT,
),
"mail_read" => array(
cDb::TF_SORT => true,
cDb::TF_SEARCH => false,
cDb::TF_TITLE => $this->gM("Read"),
cDb::TF_CLASS => 'w8 center',
cDb::TF_DB_FIELD => 'mm.mail_read',
cDb::TF_TYPE => cDb::TF_T_DROPBOX,
cDb::TF_DROPBOX_DATA => $readStatusData,
cDb::TF_DEFAULT_VALUE => '',
),
"status" => array(
cDb::TF_SORT => true,
cDb::TF_SEARCH => false,
cDb::TF_TITLE => $this->gM("Disabled"),
cDb::TF_CLASS => 'w8 center',
cDb::TF_DB_UPDATE_FIELD => 'mail_disabled',
cDb::TF_DB_FIELD => 'mm.mail_disabled',
cDb::TF_TYPE => cDb::TF_T_DROPBOX,
cDb::TF_DROPBOX_DATA => $statusData,
cDb::TF_DEFAULT_VALUE => '',
),
"mail_server_type" => array(
cDb::TF_SORT => true,
cDb::TF_SEARCH => false,
cDb::TF_TITLE => $this->gM("Server"),
cDb::TF_CLASS => 'w8 center',
cDb::TF_DB_FIELD => 'mm.mail_server_type',
cDb::TF_TYPE => cDb::TF_T_DROPBOX,
cDb::TF_DROPBOX_DATA => $srvStatusData,
cDb::TF_DEFAULT_VALUE => '',
),
"buttons" => array(
cDb::TF_SORT => false,
cDb::TF_CLASS => 'w20',
cDb::TF_TITLE => $this->gM("Actions"),
cDb::TF_BUTTONS => array(
'lsend' => array(
cDb::TF_TITLE => $this->gM("Send now"),
),
'ledit' => array(
'edit' => true,
cDb::TF_TITLE => $this->gM("Edit"),
),
'lview' => array(
'edit' => true,
cDb::TF_TITLE => $this->gM("View"),
),
'ldelete' => array(
cDb::TF_TITLE => $this->gM("Delete"),
)
)
)
);
if($this->history){
unset($tFields['status']);
unset($tFields['buttons'][cDb::TF_BUTTONS]['lsend'], $tFields['buttons'][cDb::TF_BUTTONS]['ledit']);
}else{
unset($tFields['mail_read'], $tFields['mail_sent'], $tFields[cDb::TF_BUTTONS]['btnset']['lview']);
if(!$this->chkP('CMS_MAILENGINE_ADD_NEW') && !$this->chkP('CMS_MAILENGINE_EDIT'))
$tFields[cDb::TF_BUTTONS]['btnset']['ledit'][cDb::TF_TITLE] = $this->gM("View");
}
if(!$this->chkP('SYS_SHOW_TABLE_IDS'))
unset($tFields['id']);
return $tFields;
}
/**
* Function to create fields for plugin table
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cmsMailEngine Controller
* @return array of data
* @version 1.1
*/
public function getPluginTableFields() {
$data = array(
"mail_owner" => array(
'class' => 'w15'
),
"mail_title" => array(
'class' => 'w15'
),
);
return $data;
}
/**
* Function to set plugin data to view or check if permission exists for plugin
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cmsMailEngine Controller
* @param bool $pCheck - indicates if permission check initiated
* @return array of data
*/
public function getPluginData($pCheck = false) {
if($pCheck){
return $this->chkP('CMS_MAILENGINE_OUT_SHOW_MANAGEMENT');
}else if($this->chkP('CMS_MAILENGINE_OUT_SHOW_MANAGEMENT')){
$data = $this->module->getPluginRecords();
$this->oView->LIST_DATA = $data;
$this->oView->LIST_HEADER = $this->getPluginTableFields();
return true;
}
return false;
}
/**
* Function to get js translations for view
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cmsMailEngine Controller
* @return array of data
*/
public function getTranslations(){
return array(
'yes' => $this->gM('Yes'),
'no' => $this->gM('No'),
'delTitle' => $this->gM('Delete mails?'),
'delMessage' => $this->gM('Selected mails will be permanently deleted and cannot be recovered. Confirm delete?'),
'buttonYes' => $this->gM('Delete selected mails'),
'buttonCancel' => $this->gM('Cancel operation'),
);
}
/**
* Function to get table actions
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cmsMailEngine Controller
* @return array of data
*/
public function getTableActions(){
$actions = array(
'inewmail' => array(
'lbl' => $this->gM("Add new mail"),
'icon' => 'nico-add',
),
'sepline',
'istopall' => array(
'lbl' => $this->gM("Disable all"),
),
'iresumeall' => array(
'lbl' => $this->gM("Enable all"),
),
'istatus' => array(
'lbl' => $this->gM("Change item delivery status"),
),
'sepline',
'idelete' => array(
'lbl' => $this->gM("Delete selected"),
'icon' => 'nico-delete'
),
);
if($this->history)
unset($actions['istatus'], $actions['inewmail'], $actions['istopall'], $actions['iresumeall']);
if(!$this->chkP('CMS_MAILENGINE_ADD_NEW'))
unset($actions['inewmail'], $actions['istopall'], $actions['iresumeall']);
// Reformat drop down
reformatDropDown($actions, false);
return $actions;
}
/**
* Function to show mail content
*
* @category cmsMailEngine Controller
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @returns string - html based data
*/
public function showMail($id = false){
if($id){
$mail = $this->module->getRecordById($id);
$link = $this->getFullLinkForID();
$mail['mail_attachment'] = ($mail['mail_attachment']?"<a class='att' href='{$link}?dfile=" . base64_encode(urldecode($mail['mail_attachment'])) . "'>".$this->gM('Attachement')."</a>":"");
if($this->history)
$mail['mail_sent'] = date('d-m-Y H:i', $mail['mail_sent']);
$this->oView->mail = $mail;
$mailData = $this->oView->genTemplate('qmailTemplate');
}else{
$mailData = $this->oView->genTemplate('noMailTemplate');
}
echo $mailData;
die();
}
/**
* Function to trigger file download if file id passed
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cmsMailEngine Controller
* @return array of data
* @version 1.1
*/
public function chkFileDownload(){
if($file = base64_decode(getG('dfile'))){
if(substr($file, 0, 3) == 'URL'){
$cry = new cDefuseCrypto();
// Regenerate pdf
$_GET['receipt'] = str_replace('URL:', '', $file);
$payments = new pubBuy($this->getUriDataForController(pubBuyController::CART_URI_ID, true));
$file = $payments->controller->throwDocument();
}
if(file_exists($file)){
$basename = str_replace(' ', '_', basename($file));
$ext = getExtension($basename);
$type = "text/plain";
if(isset($this->mimeTypes[$ext]))
$type = $this->mimeTypes[$ext];
// Set headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename={$basename}");
header("Content-Type: {$type}");
header("Content-Transfer-Encoding: binary");
// Read the file from disk
readfile($file);
die();
}else{
redirectToUri($this->gL());
}
}
return false;
}
/**
* Function to send mail by passed config or mail id in mail pending table
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cmsMailEngine Controller
* @param int|bool $id - mail id
* @param bool $data - mail cfg data
* @param bool $dbLock - lock mail in db
* @return array of data
* @version 1.1
*/
public function pushMail($id = false, $data = false, $dbLock = false){
// Check send mail flag
if(defined('SEND_MAILS') && !SEND_MAILS || !defined('SEND_MAILS')) cJSON::sendError('Outgoing E-Mails are DISABLED!!!');
// Get data from module table
if($id){
$data = $this->module->getRecordById($id);
if(isset($data['mail_disabled']) && $data['mail_disabled'])
return false;
if($dbLock){
$this->module->saveRecordById($id, array('mail_locked' => 1));
}
}
if($data){
// Check if attachment is URL instead of file
/*if(substr($data['mail_attachment'], 0, 3) == 'URL'){
$cry = new cDefuseCrypto();
if(!$uriData = $this->mailS->uriData){
$uriData = $this->getUriDataForController(pubBuyController::CART_URI_ID, true);
$this->mailS->uriData = $uriData;
}
if($data['mail_lang_id']){
$uriData['p_lang_id'] = $data['mail_lang_id'];
}
// Generate pdf
$payments = new pubBuy($uriData);
$_GET['receipt'] = str_replace('URL:', '', $data['mail_attachment']);
$data['mail_attachment'] = $payments->controller->throwDocument(true);
}*/
if(empty(cMail::$SERVER_CFG[$data['mail_server_type']]))
cJSON::sendError(array('msg' => "Passed mail server does'nt exist!"));
// Send mailclass
$mm = new cMail();
$oCfg = new cINI(__CFG__ . 'init.cfg.ini');
$vLocalHosts = $oCfg->getV('domain_cfg_json', 'localhost_domains', true);
//------------------------------------------------------------------------
// Add mail tracking image & other image manipulation for later view
// Preserve old content 4 sent mail insert
//------------------------------------------------------------------------
$sOldHTMLContent4sent = $data['mail_content'];
$sHost = (in_array($_SERVER['HTTP_HOST'], $vLocalHosts) ? cMail::EHLO_SERVER : $_SERVER['HTTP_HOST']);
// Create tracking url for each server
$sLoadedImg = "http://{$sHost}/img/pub/default_logo.jpg";
$sTrackingImgUrl = "http://{$sHost}/ajax/ac:track/img:x/m{$data['id']}.png";
switch($data['mail_server_type']){
case cMail::MAIL_SERVER_DEFAULT:
$sLoadedImg = "http://{$sHost}/img/pub/mails/sys_logo4.png";
$sTrackingImgUrl = "http://{$sHost}/ajax/ac:track/img:{$data['mail_server_type']}/m{$data['id']}.png";
break;
}
// Add tracking image url if space variable specified
if(strpos($data['mail_content'], cMail::MAIL_TRACKING_STR) !== false){
$data['mail_content'] = str_replace(cMail::MAIL_TRACKING_STR, $sTrackingImgUrl, $data['mail_content']);
$sOldHTMLContent4sent = str_replace(cMail::MAIL_TRACKING_STR, $sLoadedImg, $sOldHTMLContent4sent);
cMail::stripLeftDataVariableInMailContent($sOldHTMLContent4sent);
// Add tracking pixel
}else{
$data['mail_content'] .= "<img src=\"{$sTrackingImgUrl}\" alt=\"\" height=\"35px\" /><br/>\n\n";
//$data['mail_content'] .= "<img src=\"{$sTrackingImgUrl}\" alt=\"\" width=\"1px\" height=\"1px\" />";
}
//------------------------------------------------------------------------
// Send mail
//------------------------------------------------------------------------
if($mm->sendMail($data)){
$data['mail_oid'] = ($id?$id:@$data['id']);
$data['mail_sent'] = time();
$data['mail_content'] = $sOldHTMLContent4sent;
// Mail sent - move outgoing mail to the sent if $dbLock specified
if($dbLock){
$this->moveMailToSent(array($data));
return true;
}
return $data;
}
}
return false;
}
/**
* Function to move pending sent mails to sent mail table
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cmsMailEngine Controller
* @param array|bool $data - mail data
* @return array of data
* @version 1.1
*/
public function moveMailToSent($data = false){
if(count($data)){
$delId = array();
foreach ($data as &$v) {
$delId[] = $v['id'];
unset($v['id'], $v['mail_disabled'], $v['mail_locked'], $v['mail_tracking']);
}
unset($v);
$this->module->db->query("DELETE FROM mod_mail_outgoing WHERE mail_locked = '1' AND id IN (" . implode(',', $delId) . ")");
$this->module->db->_queryInsertArray('mod_mail_sent', $data, false, true);
return true;
}
return false;
}
/**
* Function to send mails with CRON
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cmsMailEngine Controller
* @return array of data
* @version 1.1
*/
public function cronSendMails(){
$ids = array();
$sent = array();
$mails = $this->module->getCronMAILS();
if(!!$mails && count($mails)){
//------------------------------------------------------------------
// Set all mails as locked
//------------------------------------------------------------------
foreach($mails as $v){
$ids[] = $v['id'];
}
$this->module->db->query("UPDATE mod_mail_outgoing SET mail_locked = '1' WHERE id IN (" . implode(',', $ids) . ")");
//------------------------------------------------------------------
// Generate mail attachments if any missing & send mail
//------------------------------------------------------------------
foreach($mails as $k=>$v){
if($mm = $this->pushMail(false, $v, false)){
$sent[] = $mm;
unset($mails[$k]);
}else{
$mails[$k]['mail_send_atempt'] = intval($mails[$k]['mail_send_atempt'])+1;
}
// Sleep seconds before next mail sent
sleep(5);
}
//------------------------------------------------------------------
// Move sent mails from outbox & update failed
//------------------------------------------------------------------
if(count($sent)){
$this->moveMailToSent($sent);
}
if(count($mails)){
$ids = array();
foreach($mails as $v){
$ids[] = $v['id'];
}
// Delete old mails & insert renewed
$this->module->db->query("DELETE FROM mod_mail_outgoing WHERE mail_locked = '1' AND id IN (" . implode(',', $ids) . ")");
$this->module->db->_queryInsertArray('mod_mail_outgoing', $mails, false, true);
}
}
}
/**
* Function to enable newsletters to send
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cmsMailEngine Controller
* @return array of data
* @version 1.1
*/
public function cronEnableNewsletters(){
$count = $this->module->getNewsletterSentCount(array(
'from' => strtotime(date('d-m-Y')),
'till' => strtotime('+1 day', strtotime(date('d-m-Y'))),
));
$dayLimit = 260; // gMail day limit
if($count !== false && $count < $dayLimit){
if($count < 140 )
$enable = 7*20;
else
$enable = $dayLimit - $count;
$this->module->enableOutgoingNewsletterCount($enable);
cDbLogModule::actionLog('enable_outgoing_newsletters', "{$enable}");
}
}
/**
* Function to send today's new order count
*
* @author Mareks Keišs <mareks.keiss@brsystems.lv>
* @category cmsMailEngine Controller
* @return array of data
* @version 1.1
*/
public function sendNewOrderCount(){
$pubPay = new pubBuyModule();
$orderCount = $pubPay->getNewOrders();
// Add to send new mail
if($orderCount > 0){
$mm = new cMail();
$langId = getDefaultAppLang();
$mm->addMail(
cMail::$SERVER_CFG[cMail::MAIL_SERVER_DEFAULT][cMail::SENDER],
false,
cMail::MAIL_SERVER_DEFAULT,
cMail::MAIL_1_DAILY_REPORT,
$langId,
array(
'prod-count' => $orderCount,
'online-link' => $this->getFullLinkForID(511, false, 1)
),
false, true, 1);
}
}
}