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.
54 * @var CRM_Mailing_BAO_MailingComponent
56 private $header = NULL;
59 * The footer associated with this mailing.
60 * @var CRM_Mailing_BAO_MailingComponent
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 * @param int $mailingID
89 public static function getRecipientsCount($mailingID) {
90 //rebuild the recipients
91 self
::getRecipients($mailingID);
93 return civicrm_api3('MailingRecipients', 'getcount', ['mailing_id' => $mailingID]);
97 * This function retrieve recipients of selected mailing groups.
99 * @param int $mailingID
103 public static function getRecipients($mailingID) {
104 // load mailing object
105 $mailingObj = new self();
106 $mailingObj->id
= $mailingID;
107 $mailingObj->find(TRUE);
109 $mailing = CRM_Mailing_BAO_Mailing
::getTableName();
110 $contact = CRM_Contact_DAO_Contact
::getTableName();
111 $isSMSmode = (!CRM_Utils_System
::isNull($mailingObj->sms_provider_id
));
113 $mailingGroup = new CRM_Mailing_DAO_MailingGroup();
114 $recipientsGroup = $excludeSmartGroupIDs = $includeSmartGroupIDs = $priorMailingIDs = [];
115 $dao = CRM_Utils_SQL_Select
::from('civicrm_mailing_group')
116 ->select('GROUP_CONCAT(DISTINCT entity_id SEPARATOR ",") as group_ids, group_type, entity_table')
117 ->where('mailing_id = #mailing_id AND entity_table RLIKE "^civicrm_(group.*|mailing)$" ')
118 ->groupBy(['group_type', 'entity_table'])
119 ->param('!groupTableName', CRM_Contact_BAO_Group
::getTableName())
120 ->param('#mailing_id', $mailingID)
122 while ($dao->fetch()) {
123 if ($dao->entity_table
== 'civicrm_mailing') {
124 $priorMailingIDs[$dao->group_type
] = explode(',', $dao->group_ids
);
127 $recipientsGroup[$dao->group_type
] = empty($recipientsGroup[$dao->group_type
]) ?
explode(',', $dao->group_ids
) : array_merge($recipientsGroup[$dao->group_type
], explode(',', $dao->group_ids
));
131 // there is no need to proceed further if no mailing group is selected to include recipients,
132 // but before return clear the mailing recipients populated earlier since as per current params no group is selected
133 if (empty($recipientsGroup['Include']) && empty($priorMailingIDs['Include'])) {
134 CRM_Core_DAO
::executeQuery(" DELETE FROM civicrm_mailing_recipients WHERE mailing_id = %1 ", [
143 list($location_filter, $order_by) = self
::getLocationFilterAndOrderBy($mailingObj->email_selection_method
, $mailingObj->location_type_id
);
145 // get all the saved searches AND hierarchical groups
146 // and load them in the cache
147 foreach ($recipientsGroup as $groupType => $groupIDs) {
148 $groupDAO = CRM_Utils_SQL_Select
::from('civicrm_group')
149 ->where('id IN (#groupIDs)')
150 ->where('saved_search_id != 0 OR saved_search_id IS NOT NULL OR children IS NOT NULL')
151 ->param('#groupIDs', $groupIDs)
153 while ($groupDAO->fetch()) {
154 // hidden smart groups always have a cache date and there is no other way
155 // we can rebuilt the contact list from UI so consider such smart group
156 if ($groupDAO->cache_date
== NULL ||
$groupDAO->is_hidden
) {
157 CRM_Contact_BAO_GroupContactCache
::load($groupDAO);
159 if ($groupType == 'Include') {
160 $includeSmartGroupIDs[] = $groupDAO->id
;
162 elseif ($groupType == 'Exclude') {
163 $excludeSmartGroupIDs[] = $groupDAO->id
;
165 //NOTE: Do nothing for base
169 // Create a temp table for contact exclusion.
170 $excludeTempTable = CRM_Utils_SQL_TempTable
::build()->setCategory('exrecipient')->setMemory()->createWithColumns('contact_id int primary key');
171 $excludeTempTablename = $excludeTempTable->getName();
172 // populate exclude temp-table with recipients to be excluded from the list
173 // on basis of selected recipients groups and/or previous mailing
174 if (!empty($recipientsGroup['Exclude'])) {
175 CRM_Utils_SQL_Select
::from('civicrm_group_contact')
176 ->select('DISTINCT contact_id')
177 ->where('status = "Added" AND group_id IN (#groups)')
178 ->param('#groups', $recipientsGroup['Exclude'])
179 ->insertInto($excludeTempTablename, ['contact_id'])
182 if (count($excludeSmartGroupIDs)) {
183 CRM_Utils_SQL_Select
::from('civicrm_group_contact_cache')
184 ->select('contact_id')
185 ->where('group_id IN (#groups)')
186 ->param('#groups', $excludeSmartGroupIDs)
187 ->insertIgnoreInto($excludeTempTablename, ['contact_id'])
191 if (!empty($priorMailingIDs['Exclude'])) {
192 CRM_Utils_SQL_Select
::from('civicrm_mailing_recipients')
193 ->select('DISTINCT contact_id')
194 ->where('mailing_id IN (#mailings)')
195 ->param('#mailings', $priorMailingIDs['Exclude'])
196 ->insertIgnoreInto($excludeTempTablename, ['contact_id'])
200 if (!empty($recipientsGroup['Base'])) {
201 CRM_Utils_SQL_Select
::from('civicrm_group_contact')
202 ->select('DISTINCT contact_id')
203 ->where('status = "Removed" AND group_id IN (#groups)')
204 ->param('#groups', $recipientsGroup['Base'])
205 ->insertIgnoreInto($excludeTempTablename, ['contact_id'])
209 $entityColumn = $isSMSmode ?
'phone_id' : 'email_id';
210 $entityTable = $isSMSmode ? CRM_Core_DAO_Phone
::getTableName() : CRM_Core_DAO_Email
::getTableName();
211 // Get all the group contacts we want to include.
212 $includedTempTable = CRM_Utils_SQL_TempTable
::build()->setCategory('inrecipient')->setMemory()->createWithColumns('contact_id int primary key, ' . $entityColumn . ' int');
213 $includedTempTablename = $includedTempTable->getName();
217 'is_deleted' => CRM_Utils_SQL_Select
::fragment()->where("$contact.is_deleted = 0"),
218 'is_opt_out' => CRM_Utils_SQL_Select
::fragment()->where("$contact.is_opt_out = 0"),
219 'is_deceased' => CRM_Utils_SQL_Select
::fragment()->where("$contact.is_deceased <> 1"),
220 'do_not_sms' => CRM_Utils_SQL_Select
::fragment()->where("$contact.do_not_sms = 0"),
221 'location_filter' => CRM_Utils_SQL_Select
::fragment()->where("$entityTable.phone_type_id = " . CRM_Core_PseudoConstant
::getKey('CRM_Core_DAO_Phone', 'phone_type_id', 'Mobile')),
222 'phone_not_null' => CRM_Utils_SQL_Select
::fragment()->where("$entityTable.phone IS NOT NULL"),
223 'phone_not_empty' => CRM_Utils_SQL_Select
::fragment()->where("$entityTable.phone != ''"),
224 'mailing_id' => CRM_Utils_SQL_Select
::fragment()->where("mg.mailing_id = #mailingID"),
225 'temp_contact_null' => CRM_Utils_SQL_Select
::fragment()->where('temp.contact_id IS null'),
226 'order_by' => CRM_Utils_SQL_Select
::fragment()->orderBy("$entityTable.is_primary"),
230 // Criteria to filter recipients that need to be included
232 'is_deleted' => CRM_Utils_SQL_Select
::fragment()->where("$contact.is_deleted = 0"),
233 'do_not_email' => CRM_Utils_SQL_Select
::fragment()->where("$contact.do_not_email = 0"),
234 'is_opt_out' => CRM_Utils_SQL_Select
::fragment()->where("$contact.is_opt_out = 0"),
235 'is_deceased' => CRM_Utils_SQL_Select
::fragment()->where("$contact.is_deceased <> 1"),
236 'location_filter' => CRM_Utils_SQL_Select
::fragment()->where($location_filter),
237 'email_not_null' => CRM_Utils_SQL_Select
::fragment()->where("$entityTable.email IS NOT NULL"),
238 'email_not_empty' => CRM_Utils_SQL_Select
::fragment()->where("$entityTable.email != ''"),
239 'email_not_on_hold' => CRM_Utils_SQL_Select
::fragment()->where("$entityTable.on_hold = 0"),
240 'mailing_id' => CRM_Utils_SQL_Select
::fragment()->where("mg.mailing_id = #mailingID"),
241 'temp_contact_null' => CRM_Utils_SQL_Select
::fragment()->where('temp.contact_id IS NULL'),
242 'order_by' => CRM_Utils_SQL_Select
::fragment()->orderBy($order_by),
246 // Allow user to alter query responsible to fetch mailing recipients before build,
247 // by changing the mail filters identified $params
248 CRM_Utils_Hook
::alterMailingRecipients($mailingObj, $criteria, 'pre');
250 // Get the group contacts, but only those which are not in the
251 // exclusion temp table.
252 if (!empty($recipientsGroup['Include'])) {
253 CRM_Utils_SQL_Select
::from($entityTable)
254 ->select("$contact.id as contact_id, $entityTable.id as $entityColumn")
255 ->join($contact, " INNER JOIN $contact ON $entityTable.contact_id = $contact.id ")
256 ->join('gc', " INNER JOIN civicrm_group_contact gc ON gc.contact_id = $contact.id ")
257 ->join('mg', " INNER JOIN civicrm_mailing_group mg ON gc.group_id = mg.entity_id AND mg.search_id IS NULL ")
258 ->join('temp', " LEFT JOIN $excludeTempTablename temp ON $contact.id = temp.contact_id ")
259 ->where('gc.group_id IN (#groups) AND gc.status = "Added"')
261 ->groupBy(["$contact.id", "$entityTable.id"])
262 ->replaceInto($includedTempTablename, ['contact_id', $entityColumn])
263 ->param('#groups', $recipientsGroup['Include'])
264 ->param('#mailingID', $mailingID)
268 // Get recipients selected in prior mailings
269 if (!empty($priorMailingIDs['Include'])) {
270 CRM_Utils_SQL_Select
::from('civicrm_mailing_recipients')
271 ->select("DISTINCT civicrm_mailing_recipients.contact_id, $entityColumn")
272 ->join('temp', " LEFT JOIN $excludeTempTablename temp ON civicrm_mailing_recipients.contact_id = temp.contact_id ")
273 ->where('mailing_id IN (#mailings)')
274 ->where('temp.contact_id IS NULL')
275 ->param('#mailings', $priorMailingIDs['Include'])
276 ->insertIgnoreInto($includedTempTablename, [
283 if (count($includeSmartGroupIDs)) {
284 $query = CRM_Utils_SQL_Select
::from($contact)
285 ->select("$contact.id as contact_id, $entityTable.id as $entityColumn")
286 ->join($entityTable, " INNER JOIN $entityTable ON $entityTable.contact_id = $contact.id ")
287 ->join('gc', " INNER JOIN civicrm_group_contact_cache gc ON $contact.id = gc.contact_id ")
288 ->join('gcr', " LEFT JOIN civicrm_group_contact gcr ON gc.group_id = gcr.group_id AND gc.contact_id = gcr.contact_id")
289 ->join('mg', " INNER JOIN civicrm_mailing_group mg ON gc.group_id = mg.entity_id AND mg.search_id IS NULL ")
290 ->join('temp', " LEFT JOIN $excludeTempTablename temp ON $contact.id = temp.contact_id ")
291 ->where('gc.group_id IN (#groups)')
292 ->where('gcr.status IS NULL OR gcr.status != "Removed"')
294 ->replaceInto($includedTempTablename, ['contact_id', $entityColumn])
295 ->param('#groups', $includeSmartGroupIDs)
296 ->param('#mailingID', $mailingID)
300 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause();
302 // clear all the mailing recipients before populating
303 CRM_Core_DAO
::executeQuery(' DELETE FROM civicrm_mailing_recipients WHERE mailing_id = %1 ', [
310 $selectClause = ['#mailingID', 'i.contact_id', "i.$entityColumn"];
312 $orderBy = ["i.contact_id", "i.$entityColumn"];
314 $query = CRM_Utils_SQL_Select
::from('civicrm_contact contact_a')
315 ->join('i', " INNER JOIN {$includedTempTablename} i ON contact_a.id = i.contact_id ");
316 if (!$isSMSmode && $mailingObj->dedupe_email
) {
317 $orderBy = ["MIN(i.contact_id)", "MIN(i.$entityColumn)"];
318 $query = $query->join('e', " INNER JOIN civicrm_email e ON e.id = i.email_id ")
319 ->groupBy("e.email");
320 if (CRM_Utils_SQL
::supportsFullGroupBy()) {
323 'ANY_VALUE(i.contact_id) contact_id',
324 "ANY_VALUE(i.$entityColumn) $entityColumn",
330 $query = $query->select($selectClause)->orderBy($orderBy);
331 if (!CRM_Utils_System
::isNull($aclFrom)) {
332 $query = $query->join('acl', $aclFrom);
334 if (!CRM_Utils_System
::isNull($aclWhere)) {
335 $query = $query->where($aclWhere);
338 // this mean if dedupe_email AND the mysql 5.7 supports ONLY_FULL_GROUP_BY mode then as
339 // SELECT must contain 'email' column as its used in GROUP BY, so in order to resolve This
340 // here the whole SQL code is wrapped up in FROM table i and not selecting email column for INSERT
341 if ($key = array_search('e.email', $selectClause)) {
342 unset($selectClause[$key]);
343 $sql = $query->toSQL();
344 CRM_Utils_SQL_Select
::from("( $sql ) AS i ")
345 ->select($selectClause)
346 ->insertInto('civicrm_mailing_recipients', ['mailing_id', 'contact_id', $entityColumn])
347 ->param('#mailingID', $mailingID)
351 $query->insertInto('civicrm_mailing_recipients', ['mailing_id', 'contact_id', $entityColumn])
352 ->param('#mailingID', $mailingID)
356 // if we need to add all emails marked bulk, do it as a post filter
357 // on the mailing recipients table
358 if (CRM_Core_BAO_Email
::isMultipleBulkMail()) {
359 self
::addMultipleEmails($mailingID);
362 // Delete the temp table.
363 $mailingGroup->reset();
364 $excludeTempTable->drop();
365 $includedTempTable->drop();
367 CRM_Utils_Hook
::alterMailingRecipients($mailingObj, $criteria, 'post');
371 * Function to retrieve location filter and order by clause later used by SQL query that is used to fetch and include mailing recipients
373 * @param string $email_selection_method
374 * @param int $location_type_id
378 public static function getLocationFilterAndOrderBy($email_selection_method, $location_type_id) {
379 if ($email_selection_method !== 'automatic' && !$location_type_id) {
380 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").'));
382 $email = CRM_Core_DAO_Email
::getTableName();
383 // Note: When determining the ORDER that results are returned, it's
384 // the record that comes last that counts. That's because we are
385 // INSERT'ing INTO a table with a primary id so that last record
386 // over writes any previous record.
387 switch ($email_selection_method) {
388 case 'location-exclude':
389 $location_filter = "($email.location_type_id != $location_type_id)";
390 // If there is more than one email that doesn't match the location,
391 // prefer the one marked is_bulkmail, followed by is_primary.
392 $orderBy = ["$email.is_bulkmail", "$email.is_primary"];
395 case 'location-only':
396 $location_filter = "($email.location_type_id = $location_type_id)";
397 // If there is more than one email of the desired location, prefer
398 // the one marked is_bulkmail, followed by is_primary.
399 $orderBy = ["$email.is_bulkmail", "$email.is_primary"];
402 case 'location-prefer':
403 $location_filter = "($email.is_bulkmail = 1 OR $email.is_primary = 1 OR $email.location_type_id = $location_type_id)";
404 // ORDER BY is more complicated because we have to set an arbitrary
405 // order that prefers the location that we want. We do that using
406 // the FIELD function. For more info, see:
407 // https://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_field
408 // We assign the location type we want the value "1" by putting it
409 // in the first position after we name the field. All other location
410 // types are left out, so they will be assigned the value 0. That
411 // means, they will all be equally tied for first place, with our
412 // location being last.
414 "FIELD($email.location_type_id, $location_type_id)",
415 "$email.is_bulkmail",
421 // fall through to default
423 $location_filter = "($email.is_bulkmail = 1 OR $email.is_primary = 1)";
424 $orderBy = ["$email.is_bulkmail"];
427 return [$location_filter, $orderBy];
431 * Returns the regex patterns that are used for preparing the text and html templates.
433 * @param bool $onlyHrefs
435 * @return array|string
437 private function getPatterns($onlyHrefs = FALSE) {
441 $protos = '(https?|ftp|mailto)';
443 $gunk = '\{\}/#~:.?+=&;%@!\,\-\|\(\)\*';
445 $any = "{$letters}{$gunk}{$punc}";
447 $pattern = "\\bhref[ ]*=[ ]*([\"'])?(($protos:[$any]+?(?=[$punc]*[^$any]|$)))([\"'])?";
450 $pattern = "\\b($protos:[$any]+?(?=[$punc]*[^$any]|$))";
453 $patterns[] = $pattern;
454 $patterns[] = '\\\\\{\w+\.\w+\\\\\}|\{\{\w+\.\w+\}\}';
455 $patterns[] = '\{\w+\.\w+\}';
457 $patterns = '{' . implode('|', $patterns) . '}imu';
463 * Returns an array that denotes the type of token that we are dealing with
464 * we use the type later on when we are doing a token replacement lookup
466 * @param string $token
467 * The token for which we will be doing adata lookup.
470 * An array that holds the token itself and the type.
471 * the type will tell us which function to use for the data lookup
472 * if we need to do a lookup at all
474 public function &getDataFunc($token) {
475 static $_categories = NULL;
476 static $_categoryString = NULL;
485 CRM_Utils_Hook
::tokens($_categories);
486 $_categoryString = implode('|', array_keys($_categories));
489 $funcStruct = ['type' => NULL, 'token' => $token];
491 if ((preg_match('/^href/i', $token) ||
preg_match('/^http/i', $token))) {
492 // it is a url so we need to check to see if there are any tokens embedded
493 // if so then call this function again to get the token dataFunc
494 // and assign the type 'embedded' so that the data retrieving function
495 // will know what how to handle this token.
496 if (preg_match_all('/(\{\w+\.\w+\})/', $token, $matches)) {
497 $funcStruct['type'] = 'embedded_url';
498 $funcStruct['embed_parts'] = $funcStruct['token'] = [];
499 foreach ($matches[1] as $match) {
500 $preg_token = '/' . preg_quote($match, '/') . '/';
501 $list = preg_split($preg_token, $token, 2);
502 $funcStruct['embed_parts'][] = $list[0];
504 $funcStruct['token'][] = $this->getDataFunc($match);
506 // fixed truncated url, CRM-7113
508 $funcStruct['embed_parts'][] = $token;
512 $funcStruct['type'] = 'url';
515 elseif (preg_match('/^\{(' . $_categoryString . ')\.(\w+)\}$/', $token, $matches)) {
516 $funcStruct['type'] = $matches[1];
517 $funcStruct['token'] = $matches[2];
519 elseif (preg_match('/\\\\\{(\w+\.\w+)\\\\\}|\{\{(\w+\.\w+)\}\}/', $token, $matches)) {
520 // we are an escaped token
521 // so remove the escape chars
522 $unescaped_token = preg_replace('/\{\{|\}\}|\\\\\{|\\\\\}/', '', $matches[0]);
523 $funcStruct['token'] = '{' . $unescaped_token . '}';
529 * Prepares the text and html templates
530 * for generating the emails and returns a copy of the
534 * This is used by CiviMail but will be made redundant by FlexMailer/TokenProcessor.
536 private function getPreparedTemplates() {
537 if (!$this->preparedTemplates
) {
538 $patterns['html'] = $this->getPatterns(TRUE);
539 $patterns['subject'] = $patterns['text'] = $this->getPatterns();
540 $templates = $this->getTemplates();
542 $this->preparedTemplates
= [];
549 if (!isset($templates[$key])) {
555 $split_template = [];
557 $email = $templates[$key];
558 preg_match_all($patterns[$key], $email, $matches, PREG_PATTERN_ORDER
);
559 foreach ($matches[0] as $idx => $token) {
560 $preg_token = '/' . preg_quote($token, '/') . '/im';
561 list($split_template[], $email) = preg_split($preg_token, $email, 2);
562 array_push($tokens, $this->getDataFunc($token));
565 $split_template[] = $email;
567 $this->preparedTemplates
[$key]['template'] = $split_template;
568 $this->preparedTemplates
[$key]['tokens'] = $tokens;
571 return ($this->preparedTemplates
);
575 * Retrieve a ref to an array that holds the email and text templates for this email
576 * assembles the complete template including the header and footer
577 * that the user has uploaded or declared (if they have done that)
580 * reference to an assoc array
582 public function getTemplates() {
583 if (!$this->templates
) {
584 $this->getHeaderFooter();
585 $this->templates
= [];
586 if ($this->body_text ||
!empty($this->header
)) {
588 if (!empty($this->header
->body_text
)) {
589 $template[] = $this->header
->body_text
;
591 elseif (!empty($this->header
->body_html
)) {
592 $template[] = CRM_Utils_String
::htmlToText($this->header
->body_html
);
595 if ($this->body_text
) {
596 $template[] = $this->body_text
;
599 $template[] = CRM_Utils_String
::htmlToText($this->body_html
);
602 if (!empty($this->footer
->body_text
)) {
603 $template[] = $this->footer
->body_text
;
605 elseif (!empty($this->footer
->body_html
)) {
606 $template[] = CRM_Utils_String
::htmlToText($this->footer
->body_html
);
609 $this->templates
['text'] = implode("\n", $template);
612 // To check for an html part strip tags
613 if (trim(strip_tags($this->body_html
, '<img>'))) {
617 $template[] = $this->header
->body_html
;
620 $template[] = $this->body_html
;
623 $template[] = $this->footer
->body_html
;
626 $this->templates
['html'] = implode("\n", $template);
628 // this is where we create a text template from the html template if the text template did not exist
629 // this way we ensure that every recipient will receive an email even if the pref is set to text and the
630 // user uploads an html email only
631 if (empty($this->templates
['text'])) {
632 $this->templates
['text'] = CRM_Utils_String
::htmlToText($this->templates
['html']);
636 if ($this->subject
) {
638 $template[] = $this->subject
;
639 $this->templates
['subject'] = implode("\n", $template);
642 $this->templates
['mailingID'] = $this->id
;
643 $this->templates
['campaign_id'] = $this->campaign_id
;
644 $this->templates
['template_type'] = $this->template_type
;
645 CRM_Utils_Hook
::alterMailContent($this->templates
);
647 return $this->templates
;
652 * Retrieve a ref to an array that holds all of the tokens in the email body
653 * where the keys are the type of token and the values are ordinal arrays
654 * that hold the token names (even repeated tokens) in the order in which
655 * they appear in the body of the email.
657 * note: the real work is done in the _getTokens() function
659 * this function needs to have some sort of a body assigned
660 * either text or html for this to have any meaningful impact
663 * reference to an assoc array
665 public function &getTokens() {
666 if (!$this->tokens
) {
668 $this->tokens
= ['html' => [], 'text' => [], 'subject' => []];
670 if ($this->body_html
) {
671 $this->_getTokens('html');
672 if (!$this->body_text
) {
673 // Since the text template was created from html, use the html tokens.
674 // @see CRM_Mailing_BAO_Mailing::getTemplates()
675 $this->tokens
['text'] = $this->tokens
['html'];
679 if ($this->body_text
) {
680 $this->_getTokens('text');
683 if ($this->subject
) {
684 $this->_getTokens('subject');
688 return $this->tokens
;
692 * Returns the token set for all 3 parts as one set. This allows it to be sent to the
693 * hook in one call and standardizes it across other token workflows
696 * reference to an assoc array
698 public function &getFlattenedTokens() {
699 if (!$this->flattenedTokens
) {
700 $tokens = $this->getTokens();
702 $this->flattenedTokens
= CRM_Utils_Token
::flattenTokens($tokens);
705 return $this->flattenedTokens
;
710 * _getTokens parses out all of the tokens that have been
711 * included in the html and text bodies of the email
712 * we get the tokens and then separate them into an
713 * internal structure named tokens that has the same
714 * form as the static tokens property(?) of the CRM_Utils_Token class.
715 * The difference is that there might be repeated token names as we want the
716 * structures to represent the order in which tokens were found from left to right, top to bottom.
719 * @param string $prop name of the property that holds the text that we want to scan for tokens (html, text).
720 * Name of the property that holds the text that we want to scan for tokens (html, text).
724 private function _getTokens($prop) {
725 $templates = $this->getTemplates();
727 $newTokens = CRM_Utils_Token
::getTokens($templates[$prop]);
729 foreach ($newTokens as $type => $names) {
730 if (!isset($this->tokens
[$prop][$type])) {
731 $this->tokens
[$prop][$type] = [];
733 foreach ($names as $key => $name) {
734 $this->tokens
[$prop][$type][] = $name;
740 * Generate an event queue for a test job.
742 * @param array $testParams
743 * Contains form values.
747 public function getTestRecipients($testParams) {
748 if (!empty($testParams['test_group']) && array_key_exists($testParams['test_group'], CRM_Core_PseudoConstant
::group())) {
749 $contacts = civicrm_api('contact', 'get', [
751 'group' => $testParams['test_group'],
754 'limit' => 100000000000,
758 foreach (array_keys($contacts['values']) as $groupContact) {
760 SELECT civicrm_email.id AS email_id,
761 civicrm_email.is_primary as is_primary,
762 civicrm_email.is_bulkmail as is_bulkmail
764 INNER JOIN civicrm_contact ON civicrm_email.contact_id = civicrm_contact.id
765 WHERE (civicrm_email.is_bulkmail = 1 OR civicrm_email.is_primary = 1)
766 AND civicrm_contact.id = {$groupContact}
767 AND civicrm_contact.do_not_email = 0
768 AND civicrm_contact.is_deceased <> 1
769 AND civicrm_email.on_hold = 0
770 AND civicrm_contact.is_opt_out = 0
771 GROUP BY civicrm_email.id
772 ORDER BY civicrm_email.is_bulkmail DESC
774 $dao = CRM_Core_DAO
::executeQuery($query);
777 'job_id' => $testParams['job_id'],
778 'email_id' => $dao->email_id
,
779 'contact_id' => $groupContact,
781 CRM_Mailing_Event_BAO_Queue
::create($params);
788 * Load this->header and this->footer.
790 private function getHeaderFooter() {
791 if (!$this->header
and $this->header_id
) {
792 $this->header
= new CRM_Mailing_BAO_MailingComponent();
793 $this->header
->id
= $this->header_id
;
794 $this->header
->find(TRUE);
797 if (!$this->footer
and $this->footer_id
) {
798 $this->footer
= new CRM_Mailing_BAO_MailingComponent();
799 $this->footer
->id
= $this->footer_id
;
800 $this->footer
->find(TRUE);
805 * Given and array of headers and a prefix, job ID, event queue ID, and hash,
806 * add a Message-ID header if needed.
808 * i.e. if the global includeMessageId is set and there isn't already a
809 * Message-ID in the array.
810 * The message ID is structured the same way as a verp. However no interpretation
811 * is placed on the values received, so they do not need to follow the verp
814 * @param array $headers
815 * Array of message headers to update, in-out.
816 * @param string $prefix
817 * Prefix for the message ID, use same prefixes as verp.
819 * @param string $job_id
820 * Job ID component of the generated message ID.
821 * @param string $event_queue_id
822 * Event Queue ID component of the generated message ID.
823 * @param string $hash
824 * Hash component of the generated message ID.
828 public static function addMessageIdHeader(&$headers, $prefix, $job_id, $event_queue_id, $hash) {
829 $config = CRM_Core_Config
::singleton();
830 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
831 $emailDomain = CRM_Core_BAO_MailSettings
::defaultDomain();
832 $includeMessageId = CRM_Core_BAO_MailSettings
::includeMessageId();
834 $fields[] = 'Message-ID';
835 // CRM-17754 check if Resent-Message-id is set also if not add it in when re-laying reply email
836 if ($prefix == 'r') {
837 $fields[] = 'Resent-Message-ID';
839 foreach ($fields as $field) {
840 if ($includeMessageId && (!array_key_exists($field, $headers))) {
841 $headers[$field] = '<' . implode($config->verpSeparator
,
843 $localpart . $prefix,
848 ) . "@{$emailDomain}>";
855 * Static wrapper for getting verp and urls.
858 * ID of the Job associated with this message.
859 * @param int $event_queue_id
860 * ID of the EventQueue.
861 * @param string $hash
862 * Hash of the EventQueue.
863 * @param string $email
864 * Destination address.
867 * (reference) array array ref that hold array refs to the verp info and urls
869 public static function getVerpAndUrls($job_id, $event_queue_id, $hash, $email) {
870 // create a skeleton object and set its properties that are required by getVerpAndUrlsAndHeaders()
871 $config = CRM_Core_Config
::singleton();
872 $bao = new CRM_Mailing_BAO_Mailing();
873 $bao->_domain
= CRM_Core_BAO_Domain
::getDomain();
874 $bao->from_name
= $bao->from_email
= $bao->subject
= '';
876 // use $bao's instance method to get verp and urls
877 list($verp, $urls, $_) = $bao->getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email);
878 return [$verp, $urls];
882 * Get verp, urls and headers
885 * ID of the Job associated with this message.
886 * @param int $event_queue_id
887 * ID of the EventQueue.
888 * @param string $hash
889 * Hash of the EventQueue.
890 * @param string $email
891 * Destination address.
893 * @param bool $isForward
896 * array ref that hold array refs to the verp info, urls, and headers
898 public function getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email, $isForward = FALSE) {
899 $config = CRM_Core_Config
::singleton();
903 * reply: user replied to mailing
904 * bounce: email address bounced
905 * unsubscribe: contact opts out of all target lists for the mailing
906 * resubscribe: contact opts back into all target lists for the mailing
907 * optOut: contact unsubscribes from the domain
913 'unsubscribe' => 'u',
914 'resubscribe' => 'e',
918 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
919 $emailDomain = CRM_Core_BAO_MailSettings
::defaultDomain();
920 // 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
921 if (empty($emailDomain)) {
922 CRM_Core_Error
::debug_log_message('Error setting verp parameters, defaultDomain is NULL. Did you configure the bounce processing account for this domain?');
925 foreach ($verpTokens as $key => $value) {
926 $verp[$key] = implode($config->verpSeparator
,
936 //handle should override VERP address.
940 self
::overrideVerp($job_id)
942 $verp['reply'] = "\"{$this->from_name}\" <{$this->from_email}>";
946 'forward' => CRM_Utils_System
::url('civicrm/mailing/forward', "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}", TRUE, NULL, TRUE, TRUE),
947 'unsubscribeUrl' => CRM_Utils_System
::url('civicrm/mailing/unsubscribe', "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}", TRUE, NULL, TRUE, TRUE),
948 'resubscribeUrl' => CRM_Utils_System
::url('civicrm/mailing/resubscribe', "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}", TRUE, NULL, TRUE, TRUE),
949 'optOutUrl' => CRM_Utils_System
::url('civicrm/mailing/optout', "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}", TRUE, NULL, TRUE, TRUE),
950 'subscribeUrl' => CRM_Utils_System
::url('civicrm/mailing/subscribe', 'reset=1', TRUE, NULL, TRUE, TRUE),
954 'Reply-To' => $verp['reply'],
955 'Return-Path' => $verp['bounce'],
956 'From' => "\"{$this->from_name}\" <{$this->from_email}>",
957 'Subject' => $this->subject
,
958 'List-Unsubscribe' => "<mailto:{$verp['unsubscribe']}>",
960 self
::addMessageIdHeader($headers, 'm', $job_id, $event_queue_id, $hash);
962 $headers['Subject'] = "[Fwd:{$this->subject}]";
964 return [&$verp, &$urls, &$headers];
971 * This is used by CiviMail but will be made redundant by FlexMailer/TokenProcessor.
973 * ID of the Job associated with this message.
974 * @param int $event_queue_id
975 * ID of the EventQueue.
976 * @param string $hash
977 * Hash of the EventQueue.
978 * @param string $contactId
980 * @param string $email
981 * Destination address.
982 * @param string $recipient
983 * To: of the recipient.
985 * Is this mailing a test?.
986 * @param $contactDetails
987 * @param $attachments
988 * @param bool $isForward
989 * Is this mailing compose for forward?.
990 * @param string $fromEmail
991 * Email address of who is forwarding it.
993 * @param null $replyToEmail
995 * @return Mail_mime The mail object
997 public function compose(
998 $job_id, $event_queue_id, $hash, $contactId,
999 $email, &$recipient, $test,
1000 $contactDetails, &$attachments, $isForward = FALSE,
1001 $fromEmail = NULL, $replyToEmail = NULL
1003 $config = CRM_Core_Config
::singleton();
1006 if ($this->_domain
== NULL) {
1007 $this->_domain
= CRM_Core_BAO_Domain
::getDomain();
1010 list($verp, $urls, $headers) = $this->getVerpAndUrlsAndHeaders(
1018 //set from email who is forwarding it and not original one.
1020 unset($headers['From']);
1021 $headers['From'] = "<{$fromEmail}>";
1024 if ($replyToEmail && ($fromEmail != $replyToEmail)) {
1025 $headers['Reply-To'] = "{$replyToEmail}";
1028 if ($contactDetails) {
1029 $contact = $contactDetails;
1031 elseif ($contactId === 0) {
1034 CRM_Utils_Hook
::tokenValues($contact, [$contactId], $job_id);
1037 $params = [['contact_id', '=', $contactId, 0, 0]];
1038 list($contact) = CRM_Contact_BAO_Query
::apiQuery($params);
1039 // $contact is an array of [ contactID => contactDetails ]
1041 // also call the hook to get contact details
1042 CRM_Utils_Hook
::tokenValues($contact, [$contactId], $job_id);
1044 // Don't send if contact doesn't exist
1045 $contact = reset($contact);
1046 if (!$contact ||
is_a($contact, 'CRM_Core_Error')) {
1047 CRM_Core_Error
::debug_log_message(ts('CiviMail will not send email to a non-existent contact: %1',
1050 // setting this because function is called by reference
1051 //@todo test not calling function by reference
1057 $pTemplates = $this->getPreparedTemplates();
1060 foreach ($pTemplates as $type => $pTemplate) {
1061 $html = $type == 'html';
1062 $pEmails[$type] = [];
1063 $pEmail = &$pEmails[$type];
1064 $template = &$pTemplates[$type]['template'];
1065 $tokens = &$pTemplates[$type]['tokens'];
1067 if (!empty($tokens)) {
1068 foreach ($tokens as $idx => $token) {
1069 $token_data = $this->getTokenData($token, $html, $contact, $verp, $urls, $event_queue_id);
1070 array_push($pEmail, $template[$idx]);
1071 array_push($pEmail, $token_data);
1075 array_push($pEmail, $template[$idx]);
1078 if (isset($template[($idx +
1)])) {
1079 array_push($pEmail, $template[($idx +
1)]);
1084 if (isset($pEmails['html']) && is_array($pEmails['html']) && count($pEmails['html'])) {
1085 $html = &$pEmails['html'];
1089 if (isset($pEmails['text']) && is_array($pEmails['text']) && count($pEmails['text'])) {
1090 $text = &$pEmails['text'];
1093 // push the tracking url on to the html email if necessary
1094 if ($this->open_tracking
&& $html) {
1095 array_push($html, "\n" . '<img src="' . CRM_Utils_System
::externUrl('extern/open', "q=$event_queue_id")
1096 . '" width="1" height="1" alt="" border="0">'
1100 $message = new Mail_mime("\n");
1102 $useSmarty = defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
;
1104 $smarty = CRM_Core_Smarty
::singleton();
1105 // also add the contact tokens to the template
1106 $smarty->assign_by_ref('contact', $contact);
1109 $mailParams = $headers;
1110 if ($text && ($test ||
$contact['preferred_mail_format'] == 'Text' ||
1111 $contact['preferred_mail_format'] == 'Both' ||
1112 ($contact['preferred_mail_format'] == 'HTML' && !array_key_exists('html', $pEmails))
1115 $textBody = implode('', $text);
1117 $textBody = $smarty->fetch("string:$textBody");
1119 $mailParams['text'] = $textBody;
1122 if ($html && ($test ||
($contact['preferred_mail_format'] == 'HTML' ||
1123 $contact['preferred_mail_format'] == 'Both'
1126 $htmlBody = implode('', $html);
1128 $htmlBody = $smarty->fetch("string:$htmlBody");
1130 $mailParams['html'] = $htmlBody;
1133 if (empty($mailParams['text']) && empty($mailParams['html'])) {
1135 // something went wrong, lets log it and return null (by reference)
1136 CRM_Core_Error
::debug_log_message(ts('CiviMail will not send an empty mail body, Skipping: %1',
1143 $mailParams['attachments'] = $attachments;
1145 $mailParams['Subject'] = $pEmails['subject'] ??
NULL;
1146 if (is_array($mailParams['Subject'])) {
1147 $mailParams['Subject'] = implode('', $mailParams['Subject']);
1150 $mailParams['toName'] = CRM_Utils_Array
::value('display_name',
1153 $mailParams['toEmail'] = $email;
1155 // Add job ID to mailParams for external email delivery service to utilise
1156 $mailParams['job_id'] = $job_id;
1158 CRM_Utils_Hook
::alterMailParams($mailParams, 'civimail');
1160 // CRM-10699 support custom email headers
1161 if (!empty($mailParams['headers'])) {
1162 $headers = array_merge($headers, $mailParams['headers']);
1164 //cycle through mailParams and set headers array
1165 foreach ($mailParams as $paramKey => $paramValue) {
1166 //exclude values not intended for the header
1167 if (!in_array($paramKey, [
1175 $headers[$paramKey] = $paramValue;
1179 if (!empty($mailParams['text'])) {
1180 $message->setTxtBody($mailParams['text']);
1183 if (!empty($mailParams['html'])) {
1184 $message->setHTMLBody($mailParams['html']);
1187 if (!empty($mailParams['attachments'])) {
1188 foreach ($mailParams['attachments'] as $fileID => $attach) {
1189 $message->addAttachment($attach['fullPath'],
1190 $attach['mime_type'],
1191 $attach['cleanName']
1196 //pickup both params from mail params.
1197 $toName = trim($mailParams['toName']);
1198 $toEmail = trim($mailParams['toEmail']);
1199 if ($toName == $toEmail ||
1200 strpos($toName, '@') !== FALSE
1205 $toName = CRM_Utils_Mail
::formatRFC2822Name($toName);
1208 $headers['To'] = "$toName <$toEmail>";
1210 $headers['Precedence'] = 'bulk';
1211 // Will test in the mail processor if the X-VERP is set in the bounced email.
1212 // (As an option to replace real VERP for those that can't set it up)
1213 $headers['X-CiviMail-Bounce'] = $verp['bounce'];
1216 //token replacement of subject
1217 $headers['Subject'] = $mailParams['Subject'];
1219 CRM_Utils_Mail
::setMimeParams($message);
1220 $headers = $message->headers($headers);
1222 //get formatted recipient
1223 $recipient = $headers['To'];
1225 // make sure we unset a lot of stuff
1238 * Get mailing object and replaces subscribeInvite, domain and mailing tokens.
1241 * This is used by CiviMail but will be made redundant by FlexMailer/TokenProcessor.
1242 * @param CRM_Mailing_BAO_Mailing $mailing
1244 public static function tokenReplace(&$mailing) {
1245 $domain = CRM_Core_BAO_Domain
::getDomain();
1247 foreach (['text', 'html'] as $type) {
1248 $tokens = $mailing->getTokens();
1249 if (isset($mailing->templates
[$type])) {
1250 $mailing->templates
[$type] = CRM_Utils_Token
::replaceSubscribeInviteTokens($mailing->templates
[$type]);
1251 $mailing->templates
[$type] = CRM_Utils_Token
::replaceDomainTokens(
1252 $mailing->templates
[$type],
1257 $mailing->templates
[$type] = CRM_Utils_Token
::replaceMailingTokens($mailing->templates
[$type], $mailing, NULL, $tokens[$type]);
1263 * Get data to resolve tokens.
1266 * This is used by CiviMail but will be made redundant by FlexMailer/TokenProcessor.
1268 * @param array $token_a
1270 * Whether to encode the token result for use in HTML email
1271 * @param array $contact
1272 * @param string $verp
1273 * @param array $urls
1274 * @param int $event_queue_id
1276 * @return bool|mixed|null|string
1278 private function getTokenData(&$token_a, $html, &$contact, &$verp, &$urls, $event_queue_id) {
1279 $type = $token_a['type'];
1280 $token = $token_a['token'];
1283 $useSmarty = defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY
;
1285 if ($type == 'embedded_url') {
1287 foreach ($token as $t) {
1288 $embed_data[] = $this->getTokenData($t, $html, $contact, $verp, $urls, $event_queue_id);
1290 $numSlices = count($embed_data);
1292 for ($i = 0; $i < $numSlices; $i++
) {
1293 $embed_url_data = parse_url($embed_data[$i]);
1294 if (!empty($embed_url_data['scheme'])) {
1295 $token_a['embed_parts'][$i] = preg_replace("/href=\"(https*:\/\/)/", "href=\"", $token_a['embed_parts'][$i]);
1297 $url .= "{$token_a['embed_parts'][$i]}{$embed_data[$i]}";
1299 if (isset($token_a['embed_parts'][$numSlices])) {
1300 $url .= $token_a['embed_parts'][$numSlices];
1302 // add trailing quote since we've gobbled it up in a previous regex
1303 // function getPatterns, line 431
1304 if (preg_match("/^href[ ]*=[ ]*'.*[^']$/", $url)) {
1307 elseif (preg_match('/^href[ ]*=[ ]*".*[^"]$/', $url)) {
1311 // CRM-20206 Fix ampersand encoding in plain text emails
1313 $data = CRM_Utils_String
::unstupifyUrl($data);
1316 elseif ($type == 'url') {
1317 if ($this->url_tracking
&& !empty($this->id
)) {
1318 // ensure that Google CSS and any .css files are not tracked.
1319 if (!(strpos($token, 'css?family') ||
strpos($token, '.css'))) {
1320 $data = CRM_Mailing_BAO_TrackableURL
::getTrackerURL($token, $this->id
, $event_queue_id);
1321 if (!empty($html)) {
1322 $data = htmlentities($data, ENT_NOQUOTES
);
1330 elseif ($type == 'contact') {
1331 $data = CRM_Utils_Token
::getContactTokenReplacement($token, $contact, FALSE, FALSE, $useSmarty);
1333 elseif ($type == 'action') {
1334 $data = CRM_Utils_Token
::getActionTokenReplacement($token, $verp, $urls, $html);
1336 elseif ($type == 'domain') {
1337 $domain = CRM_Core_BAO_Domain
::getDomain();
1338 $data = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain, $html);
1340 elseif ($type == 'mailing') {
1341 if ($token == 'name') {
1342 $data = $this->name
;
1344 elseif ($token == 'group') {
1345 $groups = $this->getGroupNames();
1346 $data = implode(', ', $groups);
1350 $data = $contact["{$type}.{$token}"] ??
NULL;
1356 * Return a list of group names for this mailing. Does not work with
1357 * prior-mailing targets.
1360 * Names of groups receiving this mailing
1362 public function &getGroupNames() {
1363 if (!isset($this->id
)) {
1366 $mg = new CRM_Mailing_DAO_MailingGroup();
1367 $mgtable = CRM_Mailing_DAO_MailingGroup
::getTableName();
1368 $group = CRM_Contact_BAO_Group
::getTableName();
1370 $mg->query("SELECT $group.title as name FROM $mgtable
1371 INNER JOIN $group ON $mgtable.entity_id = $group.id
1372 WHERE $mgtable.mailing_id = {$this->id}
1373 AND $mgtable.entity_table = '$group'
1374 AND $mgtable.group_type = 'Include'
1375 ORDER BY $group.name");
1378 while ($mg->fetch()) {
1379 $groups[] = $mg->name
;
1387 * @param array $params
1388 * Reference array contains the values submitted by the form.
1390 * Reference array contains the id.
1393 * @return CRM_Mailing_DAO_Mailing
1395 public static function add(&$params, $ids = []) {
1396 $id = $params['id'] ??
$ids['mailing_id'] ??
NULL;
1398 if (empty($params['id']) && !empty($ids)) {
1399 CRM_Core_Error
::deprecatedWarning('Parameter $ids is no longer used by Mailing::add. Use the api or just pass $params');
1403 CRM_Utils_Hook
::pre('edit', 'Mailing', $id, $params);
1406 CRM_Utils_Hook
::pre('create', 'Mailing', NULL, $params);
1409 $mailing = new static();
1412 $mailing->find(TRUE);
1414 $mailing->domain_id
= CRM_Utils_Array
::value('domain_id', $params, CRM_Core_Config
::domainID());
1416 if (((!$id && empty($params['replyto_email'])) ||
!isset($params['replyto_email'])) &&
1417 isset($params['from_email'])
1419 $params['replyto_email'] = $params['from_email'];
1421 $mailing->copyValues($params);
1423 // CRM-20892 Unset Modifed Date here so that MySQL can correctly set an updated modfied date.
1424 unset($mailing->modified_date
);
1425 $result = $mailing->save();
1427 // CRM-20892 Re find record after saing so we can set the updated modified date in the result.
1428 $mailing->find(TRUE);
1430 if (isset($mailing->modified_date
)) {
1431 $result->modified_date
= $mailing->modified_date
;
1435 CRM_Utils_Hook
::post('edit', 'Mailing', $mailing->id
, $mailing);
1438 CRM_Utils_Hook
::post('create', 'Mailing', $mailing->id
, $mailing);
1445 * Construct a new mailing object, along with job and mailing_group
1446 * objects, from the form values of the create mailing wizard.
1448 * This function is a bit evil. It not only merges $params and saves
1449 * the mailing -- it also schedules the mailing and chooses the recipients.
1450 * Since it merges $params, it's also the only place to correctly trigger
1451 * multi-field validation. It should be broken up.
1453 * In the mean time, use-cases which break under the weight of this
1454 * evil may find reprieve in these extra evil params:
1456 * - _skip_evil_bao_auto_recipients_: bool
1457 * - _skip_evil_bao_auto_schedule_: bool
1458 * - _evil_bao_validator_: string|callable
1460 * </twowrongsmakesaright>
1462 * @params array $params
1465 * @param array $params
1468 * $mailing The new mailing object
1470 * @throws \CRM_Core_Exception
1471 * @throws \CiviCRM_API3_Exception
1473 public static function create(&$params) {
1476 // If it is a mass sms, set url_tracking to false
1477 if (!empty($params['sms_provider_id'])) {
1478 $params['url_tracking'] = 0;
1482 // Do the below only for an insert
1483 // for an update, we should not set the defaults
1484 if (!isset($params['id'])) {
1485 // Retrieve domain email and name for default sender
1486 $domain = civicrm_api(
1491 'current_domain' => 1,
1495 if (isset($domain['from_email'])) {
1496 $domain_email = $domain['from_email'];
1497 $domain_name = $domain['from_name'];
1500 $domain_email = 'info@EXAMPLE.ORG';
1501 $domain_name = 'EXAMPLE.ORG';
1503 if (!isset($params['created_id'])) {
1504 $params['created_id'] = CRM_Core_Session
::getLoggedInContactID();
1507 // load the default config settings for each
1508 // eg reply_id, unsubscribe_id need to use
1509 // correct template IDs here
1510 'override_verp' => TRUE,
1511 'forward_replies' => FALSE,
1512 'open_tracking' => Civi
::settings()->get('open_tracking_default'),
1513 'url_tracking' => Civi
::settings()->get('url_tracking_default'),
1514 'visibility' => 'Public Pages',
1515 'replyto_email' => $domain_email,
1516 'header_id' => CRM_Mailing_PseudoConstant
::defaultComponent('header_id', ''),
1517 'footer_id' => CRM_Mailing_PseudoConstant
::defaultComponent('footer_id', ''),
1518 'from_email' => $domain_email,
1519 'from_name' => $domain_name,
1520 'msg_template_id' => NULL,
1521 'created_id' => $params['created_id'],
1522 'approver_id' => NULL,
1523 'auto_responder' => 0,
1524 'created_date' => date('YmdHis'),
1525 'scheduled_date' => NULL,
1526 'approval_date' => NULL,
1529 // Get the default from email address, if not provided.
1530 if (empty($defaults['from_email'])) {
1531 $defaultAddress = CRM_Core_BAO_Domain
::getNameAndEmail(TRUE, TRUE);
1532 foreach ($defaultAddress as $id => $value) {
1533 if (preg_match('/"(.*)" <(.*)>/', $value, $match)) {
1534 $defaults['from_email'] = $match[2];
1535 $defaults['from_name'] = $match[1];
1540 $params = array_merge($defaults, $params);
1544 * Could check and warn for the following cases:
1546 * - groups OR mailings should be populated.
1547 * - body html OR body text should be populated.
1550 $transaction = new CRM_Core_Transaction();
1552 $mailing = self
::add($params);
1554 if (is_a($mailing, 'CRM_Core_Error')) {
1555 $transaction->rollback();
1558 // update mailings with hash values
1559 CRM_Contact_BAO_Contact_Utils
::generateChecksum($mailing->id
, NULL, NULL, NULL, 'mailing', 16);
1561 $groupTableName = CRM_Contact_BAO_Group
::getTableName();
1563 /* Create the mailing group record */
1564 $mg = new CRM_Mailing_DAO_MailingGroup();
1566 'include' => 'Include',
1567 'exclude' => 'Exclude',
1570 foreach (['groups', 'mailings'] as $entity) {
1571 foreach (['include', 'exclude', 'base'] as $type) {
1572 if (isset($params[$entity][$type])) {
1573 self
::replaceGroups($mailing->id
, $groupTypes[$type], $entity, $params[$entity][$type]);
1578 if (!empty($params['search_id']) && !empty($params['group_id'])) {
1580 $mg->mailing_id
= $mailing->id
;
1581 $mg->entity_table
= $groupTableName;
1582 $mg->entity_id
= $params['group_id'];
1583 $mg->search_id
= $params['search_id'];
1584 $mg->search_args
= $params['search_args'];
1585 $mg->group_type
= 'Include';
1589 // check and attach and files as needed
1590 CRM_Core_BAO_File
::processAttachment($params, 'civicrm_mailing', $mailing->id
);
1592 // If we're going to autosend, then check validity before saving.
1593 if (empty($params['is_completed']) && !empty($params['scheduled_date']) && $params['scheduled_date'] != 'null' && !empty($params['_evil_bao_validator_'])) {
1594 $cb = Civi\Core\Resolver
::singleton()
1595 ->get($params['_evil_bao_validator_']);
1596 $errors = call_user_func($cb, $mailing);
1597 if (!empty($errors)) {
1598 $fields = implode(',', array_keys($errors));
1599 throw new CRM_Core_Exception("Mailing cannot be sent. There are missing or invalid fields ($fields).", 'cannot-send', $errors);
1603 $transaction->commit();
1605 // Create parent job if not yet created.
1606 // Condition on the existence of a scheduled date.
1607 if (!empty($params['scheduled_date']) && $params['scheduled_date'] != 'null' && empty($params['_skip_evil_bao_auto_schedule_'])) {
1608 $job = new CRM_Mailing_BAO_MailingJob();
1609 $job->mailing_id
= $mailing->id
;
1610 // If we are creating a new Completed mailing (e.g. import from another system) set the job to completed.
1611 // Keeping former behaviour when an id is present is precautionary and may warrant reconsideration later.
1612 $job->status
= ((empty($params['is_completed']) ||
!empty($params['id'])) ?
'Scheduled' : 'Complete');
1615 if (!$job->find(TRUE)) {
1616 // Don't schedule job until we populate the recipients.
1617 $job->scheduled_date
= NULL;
1620 // Schedule the job now that it has recipients.
1621 $job->scheduled_date
= $params['scheduled_date'];
1625 // Populate the recipients.
1626 if (empty($params['_skip_evil_bao_auto_recipients_'])) {
1627 self
::getRecipients($mailing->id
);
1635 * This is used by CiviMail but will be made redundant by FlexMailer.
1636 * @param CRM_Mailing_DAO_Mailing $mailing
1637 * The mailing which may or may not be sendable.
1639 * List of error messages.
1641 public static function checkSendable($mailing) {
1643 foreach (['subject', 'name', 'from_name', 'from_email'] as $field) {
1644 if (empty($mailing->{$field})) {
1645 $errors[$field] = ts('Field "%1" is required.', [
1650 if (empty($mailing->body_html
) && empty($mailing->body_text
)) {
1651 $errors['body'] = ts('Field "body_html" or "body_text" is required.');
1654 if (!Civi
::settings()->get('disable_mandatory_tokens_check')) {
1655 $header = $mailing->header_id
&& $mailing->header_id
!= 'null' ? CRM_Mailing_BAO_MailingComponent
::findById($mailing->header_id
) : NULL;
1656 $footer = $mailing->footer_id
&& $mailing->footer_id
!= 'null' ? CRM_Mailing_BAO_MailingComponent
::findById($mailing->footer_id
) : NULL;
1657 foreach (['body_html', 'body_text'] as $field) {
1658 if (empty($mailing->{$field})) {
1661 $str = ($header ?
$header->{$field} : '') . $mailing->{$field} . ($footer ?
$footer->{$field} : '');
1662 $err = CRM_Utils_Token
::requiredTokens($str);
1663 if ($err !== TRUE) {
1664 foreach ($err as $token => $desc) {
1665 $errors["{$field}:{$token}"] = ts('This message is missing a required token - {%1}: %2',
1666 [1 => $token, 2 => $desc]
1677 * Replace the list of recipients on a given mailing.
1679 * @param int $mailingId
1680 * @param string $type
1681 * 'include' or 'exclude'.
1682 * @param string $entity
1683 * 'groups' or 'mailings'.
1684 * @param array $entityIds
1685 * @throws CiviCRM_API3_Exception
1687 public static function replaceGroups($mailingId, $type, $entity, $entityIds) {
1689 foreach ($entityIds as $entityId) {
1690 $values[] = ['entity_id' => $entityId];
1692 civicrm_api3('mailing_group', 'replace', [
1693 'mailing_id' => $mailingId,
1694 'group_type' => $type,
1695 'entity_table' => ($entity == 'groups') ? CRM_Contact_BAO_Group
::getTableName() : CRM_Mailing_BAO_Mailing
::getTableName(),
1696 'values' => $values,
1701 * Get hash value of the mailing.
1705 * @return null|string
1707 public static function getMailingHash($id) {
1709 if (Civi
::settings()->get('hash_mailing_url') && !empty($id)) {
1710 $hash = CRM_Core_DAO
::getFieldValue('CRM_Mailing_BAO_Mailing', $id, 'hash', 'id');
1716 * Generate a report. Fetch event count information, mailing data, and job
1720 * The mailing id to report.
1721 * @param bool $skipDetails
1722 * Whether return all detailed report.
1724 * @param bool $isSMS
1727 * Associative array of reporting data
1729 public static function &report($id, $skipDetails = FALSE, $isSMS = FALSE) {
1730 $mailing_id = CRM_Utils_Type
::escape($id, 'Integer');
1732 $mailing = new CRM_Mailing_BAO_Mailing();
1735 'mailing' => self
::getTableName(),
1736 'mailing_group' => CRM_Mailing_DAO_MailingGroup
::getTableName(),
1737 'group' => CRM_Contact_BAO_Group
::getTableName(),
1738 'job' => CRM_Mailing_BAO_MailingJob
::getTableName(),
1739 'queue' => CRM_Mailing_Event_BAO_Queue
::getTableName(),
1740 'delivered' => CRM_Mailing_Event_BAO_Delivered
::getTableName(),
1741 'opened' => CRM_Mailing_Event_BAO_Opened
::getTableName(),
1742 'reply' => CRM_Mailing_Event_BAO_Reply
::getTableName(),
1743 'unsubscribe' => CRM_Mailing_Event_BAO_Unsubscribe
::getTableName(),
1744 'bounce' => CRM_Mailing_Event_BAO_Bounce
::getTableName(),
1745 'forward' => CRM_Mailing_Event_BAO_Forward
::getTableName(),
1746 'url' => CRM_Mailing_BAO_TrackableURL
::getTableName(),
1747 'urlopen' => CRM_Mailing_Event_BAO_TrackableURLOpen
::getTableName(),
1748 'component' => CRM_Mailing_BAO_MailingComponent
::getTableName(),
1749 'spool' => CRM_Mailing_BAO_Spool
::getTableName(),
1753 $additionalWhereClause = " AND ";
1755 $additionalWhereClause .= " {$t['mailing']}.sms_provider_id IS NULL ";
1758 $additionalWhereClause .= " {$t['mailing']}.sms_provider_id IS NOT NULL ";
1761 /* Get the mailing info */
1764 SELECT {$t['mailing']}.*
1765 FROM {$t['mailing']}
1766 WHERE {$t['mailing']}.id = $mailing_id {$additionalWhereClause}");
1770 $report['mailing'] = [];
1771 foreach (array_keys(self
::fields()) as $field) {
1772 $field = self
::fields()[$field]['name'];
1773 $report['mailing'][$field] = $mailing->$field;
1777 if ($campaignId = CRM_Utils_Array
::value('campaign_id', $report['mailing'])) {
1778 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1779 $report['mailing']['campaign'] = $campaigns[$campaignId];
1782 //mailing report is called by activity
1783 //we dont need all detail report
1788 /* Get the component info */
1793 'header' => ts('Header'),
1794 'footer' => ts('Footer'),
1795 'reply' => ts('Reply'),
1796 'optout' => ts('Opt-Out'),
1797 'resubscribe' => ts('Resubscribe'),
1798 'unsubscribe' => ts('Unsubscribe'),
1800 foreach (array_keys($components) as $type) {
1801 $query[] = "SELECT {$t['component']}.name as name,
1803 {$t['component']}.id as id
1804 FROM {$t['component']}
1805 INNER JOIN {$t['mailing']}
1806 ON {$t['mailing']}.{$type}_id =
1807 {$t['component']}.id
1808 WHERE {$t['mailing']}.id = $mailing_id";
1810 $q = '(' . implode(') UNION (', $query) . ')';
1811 $mailing->query($q);
1813 $report['component'] = [];
1814 while ($mailing->fetch()) {
1815 $report['component'][] = [
1816 'type' => $components[$mailing->type
],
1817 'name' => $mailing->name
,
1818 'link' => CRM_Utils_System
::url('civicrm/mailing/component', "reset=1&action=update&id={$mailing->id}"),
1822 /* Get the recipient group info */
1825 SELECT {$t['mailing_group']}.group_type as group_type,
1826 {$t['group']}.id as group_id,
1827 {$t['group']}.title as group_title,
1828 {$t['group']}.is_hidden as group_hidden,
1829 {$t['mailing']}.id as mailing_id,
1830 {$t['mailing']}.name as mailing_name
1831 FROM {$t['mailing_group']}
1832 LEFT JOIN {$t['group']}
1833 ON {$t['mailing_group']}.entity_id = {$t['group']}.id
1834 AND {$t['mailing_group']}.entity_table =
1836 LEFT JOIN {$t['mailing']}
1837 ON {$t['mailing_group']}.entity_id =
1839 AND {$t['mailing_group']}.entity_table =
1842 WHERE {$t['mailing_group']}.mailing_id = $mailing_id
1845 $report['group'] = ['include' => [], 'exclude' => [], 'base' => []];
1846 while ($mailing->fetch()) {
1848 if (isset($mailing->group_id
)) {
1849 $row['id'] = $mailing->group_id
;
1850 $row['name'] = $mailing->group_title
;
1851 $row['link'] = CRM_Utils_System
::url('civicrm/group/search',
1852 "reset=1&force=1&context=smog&gid={$row['id']}"
1856 $row['id'] = $mailing->mailing_id
;
1857 $row['name'] = $mailing->mailing_name
;
1858 $row['mailing'] = TRUE;
1859 $row['link'] = CRM_Utils_System
::url('civicrm/mailing/report',
1864 /* Rename hidden groups */
1866 if ($mailing->group_hidden
== 1) {
1867 $row['name'] = "Search Results";
1870 if ($mailing->group_type
== 'Include') {
1871 $report['group']['include'][] = $row;
1873 elseif ($mailing->group_type
== 'Base') {
1874 $report['group']['base'][] = $row;
1877 $report['group']['exclude'][] = $row;
1881 /* Get the event totals, grouped by job (retries) */
1884 SELECT {$t['job']}.*,
1885 COUNT(DISTINCT {$t['queue']}.id) as queue,
1886 COUNT(DISTINCT {$t['delivered']}.id) as delivered,
1887 COUNT(DISTINCT {$t['reply']}.id) as reply,
1888 COUNT(DISTINCT {$t['forward']}.id) as forward,
1889 COUNT(DISTINCT {$t['bounce']}.id) as bounce,
1890 COUNT(DISTINCT {$t['urlopen']}.id) as url,
1891 COUNT(DISTINCT {$t['spool']}.id) as spool
1893 LEFT JOIN {$t['queue']}
1894 ON {$t['queue']}.job_id = {$t['job']}.id
1895 LEFT JOIN {$t['reply']}
1896 ON {$t['reply']}.event_queue_id = {$t['queue']}.id
1897 LEFT JOIN {$t['forward']}
1898 ON {$t['forward']}.event_queue_id = {$t['queue']}.id
1899 LEFT JOIN {$t['bounce']}
1900 ON {$t['bounce']}.event_queue_id = {$t['queue']}.id
1901 LEFT JOIN {$t['delivered']}
1902 ON {$t['delivered']}.event_queue_id = {$t['queue']}.id
1903 AND {$t['bounce']}.id IS null
1904 LEFT JOIN {$t['urlopen']}
1905 ON {$t['urlopen']}.event_queue_id = {$t['queue']}.id
1906 LEFT JOIN {$t['spool']}
1907 ON {$t['spool']}.job_id = {$t['job']}.id
1908 WHERE {$t['job']}.mailing_id = $mailing_id
1909 AND {$t['job']}.is_test = 0
1910 GROUP BY {$t['job']}.id");
1912 $report['jobs'] = [];
1913 $report['event_totals'] = [];
1914 $path = 'civicrm/mailing/report/event';
1929 // initialize various counters
1930 foreach ($elements as $field) {
1931 $report['event_totals'][$field] = 0;
1934 while ($mailing->fetch()) {
1936 foreach ($elements as $field) {
1937 if (isset($mailing->$field)) {
1938 $row[$field] = $mailing->$field;
1939 $report['event_totals'][$field] +
= $mailing->$field;
1943 // compute open total separately to discount duplicates
1945 $row['opened'] = CRM_Mailing_Event_BAO_Opened
::getTotalCount($mailing_id, $mailing->id
, TRUE);
1946 $report['event_totals']['opened'] +
= $row['opened'];
1947 $row['total_opened'] = CRM_Mailing_Event_BAO_Opened
::getTotalCount($mailing_id, $mailing->id
);
1948 $report['event_totals']['total_opened'] +
= $row['total_opened'];
1950 // compute unsub total separately to discount duplicates
1952 $row['unsubscribe'] = CRM_Mailing_Event_BAO_Unsubscribe
::getTotalCount($mailing_id, $mailing->id
, TRUE, TRUE);
1953 $report['event_totals']['unsubscribe'] +
= $row['unsubscribe'];
1955 $row['optout'] = CRM_Mailing_Event_BAO_Unsubscribe
::getTotalCount($mailing_id, $mailing->id
, TRUE, FALSE);
1956 $report['event_totals']['optout'] +
= $row['optout'];
1958 foreach (array_keys(CRM_Mailing_BAO_MailingJob
::fields()) as $field) {
1959 // Get the field name from the MailingJob fields as that will not have any prefixing.
1961 $field = CRM_Mailing_BAO_MailingJob
::fields()[$field]['name'];
1962 $row[$field] = $mailing->$field;
1965 if ($mailing->queue
) {
1966 $row['delivered_rate'] = (100.0 * $mailing->delivered
) / $mailing->queue
;
1967 $row['bounce_rate'] = (100.0 * $mailing->bounce
) / $mailing->queue
;
1968 $row['unsubscribe_rate'] = (100.0 * $row['unsubscribe']) / $mailing->queue
;
1969 $row['optout_rate'] = (100.0 * $row['optout']) / $mailing->queue
;
1970 $row['opened_rate'] = $mailing->delivered ?
(($row['opened'] / $mailing->delivered
) * 100.0) : 0;
1971 $row['clickthrough_rate'] = $mailing->delivered ?
(($mailing->url
/ $mailing->delivered
) * 100.0) : 0;
1974 $row['delivered_rate'] = 0;
1975 $row['bounce_rate'] = 0;
1976 $row['unsubscribe_rate'] = 0;
1977 $row['optout_rate'] = 0;
1978 $row['opened_rate'] = 0;
1979 $row['clickthrough_rate'] = 0;
1982 $arg = "reset=1&mid=$mailing_id&jid={$mailing->id}";
1984 'clicks' => CRM_Utils_System
::url($path, "$arg&event=click"),
1985 'queue' => CRM_Utils_System
::url($path, "$arg&event=queue"),
1986 'delivered' => CRM_Utils_System
::url($path, "$arg&event=delivered"),
1987 'bounce' => CRM_Utils_System
::url($path, "$arg&event=bounce"),
1988 'unsubscribe' => CRM_Utils_System
::url($path, "$arg&event=unsubscribe"),
1989 'forward' => CRM_Utils_System
::url($path, "$arg&event=forward"),
1990 'reply' => CRM_Utils_System
::url($path, "$arg&event=reply"),
1991 'opened' => CRM_Utils_System
::url($path, "$arg&event=opened"),
1994 foreach (['scheduled_date', 'start_date', 'end_date'] as $key) {
1995 $row[$key] = CRM_Utils_Date
::customFormat($row[$key]);
1997 $report['jobs'][] = $row;
2000 $newTableSize = CRM_Mailing_BAO_Recipients
::mailingSize($mailing_id);
2002 // we need to do this for backward compatibility, since old mailings did not
2003 // use the mailing_recipients table
2004 if ($newTableSize > 0) {
2005 $report['event_totals']['queue'] = $newTableSize;
2008 $report['event_totals']['queue'] = self
::getRecipientsCount($mailing_id);
2011 if (!empty($report['event_totals']['queue'])) {
2012 $report['event_totals']['delivered_rate'] = (100.0 * $report['event_totals']['delivered']) / $report['event_totals']['queue'];
2013 $report['event_totals']['bounce_rate'] = (100.0 * $report['event_totals']['bounce']) / $report['event_totals']['queue'];
2014 $report['event_totals']['unsubscribe_rate'] = (100.0 * $report['event_totals']['unsubscribe']) / $report['event_totals']['queue'];
2015 $report['event_totals']['optout_rate'] = (100.0 * $report['event_totals']['optout']) / $report['event_totals']['queue'];
2016 $report['event_totals']['opened_rate'] = !empty($report['event_totals']['delivered']) ?
(($report['event_totals']['opened'] / $report['event_totals']['delivered']) * 100.0) : 0;
2017 $report['event_totals']['clickthrough_rate'] = !empty($report['event_totals']['delivered']) ?
(($report['event_totals']['url'] / $report['event_totals']['delivered']) * 100.0) : 0;
2020 $report['event_totals']['delivered_rate'] = 0;
2021 $report['event_totals']['bounce_rate'] = 0;
2022 $report['event_totals']['unsubscribe_rate'] = 0;
2023 $report['event_totals']['optout_rate'] = 0;
2024 $report['event_totals']['opened_rate'] = 0;
2025 $report['event_totals']['clickthrough_rate'] = 0;
2028 /* Get the click-through totals, grouped by URL */
2031 SELECT {$t['url']}.url,
2033 COUNT({$t['urlopen']}.id) as clicks,
2034 COUNT(DISTINCT {$t['queue']}.id) as unique_clicks
2036 LEFT JOIN {$t['urlopen']}
2037 ON {$t['urlopen']}.trackable_url_id = {$t['url']}.id
2038 LEFT JOIN {$t['queue']}
2039 ON {$t['urlopen']}.event_queue_id = {$t['queue']}.id
2040 LEFT JOIN {$t['job']}
2041 ON {$t['queue']}.job_id = {$t['job']}.id
2042 WHERE {$t['url']}.mailing_id = $mailing_id
2043 AND {$t['job']}.is_test = 0
2044 GROUP BY {$t['url']}.id
2045 ORDER BY unique_clicks DESC");
2047 $report['click_through'] = [];
2049 while ($mailing->fetch()) {
2050 $report['click_through'][] = [
2051 'url' => $mailing->url
,
2052 'link' => CRM_Utils_System
::url($path, "reset=1&event=click&mid=$mailing_id&uid={$mailing->id}"),
2053 'link_unique' => CRM_Utils_System
::url($path, "reset=1&event=click&mid=$mailing_id&uid={$mailing->id}&distinct=1"),
2054 'clicks' => $mailing->clicks
,
2055 'unique' => $mailing->unique_clicks
,
2056 'rate' => !empty($report['event_totals']['delivered']) ?
(100.0 * $mailing->unique_clicks
) / $report['event_totals']['delivered'] : 0,
2057 'report' => CRM_Report_Utils_Report
::getNextUrl('mailing/clicks', "reset=1&mailing_id_value={$mailing_id}&url_value=" . rawurlencode($mailing->url
), FALSE, TRUE),
2061 $arg = "reset=1&mid=$mailing_id";
2062 $report['event_totals']['links'] = [
2063 'clicks' => CRM_Utils_System
::url($path, "$arg&event=click"),
2064 'clicks_unique' => CRM_Utils_System
::url($path, "$arg&event=click&distinct=1"),
2065 'queue' => CRM_Utils_System
::url($path, "$arg&event=queue"),
2066 'delivered' => CRM_Utils_System
::url($path, "$arg&event=delivered"),
2067 'bounce' => CRM_Utils_System
::url($path, "$arg&event=bounce"),
2068 'unsubscribe' => CRM_Utils_System
::url($path, "$arg&event=unsubscribe"),
2069 'optout' => CRM_Utils_System
::url($path, "$arg&event=optout"),
2070 'forward' => CRM_Utils_System
::url($path, "$arg&event=forward"),
2071 'reply' => CRM_Utils_System
::url($path, "$arg&event=reply"),
2072 'opened' => CRM_Utils_System
::url($path, "$arg&event=opened"),
2075 $actionLinks = [CRM_Core_Action
::VIEW
=> ['name' => ts('Report')]];
2076 $actionLinks[CRM_Core_Action
::ADVANCED
] = [
2077 'name' => ts('Advanced Search'),
2078 'url' => 'civicrm/contact/search/advanced',
2080 $action = array_sum(array_keys($actionLinks));
2082 $report['event_totals']['actionlinks'] = [];
2083 foreach (['clicks', 'clicks_unique', 'queue', 'delivered', 'bounce', 'unsubscribe', 'forward', 'reply', 'opened', 'opened_unique', 'optout'] as $key) {
2084 $url = 'mailing/detail';
2085 $reportFilter = "reset=1&mailing_id_value={$mailing_id}";
2086 $searchFilter = "force=1&mailing_id=%%mid%%";
2089 $reportFilter .= "&delivery_status_value=successful";
2090 $searchFilter .= "&mailing_delivery_status=Y";
2094 $url = "mailing/bounce";
2095 $searchFilter .= "&mailing_delivery_status=N";
2099 $reportFilter .= "&is_forwarded_value=1";
2100 $searchFilter .= "&mailing_forward=1";
2104 $reportFilter .= "&is_replied_value=1";
2105 $searchFilter .= "&mailing_reply_status=Y";
2109 $reportFilter .= "&is_unsubscribed_value=1";
2110 $searchFilter .= "&mailing_unsubscribe=1";
2114 $reportFilter .= "&is_optout_value=1";
2115 $searchFilter .= "&mailing_optout=1";
2119 // do not use group by clause in report, because same report used for total and unique open
2120 $reportFilter .= "&distinct=0";
2121 case 'opened_unique':
2122 $url = "mailing/opened";
2123 $searchFilter .= "&mailing_open_status=Y";
2127 case 'clicks_unique':
2128 $url = "mailing/clicks";
2129 $searchFilter .= "&mailing_click_status=Y";
2132 $actionLinks[CRM_Core_Action
::VIEW
]['url'] = CRM_Report_Utils_Report
::getNextUrl($url, $reportFilter, FALSE, TRUE);
2133 if (array_key_exists(CRM_Core_Action
::ADVANCED
, $actionLinks)) {
2134 $actionLinks[CRM_Core_Action
::ADVANCED
]['qs'] = $searchFilter;
2136 $report['event_totals']['actionlinks'][$key] = CRM_Core_Action
::formLink(
2139 ['mid' => $mailing_id],
2142 'mailing.report.action',
2152 * Get the count of mailings.
2159 public function getCount() {
2161 $this->selectAdd('COUNT(id) as count');
2163 $session = CRM_Core_Session
::singleton();
2166 return $this->count
;
2174 public static function checkPermission($id) {
2179 $mailingIDs = self
::mailingACLIDs();
2180 if ($mailingIDs === TRUE) {
2184 if (!in_array($id, $mailingIDs)) {
2185 throw new CRM_Core_Exception(ts('You do not have permission to access this mailing report'));
2190 * @param null $alias
2194 public static function mailingACL($alias = NULL) {
2195 $mailingACL = " ( 0 ) ";
2197 $mailingIDs = self
::mailingACLIDs();
2198 if ($mailingIDs === TRUE) {
2202 if (!empty($mailingIDs)) {
2203 $mailingIDs = implode(',', $mailingIDs);
2204 $tableName = !$alias ? self
::getTableName() : $alias;
2205 $mailingACL = " $tableName.id IN ( $mailingIDs ) ";
2211 * Returns all the mailings that this user can access. This is dependent on
2212 * all the groups that the user has access to.
2213 * However since most civi installs dont use ACL's we special case the condition
2214 * where the user has access to ALL groups, and hence ALL mailings and return a
2215 * value of TRUE (to avoid the downstream where clause with a list of mailing list IDs
2217 * @return bool|array
2218 * TRUE if the user has access to all mailings, else array of mailing IDs (possibly empty).
2220 public static function mailingACLIDs() {
2222 // optimize common case where admin has access
2225 CRM_Core_Permission
::check('view all contacts') ||
2226 CRM_Core_Permission
::check('edit all contacts')
2233 // get all the groups that this user can access
2234 // if they dont have universal access
2235 $groupNames = civicrm_api3('Group', 'get', [
2236 'check_permissions' => TRUE,
2237 'return' => ['title', 'id'],
2238 'options' => ['limit' => 0],
2240 foreach ($groupNames['values'] as $group) {
2241 $groups[$group['id']] = $group['title'];
2243 if (!empty($groups)) {
2244 $groupIDs = implode(',', array_keys($groups));
2245 $domain_id = CRM_Core_Config
::domainID();
2247 // get all the mailings that are in this subset of groups
2249 SELECT DISTINCT( m.id ) as id
2250 FROM civicrm_mailing m
2251 LEFT JOIN civicrm_mailing_group g ON g.mailing_id = m.id
2252 WHERE ( ( g.entity_table like 'civicrm_group%' AND g.entity_id IN ( $groupIDs ) )
2253 OR ( g.entity_table IS NULL AND g.entity_id IS NULL AND m.domain_id = $domain_id ) )
2255 $dao = CRM_Core_DAO
::executeQuery($query);
2258 while ($dao->fetch()) {
2259 $mailingIDs[] = $dao->id
;
2261 //CRM-18181 Get all mailings that use the mailings found earlier as receipients
2262 if (!empty($mailingIDs)) {
2263 $mailings = implode(',', $mailingIDs);
2265 SELECT DISTINCT ( m.id ) as id
2266 FROM civicrm_mailing m
2267 LEFT JOIN civicrm_mailing_group g ON g.mailing_id = m.id
2268 WHERE g.entity_table like 'civicrm_mailing%' AND g.entity_id IN ($mailings)";
2269 $mailingDao = CRM_Core_DAO
::executeQuery($mailingQuery);
2270 while ($mailingDao->fetch()) {
2271 $mailingIDs[] = $mailingDao->id
;
2280 * Get the rows for a browse operation.
2282 * @param int $offset
2283 * The row number to start from.
2284 * @param int $rowCount
2285 * The number of rows to return.
2286 * @param string $sort
2287 * The sql string that describes the sort order.
2289 * @param null $additionalClause
2290 * @param array $additionalParams
2295 public function &getRows($offset, $rowCount, $sort, $additionalClause = NULL, $additionalParams = NULL) {
2296 $mailing = self
::getTableName();
2297 $job = CRM_Mailing_BAO_MailingJob
::getTableName();
2298 $group = CRM_Mailing_DAO_MailingGroup
::getTableName();
2299 $session = CRM_Core_Session
::singleton();
2301 $mailingACL = self
::mailingACL();
2303 //get all campaigns.
2304 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
2309 "$mailing.approval_status_id",
2310 "createdContact.sort_name as created_by",
2311 "scheduledContact.sort_name as scheduled_by",
2312 "$mailing.created_id as created_id",
2313 "$mailing.scheduled_id as scheduled_id",
2314 "$mailing.is_archived as archived",
2315 "$mailing.created_date as created_date",
2317 "$mailing.sms_provider_id as sms_provider_id",
2318 "$mailing.language",
2321 // we only care about parent jobs, since that holds all the info on
2323 $selectClause = implode(', ', $select);
2324 $groupFromSelect = CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($select, "$mailing.id");
2326 SELECT {$selectClause},
2327 MIN($job.scheduled_date) as scheduled_date,
2328 MIN($job.start_date) as start_date,
2329 MAX($job.end_date) as end_date
2331 LEFT JOIN $job ON ( $job.mailing_id = $mailing.id AND $job.is_test = 0 AND $job.parent_id IS NULL )
2332 LEFT JOIN civicrm_contact createdContact ON ( civicrm_mailing.created_id = createdContact.id )
2333 LEFT JOIN civicrm_contact scheduledContact ON ( civicrm_mailing.scheduled_id = scheduledContact.id )
2334 WHERE $mailingACL $additionalClause";
2336 if (!empty($groupFromSelect)) {
2337 $query .= $groupFromSelect;
2341 $orderBy = trim($sort->orderBy());
2342 if (!empty($orderBy)) {
2343 $query .= " ORDER BY $orderBy";
2348 $offset = CRM_Utils_Type
::escape($offset, 'Int');
2349 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
2351 $query .= " LIMIT $offset, $rowCount ";
2354 if (!$additionalParams) {
2355 $additionalParams = [];
2358 $dao = CRM_Core_DAO
::executeQuery($query, $additionalParams);
2361 while ($dao->fetch()) {
2364 'name' => $dao->name
,
2365 'status' => $dao->status ?
$dao->status
: 'Not scheduled',
2366 'created_date' => CRM_Utils_Date
::customFormat($dao->created_date
),
2367 'scheduled' => CRM_Utils_Date
::customFormat($dao->scheduled_date
),
2368 'scheduled_iso' => $dao->scheduled_date
,
2369 'start' => CRM_Utils_Date
::customFormat($dao->start_date
),
2370 'end' => CRM_Utils_Date
::customFormat($dao->end_date
),
2371 'created_by' => $dao->created_by
,
2372 'scheduled_by' => $dao->scheduled_by
,
2373 'created_id' => $dao->created_id
,
2374 'scheduled_id' => $dao->scheduled_id
,
2375 'archived' => $dao->archived
,
2376 'approval_status_id' => $dao->approval_status_id
,
2377 'campaign_id' => $dao->campaign_id
,
2378 'campaign' => empty($dao->campaign_id
) ?
NULL : $allCampaigns[$dao->campaign_id
],
2379 'sms_provider_id' => $dao->sms_provider_id
,
2380 'language' => $dao->language
,
2387 * Show detail Mailing report.
2393 public static function showEmailDetails($id) {
2394 return CRM_Utils_System
::url('civicrm/mailing/report', "mid=$id");
2398 * Delete Mails and all its associated records.
2401 * Id of the mail to delete.
2405 public static function del($id) {
2407 throw new CRM_Core_Exception(ts('No id passed to mailing del function'));
2410 CRM_Utils_Hook
::pre('delete', 'Mailing', $id);
2412 // delete all file attachments
2413 CRM_Core_BAO_File
::deleteEntityFile('civicrm_mailing',
2417 $dao = new CRM_Mailing_DAO_Mailing();
2421 CRM_Core_Session
::setStatus(ts('Selected mailing has been deleted.'), ts('Deleted'), 'success');
2423 CRM_Utils_Hook
::post('delete', 'Mailing', $id, $dao);
2428 * Use CRM_Mailing_BAO_MailingJob::del($id)
2431 * Id of the Job to delete.
2435 public static function delJob($id) {
2437 throw new CRM_Core_Exception(ts('No id passed to mailing delJob function'));
2440 CRM_Core_Error
::deprecatedWarning('This function is deprecated, use CRM_Mailing_BAO_MailingJob::del instead');
2442 CRM_Mailing_BAO_MailingJob
::del($id);
2447 * This is used by CiviMail but will be made redundant by FlexMailer/TokenProcessor.
2450 public function getReturnProperties() {
2451 $tokens = &$this->getTokens();
2454 if (isset($tokens['html']) &&
2455 isset($tokens['html']['contact'])
2457 $properties = array_merge($properties, $tokens['html']['contact']);
2460 if (isset($tokens['text']) &&
2461 isset($tokens['text']['contact'])
2463 $properties = array_merge($properties, $tokens['text']['contact']);
2466 if (isset($tokens['subject']) &&
2467 isset($tokens['subject']['contact'])
2469 $properties = array_merge($properties, $tokens['subject']['contact']);
2472 $returnProperties = [];
2473 $returnProperties['display_name'] = $returnProperties['contact_id'] = $returnProperties['preferred_mail_format'] = $returnProperties['hash'] = 1;
2475 foreach ($properties as $p) {
2476 $returnProperties[$p] = 1;
2479 return $returnProperties;
2483 * Build the compose mail form.
2485 * @param CRM_Core_Form $form
2489 public static function commonCompose(&$form) {
2493 if (method_exists($form, 'listTokens')) {
2494 $tokens = array_merge($form->listTokens(), $tokens);
2497 //sorted in ascending order tokens by ignoring word case
2498 $form->assign('tokens', CRM_Utils_Token
::formatTokensForDisplay($tokens));
2503 'text_message' => ts('HTML Format'),
2504 'sms_text_message' => ts('SMS Message'),
2506 $modePrefixes = ['Mail' => NULL, 'SMS' => 'SMS'];
2508 $className = CRM_Utils_System
::getClassName($form);
2510 if ($className != 'CRM_SMS_Form_Upload' && $className != 'CRM_Contact_Form_Task_SMS' &&
2511 $className != 'CRM_Contact_Form_Task_SMS'
2513 $form->add('wysiwyg', 'html_message',
2514 strstr($className, 'PDF') ?
ts('Document Body') : ts('HTML Format'),
2518 'onkeyup' => "return verify(this)",
2522 if ($className != 'CRM_Admin_Form_ScheduleReminders') {
2523 unset($modePrefixes['SMS']);
2527 unset($textFields['text_message']);
2528 unset($modePrefixes['Mail']);
2531 //insert message Text by selecting "Select Template option"
2532 foreach ($textFields as $id => $label) {
2534 if ($id == 'sms_text_message') {
2536 $form->assign('max_sms_length', CRM_SMS_Provider
::MAX_SMS_CHAR
);
2538 $form->add('textarea', $id, $label,
2542 'onkeyup' => "return verify(this, '{$prefix}')",
2547 foreach ($modePrefixes as $prefix) {
2548 if ($prefix == 'SMS') {
2549 $templates[$prefix] = CRM_Core_BAO_MessageTemplate
::getMessageTemplates(FALSE, TRUE);
2552 $templates[$prefix] = CRM_Core_BAO_MessageTemplate
::getMessageTemplates(FALSE);
2554 if (!empty($templates[$prefix])) {
2555 $form->assign('templates', TRUE);
2557 $form->add('select', "{$prefix}template", ts('Use Template'),
2558 ['' => ts('- select -')] +
$templates[$prefix], FALSE,
2559 ['onChange' => "selectValue( this.value, '{$prefix}');"]
2562 $form->add('checkbox', "{$prefix}updateTemplate", ts('Update Template'), NULL);
2564 $form->add('checkbox', "{$prefix}saveTemplate", ts('Save As New Template'), NULL, FALSE,
2565 ['onclick' => "showSaveDetails(this, '{$prefix}');"]
2567 $form->add('text', "{$prefix}saveTemplateName", ts('Template Title'));
2570 // I'm not sure this is ever called.
2571 $action = CRM_Utils_Request
::retrieve('action', 'String', $form, FALSE);
2572 if ((CRM_Utils_System
::getClassName($form) == 'CRM_Contact_Form_Task_PDF') &&
2573 $action == CRM_Core_Action
::VIEW
2575 $form->freeze('html_message');
2580 * Get the search based mailing Ids.
2583 * , searched base mailing ids.
2585 public function searchMailingIDs() {
2586 $group = CRM_Mailing_DAO_MailingGroup
::getTableName();
2587 $mailing = self
::getTableName();
2590 SELECT $mailing.id as mailing_id
2591 FROM $mailing, $group
2592 WHERE $group.mailing_id = $mailing.id
2593 AND $group.group_type = 'Base'";
2595 $searchDAO = CRM_Core_DAO
::executeQuery($query);
2597 while ($searchDAO->fetch()) {
2598 $mailingIDs[] = $searchDAO->mailing_id
;
2605 * Get the content/components of mailing based on mailing Id
2607 * @param array $report
2608 * of mailing report.
2611 * Reference of this.
2613 * @param bool $isSMS
2616 * array content/component.
2618 public static function getMailingContent(&$report, &$form, $isSMS = FALSE) {
2619 $htmlHeader = $textHeader = NULL;
2620 $htmlFooter = $textFooter = NULL;
2623 if ($report['mailing']['header_id']) {
2624 $header = new CRM_Mailing_BAO_MailingComponent();
2625 $header->id
= $report['mailing']['header_id'];
2626 $header->find(TRUE);
2627 $htmlHeader = $header->body_html
;
2628 $textHeader = $header->body_text
;
2631 if ($report['mailing']['footer_id']) {
2632 $footer = new CRM_Mailing_BAO_MailingComponent();
2633 $footer->id
= $report['mailing']['footer_id'];
2634 $footer->find(TRUE);
2635 $htmlFooter = $footer->body_html
;
2636 $textFooter = $footer->body_text
;
2640 $mailingKey = $form->_mailing_id
;
2642 if ($hash = CRM_Mailing_BAO_Mailing
::getMailingHash($mailingKey)) {
2643 $mailingKey = $hash;
2647 if (!empty($report['mailing']['body_text'])) {
2648 $url = CRM_Utils_System
::url('civicrm/mailing/view', 'reset=1&text=1&id=' . $mailingKey);
2649 $form->assign('textViewURL', $url);
2653 if (!empty($report['mailing']['body_html'])) {
2654 $url = CRM_Utils_System
::url('civicrm/mailing/view', 'reset=1&id=' . $mailingKey);
2655 $form->assign('htmlViewURL', $url);
2660 $report['mailing']['attachment'] = CRM_Core_BAO_File
::attachmentInfo('civicrm_mailing', $form->_mailing_id
);
2670 public static function overrideVerp($jobID) {
2671 static $_cache = [];
2673 if (!isset($_cache[$jobID])) {
2675 SELECT override_verp
2676 FROM civicrm_mailing
2677 INNER JOIN civicrm_mailing_job ON civicrm_mailing.id = civicrm_mailing_job.mailing_id
2678 WHERE civicrm_mailing_job.id = %1
2680 $params = [1 => [$jobID, 'Integer']];
2681 $_cache[$jobID] = CRM_Core_DAO
::singleValueQuery($query, $params);
2683 return $_cache[$jobID];
2692 public static function processQueue($mode = NULL) {
2693 $config = CRM_Core_Config
::singleton();
2695 if ($mode == NULL && CRM_Core_BAO_MailSettings
::defaultDomain() == "EXAMPLE.ORG") {
2696 // Using forceBackend=TRUE because WordPress sometimes fails to detect cron
2697 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>', [
2698 1 => CRM_Utils_System
::url('civicrm/admin/mailSettings', 'reset=1', FALSE, NULL, TRUE, FALSE, TRUE),
2699 2 => "https://docs.civicrm.org/sysadmin/en/latest/setup/civimail/",
2703 // check if we are enforcing number of parallel cron jobs
2705 $gotCronLock = FALSE;
2707 $mailerJobsMax = Civi
::settings()->get('mailerJobsMax');
2708 if (is_numeric($mailerJobsMax) && $mailerJobsMax > 0) {
2709 $lockArray = range(1, $mailerJobsMax);
2711 // Shuffle the array to improve chances of quickly finding an open thread
2712 shuffle($lockArray);
2714 // Check if we are using global locks
2715 foreach ($lockArray as $lockID) {
2716 $cronLock = Civi
::lockManager()
2717 ->acquire("worker.mailing.send.{$lockID}");
2718 if ($cronLock->isAcquired()) {
2719 $gotCronLock = TRUE;
2724 // Exit here since we have enough mailing processes running
2725 if (!$gotCronLock) {
2726 CRM_Core_Error
::debug_log_message('Returning early, since the maximum number of mailing processes are running');
2730 if (getenv('CIVICRM_CRON_HOLD')) {
2731 // In testing, we may need to simulate some slow activities.
2732 sleep(getenv('CIVICRM_CRON_HOLD'));
2736 // Split up the parent jobs into multiple child jobs
2737 $mailerJobSize = Civi
::settings()->get('mailerJobSize');
2738 CRM_Mailing_BAO_MailingJob
::runJobs_pre($mailerJobSize, $mode);
2739 CRM_Mailing_BAO_MailingJob
::runJobs(NULL, $mode);
2740 CRM_Mailing_BAO_MailingJob
::runJobs_post($mode);
2742 // Release the global lock if we do have one
2744 $cronLock->release();
2751 * @param int $mailingID
2753 private static function addMultipleEmails($mailingID) {
2755 INSERT INTO civicrm_mailing_recipients
2756 (mailing_id, email_id, contact_id)
2757 SELECT %1, e.id, e.contact_id FROM civicrm_email e
2759 AND e.is_bulkmail = 1
2761 ( SELECT contact_id FROM civicrm_mailing_recipients mr WHERE mailing_id = %1 )
2762 AND e.id NOT IN ( SELECT email_id FROM civicrm_mailing_recipients mr WHERE mailing_id = %1 )
2764 $params = [1 => [$mailingID, 'Integer']];
2766 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2770 * @param bool $isSMS
2774 public static function getMailingsList($isSMS = FALSE) {
2778 $where .= " civicrm_mailing.sms_provider_id IS NULL ";
2781 $where .= " civicrm_mailing.sms_provider_id IS NOT NULL ";
2786 SELECT civicrm_mailing.id, civicrm_mailing.name, civicrm_mailing_job.end_date
2787 FROM civicrm_mailing
2788 INNER JOIN civicrm_mailing_job ON civicrm_mailing.id = civicrm_mailing_job.mailing_id {$where}
2789 ORDER BY civicrm_mailing.name";
2790 $mailing = CRM_Core_DAO
::executeQuery($query);
2792 while ($mailing->fetch()) {
2793 $list[$mailing->id
] = "{$mailing->name} :: {$mailing->end_date}";
2801 * wrapper for ajax activity selector.
2803 * @param array $params
2804 * Associated array for params record id.
2807 * associated array of contact activities
2809 public static function getContactMailingSelector(&$params) {
2810 // format the params
2811 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2812 $params['rowCount'] = $params['rp'];
2813 $params['sort'] = $params['sortBy'] ??
NULL;
2814 $params['caseId'] = NULL;
2816 // get contact mailings
2817 $mailings = CRM_Mailing_BAO_Mailing
::getContactMailings($params);
2820 $params['total'] = CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2823 if (!empty($mailings)) {
2824 $openCounts = CRM_Mailing_Event_BAO_Opened
::getMailingContactCount(array_keys($mailings), $params['contact_id']);
2825 $clickCounts = CRM_Mailing_Event_BAO_TrackableURLOpen
::getMailingContactCount(array_keys($mailings), $params['contact_id']);
2828 // format params and add links
2829 $contactMailings = [];
2830 foreach ($mailings as $mailingId => $values) {
2832 $mailing['subject'] = $values['subject'];
2833 $mailing['creator_name'] = CRM_Utils_System
::href(
2834 $values['creator_name'],
2835 'civicrm/contact/view',
2836 "reset=1&cid={$values['creator_id']}");
2837 $mailing['recipients'] = CRM_Utils_System
::href(ts('(recipients)'), 'civicrm/mailing/report/event',
2838 "mid={$values['mailing_id']}&reset=1&cid={$params['contact_id']}&event=queue&context=mailing");
2839 $mailing['start_date'] = CRM_Utils_Date
::customFormat($values['start_date']);
2841 $mailing['openstats'] = "Opens: " .
2842 CRM_Utils_Array
::value($values['mailing_id'], $openCounts, 0) .
2844 CRM_Utils_Array
::value($values['mailing_id'], $clickCounts, 0);
2847 CRM_Core_Action
::VIEW
=> [
2848 'name' => ts('View'),
2849 'url' => 'civicrm/mailing/view',
2850 'qs' => "reset=1&id=%%mkey%%",
2851 'title' => ts('View Mailing'),
2852 'class' => 'crm-popup',
2854 CRM_Core_Action
::BROWSE
=> [
2855 'name' => ts('Mailing Report'),
2856 'url' => 'civicrm/mailing/report',
2857 'qs' => "mid=%%mid%%&reset=1&cid=%%cid%%&context=mailing",
2858 'title' => ts('View Mailing Report'),
2862 $mailingKey = $values['mailing_id'];
2863 if ($hash = CRM_Mailing_BAO_Mailing
::getMailingHash($mailingKey)) {
2864 $mailingKey = $hash;
2867 $mailing['links'] = CRM_Core_Action
::formLink(
2871 'mid' => $values['mailing_id'],
2872 'cid' => $params['contact_id'],
2873 'mkey' => $mailingKey,
2877 'mailing.contact.action',
2879 $values['mailing_id']
2882 array_push($contactMailings, $mailing);
2885 $contactMailingsDT = [];
2886 $contactMailingsDT['data'] = $contactMailings;
2887 $contactMailingsDT['recordsTotal'] = $params['total'];
2888 $contactMailingsDT['recordsFiltered'] = $params['total'];
2890 return $contactMailingsDT;
2894 * Retrieve contact mailing.
2896 * @param array $params
2899 * Array of mailings for a contact
2902 public static function getContactMailings(&$params) {
2903 $params['version'] = 3;
2904 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2905 $params['limit'] = $params['rp'];
2906 $params['sort'] = $params['sortBy'] ??
NULL;
2908 $result = civicrm_api('MailingContact', 'get', $params);
2909 return $result['values'];
2913 * Retrieve contact mailing count.
2915 * @param array $params
2918 * count of mailings for a contact
2921 public static function getContactMailingsCount(&$params) {
2922 $params['version'] = 3;
2923 return civicrm_api('MailingContact', 'getcount', $params);
2927 * Get a list of permissions required for CRUD'ing each field
2928 * (when workflow is enabled).
2931 * Array (string $fieldName => string $permName)
2933 public static function getWorkflowFieldPerms() {
2934 $fieldNames = array_keys(CRM_Mailing_DAO_Mailing
::fields());
2936 foreach ($fieldNames as $fieldName) {
2937 if ($fieldName == 'id') {
2938 $fieldPerms[$fieldName] = [
2942 'schedule mailings',
2947 elseif (in_array($fieldName, ['scheduled_date', 'scheduled_id'])) {
2948 $fieldPerms[$fieldName] = [
2950 ['access CiviMail', 'schedule mailings'],
2953 elseif (in_array($fieldName, [
2956 'approval_status_id',
2959 $fieldPerms[$fieldName] = [
2961 ['access CiviMail', 'approve mailings'],
2965 $fieldPerms[$fieldName] = [
2967 ['access CiviMail', 'create mailings'],
2975 * White-list of possible values for the entity_table field.
2979 public static function mailingGroupEntityTables() {
2981 CRM_Contact_BAO_Group
::getTableName() => 'Group',
2982 CRM_Mailing_BAO_Mailing
::getTableName() => 'Mailing',
2987 * Get the public view url.
2990 * @param bool $absolute
2994 public static function getPublicViewUrl($id, $absolute = TRUE) {
2995 if ((civicrm_api3('Mailing', 'getvalue', [
2997 'return' => 'visibility',
2998 ])) === 'Public Pages') {
3000 // if hash setting is on then we change the public url into a hash
3001 $hash = CRM_Mailing_BAO_Mailing
::getMailingHash($id);
3002 if (!empty($hash)) {
3006 return CRM_Utils_System
::url('civicrm/mailing/view', ['id' => $id], $absolute, NULL, TRUE, TRUE);
3011 * Get a list of template types which can be used as `civicrm_mailing.template_type`.
3014 * A list of template-types, keyed numerically. Each defines:
3015 * - name: string, a short symbolic name
3016 * - editorUrl: string, Angular template name
3018 * Ex: $templateTypes[0] === array('name' => 'mosaico', 'editorUrl' => '~/crmMosaico/editor.html').
3020 public static function getTemplateTypes() {
3021 if (!isset(Civi
::$statics[__CLASS__
]['templateTypes'])) {
3024 'name' => 'traditional',
3025 'editorUrl' => CRM_Mailing_Info
::workflowEnabled() ?
'~/crmMailing/EditMailingCtrl/workflow.html' : '~/crmMailing/EditMailingCtrl/2step.html',
3029 CRM_Utils_Hook
::mailingTemplateTypes($types);
3031 $defaults = ['weight' => 0];
3032 foreach (array_keys($types) as $typeName) {
3033 $types[$typeName] = array_merge($defaults, $types[$typeName]);
3035 usort($types, function ($a, $b) {
3036 if ($a['weight'] === $b['weight']) {
3039 return $a['weight'] < $b['weight'] ?
-1 : 1;
3042 Civi
::$statics[__CLASS__
]['templateTypes'] = $types;
3045 return Civi
::$statics[__CLASS__
]['templateTypes'];
3049 * Get a list of template types.
3052 * Array(string $name => string $label).
3054 public static function getTemplateTypeNames() {
3056 foreach (self
::getTemplateTypes() as $type) {
3057 $r[$type['name']] = $type['name'];