/i","/
/i","/
/i"),array("\n","\n","\n"),$textmessage));
$textmessage = str_replace('#link#','<',$textmessage);
$textmessage = str_replace('#link-e#','>',$textmessage);
return array('html'=>$htmlmessage,'text'=>$textmessage);
}
function saveTemplateEmail($templateid = null) {
global $adb, $table_prefix;
if (empty($templateid)) $templateid = $this->column_fields['templateemailid'];
if (empty($templateid)) return false;
$date_scheduled = $this->column_fields['date_scheduled'].' '.$this->column_fields['time_scheduled'];
$tplres = $adb->pquery("select * from {$table_prefix}_emailtemplates where templateid = ?", array($templateid));
if ($tplres && $adb->num_rows($tplres) > 0) {
$tplinfo = $adb->FetchByAssoc($tplres, -1, false);
$tplid = $adb->getUniqueID('tbl_s_newsletter_tpl');
$tplnl = array($tplid, $this->id, $adb->formatDate($date_scheduled,true), $tplinfo['templatename'], $tplinfo['subject']);
$res = $adb->pquery('insert into tbl_s_newsletter_tpl (tplid, newsletterid, datesent, templatename, subject) values ('.generateQuestionMarks($tplnl).')', $tplnl);
// update longtext columns
$adb->updateClob('tbl_s_newsletter_tpl','description',"tplid=$tplid",$tplinfo['description']);
$adb->updateClob('tbl_s_newsletter_tpl','body',"tplid=$tplid",$tplinfo['body']);
// calculate fields
$fields = array('subject'=>array(), 'body'=>array());
if (preg_match_all('/\$[^|]+\|[^|]*\|[^$]+\$/', $tplinfo['subject'], $matches) && count($matches[0]) > 0) {
foreach ($matches[0] as $m) {
$fields['subject'][] = $m;
}
}
if (preg_match_all('/\$[^|]+\|[^|]*\|[^$]+\$/', $tplinfo['body'], $matches) && count($matches[0]) > 0) {
foreach ($matches[0] as $m) {
$fields['body'][] = $m;
}
}
// and save them
$adb->updateClob('tbl_s_newsletter_tpl','fields',"tplid=$tplid",Zend_Json::encode($fields));
}
}
// shows the newsletter
// NOTE: this method may be called from un-logged users
function showNewsletter($crmid = null, $hideAddress = false, $trackUser = true, $showBackButton = false) { // crmv@47490 crmv@135115
global $adb, $table_prefix, $default_charset; //crmv@170167
if (empty($this->id)) return null;
$templateid = intval($this->column_fields['templateemailid']);
// try to retrieve from saved templates
$res = $adb->pquery("select * from tbl_s_newsletter_tpl where newsletterid = ? order by tplid desc", array($this->id)); // crmv@175282
if ($res && $adb->num_rows($res) > 0) {
$templateInfo = $adb->FetchByAssoc($res, -1, false);
$jsonStruct = Zend_Json::decode($templateInfo['fields']);
} elseif ($templateid > 0) {
// retrieve from current templates
$res = $adb->pquery("select * from {$table_prefix}_emailtemplates where deleted = 0 and templateid = ?", array($templateid));
if ($res && $adb->num_rows($res) > 0) {
$templateInfo = $adb->FetchByAssoc($res, -1, false);
}
} else {
return null;
}
if (empty($templateInfo)) return null;
// crmid-dependant replacements
if ($crmid > 0) {
// initialize related module
$module = getSalesEntityType($crmid);
if (empty($module) || !array_key_exists($module,$this->email_fields)) { //crmv@181281
$module = $crimd = '';
} else {
$focus = CRMEntity::getInstance($module);
// global substitutions
$replacements = array();
$templateInfo['body'] = $this->setGlobalLinks($templateInfo['body'], $crmid, $replacements);
if (is_array($jsonStruct['body']) && is_array($replacements) && count($replacements) > 0) {
$jsonStruct['body'] = array_diff($jsonStruct['body'], array_keys($replacements));
}
// check if we have saved fields
$res = $adb->pquery("select fieldvalues from tbl_s_newsletter_queue where newsletterid = ? and crmid = ?", array($this->id, $crmid));
if ($res && $adb->num_rows($res) > 0 && is_array($jsonStruct) && count($jsonStruct) > 0) {
$jsonFields = Zend_Json::decode($adb->query_result_no_html($res, 0, 'fieldvalues'));
if (is_array($jsonFields) && count($jsonFields) > 0) {
if (is_array($jsonStruct['subject']) && count($jsonStruct['subject']) > 0) {
$subfields = array_slice($jsonFields, 0, count($jsonStruct['subject']));
$bodyfields = array_slice($jsonFields, count($jsonStruct['subject']));
} else {
$subfields = array();
$bodyfields = $jsonFields;
}
if (!empty($subfields)) {
$templateInfo['subject'] = str_replace($jsonStruct['subject'], $subfields, $templateInfo['subject']);
}
if (!empty($bodyfields)) {
$templateInfo['body'] = str_replace($jsonStruct['body'], $bodyfields, $templateInfo['body']);
//crmv@94298
$body = $this->setTrackLinks(htmlentities($templateInfo['body'],ENT_QUOTES,$default_charset),$crmid, $trackUser); // stupid and useless trick to have correct chars, crmv@47490 crmv@170167
$templateInfo['body'] = $body['html'];
//crmv@94298e
}
}
} else {
$templateInfo['subject'] = getMergedDescription($templateInfo['subject'],$crmid,$module);
$templateInfo['body'] = getMergedDescription($templateInfo['body'],$crmid,$module);
$body = $this->setTrackLinks(htmlentities($templateInfo['body'],ENT_QUOTES,$default_charset),$crmid, $trackUser); // stupid and useless trick to have correct chars, crmv@47490 crmv@170167
$templateInfo['body'] = $body['html'];
}
}
// global substitutions
} else {
$templateInfo['body'] = $this->setGlobalLinks($templateInfo['body']);
}
global $small_page_title, $small_page_path;
$small_page_title= getTranslatedString('LBL_PREVIEW_NEWSLETTER', 'Newsletter');
// crmv@135115
if ($showBackButton) {
$small_page_buttons = '';
}
// crmv@135115e
// draw header and get smarty instance
include('themes/SmallHeader.php');
$smarty->assign('NEWSLETTERINFO', $this->column_fields);
$smarty->assign('TEMPLATEINFO', $templateInfo);
if ($crmid > 0 && $focus && !$hideAddress) {
// get address
$error = $focus->retrieve_entity_info($crmid,$module,false);
if ($error == '') {
$to_address = $focus->column_fields[$this->email_fields[$module]['fieldname']];
$smarty->assign('TO_ADDRESS', $to_address);
$ename = getEntityName($module, $crmid);
$smarty->assign('TO_NAME', $ename[$crmid]);
}
}
$smarty->display('modules/Newsletter/ShowPreview.tpl');
}
// crmv@38592e
function cleanTrackUrl($url,$disallowed_params = array('PHPSESSID')) {
$parsed = @parse_url($url);
$params = array();
if (empty($parsed['query'])) {
$parsed['query'] = '';
}
# hmm parse_str should take the delimiters as a parameter
if (strpos($parsed['query'],'&')) {
$pairs = explode('&',$parsed['query']);
foreach ($pairs as $pair) {
list($key,$val) = explode('=',$pair);
$params[$key] = $val;
}
} else {
parse_str($parsed['query'],$params);
}
$uri = !empty($parsed['scheme']) ? $parsed['scheme'].':'.((strtolower($parsed['scheme']) == 'mailto') ? '':'//'): '';
$uri .= !empty($parsed['user']) ? $parsed['user'].(!empty($parsed['pass'])? ':'.$parsed['pass']:'').'@':'';
$uri .= !empty($parsed['host']) ? $parsed['host'] : '';
$uri .= !empty($parsed['port']) ? ':'.$parsed['port'] : '';
$uri .= !empty($parsed['path']) ? $parsed['path'] : '';
# $uri .= $parsed['query'] ? '?'.$parsed['query'] : '';
$query = '';
foreach ($params as $key => $val) {
if (!in_array($key,$disallowed_params)) {
//0008980: Link Conversion for Click Tracking. no = will be added if key is empty.
$query .= $key . ( ($val !== '' && !is_null($val)) ? '=' . $val . '&' : '&' ); //crmv@36574
}
}
$query = substr($query,0,-1);
$uri .= $query ? '?'.$query : '';
# if (!empty($params['p'])) {
# $uri .= '?p='.$params['p'];
# }
$uri .= !empty($parsed['fragment']) ? '#'.$parsed['fragment'] : '';
return $uri;
}
//crmv@55961
function unsubscribe($crmid, $mode) {
//il controllo lo faccio sul campo email perche' se modifico il target e aggiungo un lead con
//la stessa email di un contatto che si e' gia' disiscritto non devo comunque mandargli la mail
/*
* return: 1 done
* return: 2 already done
* return: 3 problems
*/
global $adb;
$module = getSalesEntityType($crmid);
$focus = CRMEntity::getInstance($module);
$focus->retrieve_entity_info($crmid,$module);
$email = $focus->column_fields[$this->email_fields[$module]['fieldname']];
if ($mode == 'campaign') {
$result = $adb->pquery('select * from tbl_s_newsletter_unsub where newsletterid = ? and email = ?',array($this->id,$email));
if ($result && $adb->num_rows($result)>0) {
return 2;
} else {
$adb->pquery('insert into tbl_s_newsletter_unsub (newsletterid,email,statusid) values (?,?,?)',array($this->id,$email,1)); //crmv@38592
$result = $adb->pquery('select * from tbl_s_newsletter_unsub where newsletterid = ? and email = ?',array($this->id,$email));
if ($result && $adb->num_rows($result)>0) {
$this->saveUnsubscribeChangelog($crmid, $mode); // crmv@151474
return 1;
}
}
} elseif ($mode == 'all') {
$result = $adb->pquery('select * from tbl_s_newsletter_g_unsub where email = ?',array($email));
if ($result && $adb->num_rows($result)>0) {
return 2;
} else {
$this->lockReceivingNewsletter($email,'lock');
$result = $adb->pquery('select * from tbl_s_newsletter_g_unsub where email = ?',array($email));
if ($result && $adb->num_rows($result)>0) {
$this->saveUnsubscribeChangelog($crmid, $mode); // crmv@151474
return 1;
}
}
}
return 3;
}
// crmv@151474
public function saveUnsubscribeChangelog($crmid, $mode, $unsubscribe = true) {
global $current_user;
// crmv@164120
if (vtlib_isModuleActive('ChangeLog')) {
// as if admin unsubscribed the contact
$current_user_bkp = $current_user;
$current_user = Users::getActiveAdminUser();
$changeLogType = ($unsubscribe ? 'ChangeLogNLUnsubscribe' : 'ChangeLogNLSubscribe');
$obj = ChangeLog::getInstance();
$obj->column_fields['modified_date'] = date('Y-m-d H:i:s');
$obj->column_fields['audit_no'] = $obj->get_revision_id($crmid);
$obj->column_fields['user_id'] = $current_user->id;
$obj->column_fields['parent_id'] = $crmid;
$obj->column_fields['user_name'] = $current_user->column_fields['user_name'];
$obj->column_fields['description'] = Zend_Json::encode(array($changeLogType,$this->id,$mode,$this->column_fields['newslettername']));
$obj->save();
$current_user = $current_user_bkp;
}
// crmv@164120e
}
// crmv@151474e
function receivingNewsletter($email) {
global $adb;
if ($email == 'Anonymous') return false; //crmv@161554
static $_cache = array();
if (!isset($_cache[$email])) {
$result = $adb->pquery("select * from tbl_s_newsletter_g_unsub where email = ?",array($email));
if ($result && $adb->num_rows($result) > 0) {
// this email is locked
$_cache[$email] = false;
} else {
$_cache[$email] = true;
}
}
return $_cache[$email];
}
function lockReceivingNewsletter($email, $mode) {
global $adb;
if ($mode == 'lock') {
if ($adb->isMysql()){
$adb->pquery('insert ignore into tbl_s_newsletter_g_unsub (email,unsub_date) values (?,?)',array($email,date('Y-m-d H:i:s')));
// crmv@87062
} else {
$result = $adb->pquery('select email from tbl_s_newsletter_g_unsub where email = ?',array($email));
if ($result && $adb->num_rows($result) == 0) {
$adb->pquery('insert into tbl_s_newsletter_g_unsub (email,unsub_date) values (?,?)',array($email,date('Y-m-d H:i:s')));
}
}
// crmv@87062e
} elseif ($mode == 'unlock') {
$adb->pquery('delete from tbl_s_newsletter_g_unsub where email = ?',array($email));
}
}
//crmv@55961e
function getUnsubscriptedList() {
global $adb;
global $table_prefix;
$newsletterid = array();
if ($this->column_fields['campaignid'] != '') {
$result = $adb->query('SELECT newsletterid FROM '.$table_prefix.'_newsletter
INNER JOIN '.$table_prefix.'_crmentity ON '.$table_prefix.'_crmentity.crmid = '.$table_prefix.'_newsletter.newsletterid
WHERE deleted = 0 AND campaignid = '.$this->column_fields['campaignid']);
if ($result && $adb->num_rows($result)>0) {
while($row=$adb->fetchByAssoc($result)) {
$newsletterid[] = $row['newsletterid'];
}
}
} else {
$newsletterid[] = $this->id;
}
$unsubscripted = array();
$result = $adb->query('select email from tbl_s_newsletter_unsub where newsletterid in ('.implode(',',$newsletterid).')');
if ($result && $adb->num_rows($result)>0) {
while($row=$adb->fetchByAssoc($result)) {
$unsubscripted[] = $row['email'];
}
}
//crmv@55961
$result = $adb->query('select email from tbl_s_newsletter_g_unsub');
if ($result && $adb->num_rows($result)>0) {
while($row=$adb->fetchByAssoc($result)) {
if (!in_array($row['email'],$unsubscripted)) $unsubscripted[] = $row['email'];
}
}
//crmv@55961e
return $unsubscripted;
}
function getNoEmailProcessedBySchedule() {
return $this->no_email_processed_by_schedule;
}
function getIntervalBetweenEmailDelivery() {
return $this->interval_between_email_delivery;
}
function getIntervalBetweenBlocksEmailDelivery() {
return $this->interval_between_blocks_email_delivery;
}
/* crmv@24933 crmv@55961 */
function trackLink($linkid,$newsletterid,$crmid,$linkurlid,$msgtype) {
global $adb;
// get existing tracklink
$result = $adb->pquery('select * from tbl_s_newsletter_tl where linkurlid = ? and newsletterid = ? and crmid = ?',array($linkid,$newsletterid,$crmid));
$trackdata = $adb->FetchByAssoc($result, -1, false);
$date = $adb->formatDate(date('Y-m-d H:i:s'),true);
if (empty($trackdata['trackid'])) {
// insert
$trackid = $adb->getUniqueID('tbl_s_newsletter_tl');
$adb->pquery('insert into tbl_s_newsletter_tl (trackid, newsletterid, linkurlid, crmid, firstclick, latestclick, clicked) values(?,?,?,?,?,?,?)',
array($trackid, $newsletterid, $linkid, $crmid, $date, $date, 1)
);
} else {
$trackid = $trackdata['trackid'];
// update
$adb->pquery('update tbl_s_newsletter_tl set latestclick = ?, clicked = clicked + 1 where trackid = ? and crmid = ? and newsletterid = ? and linkurlid = ?',array($date,$trackid,$crmid,$newsletterid,$linkurlid));
}
$result = $adb->pquery('select first_view,last_view,num_views from tbl_s_newsletter_queue where newsletterid = ? and crmid = ?',array($newsletterid,$crmid));
if ($result && $adb->num_rows($result)>0) {
$first_view = $adb->query_result($result,0,'first_view');
$last_view = $adb->query_result($result,0,'last_view');
$num_views = $adb->query_result($result,0,'num_views');
if (in_array($first_view,array('','0000-00-00 00:00:00'))) {
$adb->pquery('update tbl_s_newsletter_queue set first_view = ? where newsletterid = ? and crmid = ?',array($date,$newsletterid,$crmid));
}
if ($msgtype == 'T' || in_array($last_view,array('','0000-00-00 00:00:00'))) {
//questa parte viene eseguita qui quando la mail viene letta come testo semplice in quanto non viene mostrata l'immagine per il track user
$adb->pquery('update tbl_s_newsletter_queue set last_view = ? where newsletterid = ? and crmid = ?',array($date,$newsletterid,$crmid));
}
if ($msgtype == 'T' || $num_views == 0) {
$adb->pquery('update tbl_s_newsletter_queue set num_views = ? where newsletterid = ? and crmid = ?',array(($num_views+1),$newsletterid,$crmid));
}
}
}
//crmv@101506 crmv@104975
function getExtraDetailTabs() {
$return = array();
$return = array(
array('label'=>getTranslatedString('LBL_STATISTICS', 'Newsletter'),'href'=>'','onclick'=>"changeDetailTab('{$this->modulename}', '{$this->id}', 'Statistics', this)")
);
$others = parent::getExtraDetailTabs() ?: array();
return array_merge($return, $others);
}
// crmv@104975e
function getExtraDetailBlock() {
return '