3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 require_once 'Mail/mime.php';
20 * Class CRM_Mailing_BAO_Mailing
22 class CRM_Mailing_BAO_Mailing
extends CRM_Mailing_DAO_Mailing
{
25 * An array that holds the complete templates
26 * including any headers or footers that need to be prepended
27 * or appended to the body.
30 private $preparedTemplates = NULL;
33 * An array that holds the complete templates
34 * including any headers or footers that need to be prepended
35 * or appended to the body.
38 private $templates = NULL;
41 * An array that holds the tokens that are specifically found in our text and html bodies.
44 private $tokens = NULL;
47 * An array that holds the tokens that are specifically found in our text and html bodies.
50 private $flattenedTokens = NULL;
53 * The header associated with this mailing.
56 private $header = NULL;
59 * The footer associated with this mailing.
62 private $footer = NULL;
65 * The HTML content of the message.
71 * The text content of the message.
77 * Cached BAO for the domain.
80 private $_domain = NULL;
85 public function __construct() {
86 parent
::__construct();
92 * @param int $mailingID
96 public static function getRecipientsCount($mailingID) {
97 //rebuild the recipients
98 self
::getRecipients($mailingID);
100 return civicrm_api3('MailingRecipients', 'getcount', ['mailing_id' => $mailingID]);
104 * This function retrieve recipients of selected mailing groups.
106 * @param int $mailingID
110 public static function getRecipients($mailingID) {
111 // load mailing object
112 $mailingObj = new self();
113 $mailingObj->id
= $mailingID;
114 $mailingObj->find(TRUE);
116 $mailing = CRM_Mailing_BAO_Mailing
::getTableName();
117 $contact = CRM_Contact_DAO_Contact
::getTableName();
118 $isSMSmode = (!CRM_Utils_System
::isNull($mailingObj->sms_provider_id
));
120 $mailingGroup = new CRM_Mailing_DAO_MailingGroup();
121 $recipientsGroup = $excludeSmartGroupIDs = $includeSmartGroupIDs = $priorMailingIDs = [];
122 $dao = CRM_Utils_SQL_Select
::from('civicrm_mailing_group')
123 ->select('GROUP_CONCAT(DISTINCT entity_id SEPARATOR ",") as group_ids, group_type, entity_table')
124 ->where('mailing_id = #mailing_id AND entity_table RLIKE "^civicrm_(group.*|mailing)$" ')
125 ->groupBy(['group_type', 'entity_table'])
126 ->param('!groupTableName', CRM_Contact_BAO_Group
::getTableName())
127 ->param('#mailing_id', $mailingID)
129 while ($dao->fetch()) {
130 if ($dao->entity_table
== 'civicrm_mailing') {
131 $priorMailingIDs[$dao->group_type
] = explode(',', $dao->group_ids
);
134 $recipientsGroup[$dao->group_type
] = empty($recipientsGroup[$dao->group_type
]) ?
explode(',', $dao->group_ids
) : array_merge($recipientsGroup[$dao->group_type
], explode(',', $dao->group_ids
));
138 // there is no need to proceed further if no mailing group is selected to include recipients,
139 // but before return clear the mailing recipients populated earlier since as per current params no group is selected
140 if (empty($recipientsGroup['Include']) && empty($priorMailingIDs['Include'])) {
141 CRM_Core_DAO
::executeQuery(" DELETE FROM civicrm_mailing_recipients WHERE mailing_id = %1 ", [
150 list($location_filter, $order_by) = self
::getLocationFilterAndOrderBy($mailingObj->email_selection_method
, $mailingObj->location_type_id
);
152 // get all the saved searches AND hierarchical groups
153 // and load them in the cache
154 foreach ($recipientsGroup as $groupType => $groupIDs) {
155 $groupDAO = CRM_Utils_SQL_Select
::from('civicrm_group')
156 ->where('id IN (#groupIDs)')
157 ->where('saved_search_id != 0 OR saved_search_id IS NOT NULL OR children IS NOT NULL')
158 ->param('#groupIDs', $groupIDs)
160 while ($groupDAO->fetch()) {
161 // hidden smart groups always have a cache date and there is no other way
162 // we can rebuilt the contact list from UI so consider such smart group
163 if ($groupDAO->cache_date
== NULL ||
$groupDAO->is_hidden
) {
164 CRM_Contact_BAO_GroupContactCache
::load($groupDAO);
166 if ($groupType == 'Include') {
167 $includeSmartGroupIDs[] = $groupDAO->id
;
169 elseif ($groupType == 'Exclude') {
170 $excludeSmartGroupIDs[] = $groupDAO->id
;
172 //NOTE: Do nothing for base
176 // Create a temp table for contact exclusion.
177 $excludeTempTable = CRM_Utils_SQL_TempTable
::build()->setCategory('exrecipient')->setMemory()->createWithColumns('contact_id int primary key');
178 $excludeTempTablename = $excludeTempTable->getName();
179 // populate exclude temp-table with recipients to be excluded from the list
180 // on basis of selected recipients groups and/or previous mailing
181 if (!empty($recipientsGroup['Exclude'])) {
182 CRM_Utils_SQL_Select
::from('civicrm_group_contact')
183 ->select('DISTINCT contact_id')
184 ->where('status = "Added" AND group_id IN (#groups)')
185 ->param('#groups', $recipientsGroup['Exclude'])
186 ->insertInto($excludeTempTablename, ['contact_id'])
189 if (count($excludeSmartGroupIDs)) {
190 CRM_Utils_SQL_Select
::from('civicrm_group_contact_cache')
191 ->select('contact_id')
192 ->where('group_id IN (#groups)')
193 ->param('#groups', $excludeSmartGroupIDs)
194 ->insertIgnoreInto($excludeTempTablename, ['contact_id'])
198 if (!empty($priorMailingIDs['Exclude'])) {
199 CRM_Utils_SQL_Select
::from('civicrm_mailing_recipients')
200 ->select('DISTINCT contact_id')
201 ->where('mailing_id IN (#mailings)')
202 ->param('#mailings', $priorMailingIDs['Exclude'])
203 ->insertIgnoreInto($excludeTempTablename, ['contact_id'])
207 if (!empty($recipientsGroup['Base'])) {
208 CRM_Utils_SQL_Select
::from('civicrm_group_contact')
209 ->select('DISTINCT contact_id')
210 ->where('status = "Removed" AND group_id IN (#groups)')
211 ->param('#groups', $recipientsGroup['Base'])
212 ->insertIgnoreInto($excludeTempTablename, ['contact_id'])
216 $entityColumn = $isSMSmode ?
'phone_id' : 'email_id';
217 $entityTable = $isSMSmode ? CRM_Core_DAO_Phone
::getTableName() : CRM_Core_DAO_Email
::getTableName();
218 // Get all the group contacts we want to include.
219 $includedTempTable = CRM_Utils_SQL_TempTable
::build()->setCategory('inrecipient')->setMemory()->createWithColumns('contact_id int primary key, ' . $entityColumn . ' int');
220 $includedTempTablename = $includedTempTable->getName();
224 'is_deleted' => CRM_Utils_SQL_Select
::fragment()->where("$contact.is_deleted = 0"),
225 'is_opt_out' => CRM_Utils_SQL_Select
::fragment()->where("$contact.is_opt_out = 0"),
226 'is_deceased' => CRM_Utils_SQL_Select
::fragment()->where("$contact.is_deceased <> 1"),
227 'do_not_sms' => CRM_Utils_SQL_Select
::fragment()->where("$contact.do_not_sms = 0"),
228 'location_filter' => CRM_Utils_SQL_Select
::fragment()->where("$entityTable.phone_type_id = " . CRM_Core_PseudoConstant
::getKey('CRM_Core_DAO_Phone', 'phone_type_id', 'Mobile')),
229 'phone_not_null' => CRM_Utils_SQL_Select
::fragment()->where("$entityTable.phone IS NOT NULL"),
230 'phone_not_empty' => CRM_Utils_SQL_Select
::fragment()->where("$entityTable.phone != ''"),
231 'mailing_id' => CRM_Utils_SQL_Select
::fragment()->where("mg.mailing_id = #mailingID"),
232 'temp_contact_null' => CRM_Utils_SQL_Select
::fragment()->where('temp.contact_id IS null'),
233 'order_by' => CRM_Utils_SQL_Select
::fragment()->orderBy("$entityTable.is_primary"),
237 // Criteria to filter recipients that need to be included
239 'is_deleted' => CRM_Utils_SQL_Select
::fragment()->where("$contact.is_deleted = 0"),
240 'do_not_email' => CRM_Utils_SQL_Select
::fragment()->where("$contact.do_not_email = 0"),
241 'is_opt_out' => CRM_Utils_SQL_Select
::fragment()->where("$contact.is_opt_out = 0"),
242 'is_deceased' => CRM_Utils_SQL_Select
::fragment()->where("$contact.is_deceased <> 1"),
243 'location_filter' => CRM_Utils_SQL_Select
::fragment()->where($location_filter),
244 'email_not_null' => CRM_Utils_SQL_Select
::fragment()->where("$entityTable.email IS NOT NULL"),
245 'email_not_empty' => CRM_Utils_SQL_Select
::fragment()->where("$entityTable.email != ''"),
246 'email_not_on_hold' => CRM_Utils_SQL_Select
::fragment()->where("$entityTable.on_hold = 0"),
247 'mailing_id' => CRM_Utils_SQL_Select
::fragment()->where("mg.mailing_id = #mailingID"),
248 'temp_contact_null' => CRM_Utils_SQL_Select
::fragment()->where('temp.contact_id IS NULL'),
249 'order_by' => CRM_Utils_SQL_Select
::fragment()->orderBy($order_by),
253 // Allow user to alter query responsible to fetch mailing recipients before build,
254 // by changing the mail filters identified $params
255 CRM_Utils_Hook
::alterMailingRecipients($mailingObj, $criteria, 'pre');
257 // Get the group contacts, but only those which are not in the
258 // exclusion temp table.
259 if (!empty($recipientsGroup['Include'])) {
260 CRM_Utils_SQL_Select
::from($entityTable)
261 ->select("$contact.id as contact_id, $entityTable.id as $entityColumn")
262 ->join($contact, " INNER JOIN $contact ON $entityTable.contact_id = $contact.id ")
263 ->join('gc', " INNER JOIN civicrm_group_contact gc ON gc.contact_id = $contact.id ")
264 ->join('mg', " INNER JOIN civicrm_mailing_group mg ON gc.group_id = mg.entity_id AND mg.search_id IS NULL ")
265 ->join('temp', " LEFT JOIN $excludeTempTablename temp ON $contact.id = temp.contact_id ")
266 ->where('gc.group_id IN (#groups) AND gc.status = "Added"')
268 ->groupBy(["$contact.id", "$entityTable.id"])
269 ->replaceInto($includedTempTablename, ['contact_id', $entityColumn])
270 ->param('#groups', $recipientsGroup['Include'])
271 ->param('#mailingID', $mailingID)
275 // Get recipients selected in prior mailings
276 if (!empty($priorMailingIDs['Include'])) {
277 CRM_Utils_SQL_Select
::from('civicrm_mailing_recipients')
278 ->select("DISTINCT civicrm_mailing_recipients.contact_id, $entityColumn")
279 ->join('temp', " LEFT JOIN $excludeTempTablename temp ON civicrm_mailing_recipients.contact_id = temp.contact_id ")
280 ->where('mailing_id IN (#mailings)')
281 ->where('temp.contact_id IS NULL')
282 ->param('#mailings', $priorMailingIDs['Include'])
283 ->insertIgnoreInto($includedTempTablename, [
290 if (count($includeSmartGroupIDs)) {
291 $query = CRM_Utils_SQL_Select
::from($contact)
292 ->select("$contact.id as contact_id, $entityTable.id as $entityColumn")
293 ->join($entityTable, " INNER JOIN $entityTable ON $entityTable.contact_id = $contact.id ")
294 ->join('gc', " INNER JOIN civicrm_group_contact_cache gc ON $contact.id = gc.contact_id ")
295 ->join('gcr', " LEFT JOIN civicrm_group_contact gcr ON gc.group_id = gcr.group_id AND gc.contact_id = gcr.contact_id")
296 ->join('mg', " INNER JOIN civicrm_mailing_group mg ON gc.group_id = mg.entity_id AND mg.search_id IS NULL ")
297 ->join('temp', " LEFT JOIN $excludeTempTablename temp ON $contact.id = temp.contact_id ")
298 ->where('gc.group_id IN (#groups)')
299 ->where('gcr.status IS NULL OR gcr.status != "Removed"')
301 ->replaceInto($includedTempTablename, ['contact_id', $entityColumn])
302 ->param('#groups', $includeSmartGroupIDs)
303 ->param('#mailingID', $mailingID)
307 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause();
309 // clear all the mailing recipients before populating
310 CRM_Core_DAO
::executeQuery(' DELETE FROM civicrm_mailing_recipients WHERE mailing_id = %1 ', [
317 $selectClause = ['#mailingID', 'i.contact_id', "i.$entityColumn"];
319 $orderBy = ["i.contact_id", "i.$entityColumn"];
321 $query = CRM_Utils_SQL_Select
::from('civicrm_contact contact_a')
322 ->join('i', " INNER JOIN {$includedTempTablename} i ON contact_a.id = i.contact_id ");
323 if (!$isSMSmode && $mailingObj->dedupe_email
) {
324 $orderBy = ["MIN(i.contact_id)", "MIN(i.$entityColumn)"];
325 $query = $query->join('e', " INNER JOIN civicrm_email e ON e.id = i.email_id ")
326 ->groupBy("e.email");
327 if (CRM_Utils_SQL
::supportsFullGroupBy()) {
330 'ANY_VALUE(i.contact_id) contact_id',
331 "ANY_VALUE(i.$entityColumn) $entityColumn",
337 $query = $query->select($selectClause)->orderBy($orderBy);
338 if (!CRM_Utils_System
::isNull($aclFrom)) {
339 $query = $query->join('acl', $aclFrom);
341 if (!CRM_Utils_System
::isNull($aclWhere)) {
342 $query = $query->where($aclWhere);
345 // this mean if dedupe_email AND the mysql 5.7 supports ONLY_FULL_GROUP_BY mode then as
346 // SELECT must contain 'email' column as its used in GROUP BY, so in order to resolve This
347 // here the whole SQL code is wrapped up in FROM table i and not selecting email column for INSERT
348 if ($key = array_search('e.email', $selectClause)) {
349 unset($selectClause[$key]);
350 $sql = $query->toSQL();
351 CRM_Utils_SQL_Select
::from("( $sql ) AS i ")
352 ->select($selectClause)
353 ->insertInto('civicrm_mailing_recipients', ['mailing_id', 'contact_id', $entityColumn])
354 ->param('#mailingID', $mailingID)
358 $query->insertInto('civicrm_mailing_recipients', ['mailing_id', 'contact_id', $entityColumn])
359 ->param('#mailingID', $mailingID)
363 // if we need to add all emails marked bulk, do it as a post filter
364 // on the mailing recipients table
365 if (CRM_Core_BAO_Email
::isMultipleBulkMail()) {
366 self
::addMultipleEmails($mailingID);
369 // Delete the temp table.
370 $mailingGroup->reset();
371 $excludeTempTable->drop();
372 $includedTempTable->drop();
374 CRM_Utils_Hook
::alterMailingRecipients($mailingObj, $criteria, 'post');
378 * Function to retrieve location filter and order by clause later used by SQL query that is used to fetch and include mailing recipients
380 * @param string $email_selection_method
381 * @param int $location_type_id
385 public static function getLocationFilterAndOrderBy($email_selection_method, $location_type_id) {
386 if ($email_selection_method !== 'automatic' && !$location_type_id) {
387 throw new \
CRM_Core_Exception(ts('You have selected an email Selection Method without specifying a Location Type. Please go back and change your recipient settings (using the wrench icon next to "Recipients").'));
389 $email = CRM_Core_DAO_Email
::getTableName();
390 // Note: When determining the ORDER that results are returned, it's
391 // the record that comes last that counts. That's because we are
392 // INSERT'ing INTO a table with a primary id so that last record
393 // over writes any previous record.
394 switch ($email_selection_method) {
395 case 'location-exclude':
396 $location_filter = "($email.location_type_id != $location_type_id)";
397 // If there is more than one email that doesn't match the location,
398 // prefer the one marked is_bulkmail, followed by is_primary.
399 $orderBy = ["$email.is_bulkmail", "$email.is_primary"];
402 case 'location-only':
403 $location_filter = "($email.location_type_id = $location_type_id)";
404 // If there is more than one email of the desired location, prefer
405 // the one marked is_bulkmail, followed by is_primary.
406 $orderBy = ["$email.is_bulkmail", "$email.is_primary"];
409 case 'location-prefer':
410 $location_filter = "($email.is_bulkmail = 1 OR $email.is_primary = 1 OR $email.location_type_id = $location_type_id)";
411 // ORDER BY is more complicated because we have to set an arbitrary
412 // order that prefers the location that we want. We do that using
413 // the FIELD function. For more info, see:
414 // https://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_field
415 // We assign the location type we want the value "1" by putting it
416 // in the first position after we name the field. All other location
417 // types are left out, so they will be assigned the value 0. That
418 // means, they will all be equally tied for first place, with our
419 // location being last.
421 "FIELD($email.location_type_id, $location_type_id)",
422 "$email.is_bulkmail",
428 // fall through to default
430 $location_filter = "($email.is_bulkmail = 1 OR $email.is_primary = 1)";
431 $orderBy = ["$email.is_bulkmail"];
434 return [$location_filter, $orderBy];
438 * Returns the regex patterns that are used for preparing the text and html templates.
440 * @param bool $onlyHrefs
442 * @return array|string
444 private function getPatterns($onlyHrefs = FALSE) {
448 $protos = '(https?|ftp|mailto)';
450 $gunk = '\{\}/#~:.?+=&;%@!\,\-\|\(\)\*';
452 $any = "{$letters}{$gunk}{$punc}";
454 $pattern = "\\bhref[ ]*=[ ]*([\"'])?(($protos:[$any]+?(?=[$punc]*[^$any]|$)))([\"'])?";
457 $pattern = "\\b($protos:[$any]+?(?=[$punc]*[^$any]|$))";
460 $patterns[] = $pattern;
461 $patterns[] = '\\\\\{\w+\.\w+\\\\\}|\{\{\w+\.\w+\}\}';
462 $patterns[] = '\{\w+\.\w+\}';
464 $patterns = '{' . implode('|', $patterns) . '}imu';
470 * Returns an array that denotes the type of token that we are dealing with
471 * we use the type later on when we are doing a token replacement lookup
473 * @param string $token
474 * The token for which we will be doing adata lookup.
477 * An array that holds the token itself and the type.
478 * the type will tell us which function to use for the data lookup
479 * if we need to do a lookup at all
481 public function &getDataFunc($token) {
482 static $_categories = NULL;
483 static $_categoryString = NULL;
492 CRM_Utils_Hook
::tokens($_categories);
493 $_categoryString = implode('|', array_keys($_categories));
496 $funcStruct = ['type' => NULL, 'token' => $token];
498 if ((preg_match('/^href/i', $token) ||
preg_match('/^http/i', $token))) {
499 // it is a url so we need to check to see if there are any tokens embedded
500 // if so then call this function again to get the token dataFunc
501 // and assign the type 'embedded' so that the data retrieving function
502 // will know what how to handle this token.
503 if (preg_match_all('/(\{\w+\.\w+\})/', $token, $matches)) {
504 $funcStruct['type'] = 'embedded_url';
505 $funcStruct['embed_parts'] = $funcStruct['token'] = [];
506 foreach ($matches[1] as $match) {
507 $preg_token = '/' . preg_quote($match, '/') . '/';
508 $list = preg_split($preg_token, $token, 2);
509 $funcStruct['embed_parts'][] = $list[0];
511 $funcStruct['token'][] = $this->getDataFunc($match);
513 // fixed truncated url, CRM-7113
515 $funcStruct['embed_parts'][] = $token;
519 $funcStruct['type'] = 'url';
522 elseif (preg_match('/^\{(' . $_categoryString . ')\.(\w+)\}$/', $token, $matches)) {
523 $funcStruct['type'] = $matches[1];
524 $funcStruct['token'] = $matches[2];
526 elseif (preg_match('/\\\\\{(\w+\.\w+)\\\\\}|\{\{(\w+\.\w+)\}\}/', $token, $matches)) {
527 // we are an escaped token
528 // so remove the escape chars
529 $unescaped_token = preg_replace('/\{\{|\}\}|\\\\\{|\\\\\}/', '', $matches[0]);
530 $funcStruct['token'] = '{' . $unescaped_token . '}';
536 * Prepares the text and html templates
537 * for generating the emails and returns a copy of the
541 * This is used by CiviMail but will be made redundant by FlexMailer/TokenProcessor.
543 private function getPreparedTemplates() {
544 if (!$this->preparedTemplates
) {
545 $patterns['html'] = $this->getPatterns(TRUE);
546 $patterns['subject'] = $patterns['text'] = $this->getPatterns();
547 $templates = $this->getTemplates();
549 $this->preparedTemplates
= [];
556 if (!isset($templates[$key])) {
562 $split_template = [];
564 $email = $templates[$key];
565 preg_match_all($patterns[$key], $email, $matches, PREG_PATTERN_ORDER
);
566 foreach ($matches[0] as $idx => $token) {
567 $preg_token = '/' . preg_quote($token, '/') . '/im';
568 list($split_template[], $email) = preg_split($preg_token, $email, 2);
569 array_push($tokens, $this->getDataFunc($token));
572 $split_template[] = $email;
574 $this->preparedTemplates
[$key]['template'] = $split_template;
575 $this->preparedTemplates
[$key]['tokens'] = $tokens;
578 return ($this->preparedTemplates
);
582 * Retrieve a ref to an array that holds the email and text templates for this email
583 * assembles the complete template including the header and footer
584 * that the user has uploaded or declared (if they have done that)
587 * reference to an assoc array
589 public function getTemplates() {
590 if (!$this->templates
) {
591 $this->getHeaderFooter();
592 $this->templates
= [];
593 if ($this->body_text ||
!empty($this->header
)) {
595 if (!empty($this->header
->body_text
)) {
596 $template[] = $this->header
->body_text
;
598 elseif (!empty($this->header
->body_html
)) {
599 $template[] = CRM_Utils_String
::htmlToText($this->header
->body_html
);
602 if ($this->body_text
) {
603 $template[] = $this->body_text
;
606 $template[] = CRM_Utils_String
::htmlToText($this->body_html
);
609 if (!empty($this->footer
->body_text
)) {
610 $template[] = $this->footer
->body_text
;
612 elseif (!empty($this->footer
->body_html
)) {
613 $template[] = CRM_Utils_String
::htmlToText($this->footer
->body_html
);
616 $this->templates
['text'] = implode("\n", $template);
619 // To check for an html part strip tags
620 if (trim(strip_tags($this->body_html
, '<img>'))) {
624 $template[] = $this->header
->body_html
;
627 $template[] = $this->body_html
;
630 $template[] = $this->footer
->body_html
;
633 $this->templates
['html'] = implode("\n", $template);
635 // this is where we create a text template from the html template if the text template did not exist
636 // this way we ensure that every recipient will receive an email even if the pref is set to text and the
637 // user uploads an html email only
638 if (empty($this->templates
['text'])) {
639 $this->templates
['text'] = CRM_Utils_String
::htmlToText($this->templates
['html']);
643 if ($this->subject
) {
645 $template[] = $this->subject
;
646 $this->templates
['subject'] = implode("\n", $template);
649 $this->templates
['mailingID'] = $this->id
;
650 $this->templates
['campaign_id'] = $this->campaign_id
;
651 $this->templates
['template_type'] = $this->template_type
;
652 CRM_Utils_Hook
::alterMailContent($this->templates
);
654 return $this->templates
;
659 * Retrieve a ref to an array that holds all of the tokens in the email body
660 * where the keys are the type of token and the values are ordinal arrays
661 * that hold the token names (even repeated tokens) in the order in which
662 * they appear in the body of the email.
664 * note: the real work is done in the _getTokens() function
666 * this function needs to have some sort of a body assigned
667 * either text or html for this to have any meaningful impact
670 * reference to an assoc array
672 public function &getTokens() {
673 if (!$this->tokens
) {
675 $this->tokens
= ['html' => [], 'text' => [], 'subject' => []];
677 if ($this->body_html
) {
678 $this->_getTokens('html');
679 if (!$this->body_text
) {
680 // Since the text template was created from html, use the html tokens.
681 // @see CRM_Mailing_BAO_Mailing::getTemplates()
682 $this->tokens
['text'] = $this->tokens
['html'];
686 if ($this->body_text
) {
687 $this->_getTokens('text');
690 if ($this->subject
) {
691 $this->_getTokens('subject');
695 return $this->tokens
;
699 * Returns the token set for all 3 parts as one set. This allows it to be sent to the
700 * hook in one call and standardizes it across other token workflows
703 * reference to an assoc array
705 public function &getFlattenedTokens() {
706 if (!$this->flattenedTokens
) {
707 $tokens = $this->getTokens();
709 $this->flattenedTokens
= CRM_Utils_Token
::flattenTokens($tokens);
712 return $this->flattenedTokens
;
717 * _getTokens parses out all of the tokens that have been
718 * included in the html and text bodies of the email
719 * we get the tokens and then separate them into an
720 * internal structure named tokens that has the same
721 * form as the static tokens property(?) of the CRM_Utils_Token class.
722 * The difference is that there might be repeated token names as we want the
723 * structures to represent the order in which tokens were found from left to right, top to bottom.
726 * @param string $prop name of the property that holds the text that we want to scan for tokens (html, text).
727 * Name of the property that holds the text that we want to scan for tokens (html, text).
731 private function _getTokens($prop) {
732 $templates = $this->getTemplates();
734 $newTokens = CRM_Utils_Token
::getTokens($templates[$prop]);
736 foreach ($newTokens as $type => $names) {
737 if (!isset($this->tokens
[$prop][$type])) {
738 $this->tokens
[$prop][$type] = [];
740 foreach ($names as $key => $name) {
741 $this->tokens
[$prop][$type][] = $name;
747 * Generate an event queue for a test job.
749 * @param array $testParams
750 * Contains form values.
754 public function getTestRecipients($testParams) {
755 if (!empty($testParams['test_group']) && array_key_exists($testParams['test_group'], CRM_Core_PseudoConstant
::group())) {
756 $contacts = civicrm_api('contact', 'get', [
758 'group' => $testParams['test_group'],
761 'limit' => 100000000000,
765 foreach (array_keys($contacts['values']) as $groupContact) {
767 SELECT civicrm_email.id AS email_id,
768 civicrm_email.is_primary as is_primary,
769 civicrm_email.is_bulkmail as is_bulkmail
771 INNER JOIN civicrm_contact ON civicrm_email.contact_id = civicrm_contact.id
772 WHERE (civicrm_email.is_bulkmail = 1 OR civicrm_email.is_primary = 1)
773 AND civicrm_contact.id = {$groupContact}
774 AND civicrm_contact.do_not_email = 0
775 AND civicrm_contact.is_deceased <> 1
776 AND civicrm_email.on_hold = 0
777 AND civicrm_contact.is_opt_out = 0
778 GROUP BY civicrm_email.id
779 ORDER BY civicrm_email.is_bulkmail DESC
781 $dao = CRM_Core_DAO
::executeQuery($query);
784 'job_id' => $testParams['job_id'],
785 'email_id' => $dao->email_id
,
786 'contact_id' => $groupContact,
788 CRM_Mailing_Event_BAO_Queue
::create($params);
795 * Load this->header and this->footer.
797 private function getHeaderFooter() {
798 if (!$this->header
and $this->header_id
) {
799 $this->header
= new CRM_Mailing_BAO_MailingComponent();
800 $this->header
->id
= $this->header_id
;
801 $this->header
->find(TRUE);
804 if (!$this->footer
and $this->footer_id
) {
805 $this->footer
= new CRM_Mailing_BAO_MailingComponent();
806 $this->footer
->id
= $this->footer_id
;
807 $this->footer
->find(TRUE);
812 * Given and array of headers and a prefix, job ID, event queue ID, and hash,
813 * add a Message-ID header if needed.
815 * i.e. if the global includeMessageId is set and there isn't already a
816 * Message-ID in the array.
817 * The message ID is structured the same way as a verp. However no interpretation
818 * is placed on the values received, so they do not need to follow the verp
821 * @param array $headers
822 * Array of message headers to update, in-out.
823 * @param string $prefix
824 * Prefix for the message ID, use same prefixes as verp.
826 * @param string $job_id
827 * Job ID component of the generated message ID.
828 * @param string $event_queue_id
829 * Event Queue ID component of the generated message ID.
830 * @param string $hash
831 * Hash component of the generated message ID.
835 public static function addMessageIdHeader(&$headers, $prefix, $job_id, $event_queue_id, $hash) {
836 $config = CRM_Core_Config
::singleton();
837 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
838 $emailDomain = CRM_Core_BAO_MailSettings
::defaultDomain();
839 $includeMessageId = CRM_Core_BAO_MailSettings
::includeMessageId();
841 $fields[] = 'Message-ID';
842 // CRM-17754 check if Resent-Message-id is set also if not add it in when re-laying reply email
843 if ($prefix == 'r') {
844 $fields[] = 'Resent-Message-ID';
846 foreach ($fields as $field) {
847 if ($includeMessageId && (!array_key_exists($field, $headers))) {
848 $headers[$field] = '<' . implode($config->verpSeparator
,
850 $localpart . $prefix,
855 ) . "@{$emailDomain}>";
862 * Static wrapper for getting verp and urls.
865 * ID of the Job associated with this message.
866 * @param int $event_queue_id
867 * ID of the EventQueue.
868 * @param string $hash
869 * Hash of the EventQueue.
870 * @param string $email
871 * Destination address.
874 * (reference) array array ref that hold array refs to the verp info and urls
876 public static function getVerpAndUrls($job_id, $event_queue_id, $hash, $email) {
877 // create a skeleton object and set its properties that are required by getVerpAndUrlsAndHeaders()
878 $config = CRM_Core_Config
::singleton();
879 $bao = new CRM_Mailing_BAO_Mailing();
880 $bao->_domain
= CRM_Core_BAO_Domain
::getDomain();
881 $bao->from_name
= $bao->from_email
= $bao->subject
= '';
883 // use $bao's instance method to get verp and urls
884 list($verp, $urls, $_) = $bao->getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email);
885 return [$verp, $urls];
889 * Get verp, urls and headers
892 * ID of the Job associated with this message.
893 * @param int $event_queue_id
894 * ID of the EventQueue.
895 * @param string $hash
896 * Hash of the EventQueue.
897 * @param string $email
898 * Destination address.
900 * @param bool $isForward
903 * array ref that hold array refs to the verp info, urls, and headers
905 public function getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email, $isForward = FALSE) {
906 $config = CRM_Core_Config
::singleton();
910 * reply: user replied to mailing
911 * bounce: email address bounced
912 * unsubscribe: contact opts out of all target lists for the mailing
913 * resubscribe: contact opts back into all target lists for the mailing
914 * optOut: contact unsubscribes from the domain
920 'unsubscribe' => 'u',
921 'resubscribe' => 'e',
925 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
926 $emailDomain = CRM_Core_BAO_MailSettings
::defaultDomain();
927 // Make sure the user configured the site correctly, otherwise you just get "Could not identify any recipients. Perhaps the group is empty?" from the mailing UI
928 if (empty($emailDomain)) {
929 CRM_Core_Error
::debug_log_message('Error setting verp parameters, defaultDomain is NULL. Did you configure the bounce processing account for this domain?');
932 foreach ($verpTokens as $key => $value) {
933 $verp[$key] = implode($config->verpSeparator
,
943 //handle should override VERP address.
947 self
::overrideVerp($job_id)
949 $verp['reply'] = "\"{$this->from_name}\" <{$this->from_email}>";
953 'forward' => CRM_Utils_System
::url('civicrm/mailing/forward', "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}", TRUE, NULL, TRUE, TRUE),
954 'unsubscribeUrl' => CRM_Utils_System
::url('civicrm/mailing/unsubscribe', "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}", TRUE, NULL, TRUE, TRUE),
955 'resubscribeUrl' => CRM_Utils_System
::url('civicrm/mailing/resubscribe', "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}", TRUE, NULL, TRUE, TRUE),
956 'optOutUrl' => CRM_Utils_System
::url('civicrm/mailing/optout', "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}", TRUE, NULL, TRUE, TRUE),
957 'subscribeUrl' => CRM_Utils_System
::url('civicrm/mailing/subscribe', 'reset=1', TRUE, NULL, TRUE, TRUE),
961 'Reply-To' => $verp['reply'],
962 'Return-Path' => $verp['bounce'],
963 'From' => "\"{$this->from_name}\" <{$this->from_email}>",
964 'Subject' => $this->subject
,
965 'List-Unsubscribe' => "<mailto:{$verp['unsubscribe']}>",
967 self
::addMessageIdHeader($headers, 'm', $job_id, $event_queue_id, $hash);
969 $headers['Subject'] = "[Fwd:{$this->subject}]";
971 return [&$verp, &$urls, &$headers];
978 * This is used by CiviMail but will be made redundant by FlexMailer/TokenProcessor.
980 * ID of the Job associated with this message.
981 * @param int $event_queue_id
982 * ID of the EventQueue.
983 * @param string $hash
984 * Hash of the EventQueue.
985 * @param string $contactId
987 * @param string $email
988 * Destination address.
989 * @param string $recipient
990 * To: of the recipient.
992 * Is this mailing a test?.
993 * @param $contactDetails
994 * @param $attachments
995 * @param bool $isForward
996 * Is this mailing compose for forward?.
997 * @param string $fromEmail
998 * Email address of who is forwardinf it.
1000 * @param null $replyToEmail
1002 * @return Mail_mime The mail object
1004 public function compose(
1005 $job_id, $event_queue_id, $hash, $contactId,
1006 $email, &$recipient, $test,
1007 $contactDetails, &$attachments, $isForward = FALSE,
1008 $fromEmail = NULL, $replyToEmail = NULL
1010 $config = CRM_Core_Config
::singleton();
1013 if ($this->_domain
== NULL) {
1014 $this->_domain
= CRM_Core_BAO_Domain
::getDomain();
1017 list($verp, $urls, $headers) = $this->getVerpAndUrlsAndHeaders(
1025 //set from email who is forwarding it and not original one.
1027 unset($headers['From']);
1028 $headers['From'] = "<{$fromEmail}>";
1031 if ($replyToEmail && ($fromEmail != $replyToEmail)) {
1032 $headers['Reply-To'] = "{$replyToEmail}";
1035 if ($contactDetails) {
1036 $contact = $contactDetails;
1038 elseif ($contactId === 0) {
1041 CRM_Utils_Hook
::tokenValues($contact, [$contactId], $job_id);
1044 $params = [['contact_id', '=', $contactId, 0, 0]];
1045 list($contact) = CRM_Contact_BAO_Query
::apiQuery($params);
1046 // $contact is an array of [ contactID => contactDetails ]
1048 // also call the hook to get contact details
1049 CRM_Utils_Hook
::tokenValues($contact, [$contactId], $job_id);
1051 // Don't send if contact doesn't exist
1052 $contact = reset($contact);
1053 if (!$contact ||
is_a($contact, 'CRM_Core_Error')) {
1054 CRM_Core_Error
::debug_log_message(ts('CiviMail will not send email to a non-existent contact: %1',
1057 // setting this because function is called by reference
1058 //@todo test not calling function by reference
1064 $pTemplates = $this->getPreparedTemplates();
1067 foreach ($pTemplates as $type => $pTemplate) {
1068 $html = $type == 'html';
1069 $pEmails[$type] = [];
1070 $pEmail = &$pEmails[$type];
1071 $template = &$pTemplates[$type]['template'];
1072 $tokens = &$pTemplates[$type]['tokens'];
1074 if (!empty($tokens)) {
1075 foreach ($tokens as $idx => $token) {
1076 $token_data = $this->getTokenData($token, $html, $contact, $verp, $urls, $event_queue_id);
1077 array_push($pEmail, $template[$idx]);
1078 array_push($pEmail, $token_data);
1082 array_push($pEmail, $template[$idx]);
1085 if (isset($template[($idx +
1)])) {
1086 array_push($pEmail, $template[($idx +
1)]);
1091 if (isset($pEmails['html']) && is_array($pEmails['html']) && count($pEmails['html'])) {
1092 $html = &$pEmails['html'];
1096 if (isset($pEmails['text']) && is_array($pEmails['text']) && count($pEmails['text'])) {
1097 $text = &$pEmails['text'];
1100 // push the tracking url on to the html email if necessary
1101 if ($this->open_tracking
&& $html) {
1102 array_push($html, "\n" . '<img src="' . CRM_Utils_System
::externUrl('extern/open', "q=$event_queue_id")
1103 . '" width="1" height="1" alt="" border="0">'
1107 $message = new Mail_mime("\n");
1109 $useSmarty = defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
;
1111 $smarty = CRM_Core_Smarty
::singleton();
1112 // also add the contact tokens to the template
1113 $smarty->assign_by_ref('contact', $contact);
1116 $mailParams = $headers;
1117 if ($text && ($test ||
$contact['preferred_mail_format'] == 'Text' ||
1118 $contact['preferred_mail_format'] == 'Both' ||
1119 ($contact['preferred_mail_format'] == 'HTML' && !array_key_exists('html', $pEmails))
1122 $textBody = implode('', $text);
1124 $textBody = $smarty->fetch("string:$textBody");
1126 $mailParams['text'] = $textBody;
1129 if ($html && ($test ||
($contact['preferred_mail_format'] == 'HTML' ||
1130 $contact['preferred_mail_format'] == 'Both'
1133 $htmlBody = implode('', $html);
1135 $htmlBody = $smarty->fetch("string:$htmlBody");
1137 $mailParams['html'] = $htmlBody;
1140 if (empty($mailParams['text']) && empty($mailParams['html'])) {
1142 // something went wrong, lets log it and return null (by reference)
1143 CRM_Core_Error
::debug_log_message(ts('CiviMail will not send an empty mail body, Skipping: %1',
1150 $mailParams['attachments'] = $attachments;
1152 $mailParams['Subject'] = $pEmails['subject'] ??
NULL;
1153 if (is_array($mailParams['Subject'])) {
1154 $mailParams['Subject'] = implode('', $mailParams['Subject']);
1157 $mailParams['toName'] = CRM_Utils_Array
::value('display_name',
1160 $mailParams['toEmail'] = $email;
1162 // Add job ID to mailParams for external email delivery service to utilise
1163 $mailParams['job_id'] = $job_id;
1165 CRM_Utils_Hook
::alterMailParams($mailParams, 'civimail');
1167 // CRM-10699 support custom email headers
1168 if (!empty($mailParams['headers'])) {
1169 $headers = array_merge($headers, $mailParams['headers']);
1171 //cycle through mailParams and set headers array
1172 foreach ($mailParams as $paramKey => $paramValue) {
1173 //exclude values not intended for the header
1174 if (!in_array($paramKey, [
1182 $headers[$paramKey] = $paramValue;
1186 if (!empty($mailParams['text'])) {
1187 $message->setTxtBody($mailParams['text']);
1190 if (!empty($mailParams['html'])) {
1191 $message->setHTMLBody($mailParams['html']);
1194 if (!empty($mailParams['attachments'])) {
1195 foreach ($mailParams['attachments'] as $fileID => $attach) {
1196 $message->addAttachment($attach['fullPath'],
1197 $attach['mime_type'],
1198 $attach['cleanName']
1203 //pickup both params from mail params.
1204 $toName = trim($mailParams['toName']);
1205 $toEmail = trim($mailParams['toEmail']);
1206 if ($toName == $toEmail ||
1207 strpos($toName, '@') !== FALSE
1212 $toName = CRM_Utils_Mail
::formatRFC2822Name($toName);
1215 $headers['To'] = "$toName <$toEmail>";
1217 $headers['Precedence'] = 'bulk';
1218 // Will test in the mail processor if the X-VERP is set in the bounced email.
1219 // (As an option to replace real VERP for those that can't set it up)
1220 $headers['X-CiviMail-Bounce'] = $verp['bounce'];
1223 //token replacement of subject
1224 $headers['Subject'] = $mailParams['Subject'];
1226 CRM_Utils_Mail
::setMimeParams($message);
1227 $headers = $message->headers($headers);
1229 //get formatted recipient
1230 $recipient = $headers['To'];
1232 // make sure we unset a lot of stuff
1245 * Get mailing object and replaces subscribeInvite, domain and mailing tokens.
1248 * This is used by CiviMail but will be made redundant by FlexMailer/TokenProcessor.
1249 * @param CRM_Mailing_BAO_Mailing $mailing
1251 public static function tokenReplace(&$mailing) {
1252 $domain = CRM_Core_BAO_Domain
::getDomain();
1254 foreach (['text', 'html'] as $type) {
1255 $tokens = $mailing->getTokens();
1256 if (isset($mailing->templates
[$type])) {
1257 $mailing->templates
[$type] = CRM_Utils_Token
::replaceSubscribeInviteTokens($mailing->templates
[$type]);
1258 $mailing->templates
[$type] = CRM_Utils_Token
::replaceDomainTokens(
1259 $mailing->templates
[$type],
1264 $mailing->templates
[$type] = CRM_Utils_Token
::replaceMailingTokens($mailing->templates
[$type], $mailing, NULL, $tokens[$type]);
1270 * Get data to resolve tokens.
1273 * This is used by CiviMail but will be made redundant by FlexMailer/TokenProcessor.
1275 * @param array $token_a
1277 * Whether to encode the token result for use in HTML email
1278 * @param array $contact
1279 * @param string $verp
1280 * @param array $urls
1281 * @param int $event_queue_id
1283 * @return bool|mixed|null|string
1285 private function getTokenData(&$token_a, $html, &$contact, &$verp, &$urls, $event_queue_id) {
1286 $type = $token_a['type'];
1287 $token = $token_a['token'];
1290 $useSmarty = defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
;
1292 if ($type == 'embedded_url') {
1294 foreach ($token as $t) {
1295 $embed_data[] = $this->getTokenData($t, $html, $contact, $verp, $urls, $event_queue_id);
1297 $numSlices = count($embed_data);
1299 for ($i = 0; $i < $numSlices; $i++
) {
1300 $embed_url_data = parse_url($embed_data[$i]);
1301 if (!empty($embed_url_data['scheme'])) {
1302 $token_a['embed_parts'][$i] = preg_replace("/href=\"(https*:\/\/)/", "href=\"", $token_a['embed_parts'][$i]);
1304 $url .= "{$token_a['embed_parts'][$i]}{$embed_data[$i]}";
1306 if (isset($token_a['embed_parts'][$numSlices])) {
1307 $url .= $token_a['embed_parts'][$numSlices];
1309 // add trailing quote since we've gobbled it up in a previous regex
1310 // function getPatterns, line 431
1311 if (preg_match("/^href[ ]*=[ ]*'.*[^']$/", $url)) {
1314 elseif (preg_match('/^href[ ]*=[ ]*".*[^"]$/', $url)) {
1318 // CRM-20206 Fix ampersand encoding in plain text emails
1320 $data = CRM_Utils_String
::unstupifyUrl($data);
1323 elseif ($type == 'url') {
1324 if ($this->url_tracking
&& !empty($this->id
)) {
1325 // ensure that Google CSS and any .css files are not tracked.
1326 if (!(strpos($token, 'css?family') ||
strpos($token, '.css'))) {
1327 $data = CRM_Mailing_BAO_TrackableURL
::getTrackerURL($token, $this->id
, $event_queue_id);
1328 if (!empty($html)) {
1329 $data = htmlentities($data, ENT_NOQUOTES
);
1337 elseif ($type == 'contact') {
1338 $data = CRM_Utils_Token
::getContactTokenReplacement($token, $contact, FALSE, FALSE, $useSmarty);
1340 elseif ($type == 'action') {
1341 $data = CRM_Utils_Token
::getActionTokenReplacement($token, $verp, $urls, $html);
1343 elseif ($type == 'domain') {
1344 $domain = CRM_Core_BAO_Domain
::getDomain();
1345 $data = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain, $html);
1347 elseif ($type == 'mailing') {
1348 if ($token == 'name') {
1349 $data = $this->name
;
1351 elseif ($token == 'group') {
1352 $groups = $this->getGroupNames();
1353 $data = implode(', ', $groups);
1357 $data = $contact["{$type}.{$token}"] ??
NULL;
1363 * Return a list of group names for this mailing. Does not work with
1364 * prior-mailing targets.
1367 * Names of groups receiving this mailing
1369 public function &getGroupNames() {
1370 if (!isset($this->id
)) {
1373 $mg = new CRM_Mailing_DAO_MailingGroup();
1374 $mgtable = CRM_Mailing_DAO_MailingGroup
::getTableName();
1375 $group = CRM_Contact_BAO_Group
::getTableName();
1377 $mg->query("SELECT $group.title as name FROM $mgtable
1378 INNER JOIN $group ON $mgtable.entity_id = $group.id
1379 WHERE $mgtable.mailing_id = {$this->id}
1380 AND $mgtable.entity_table = '$group'
1381 AND $mgtable.group_type = 'Include'
1382 ORDER BY $group.name");
1385 while ($mg->fetch()) {
1386 $groups[] = $mg->name
;
1394 * @param array $params
1395 * Reference array contains the values submitted by the form.
1397 * Reference array contains the id.
1400 * @return CRM_Mailing_DAO_Mailing
1402 public static function add(&$params, $ids = []) {
1403 $id = $params['id'] ??
$ids['mailing_id'] ??
NULL;
1405 if (empty($params['id']) && !empty($ids)) {
1406 CRM_Core_Error
::deprecatedWarning('Parameter $ids is no longer used by Mailing::add. Use the api or just pass $params');
1410 CRM_Utils_Hook
::pre('edit', 'Mailing', $id, $params);
1413 CRM_Utils_Hook
::pre('create', 'Mailing', NULL, $params);
1416 $mailing = new static();
1419 $mailing->find(TRUE);
1421 $mailing->domain_id
= CRM_Utils_Array
::value('domain_id', $params, CRM_Core_Config
::domainID());
1423 if (((!$id && empty($params['replyto_email'])) ||
!isset($params['replyto_email'])) &&
1424 isset($params['from_email'])
1426 $params['replyto_email'] = $params['from_email'];
1428 $mailing->copyValues($params);
1430 // CRM-20892 Unset Modifed Date here so that MySQL can correctly set an updated modfied date.
1431 unset($mailing->modified_date
);
1432 $result = $mailing->save();
1434 // CRM-20892 Re find record after saing so we can set the updated modified date in the result.
1435 $mailing->find(TRUE);
1437 if (isset($mailing->modified_date
)) {
1438 $result->modified_date
= $mailing->modified_date
;
1442 CRM_Utils_Hook
::post('edit', 'Mailing', $mailing->id
, $mailing);
1445 CRM_Utils_Hook
::post('create', 'Mailing', $mailing->id
, $mailing);
1452 * Construct a new mailing object, along with job and mailing_group
1453 * objects, from the form values of the create mailing wizard.
1455 * This function is a bit evil. It not only merges $params and saves
1456 * the mailing -- it also schedules the mailing and chooses the recipients.
1457 * Since it merges $params, it's also the only place to correctly trigger
1458 * multi-field validation. It should be broken up.
1460 * In the mean time, use-cases which break under the weight of this
1461 * evil may find reprieve in these extra evil params:
1463 * - _skip_evil_bao_auto_recipients_: bool
1464 * - _skip_evil_bao_auto_schedule_: bool
1465 * - _evil_bao_validator_: string|callable
1467 * </twowrongsmakesaright>
1469 * @params array $params
1472 * @param array $params
1475 * $mailing The new mailing object
1477 * @throws \CRM_Core_Exception
1478 * @throws \CiviCRM_API3_Exception
1480 public static function create(&$params) {
1483 // If it is a mass sms, set url_tracking to false
1484 if (!empty($params['sms_provider_id'])) {
1485 $params['url_tracking'] = 0;
1489 // Do the below only for an insert
1490 // for an update, we should not set the defaults
1491 if (!isset($params['id'])) {
1492 // Retrieve domain email and name for default sender
1493 $domain = civicrm_api(
1498 'current_domain' => 1,
1502 if (isset($domain['from_email'])) {
1503 $domain_email = $domain['from_email'];
1504 $domain_name = $domain['from_name'];
1507 $domain_email = 'info@EXAMPLE.ORG';
1508 $domain_name = 'EXAMPLE.ORG';
1510 if (!isset($params['created_id'])) {
1511 $params['created_id'] = CRM_Core_Session
::getLoggedInContactID();
1514 // load the default config settings for each
1515 // eg reply_id, unsubscribe_id need to use
1516 // correct template IDs here
1517 'override_verp' => TRUE,
1518 'forward_replies' => FALSE,
1519 'open_tracking' => Civi
::settings()->get('open_tracking_default'),
1520 'url_tracking' => Civi
::settings()->get('url_tracking_default'),
1521 'visibility' => 'Public Pages',
1522 'replyto_email' => $domain_email,
1523 'header_id' => CRM_Mailing_PseudoConstant
::defaultComponent('header_id', ''),
1524 'footer_id' => CRM_Mailing_PseudoConstant
::defaultComponent('footer_id', ''),
1525 'from_email' => $domain_email,
1526 'from_name' => $domain_name,
1527 'msg_template_id' => NULL,
1528 'created_id' => $params['created_id'],
1529 'approver_id' => NULL,
1530 'auto_responder' => 0,
1531 'created_date' => date('YmdHis'),
1532 'scheduled_date' => NULL,
1533 'approval_date' => NULL,
1536 // Get the default from email address, if not provided.
1537 if (empty($defaults['from_email'])) {
1538 $defaultAddress = CRM_Core_BAO_Domain
::getNameAndEmail(TRUE, TRUE);
1539 foreach ($defaultAddress as $id => $value) {
1540 if (preg_match('/"(.*)" <(.*)>/', $value, $match)) {
1541 $defaults['from_email'] = $match[2];
1542 $defaults['from_name'] = $match[1];
1547 $params = array_merge($defaults, $params);
1551 * Could check and warn for the following cases:
1553 * - groups OR mailings should be populated.
1554 * - body html OR body text should be populated.
1557 $transaction = new CRM_Core_Transaction();
1559 $mailing = self
::add($params);
1561 if (is_a($mailing, 'CRM_Core_Error')) {
1562 $transaction->rollback();
1565 // update mailings with hash values
1566 CRM_Contact_BAO_Contact_Utils
::generateChecksum($mailing->id
, NULL, NULL, NULL, 'mailing', 16);
1568 $groupTableName = CRM_Contact_BAO_Group
::getTableName();
1570 /* Create the mailing group record */
1571 $mg = new CRM_Mailing_DAO_MailingGroup();
1573 'include' => 'Include',
1574 'exclude' => 'Exclude',
1577 foreach (['groups', 'mailings'] as $entity) {
1578 foreach (['include', 'exclude', 'base'] as $type) {
1579 if (isset($params[$entity][$type])) {
1580 self
::replaceGroups($mailing->id
, $groupTypes[$type], $entity, $params[$entity][$type]);
1585 if (!empty($params['search_id']) && !empty($params['group_id'])) {
1587 $mg->mailing_id
= $mailing->id
;
1588 $mg->entity_table
= $groupTableName;
1589 $mg->entity_id
= $params['group_id'];
1590 $mg->search_id
= $params['search_id'];
1591 $mg->search_args
= $params['search_args'];
1592 $mg->group_type
= 'Include';
1596 // check and attach and files as needed
1597 CRM_Core_BAO_File
::processAttachment($params, 'civicrm_mailing', $mailing->id
);
1599 // If we're going to autosend, then check validity before saving.
1600 if (empty($params['is_completed']) && !empty($params['scheduled_date']) && $params['scheduled_date'] != 'null' && !empty($params['_evil_bao_validator_'])) {
1601 $cb = Civi\Core\Resolver
::singleton()
1602 ->get($params['_evil_bao_validator_']);
1603 $errors = call_user_func($cb, $mailing);
1604 if (!empty($errors)) {
1605 $fields = implode(',', array_keys($errors));
1606 throw new CRM_Core_Exception("Mailing cannot be sent. There are missing or invalid fields ($fields).", 'cannot-send', $errors);
1610 $transaction->commit();
1612 // Create parent job if not yet created.
1613 // Condition on the existence of a scheduled date.
1614 if (!empty($params['scheduled_date']) && $params['scheduled_date'] != 'null' && empty($params['_skip_evil_bao_auto_schedule_'])) {
1615 $job = new CRM_Mailing_BAO_MailingJob();
1616 $job->mailing_id
= $mailing->id
;
1617 // If we are creating a new Completed mailing (e.g. import from another system) set the job to completed.
1618 // Keeping former behaviour when an id is present is precautionary and may warrant reconsideration later.
1619 $job->status
= ((empty($params['is_completed']) ||
!empty($params['id'])) ?
'Scheduled' : 'Complete');
1622 if (!$job->find(TRUE)) {
1623 // Don't schedule job until we populate the recipients.
1624 $job->scheduled_date
= NULL;
1627 // Schedule the job now that it has recipients.
1628 $job->scheduled_date
= $params['scheduled_date'];
1632 // Populate the recipients.
1633 if (empty($params['_skip_evil_bao_auto_recipients_'])) {
1634 self
::getRecipients($mailing->id
);
1642 * This is used by CiviMail but will be made redundant by FlexMailer.
1643 * @param CRM_Mailing_DAO_Mailing $mailing
1644 * The mailing which may or may not be sendable.
1646 * List of error messages.
1648 public static function checkSendable($mailing) {
1650 foreach (['subject', 'name', 'from_name', 'from_email'] as $field) {
1651 if (empty($mailing->{$field})) {
1652 $errors[$field] = ts('Field "%1" is required.', [
1657 if (empty($mailing->body_html
) && empty($mailing->body_text
)) {
1658 $errors['body'] = ts('Field "body_html" or "body_text" is required.');
1661 if (!Civi
::settings()->get('disable_mandatory_tokens_check')) {
1662 $header = $mailing->header_id
&& $mailing->header_id
!= 'null' ? CRM_Mailing_BAO_MailingComponent
::findById($mailing->header_id
) : NULL;
1663 $footer = $mailing->footer_id
&& $mailing->footer_id
!= 'null' ? CRM_Mailing_BAO_MailingComponent
::findById($mailing->footer_id
) : NULL;
1664 foreach (['body_html', 'body_text'] as $field) {
1665 if (empty($mailing->{$field})) {
1668 $str = ($header ?
$header->{$field} : '') . $mailing->{$field} . ($footer ?
$footer->{$field} : '');
1669 $err = CRM_Utils_Token
::requiredTokens($str);
1670 if ($err !== TRUE) {
1671 foreach ($err as $token => $desc) {
1672 $errors["{$field}:{$token}"] = ts('This message is missing a required token - {%1}: %2',
1673 [1 => $token, 2 => $desc]
1684 * Replace the list of recipients on a given mailing.
1686 * @param int $mailingId
1687 * @param string $type
1688 * 'include' or 'exclude'.
1689 * @param string $entity
1690 * 'groups' or 'mailings'.
1691 * @param array $entityIds
1692 * @throws CiviCRM_API3_Exception
1694 public static function replaceGroups($mailingId, $type, $entity, $entityIds) {
1696 foreach ($entityIds as $entityId) {
1697 $values[] = ['entity_id' => $entityId];
1699 civicrm_api3('mailing_group', 'replace', [
1700 'mailing_id' => $mailingId,
1701 'group_type' => $type,
1702 'entity_table' => ($entity == 'groups') ? CRM_Contact_BAO_Group
::getTableName() : CRM_Mailing_BAO_Mailing
::getTableName(),
1703 'values' => $values,
1708 * Get hash value of the mailing.
1712 * @return null|string
1714 public static function getMailingHash($id) {
1716 if (Civi
::settings()->get('hash_mailing_url') && !empty($id)) {
1717 $hash = CRM_Core_DAO
::getFieldValue('CRM_Mailing_BAO_Mailing', $id, 'hash', 'id');
1723 * Generate a report. Fetch event count information, mailing data, and job
1727 * The mailing id to report.
1728 * @param bool $skipDetails
1729 * Whether return all detailed report.
1731 * @param bool $isSMS
1734 * Associative array of reporting data
1736 public static function &report($id, $skipDetails = FALSE, $isSMS = FALSE) {
1737 $mailing_id = CRM_Utils_Type
::escape($id, 'Integer');
1739 $mailing = new CRM_Mailing_BAO_Mailing();
1742 'mailing' => self
::getTableName(),
1743 'mailing_group' => CRM_Mailing_DAO_MailingGroup
::getTableName(),
1744 'group' => CRM_Contact_BAO_Group
::getTableName(),
1745 'job' => CRM_Mailing_BAO_MailingJob
::getTableName(),
1746 'queue' => CRM_Mailing_Event_BAO_Queue
::getTableName(),
1747 'delivered' => CRM_Mailing_Event_BAO_Delivered
::getTableName(),
1748 'opened' => CRM_Mailing_Event_BAO_Opened
::getTableName(),
1749 'reply' => CRM_Mailing_Event_BAO_Reply
::getTableName(),
1750 'unsubscribe' => CRM_Mailing_Event_BAO_Unsubscribe
::getTableName(),
1751 'bounce' => CRM_Mailing_Event_BAO_Bounce
::getTableName(),
1752 'forward' => CRM_Mailing_Event_BAO_Forward
::getTableName(),
1753 'url' => CRM_Mailing_BAO_TrackableURL
::getTableName(),
1754 'urlopen' => CRM_Mailing_Event_BAO_TrackableURLOpen
::getTableName(),
1755 'component' => CRM_Mailing_BAO_MailingComponent
::getTableName(),
1756 'spool' => CRM_Mailing_BAO_Spool
::getTableName(),
1760 $additionalWhereClause = " AND ";
1762 $additionalWhereClause .= " {$t['mailing']}.sms_provider_id IS NULL ";
1765 $additionalWhereClause .= " {$t['mailing']}.sms_provider_id IS NOT NULL ";
1768 /* Get the mailing info */
1771 SELECT {$t['mailing']}.*
1772 FROM {$t['mailing']}
1773 WHERE {$t['mailing']}.id = $mailing_id {$additionalWhereClause}");
1777 $report['mailing'] = [];
1778 foreach (array_keys(self
::fields()) as $field) {
1779 $field = self
::fields()[$field]['name'];
1780 $report['mailing'][$field] = $mailing->$field;
1784 if ($campaignId = CRM_Utils_Array
::value('campaign_id', $report['mailing'])) {
1785 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1786 $report['mailing']['campaign'] = $campaigns[$campaignId];
1789 //mailing report is called by activity
1790 //we dont need all detail report
1795 /* Get the component info */
1800 'header' => ts('Header'),
1801 'footer' => ts('Footer'),
1802 'reply' => ts('Reply'),
1803 'optout' => ts('Opt-Out'),
1804 'resubscribe' => ts('Resubscribe'),
1805 'unsubscribe' => ts('Unsubscribe'),
1807 foreach (array_keys($components) as $type) {
1808 $query[] = "SELECT {$t['component']}.name as name,
1810 {$t['component']}.id as id
1811 FROM {$t['component']}
1812 INNER JOIN {$t['mailing']}
1813 ON {$t['mailing']}.{$type}_id =
1814 {$t['component']}.id
1815 WHERE {$t['mailing']}.id = $mailing_id";
1817 $q = '(' . implode(') UNION (', $query) . ')';
1818 $mailing->query($q);
1820 $report['component'] = [];
1821 while ($mailing->fetch()) {
1822 $report['component'][] = [
1823 'type' => $components[$mailing->type
],
1824 'name' => $mailing->name
,
1825 'link' => CRM_Utils_System
::url('civicrm/mailing/component', "reset=1&action=update&id={$mailing->id}"),
1829 /* Get the recipient group info */
1832 SELECT {$t['mailing_group']}.group_type as group_type,
1833 {$t['group']}.id as group_id,
1834 {$t['group']}.title as group_title,
1835 {$t['group']}.is_hidden as group_hidden,
1836 {$t['mailing']}.id as mailing_id,
1837 {$t['mailing']}.name as mailing_name
1838 FROM {$t['mailing_group']}
1839 LEFT JOIN {$t['group']}
1840 ON {$t['mailing_group']}.entity_id = {$t['group']}.id
1841 AND {$t['mailing_group']}.entity_table =
1843 LEFT JOIN {$t['mailing']}
1844 ON {$t['mailing_group']}.entity_id =
1846 AND {$t['mailing_group']}.entity_table =
1849 WHERE {$t['mailing_group']}.mailing_id = $mailing_id
1852 $report['group'] = ['include' => [], 'exclude' => [], 'base' => []];
1853 while ($mailing->fetch()) {
1855 if (isset($mailing->group_id
)) {
1856 $row['id'] = $mailing->group_id
;
1857 $row['name'] = $mailing->group_title
;
1858 $row['link'] = CRM_Utils_System
::url('civicrm/group/search',
1859 "reset=1&force=1&context=smog&gid={$row['id']}"
1863 $row['id'] = $mailing->mailing_id
;
1864 $row['name'] = $mailing->mailing_name
;
1865 $row['mailing'] = TRUE;
1866 $row['link'] = CRM_Utils_System
::url('civicrm/mailing/report',
1871 /* Rename hidden groups */
1873 if ($mailing->group_hidden
== 1) {
1874 $row['name'] = "Search Results";
1877 if ($mailing->group_type
== 'Include') {
1878 $report['group']['include'][] = $row;
1880 elseif ($mailing->group_type
== 'Base') {
1881 $report['group']['base'][] = $row;
1884 $report['group']['exclude'][] = $row;
1888 /* Get the event totals, grouped by job (retries) */
1891 SELECT {$t['job']}.*,
1892 COUNT(DISTINCT {$t['queue']}.id) as queue,
1893 COUNT(DISTINCT {$t['delivered']}.id) as delivered,
1894 COUNT(DISTINCT {$t['reply']}.id) as reply,
1895 COUNT(DISTINCT {$t['forward']}.id) as forward,
1896 COUNT(DISTINCT {$t['bounce']}.id) as bounce,
1897 COUNT(DISTINCT {$t['urlopen']}.id) as url,
1898 COUNT(DISTINCT {$t['spool']}.id) as spool
1900 LEFT JOIN {$t['queue']}
1901 ON {$t['queue']}.job_id = {$t['job']}.id
1902 LEFT JOIN {$t['reply']}
1903 ON {$t['reply']}.event_queue_id = {$t['queue']}.id
1904 LEFT JOIN {$t['forward']}
1905 ON {$t['forward']}.event_queue_id = {$t['queue']}.id
1906 LEFT JOIN {$t['bounce']}
1907 ON {$t['bounce']}.event_queue_id = {$t['queue']}.id
1908 LEFT JOIN {$t['delivered']}
1909 ON {$t['delivered']}.event_queue_id = {$t['queue']}.id
1910 AND {$t['bounce']}.id IS null
1911 LEFT JOIN {$t['urlopen']}
1912 ON {$t['urlopen']}.event_queue_id = {$t['queue']}.id
1913 LEFT JOIN {$t['spool']}
1914 ON {$t['spool']}.job_id = {$t['job']}.id
1915 WHERE {$t['job']}.mailing_id = $mailing_id
1916 AND {$t['job']}.is_test = 0
1917 GROUP BY {$t['job']}.id");
1919 $report['jobs'] = [];
1920 $report['event_totals'] = [];
1921 $path = 'civicrm/mailing/report/event';
1936 // initialize various counters
1937 foreach ($elements as $field) {
1938 $report['event_totals'][$field] = 0;
1941 while ($mailing->fetch()) {
1943 foreach ($elements as $field) {
1944 if (isset($mailing->$field)) {
1945 $row[$field] = $mailing->$field;
1946 $report['event_totals'][$field] +
= $mailing->$field;
1950 // compute open total separately to discount duplicates
1952 $row['opened'] = CRM_Mailing_Event_BAO_Opened
::getTotalCount($mailing_id, $mailing->id
, TRUE);
1953 $report['event_totals']['opened'] +
= $row['opened'];
1954 $row['total_opened'] = CRM_Mailing_Event_BAO_Opened
::getTotalCount($mailing_id, $mailing->id
);
1955 $report['event_totals']['total_opened'] +
= $row['total_opened'];
1957 // compute unsub total separately to discount duplicates
1959 $row['unsubscribe'] = CRM_Mailing_Event_BAO_Unsubscribe
::getTotalCount($mailing_id, $mailing->id
, TRUE, TRUE);
1960 $report['event_totals']['unsubscribe'] +
= $row['unsubscribe'];
1962 $row['optout'] = CRM_Mailing_Event_BAO_Unsubscribe
::getTotalCount($mailing_id, $mailing->id
, TRUE, FALSE);
1963 $report['event_totals']['optout'] +
= $row['optout'];
1965 foreach (array_keys(CRM_Mailing_BAO_MailingJob
::fields()) as $field) {
1966 // Get the field name from the MailingJob fields as that will not have any prefixing.
1968 $field = CRM_Mailing_BAO_MailingJob
::fields()[$field]['name'];
1969 $row[$field] = $mailing->$field;
1972 if ($mailing->queue
) {
1973 $row['delivered_rate'] = (100.0 * $mailing->delivered
) / $mailing->queue
;
1974 $row['bounce_rate'] = (100.0 * $mailing->bounce
) / $mailing->queue
;
1975 $row['unsubscribe_rate'] = (100.0 * $row['unsubscribe']) / $mailing->queue
;
1976 $row['optout_rate'] = (100.0 * $row['optout']) / $mailing->queue
;
1977 $row['opened_rate'] = $mailing->delivered ?
(($row['opened'] / $mailing->delivered
) * 100.0) : 0;
1978 $row['clickthrough_rate'] = $mailing->delivered ?
(($mailing->url
/ $mailing->delivered
) * 100.0) : 0;
1981 $row['delivered_rate'] = 0;
1982 $row['bounce_rate'] = 0;
1983 $row['unsubscribe_rate'] = 0;
1984 $row['optout_rate'] = 0;
1985 $row['opened_rate'] = 0;
1986 $row['clickthrough_rate'] = 0;
1989 $arg = "reset=1&mid=$mailing_id&jid={$mailing->id}";
1991 'clicks' => CRM_Utils_System
::url($path, "$arg&event=click"),
1992 'queue' => CRM_Utils_System
::url($path, "$arg&event=queue"),
1993 'delivered' => CRM_Utils_System
::url($path, "$arg&event=delivered"),
1994 'bounce' => CRM_Utils_System
::url($path, "$arg&event=bounce"),
1995 'unsubscribe' => CRM_Utils_System
::url($path, "$arg&event=unsubscribe"),
1996 'forward' => CRM_Utils_System
::url($path, "$arg&event=forward"),
1997 'reply' => CRM_Utils_System
::url($path, "$arg&event=reply"),
1998 'opened' => CRM_Utils_System
::url($path, "$arg&event=opened"),
2001 foreach (['scheduled_date', 'start_date', 'end_date'] as $key) {
2002 $row[$key] = CRM_Utils_Date
::customFormat($row[$key]);
2004 $report['jobs'][] = $row;
2007 $newTableSize = CRM_Mailing_BAO_Recipients
::mailingSize($mailing_id);
2009 // we need to do this for backward compatibility, since old mailings did not
2010 // use the mailing_recipients table
2011 if ($newTableSize > 0) {
2012 $report['event_totals']['queue'] = $newTableSize;
2015 $report['event_totals']['queue'] = self
::getRecipientsCount($mailing_id);
2018 if (!empty($report['event_totals']['queue'])) {
2019 $report['event_totals']['delivered_rate'] = (100.0 * $report['event_totals']['delivered']) / $report['event_totals']['queue'];
2020 $report['event_totals']['bounce_rate'] = (100.0 * $report['event_totals']['bounce']) / $report['event_totals']['queue'];
2021 $report['event_totals']['unsubscribe_rate'] = (100.0 * $report['event_totals']['unsubscribe']) / $report['event_totals']['queue'];
2022 $report['event_totals']['optout_rate'] = (100.0 * $report['event_totals']['optout']) / $report['event_totals']['queue'];
2023 $report['event_totals']['opened_rate'] = !empty($report['event_totals']['delivered']) ?
(($report['event_totals']['opened'] / $report['event_totals']['delivered']) * 100.0) : 0;
2024 $report['event_totals']['clickthrough_rate'] = !empty($report['event_totals']['delivered']) ?
(($report['event_totals']['url'] / $report['event_totals']['delivered']) * 100.0) : 0;
2027 $report['event_totals']['delivered_rate'] = 0;
2028 $report['event_totals']['bounce_rate'] = 0;
2029 $report['event_totals']['unsubscribe_rate'] = 0;
2030 $report['event_totals']['optout_rate'] = 0;
2031 $report['event_totals']['opened_rate'] = 0;
2032 $report['event_totals']['clickthrough_rate'] = 0;
2035 /* Get the click-through totals, grouped by URL */
2038 SELECT {$t['url']}.url,
2040 COUNT({$t['urlopen']}.id) as clicks,
2041 COUNT(DISTINCT {$t['queue']}.id) as unique_clicks
2043 LEFT JOIN {$t['urlopen']}
2044 ON {$t['urlopen']}.trackable_url_id = {$t['url']}.id
2045 LEFT JOIN {$t['queue']}
2046 ON {$t['urlopen']}.event_queue_id = {$t['queue']}.id
2047 LEFT JOIN {$t['job']}
2048 ON {$t['queue']}.job_id = {$t['job']}.id
2049 WHERE {$t['url']}.mailing_id = $mailing_id
2050 AND {$t['job']}.is_test = 0
2051 GROUP BY {$t['url']}.id
2052 ORDER BY unique_clicks DESC");
2054 $report['click_through'] = [];
2056 while ($mailing->fetch()) {
2057 $report['click_through'][] = [
2058 'url' => $mailing->url
,
2059 'link' => CRM_Utils_System
::url($path, "reset=1&event=click&mid=$mailing_id&uid={$mailing->id}"),
2060 'link_unique' => CRM_Utils_System
::url($path, "reset=1&event=click&mid=$mailing_id&uid={$mailing->id}&distinct=1"),
2061 'clicks' => $mailing->clicks
,
2062 'unique' => $mailing->unique_clicks
,
2063 'rate' => !empty($report['event_totals']['delivered']) ?
(100.0 * $mailing->unique_clicks
) / $report['event_totals']['delivered'] : 0,
2064 'report' => CRM_Report_Utils_Report
::getNextUrl('mailing/clicks', "reset=1&mailing_id_value={$mailing_id}&url_value={$mailing->url}", FALSE, TRUE),
2068 $arg = "reset=1&mid=$mailing_id";
2069 $report['event_totals']['links'] = [
2070 'clicks' => CRM_Utils_System
::url($path, "$arg&event=click"),
2071 'clicks_unique' => CRM_Utils_System
::url($path, "$arg&event=click&distinct=1"),
2072 'queue' => CRM_Utils_System
::url($path, "$arg&event=queue"),
2073 'delivered' => CRM_Utils_System
::url($path, "$arg&event=delivered"),
2074 'bounce' => CRM_Utils_System
::url($path, "$arg&event=bounce"),
2075 'unsubscribe' => CRM_Utils_System
::url($path, "$arg&event=unsubscribe"),
2076 'optout' => CRM_Utils_System
::url($path, "$arg&event=optout"),
2077 'forward' => CRM_Utils_System
::url($path, "$arg&event=forward"),
2078 'reply' => CRM_Utils_System
::url($path, "$arg&event=reply"),
2079 'opened' => CRM_Utils_System
::url($path, "$arg&event=opened"),
2082 $actionLinks = [CRM_Core_Action
::VIEW
=> ['name' => ts('Report')]];
2083 $actionLinks[CRM_Core_Action
::ADVANCED
] = [
2084 'name' => ts('Advanced Search'),
2085 'url' => 'civicrm/contact/search/advanced',
2087 $action = array_sum(array_keys($actionLinks));
2089 $report['event_totals']['actionlinks'] = [];
2090 foreach (['clicks', 'clicks_unique', 'queue', 'delivered', 'bounce', 'unsubscribe', 'forward', 'reply', 'opened', 'opened_unique', 'optout'] as $key) {
2091 $url = 'mailing/detail';
2092 $reportFilter = "reset=1&mailing_id_value={$mailing_id}";
2093 $searchFilter = "force=1&mailing_id=%%mid%%";
2096 $reportFilter .= "&delivery_status_value=successful";
2097 $searchFilter .= "&mailing_delivery_status=Y";
2101 $url = "mailing/bounce";
2102 $searchFilter .= "&mailing_delivery_status=N";
2106 $reportFilter .= "&is_forwarded_value=1";
2107 $searchFilter .= "&mailing_forward=1";
2111 $reportFilter .= "&is_replied_value=1";
2112 $searchFilter .= "&mailing_reply_status=Y";
2116 $reportFilter .= "&is_unsubscribed_value=1";
2117 $searchFilter .= "&mailing_unsubscribe=1";
2121 $reportFilter .= "&is_optout_value=1";
2122 $searchFilter .= "&mailing_optout=1";
2126 // do not use group by clause in report, because same report used for total and unique open
2127 $reportFilter .= "&distinct=0";
2128 case 'opened_unique':
2129 $url = "mailing/opened";
2130 $searchFilter .= "&mailing_open_status=Y";
2134 case 'clicks_unique':
2135 $url = "mailing/clicks";
2136 $searchFilter .= "&mailing_click_status=Y";
2139 $actionLinks[CRM_Core_Action
::VIEW
]['url'] = CRM_Report_Utils_Report
::getNextUrl($url, $reportFilter, FALSE, TRUE);
2140 if (array_key_exists(CRM_Core_Action
::ADVANCED
, $actionLinks)) {
2141 $actionLinks[CRM_Core_Action
::ADVANCED
]['qs'] = $searchFilter;
2143 $report['event_totals']['actionlinks'][$key] = CRM_Core_Action
::formLink(
2146 ['mid' => $mailing_id],
2149 'mailing.report.action',
2159 * Get the count of mailings.
2166 public function getCount() {
2168 $this->selectAdd('COUNT(id) as count');
2170 $session = CRM_Core_Session
::singleton();
2173 return $this->count
;
2181 public static function checkPermission($id) {
2186 $mailingIDs = self
::mailingACLIDs();
2187 if ($mailingIDs === TRUE) {
2191 if (!in_array($id, $mailingIDs)) {
2192 throw new CRM_Core_Exception(ts('You do not have permission to access this mailing report'));
2197 * @param null $alias
2201 public static function mailingACL($alias = NULL) {
2202 $mailingACL = " ( 0 ) ";
2204 $mailingIDs = self
::mailingACLIDs();
2205 if ($mailingIDs === TRUE) {
2209 if (!empty($mailingIDs)) {
2210 $mailingIDs = implode(',', $mailingIDs);
2211 $tableName = !$alias ? self
::getTableName() : $alias;
2212 $mailingACL = " $tableName.id IN ( $mailingIDs ) ";
2218 * Returns all the mailings that this user can access. This is dependent on
2219 * all the groups that the user has access to.
2220 * However since most civi installs dont use ACL's we special case the condition
2221 * where the user has access to ALL groups, and hence ALL mailings and return a
2222 * value of TRUE (to avoid the downstream where clause with a list of mailing list IDs
2224 * @return bool|array
2225 * TRUE if the user has access to all mailings, else array of mailing IDs (possibly empty).
2227 public static function mailingACLIDs() {
2229 // optimize common case where admin has access
2232 CRM_Core_Permission
::check('view all contacts') ||
2233 CRM_Core_Permission
::check('edit all contacts')
2240 // get all the groups that this user can access
2241 // if they dont have universal access
2242 $groupNames = civicrm_api3('Group', 'get', [
2243 'check_permissions' => TRUE,
2244 'return' => ['title', 'id'],
2245 'options' => ['limit' => 0],
2247 foreach ($groupNames['values'] as $group) {
2248 $groups[$group['id']] = $group['title'];
2250 if (!empty($groups)) {
2251 $groupIDs = implode(',', array_keys($groups));
2252 $domain_id = CRM_Core_Config
::domainID();
2254 // get all the mailings that are in this subset of groups
2256 SELECT DISTINCT( m.id ) as id
2257 FROM civicrm_mailing m
2258 LEFT JOIN civicrm_mailing_group g ON g.mailing_id = m.id
2259 WHERE ( ( g.entity_table like 'civicrm_group%' AND g.entity_id IN ( $groupIDs ) )
2260 OR ( g.entity_table IS NULL AND g.entity_id IS NULL AND m.domain_id = $domain_id ) )
2262 $dao = CRM_Core_DAO
::executeQuery($query);
2265 while ($dao->fetch()) {
2266 $mailingIDs[] = $dao->id
;
2268 //CRM-18181 Get all mailings that use the mailings found earlier as receipients
2269 if (!empty($mailingIDs)) {
2270 $mailings = implode(',', $mailingIDs);
2272 SELECT DISTINCT ( m.id ) as id
2273 FROM civicrm_mailing m
2274 LEFT JOIN civicrm_mailing_group g ON g.mailing_id = m.id
2275 WHERE g.entity_table like 'civicrm_mailing%' AND g.entity_id IN ($mailings)";
2276 $mailingDao = CRM_Core_DAO
::executeQuery($mailingQuery);
2277 while ($mailingDao->fetch()) {
2278 $mailingIDs[] = $mailingDao->id
;
2287 * Get the rows for a browse operation.
2289 * @param int $offset
2290 * The row number to start from.
2291 * @param int $rowCount
2292 * The nmber of rows to return.
2293 * @param string $sort
2294 * The sql string that describes the sort order.
2296 * @param null $additionalClause
2297 * @param array $additionalParams
2302 public function &getRows($offset, $rowCount, $sort, $additionalClause = NULL, $additionalParams = NULL) {
2303 $mailing = self
::getTableName();
2304 $job = CRM_Mailing_BAO_MailingJob
::getTableName();
2305 $group = CRM_Mailing_DAO_MailingGroup
::getTableName();
2306 $session = CRM_Core_Session
::singleton();
2308 $mailingACL = self
::mailingACL();
2310 //get all campaigns.
2311 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
2316 "$mailing.approval_status_id",
2317 "createdContact.sort_name as created_by",
2318 "scheduledContact.sort_name as scheduled_by",
2319 "$mailing.created_id as created_id",
2320 "$mailing.scheduled_id as scheduled_id",
2321 "$mailing.is_archived as archived",
2322 "$mailing.created_date as created_date",
2324 "$mailing.sms_provider_id as sms_provider_id",
2325 "$mailing.language",
2328 // we only care about parent jobs, since that holds all the info on
2330 $selectClause = implode(', ', $select);
2331 $groupFromSelect = CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($select, "$mailing.id");
2333 SELECT {$selectClause},
2334 MIN($job.scheduled_date) as scheduled_date,
2335 MIN($job.start_date) as start_date,
2336 MAX($job.end_date) as end_date
2338 LEFT JOIN $job ON ( $job.mailing_id = $mailing.id AND $job.is_test = 0 AND $job.parent_id IS NULL )
2339 LEFT JOIN civicrm_contact createdContact ON ( civicrm_mailing.created_id = createdContact.id )
2340 LEFT JOIN civicrm_contact scheduledContact ON ( civicrm_mailing.scheduled_id = scheduledContact.id )
2341 WHERE $mailingACL $additionalClause";
2343 if (!empty($groupFromSelect)) {
2344 $query .= $groupFromSelect;
2348 $orderBy = trim($sort->orderBy());
2349 if (!empty($orderBy)) {
2350 $query .= " ORDER BY $orderBy";
2355 $offset = CRM_Utils_Type
::escape($offset, 'Int');
2356 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
2358 $query .= " LIMIT $offset, $rowCount ";
2361 if (!$additionalParams) {
2362 $additionalParams = [];
2365 $dao = CRM_Core_DAO
::executeQuery($query, $additionalParams);
2368 while ($dao->fetch()) {
2371 'name' => $dao->name
,
2372 'status' => $dao->status ?
$dao->status
: 'Not scheduled',
2373 'created_date' => CRM_Utils_Date
::customFormat($dao->created_date
),
2374 'scheduled' => CRM_Utils_Date
::customFormat($dao->scheduled_date
),
2375 'scheduled_iso' => $dao->scheduled_date
,
2376 'start' => CRM_Utils_Date
::customFormat($dao->start_date
),
2377 'end' => CRM_Utils_Date
::customFormat($dao->end_date
),
2378 'created_by' => $dao->created_by
,
2379 'scheduled_by' => $dao->scheduled_by
,
2380 'created_id' => $dao->created_id
,
2381 'scheduled_id' => $dao->scheduled_id
,
2382 'archived' => $dao->archived
,
2383 'approval_status_id' => $dao->approval_status_id
,
2384 'campaign_id' => $dao->campaign_id
,
2385 'campaign' => empty($dao->campaign_id
) ?
NULL : $allCampaigns[$dao->campaign_id
],
2386 'sms_provider_id' => $dao->sms_provider_id
,
2387 'language' => $dao->language
,
2394 * Show detail Mailing report.
2400 public static function showEmailDetails($id) {
2401 return CRM_Utils_System
::url('civicrm/mailing/report', "mid=$id");
2405 * Delete Mails and all its associated records.
2408 * Id of the mail to delete.
2412 public static function del($id) {
2414 throw new CRM_Core_Exception(ts('No id passed to mailing del function'));
2417 CRM_Utils_Hook
::pre('delete', 'Mailing', $id);
2419 // delete all file attachments
2420 CRM_Core_BAO_File
::deleteEntityFile('civicrm_mailing',
2424 $dao = new CRM_Mailing_DAO_Mailing();
2428 CRM_Core_Session
::setStatus(ts('Selected mailing has been deleted.'), ts('Deleted'), 'success');
2430 CRM_Utils_Hook
::post('delete', 'Mailing', $id, $dao);
2435 * Use CRM_Mailing_BAO_MailingJob::del($id)
2438 * Id of the Job to delete.
2442 public static function delJob($id) {
2444 throw new CRM_Core_Exception(ts('No id passed to mailing delJob function'));
2447 CRM_Core_Error
::deprecatedWarning('This function is deprecated, use CRM_Mailing_BAO_MailingJob::del instead');
2449 CRM_Mailing_BAO_MailingJob
::del($id);
2454 * This is used by CiviMail but will be made redundant by FlexMailer/TokenProcessor.
2457 public function getReturnProperties() {
2458 $tokens = &$this->getTokens();
2461 if (isset($tokens['html']) &&
2462 isset($tokens['html']['contact'])
2464 $properties = array_merge($properties, $tokens['html']['contact']);
2467 if (isset($tokens['text']) &&
2468 isset($tokens['text']['contact'])
2470 $properties = array_merge($properties, $tokens['text']['contact']);
2473 if (isset($tokens['subject']) &&
2474 isset($tokens['subject']['contact'])
2476 $properties = array_merge($properties, $tokens['subject']['contact']);
2479 $returnProperties = [];
2480 $returnProperties['display_name'] = $returnProperties['contact_id'] = $returnProperties['preferred_mail_format'] = $returnProperties['hash'] = 1;
2482 foreach ($properties as $p) {
2483 $returnProperties[$p] = 1;
2486 return $returnProperties;
2490 * Build the compose mail form.
2492 * @param CRM_Core_Form $form
2496 public static function commonCompose(&$form) {
2500 if (method_exists($form, 'listTokens')) {
2501 $tokens = array_merge($form->listTokens(), $tokens);
2504 //sorted in ascending order tokens by ignoring word case
2505 $form->assign('tokens', CRM_Utils_Token
::formatTokensForDisplay($tokens));
2510 'text_message' => ts('HTML Format'),
2511 'sms_text_message' => ts('SMS Message'),
2513 $modePrefixes = ['Mail' => NULL, 'SMS' => 'SMS'];
2515 $className = CRM_Utils_System
::getClassName($form);
2517 if ($className != 'CRM_SMS_Form_Upload' && $className != 'CRM_Contact_Form_Task_SMS' &&
2518 $className != 'CRM_Contact_Form_Task_SMS'
2520 $form->add('wysiwyg', 'html_message',
2521 strstr($className, 'PDF') ?
ts('Document Body') : ts('HTML Format'),
2525 'onkeyup' => "return verify(this)",
2529 if ($className != 'CRM_Admin_Form_ScheduleReminders') {
2530 unset($modePrefixes['SMS']);
2534 unset($textFields['text_message']);
2535 unset($modePrefixes['Mail']);
2538 //insert message Text by selecting "Select Template option"
2539 foreach ($textFields as $id => $label) {
2541 if ($id == 'sms_text_message') {
2543 $form->assign('max_sms_length', CRM_SMS_Provider
::MAX_SMS_CHAR
);
2545 $form->add('textarea', $id, $label,
2549 'onkeyup' => "return verify(this, '{$prefix}')",
2554 foreach ($modePrefixes as $prefix) {
2555 if ($prefix == 'SMS') {
2556 $templates[$prefix] = CRM_Core_BAO_MessageTemplate
::getMessageTemplates(FALSE, TRUE);
2559 $templates[$prefix] = CRM_Core_BAO_MessageTemplate
::getMessageTemplates(FALSE);
2561 if (!empty($templates[$prefix])) {
2562 $form->assign('templates', TRUE);
2564 $form->add('select', "{$prefix}template", ts('Use Template'),
2565 ['' => ts('- select -')] +
$templates[$prefix], FALSE,
2566 ['onChange' => "selectValue( this.value, '{$prefix}');"]
2569 $form->add('checkbox', "{$prefix}updateTemplate", ts('Update Template'), NULL);
2571 $form->add('checkbox', "{$prefix}saveTemplate", ts('Save As New Template'), NULL, FALSE,
2572 ['onclick' => "showSaveDetails(this, '{$prefix}');"]
2574 $form->add('text', "{$prefix}saveTemplateName", ts('Template Title'));
2577 // I'm not sure this is ever called.
2578 $action = CRM_Utils_Request
::retrieve('action', 'String', $form, FALSE);
2579 if ((CRM_Utils_System
::getClassName($form) == 'CRM_Contact_Form_Task_PDF') &&
2580 $action == CRM_Core_Action
::VIEW
2582 $form->freeze('html_message');
2587 * Get the search based mailing Ids.
2590 * , searched base mailing ids.
2592 public function searchMailingIDs() {
2593 $group = CRM_Mailing_DAO_MailingGroup
::getTableName();
2594 $mailing = self
::getTableName();
2597 SELECT $mailing.id as mailing_id
2598 FROM $mailing, $group
2599 WHERE $group.mailing_id = $mailing.id
2600 AND $group.group_type = 'Base'";
2602 $searchDAO = CRM_Core_DAO
::executeQuery($query);
2604 while ($searchDAO->fetch()) {
2605 $mailingIDs[] = $searchDAO->mailing_id
;
2612 * Get the content/components of mailing based on mailing Id
2614 * @param array $report
2615 * of mailing report.
2618 * Reference of this.
2620 * @param bool $isSMS
2623 * array content/component.
2625 public static function getMailingContent(&$report, &$form, $isSMS = FALSE) {
2626 $htmlHeader = $textHeader = NULL;
2627 $htmlFooter = $textFooter = NULL;
2630 if ($report['mailing']['header_id']) {
2631 $header = new CRM_Mailing_BAO_MailingComponent();
2632 $header->id
= $report['mailing']['header_id'];
2633 $header->find(TRUE);
2634 $htmlHeader = $header->body_html
;
2635 $textHeader = $header->body_text
;
2638 if ($report['mailing']['footer_id']) {
2639 $footer = new CRM_Mailing_BAO_MailingComponent();
2640 $footer->id
= $report['mailing']['footer_id'];
2641 $footer->find(TRUE);
2642 $htmlFooter = $footer->body_html
;
2643 $textFooter = $footer->body_text
;
2647 $mailingKey = $form->_mailing_id
;
2649 if ($hash = CRM_Mailing_BAO_Mailing
::getMailingHash($mailingKey)) {
2650 $mailingKey = $hash;
2654 if (!empty($report['mailing']['body_text'])) {
2655 $url = CRM_Utils_System
::url('civicrm/mailing/view', 'reset=1&text=1&id=' . $mailingKey);
2656 $form->assign('textViewURL', $url);
2660 if (!empty($report['mailing']['body_html'])) {
2661 $url = CRM_Utils_System
::url('civicrm/mailing/view', 'reset=1&id=' . $mailingKey);
2662 $form->assign('htmlViewURL', $url);
2667 $report['mailing']['attachment'] = CRM_Core_BAO_File
::attachmentInfo('civicrm_mailing', $form->_mailing_id
);
2677 public static function overrideVerp($jobID) {
2678 static $_cache = [];
2680 if (!isset($_cache[$jobID])) {
2682 SELECT override_verp
2683 FROM civicrm_mailing
2684 INNER JOIN civicrm_mailing_job ON civicrm_mailing.id = civicrm_mailing_job.mailing_id
2685 WHERE civicrm_mailing_job.id = %1
2687 $params = [1 => [$jobID, 'Integer']];
2688 $_cache[$jobID] = CRM_Core_DAO
::singleValueQuery($query, $params);
2690 return $_cache[$jobID];
2699 public static function processQueue($mode = NULL) {
2700 $config = CRM_Core_Config
::singleton();
2702 if ($mode == NULL && CRM_Core_BAO_MailSettings
::defaultDomain() == "EXAMPLE.ORG") {
2703 // Using forceBackend=TRUE because WordPress sometimes fails to detect cron
2704 throw new CRM_Core_Exception(ts('The <a href="%1">default mailbox</a> has not been configured. You will find <a href="%2">more info in the online system administrator guide</a>', [
2705 1 => CRM_Utils_System
::url('civicrm/admin/mailSettings', 'reset=1', FALSE, NULL, TRUE, FALSE, TRUE),
2706 2 => "https://docs.civicrm.org/sysadmin/en/latest/setup/civimail/",
2710 // check if we are enforcing number of parallel cron jobs
2712 $gotCronLock = FALSE;
2714 $mailerJobsMax = Civi
::settings()->get('mailerJobsMax');
2715 if (is_numeric($mailerJobsMax) && $mailerJobsMax > 0) {
2716 $lockArray = range(1, $mailerJobsMax);
2718 // Shuffle the array to improve chances of quickly finding an open thread
2719 shuffle($lockArray);
2721 // Check if we are using global locks
2722 foreach ($lockArray as $lockID) {
2723 $cronLock = Civi
::lockManager()
2724 ->acquire("worker.mailing.send.{$lockID}");
2725 if ($cronLock->isAcquired()) {
2726 $gotCronLock = TRUE;
2731 // Exit here since we have enough mailing processes running
2732 if (!$gotCronLock) {
2733 CRM_Core_Error
::debug_log_message('Returning early, since the maximum number of mailing processes are running');
2737 if (getenv('CIVICRM_CRON_HOLD')) {
2738 // In testing, we may need to simulate some slow activities.
2739 sleep(getenv('CIVICRM_CRON_HOLD'));
2743 // Split up the parent jobs into multiple child jobs
2744 $mailerJobSize = Civi
::settings()->get('mailerJobSize');
2745 CRM_Mailing_BAO_MailingJob
::runJobs_pre($mailerJobSize, $mode);
2746 CRM_Mailing_BAO_MailingJob
::runJobs(NULL, $mode);
2747 CRM_Mailing_BAO_MailingJob
::runJobs_post($mode);
2749 // Release the global lock if we do have one
2751 $cronLock->release();
2758 * @param int $mailingID
2760 private static function addMultipleEmails($mailingID) {
2762 INSERT INTO civicrm_mailing_recipients
2763 (mailing_id, email_id, contact_id)
2764 SELECT %1, e.id, e.contact_id FROM civicrm_email e
2766 AND e.is_bulkmail = 1
2768 ( SELECT contact_id FROM civicrm_mailing_recipients mr WHERE mailing_id = %1 )
2769 AND e.id NOT IN ( SELECT email_id FROM civicrm_mailing_recipients mr WHERE mailing_id = %1 )
2771 $params = [1 => [$mailingID, 'Integer']];
2773 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2777 * @param bool $isSMS
2781 public static function getMailingsList($isSMS = FALSE) {
2785 $where .= " civicrm_mailing.sms_provider_id IS NULL ";
2788 $where .= " civicrm_mailing.sms_provider_id IS NOT NULL ";
2793 SELECT civicrm_mailing.id, civicrm_mailing.name, civicrm_mailing_job.end_date
2794 FROM civicrm_mailing
2795 INNER JOIN civicrm_mailing_job ON civicrm_mailing.id = civicrm_mailing_job.mailing_id {$where}
2796 ORDER BY civicrm_mailing.name";
2797 $mailing = CRM_Core_DAO
::executeQuery($query);
2799 while ($mailing->fetch()) {
2800 $list[$mailing->id
] = "{$mailing->name} :: {$mailing->end_date}";
2808 * wrapper for ajax activity selector.
2810 * @param array $params
2811 * Associated array for params record id.
2814 * associated array of contact activities
2816 public static function getContactMailingSelector(&$params) {
2817 // format the params
2818 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2819 $params['rowCount'] = $params['rp'];
2820 $params['sort'] = $params['sortBy'] ??
NULL;
2821 $params['caseId'] = NULL;
2823 // get contact mailings
2824 $mailings = CRM_Mailing_BAO_Mailing
::getContactMailings($params);
2827 $params['total'] = CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2830 if (!empty($mailings)) {
2831 $openCounts = CRM_Mailing_Event_BAO_Opened
::getMailingContactCount(array_keys($mailings), $params['contact_id']);
2832 $clickCounts = CRM_Mailing_Event_BAO_TrackableURLOpen
::getMailingContactCount(array_keys($mailings), $params['contact_id']);
2835 // format params and add links
2836 $contactMailings = [];
2837 foreach ($mailings as $mailingId => $values) {
2839 $mailing['subject'] = $values['subject'];
2840 $mailing['creator_name'] = CRM_Utils_System
::href(
2841 $values['creator_name'],
2842 'civicrm/contact/view',
2843 "reset=1&cid={$values['creator_id']}");
2844 $mailing['recipients'] = CRM_Utils_System
::href(ts('(recipients)'), 'civicrm/mailing/report/event',
2845 "mid={$values['mailing_id']}&reset=1&cid={$params['contact_id']}&event=queue&context=mailing");
2846 $mailing['start_date'] = CRM_Utils_Date
::customFormat($values['start_date']);
2848 $mailing['openstats'] = "Opens: " .
2849 CRM_Utils_Array
::value($values['mailing_id'], $openCounts, 0) .
2851 CRM_Utils_Array
::value($values['mailing_id'], $clickCounts, 0);
2854 CRM_Core_Action
::VIEW
=> [
2855 'name' => ts('View'),
2856 'url' => 'civicrm/mailing/view',
2857 'qs' => "reset=1&id=%%mkey%%",
2858 'title' => ts('View Mailing'),
2859 'class' => 'crm-popup',
2861 CRM_Core_Action
::BROWSE
=> [
2862 'name' => ts('Mailing Report'),
2863 'url' => 'civicrm/mailing/report',
2864 'qs' => "mid=%%mid%%&reset=1&cid=%%cid%%&context=mailing",
2865 'title' => ts('View Mailing Report'),
2869 $mailingKey = $values['mailing_id'];
2870 if ($hash = CRM_Mailing_BAO_Mailing
::getMailingHash($mailingKey)) {
2871 $mailingKey = $hash;
2874 $mailing['links'] = CRM_Core_Action
::formLink(
2878 'mid' => $values['mailing_id'],
2879 'cid' => $params['contact_id'],
2880 'mkey' => $mailingKey,
2884 'mailing.contact.action',
2886 $values['mailing_id']
2889 array_push($contactMailings, $mailing);
2892 $contactMailingsDT = [];
2893 $contactMailingsDT['data'] = $contactMailings;
2894 $contactMailingsDT['recordsTotal'] = $params['total'];
2895 $contactMailingsDT['recordsFiltered'] = $params['total'];
2897 return $contactMailingsDT;
2901 * Retrieve contact mailing.
2903 * @param array $params
2906 * Array of mailings for a contact
2909 public static function getContactMailings(&$params) {
2910 $params['version'] = 3;
2911 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2912 $params['limit'] = $params['rp'];
2913 $params['sort'] = $params['sortBy'] ??
NULL;
2915 $result = civicrm_api('MailingContact', 'get', $params);
2916 return $result['values'];
2920 * Retrieve contact mailing count.
2922 * @param array $params
2925 * count of mailings for a contact
2928 public static function getContactMailingsCount(&$params) {
2929 $params['version'] = 3;
2930 return civicrm_api('MailingContact', 'getcount', $params);
2934 * Get a list of permissions required for CRUD'ing each field
2935 * (when workflow is enabled).
2938 * Array (string $fieldName => string $permName)
2940 public static function getWorkflowFieldPerms() {
2941 $fieldNames = array_keys(CRM_Mailing_DAO_Mailing
::fields());
2943 foreach ($fieldNames as $fieldName) {
2944 if ($fieldName == 'id') {
2945 $fieldPerms[$fieldName] = [
2949 'schedule mailings',
2954 elseif (in_array($fieldName, ['scheduled_date', 'scheduled_id'])) {
2955 $fieldPerms[$fieldName] = [
2957 ['access CiviMail', 'schedule mailings'],
2960 elseif (in_array($fieldName, [
2963 'approval_status_id',
2966 $fieldPerms[$fieldName] = [
2968 ['access CiviMail', 'approve mailings'],
2972 $fieldPerms[$fieldName] = [
2974 ['access CiviMail', 'create mailings'],
2982 * White-list of possible values for the entity_table field.
2986 public static function mailingGroupEntityTables() {
2988 CRM_Contact_BAO_Group
::getTableName() => 'Group',
2989 CRM_Mailing_BAO_Mailing
::getTableName() => 'Mailing',
2994 * Get the public view url.
2997 * @param bool $absolute
3001 public static function getPublicViewUrl($id, $absolute = TRUE) {
3002 if ((civicrm_api3('Mailing', 'getvalue', [
3004 'return' => 'visibility',
3005 ])) === 'Public Pages') {
3007 // if hash setting is on then we change the public url into a hash
3008 $hash = CRM_Mailing_BAO_Mailing
::getMailingHash($id);
3009 if (!empty($hash)) {
3013 return CRM_Utils_System
::url('civicrm/mailing/view', ['id' => $id], $absolute, NULL, TRUE, TRUE);
3018 * Get a list of template types which can be used as `civicrm_mailing.template_type`.
3021 * A list of template-types, keyed numerically. Each defines:
3022 * - name: string, a short symbolic name
3023 * - editorUrl: string, Angular template name
3025 * Ex: $templateTypes[0] === array('name' => 'mosaico', 'editorUrl' => '~/crmMosaico/editor.html').
3027 public static function getTemplateTypes() {
3028 if (!isset(Civi
::$statics[__CLASS__
]['templateTypes'])) {
3031 'name' => 'traditional',
3032 'editorUrl' => CRM_Mailing_Info
::workflowEnabled() ?
'~/crmMailing/EditMailingCtrl/workflow.html' : '~/crmMailing/EditMailingCtrl/2step.html',
3036 CRM_Utils_Hook
::mailingTemplateTypes($types);
3038 $defaults = ['weight' => 0];
3039 foreach (array_keys($types) as $typeName) {
3040 $types[$typeName] = array_merge($defaults, $types[$typeName]);
3042 usort($types, function ($a, $b) {
3043 if ($a['weight'] === $b['weight']) {
3046 return $a['weight'] < $b['weight'] ?
-1 : 1;
3049 Civi
::$statics[__CLASS__
]['templateTypes'] = $types;
3052 return Civi
::$statics[__CLASS__
]['templateTypes'];
3056 * Get a list of template types.
3059 * Array(string $name => string $label).
3061 public static function getTemplateTypeNames() {
3063 foreach (self
::getTemplateTypes() as $type) {
3064 $r[$type['name']] = $type['name'];