3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2017 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
31 * @copyright CiviCRM LLC (c) 2004-2017
33 require_once 'Mail/mime.php';
36 * Class CRM_Mailing_BAO_Mailing
38 class CRM_Mailing_BAO_Mailing
extends CRM_Mailing_DAO_Mailing
{
41 * An array that holds the complete templates
42 * including any headers or footers that need to be prepended
43 * or appended to the body.
45 private $preparedTemplates = NULL;
48 * An array that holds the complete templates
49 * including any headers or footers that need to be prepended
50 * or appended to the body.
52 private $templates = NULL;
55 * An array that holds the tokens that are specifically found in our text and html bodies.
57 private $tokens = NULL;
60 * An array that holds the tokens that are specifically found in our text and html bodies.
62 private $flattenedTokens = NULL;
65 * The header associated with this mailing.
67 private $header = NULL;
70 * The footer associated with this mailing.
72 private $footer = NULL;
75 * The HTML content of the message.
80 * The text content of the message.
85 * Cached BAO for the domain.
87 private $_domain = NULL;
92 public function __construct() {
93 parent
::__construct();
100 * @param int $mailing_id
104 public static function getRecipientsCount($job_id, $mailing_id = NULL) {
105 // need this for backward compatibility, so we can get count for old mailings
106 // please do not use this function if possible.
107 $eq = self
::getRecipients($job_id, $mailing_id);
112 * note that $job_id is used only as a variable in the temp table construction
113 * and does not play a role in the queries generated.
115 * (misnomer) a nonce value used to name temporary tables.
116 * @param int $mailing_id
117 * @param bool $storeRecipients
118 * @param bool $dedupeEmail
121 * @return CRM_Mailing_Event_BAO_Queue|string
123 public static function getRecipients(
126 $storeRecipients = FALSE,
127 $dedupeEmail = FALSE,
129 $mailingGroup = new CRM_Mailing_DAO_MailingGroup();
131 $mailing = CRM_Mailing_BAO_Mailing
::getTableName();
132 $job = CRM_Mailing_BAO_MailingJob
::getTableName();
133 $mg = CRM_Mailing_DAO_MailingGroup
::getTableName();
134 $eq = CRM_Mailing_Event_DAO_Queue
::getTableName();
136 $email = CRM_Core_DAO_Email
::getTableName();
137 if ($mode == 'sms') {
138 $phone = CRM_Core_DAO_Phone
::getTableName();
140 $contact = CRM_Contact_DAO_Contact
::getTableName();
142 $group = CRM_Contact_DAO_Group
::getTableName();
143 $g2contact = CRM_Contact_DAO_GroupContact
::getTableName();
145 $m = new CRM_Mailing_DAO_Mailing();
146 $m->id
= $mailing_id;
149 $email_selection_method = $m->email_selection_method
;
150 $location_type_id = $m->location_type_id
;
152 // Note: When determining the ORDER that results are returned, it's
153 // the record that comes last that counts. That's because we are
154 // INSERT'ing INTO a table with a primary id so that last record
155 // over writes any previous record.
156 switch ($email_selection_method) {
157 case 'location-exclude':
158 $location_filter = "($email.location_type_id != $location_type_id)";
159 // If there is more than one email that doesn't match the location,
160 // prefer the one marked is_bulkmail, followed by is_primary.
161 $order_by = "ORDER BY $email.is_bulkmail, $email.is_primary";
164 case 'location-only':
165 $location_filter = "($email.location_type_id = $location_type_id)";
166 // If there is more than one email of the desired location, prefer
167 // the one marked is_bulkmail, followed by is_primary.
168 $order_by = "ORDER BY $email.is_bulkmail, $email.is_primary";
171 case 'location-prefer':
172 $location_filter = "($email.is_bulkmail = 1 OR $email.is_primary = 1 OR $email.location_type_id = $location_type_id)";
174 // ORDER BY is more complicated because we have to set an arbitrary
175 // order that prefers the location that we want. We do that using
176 // the FIELD function. For more info, see:
177 // https://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_field
178 // We assign the location type we want the value "1" by putting it
179 // in the first position after we name the field. All other location
180 // types are left out, so they will be assigned the value 0. That
181 // means, they will all be equally tied for first place, with our
182 // location being last.
183 $order_by = "ORDER BY FIELD($email.location_type_id, $location_type_id), $email.is_bulkmail, $email.is_primary";
187 // fall through to default
189 $location_filter = "($email.is_bulkmail = 1 OR $email.is_primary = 1)";
190 $order_by = "ORDER BY $email.is_bulkmail";
193 // Create a temp table for contact exclusion.
194 $mailingGroup->query(
195 "CREATE TEMPORARY TABLE X_$job_id
196 (contact_id int primary key)
200 // Add all the members of groups excluded from this mailing to the temp
203 $excludeSubGroup = "INSERT INTO X_$job_id (contact_id)
204 SELECT DISTINCT $g2contact.contact_id
207 ON $g2contact.group_id = $mg.entity_id AND $mg.entity_table = '$group'
209 $mg.mailing_id = {$mailing_id}
210 AND $g2contact.status = 'Added'
211 AND $mg.group_type = 'Exclude'";
212 $mailingGroup->query($excludeSubGroup);
214 // Add all unsubscribe members of base group from this mailing to the temp
217 $unSubscribeBaseGroup = "INSERT INTO X_$job_id (contact_id)
218 SELECT DISTINCT $g2contact.contact_id
221 ON $g2contact.group_id = $mg.entity_id AND $mg.entity_table = '$group'
223 $mg.mailing_id = {$mailing_id}
224 AND $g2contact.status = 'Removed'
225 AND $mg.group_type = 'Base'";
226 $mailingGroup->query($unSubscribeBaseGroup);
228 // Add all the (intended) recipients of an excluded prior mailing to
231 $excludeSubMailing = "INSERT IGNORE INTO X_$job_id (contact_id)
232 SELECT DISTINCT $eq.contact_id
235 ON $eq.job_id = $job.id
237 ON $job.mailing_id = $mg.entity_id AND $mg.entity_table = '$mailing'
239 $mg.mailing_id = {$mailing_id}
240 AND $mg.group_type = 'Exclude'";
241 $mailingGroup->query($excludeSubMailing);
243 // get all the saved searches AND hierarchical groups
244 // and load them in the cache
246 SELECT $group.id, $group.cache_date, $group.saved_search_id, $group.children
248 INNER JOIN $mg ON $mg.entity_id = $group.id
249 WHERE $mg.entity_table = '$group'
250 AND $mg.group_type = 'Exclude'
251 AND $mg.mailing_id = {$mailing_id}
252 AND ( saved_search_id != 0
253 OR saved_search_id IS NOT NULL
254 OR children IS NOT NULL )
257 $groupDAO = CRM_Core_DAO
::executeQuery($sql);
258 while ($groupDAO->fetch()) {
259 if ($groupDAO->cache_date
== NULL) {
260 CRM_Contact_BAO_GroupContactCache
::load($groupDAO);
263 $smartGroupExclude = "
264 INSERT IGNORE INTO X_$job_id (contact_id)
266 FROM civicrm_group_contact_cache c
267 WHERE c.group_id = {$groupDAO->id}
269 $mailingGroup->query($smartGroupExclude);
272 $tempColumn = 'email_id';
273 if ($mode == 'sms') {
274 $tempColumn = 'phone_id';
277 // Get all the group contacts we want to include.
279 $mailingGroup->query(
280 "CREATE TEMPORARY TABLE I_$job_id
281 ($tempColumn int, contact_id int primary key)
285 // Get the group contacts, but only those which are not in the
286 // exclusion temp table.
288 $query = "REPLACE INTO I_$job_id (email_id, contact_id)
290 SELECT $email.id as email_id,
291 $contact.id as contact_id
294 ON $email.contact_id = $contact.id
295 INNER JOIN $g2contact
296 ON $contact.id = $g2contact.contact_id
298 ON $g2contact.group_id = $mg.entity_id
299 AND $mg.entity_table = '$group'
301 ON $contact.id = X_$job_id.contact_id
303 ($mg.group_type = 'Include')
304 AND $mg.search_id IS NULL
305 AND $g2contact.status = 'Added'
306 AND $contact.do_not_email = 0
307 AND $contact.is_opt_out = 0
308 AND $contact.is_deceased <> 1
310 AND $email.email IS NOT NULL
311 AND $email.email != ''
312 AND $email.on_hold = 0
313 AND $mg.mailing_id = {$mailing_id}
314 AND X_$job_id.contact_id IS null
315 GROUP BY $email.id, $contact.id
318 if ($mode == 'sms') {
319 $phoneTypes = CRM_Core_OptionGroup
::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
320 $query = "REPLACE INTO I_$job_id (phone_id, contact_id)
322 SELECT DISTINCT $phone.id as phone_id,
323 $contact.id as contact_id
326 ON $phone.contact_id = $contact.id
327 INNER JOIN $g2contact
328 ON $contact.id = $g2contact.contact_id
330 ON $g2contact.group_id = $mg.entity_id
331 AND $mg.entity_table = '$group'
333 ON $contact.id = X_$job_id.contact_id
335 ($mg.group_type = 'Include')
336 AND $mg.search_id IS NULL
337 AND $g2contact.status = 'Added'
338 AND $contact.do_not_sms = 0
339 AND $contact.is_opt_out = 0
340 AND $contact.is_deceased <> 1
341 AND $phone.phone_type_id = {$phoneTypes['Mobile']}
342 AND $phone.phone IS NOT NULL
343 AND $phone.phone != ''
344 AND $mg.mailing_id = {$mailing_id}
345 AND X_$job_id.contact_id IS null";
347 $mailingGroup->query($query);
349 // Query prior mailings.
351 $query = "REPLACE INTO I_$job_id (email_id, contact_id)
352 SELECT $email.id as email_id,
353 $contact.id as contact_id
356 ON $email.contact_id = $contact.id
358 ON $eq.contact_id = $contact.id
360 ON $eq.job_id = $job.id
362 ON $job.mailing_id = $mg.entity_id AND $mg.entity_table = '$mailing'
364 ON $contact.id = X_$job_id.contact_id
366 ($mg.group_type = 'Include')
367 AND $contact.do_not_email = 0
368 AND $contact.is_opt_out = 0
369 AND $contact.is_deceased <> 1
371 AND $email.on_hold = 0
372 AND $mg.mailing_id = {$mailing_id}
373 AND X_$job_id.contact_id IS null
374 GROUP BY $email.id, $contact.id
377 if ($mode == 'sms') {
378 $query = "REPLACE INTO I_$job_id (phone_id, contact_id)
379 SELECT DISTINCT $phone.id as phone_id,
380 $contact.id as contact_id
383 ON $phone.contact_id = $contact.id
385 ON $eq.contact_id = $contact.id
387 ON $eq.job_id = $job.id
389 ON $job.mailing_id = $mg.entity_id AND $mg.entity_table = '$mailing'
391 ON $contact.id = X_$job_id.contact_id
393 ($mg.group_type = 'Include')
394 AND $contact.do_not_sms = 0
395 AND $contact.is_opt_out = 0
396 AND $contact.is_deceased <> 1
397 AND $phone.phone_type_id = {$phoneTypes['Mobile']}
398 AND $mg.mailing_id = {$mailing_id}
399 AND X_$job_id.contact_id IS null";
401 $mailingGroup->query($query);
404 SELECT $group.id, $group.cache_date, $group.saved_search_id, $group.children
406 INNER JOIN $mg ON $mg.entity_id = $group.id
407 WHERE $mg.entity_table = '$group'
408 AND $mg.group_type = 'Include'
409 AND $mg.search_id IS NULL
410 AND $mg.mailing_id = {$mailing_id}
411 AND ( saved_search_id != 0
412 OR saved_search_id IS NOT NULL
413 OR children IS NOT NULL )
416 $groupDAO = CRM_Core_DAO
::executeQuery($sql);
417 while ($groupDAO->fetch()) {
418 if ($groupDAO->cache_date
== NULL) {
419 CRM_Contact_BAO_GroupContactCache
::load($groupDAO);
422 $smartGroupInclude = "
423 REPLACE INTO I_$job_id (email_id, contact_id)
424 SELECT civicrm_email.id as email_id, c.id as contact_id
425 FROM civicrm_contact c
426 INNER JOIN civicrm_email ON civicrm_email.contact_id = c.id
427 INNER JOIN civicrm_group_contact_cache gc ON gc.contact_id = c.id
428 LEFT JOIN X_$job_id ON X_$job_id.contact_id = c.id
429 WHERE gc.group_id = {$groupDAO->id}
430 AND c.do_not_email = 0
432 AND c.is_deceased <> 1
434 AND civicrm_email.on_hold = 0
435 AND X_$job_id.contact_id IS null
438 if ($mode == 'sms') {
439 $smartGroupInclude = "
440 REPLACE INTO I_$job_id (phone_id, contact_id)
441 SELECT p.id as phone_id, c.id as contact_id
442 FROM civicrm_contact c
443 INNER JOIN civicrm_phone p ON p.contact_id = c.id
444 INNER JOIN civicrm_group_contact_cache gc ON gc.contact_id = c.id
445 LEFT JOIN X_$job_id ON X_$job_id.contact_id = c.id
446 WHERE gc.group_id = {$groupDAO->id}
449 AND c.is_deceased <> 1
450 AND p.phone_type_id = {$phoneTypes['Mobile']}
451 AND X_$job_id.contact_id IS null";
453 $mailingGroup->query($smartGroupInclude);
456 // Construct the filtered search queries.
458 SELECT search_id, search_args, entity_id
460 WHERE $mg.search_id IS NOT NULL
461 AND $mg.mailing_id = {$mailing_id}
463 $dao = CRM_Core_DAO
::executeQuery($query);
464 while ($dao->fetch()) {
465 $customSQL = CRM_Contact_BAO_SearchCustom
::civiMailSQL($dao->search_id
,
469 $query = "REPLACE INTO I_$job_id ({$tempColumn}, contact_id)
471 $mailingGroup->query($query);
474 // Get the emails with only location override.
476 $query = "REPLACE INTO I_$job_id (email_id, contact_id)
477 SELECT $email.id as local_email_id,
478 $contact.id as contact_id
481 ON $email.contact_id = $contact.id
482 INNER JOIN $g2contact
483 ON $contact.id = $g2contact.contact_id
485 ON $g2contact.group_id = $mg.entity_id
487 ON $contact.id = X_$job_id.contact_id
489 $mg.entity_table = '$group'
490 AND $mg.group_type = 'Include'
491 AND $g2contact.status = 'Added'
492 AND $contact.do_not_email = 0
493 AND $contact.is_opt_out = 0
494 AND $contact.is_deceased <> 1
496 AND $email.on_hold = 0
497 AND $mg.mailing_id = {$mailing_id}
498 AND X_$job_id.contact_id IS null
499 GROUP BY $email.id, $contact.id
501 if ($mode == "sms") {
502 $query = "REPLACE INTO I_$job_id (phone_id, contact_id)
503 SELECT DISTINCT $phone.id as phone_id,
504 $contact.id as contact_id
507 ON $phone.contact_id = $contact.id
508 INNER JOIN $g2contact
509 ON $contact.id = $g2contact.contact_id
511 ON $g2contact.group_id = $mg.entity_id
513 ON $contact.id = X_$job_id.contact_id
515 $mg.entity_table = '$group'
516 AND $mg.group_type = 'Include'
517 AND $g2contact.status = 'Added'
518 AND $contact.do_not_sms = 0
519 AND $contact.is_opt_out = 0
520 AND $contact.is_deceased <> 1
521 AND $phone.phone_type_id = {$phoneTypes['Mobile']}
522 AND $mg.mailing_id = {$mailing_id}
523 AND X_$job_id.contact_id IS null";
525 $mailingGroup->query($query);
527 $eq = new CRM_Mailing_Event_BAO_Queue();
529 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause();
530 $aclWhere = $aclWhere ?
"WHERE {$aclWhere}" : '';
532 if ($storeRecipients && $mailing_id) {
535 FROM civicrm_mailing_recipients
536 WHERE mailing_id = %1
538 $params = array(1 => array($mailing_id, 'Integer'));
539 CRM_Core_DAO
::executeQuery($sql, $params);
541 $selectClause = array('%1', 'i.contact_id', "i.{$tempColumn}");
542 $select = "SELECT " . implode(', ', $selectClause);
544 $groupBy = $groupJoin = '';
545 $orderBy = "i.contact_id, i.{$tempColumn}";
547 $orderBy = "MIN(i.contact_id), MIN(i.{$tempColumn})";
548 $groupJoin = " INNER JOIN civicrm_email e ON e.id = i.email_id";
549 $groupBy = " GROUP BY e.email ";
550 $select = CRM_Contact_BAO_Query
::appendAnyValueToSelect($selectClause, 'e.email');
554 INSERT INTO civicrm_mailing_recipients ( mailing_id, contact_id, {$tempColumn} )
556 FROM civicrm_contact contact_a
557 INNER JOIN I_$job_id i ON contact_a.id = i.contact_id
565 CRM_Core_DAO
::executeQuery($sql, $params);
567 // if we need to add all emails marked bulk, do it as a post filter
568 // on the mailing recipients table
569 if (CRM_Core_BAO_Email
::isMultipleBulkMail()) {
570 self
::addMultipleEmails($mailing_id);
574 // Delete the temp table.
576 $mailingGroup->reset();
577 $mailingGroup->query("DROP TEMPORARY TABLE X_$job_id");
578 $mailingGroup->query("DROP TEMPORARY TABLE I_$job_id");
584 * @param string $type
588 private function _getMailingGroupIds($type = 'Include') {
589 $mailingGroup = new CRM_Mailing_DAO_MailingGroup();
590 $group = CRM_Contact_DAO_Group
::getTableName();
591 if (!isset($this->id
)) {
592 // we're just testing tokens, so return any group
593 $query = "SELECT id AS entity_id
599 $mg = CRM_Mailing_DAO_MailingGroup
::getTableName();
600 $query = "SELECT entity_id
602 WHERE mailing_id = {$this->id}
603 AND group_type = '$type'
604 AND entity_table = '$group'";
606 $mailingGroup->query($query);
609 while ($mailingGroup->fetch()) {
610 $groupIds[] = $mailingGroup->entity_id
;
617 * Returns the regex patterns that are used for preparing the text and html templates.
619 * @param bool $onlyHrefs
621 * @return array|string
623 private function getPatterns($onlyHrefs = FALSE) {
627 $protos = '(https?|ftp|mailto)';
629 $gunk = '\{\}/#~:.?+=&;%@!\,\-\|\(\)\*';
631 $any = "{$letters}{$gunk}{$punc}";
633 $pattern = "\\bhref[ ]*=[ ]*([\"'])?(($protos:[$any]+?(?=[$punc]*[^$any]|$)))([\"'])?";
636 $pattern = "\\b($protos:[$any]+?(?=[$punc]*[^$any]|$))";
639 $patterns[] = $pattern;
640 $patterns[] = '\\\\\{\w+\.\w+\\\\\}|\{\{\w+\.\w+\}\}';
641 $patterns[] = '\{\w+\.\w+\}';
643 $patterns = '{' . implode('|', $patterns) . '}imu';
649 * Returns an array that denotes the type of token that we are dealing with
650 * we use the type later on when we are doing a token replacement lookup
652 * @param string $token
653 * The token for which we will be doing adata lookup.
656 * An array that holds the token itself and the type.
657 * the type will tell us which function to use for the data lookup
658 * if we need to do a lookup at all
660 public function &getDataFunc($token) {
661 static $_categories = NULL;
662 static $_categoryString = NULL;
664 $_categories = array(
671 CRM_Utils_Hook
::tokens($_categories);
672 $_categoryString = implode('|', array_keys($_categories));
675 $funcStruct = array('type' => NULL, 'token' => $token);
677 if ((preg_match('/^href/i', $token) ||
preg_match('/^http/i', $token))) {
678 // it is a url so we need to check to see if there are any tokens embedded
679 // if so then call this function again to get the token dataFunc
680 // and assign the type 'embedded' so that the data retrieving function
681 // will know what how to handle this token.
682 if (preg_match_all('/(\{\w+\.\w+\})/', $token, $matches)) {
683 $funcStruct['type'] = 'embedded_url';
684 $funcStruct['embed_parts'] = $funcStruct['token'] = array();
685 foreach ($matches[1] as $match) {
686 $preg_token = '/' . preg_quote($match, '/') . '/';
687 $list = preg_split($preg_token, $token, 2);
688 $funcStruct['embed_parts'][] = $list[0];
690 $funcStruct['token'][] = $this->getDataFunc($match);
692 // fixed truncated url, CRM-7113
694 $funcStruct['embed_parts'][] = $token;
698 $funcStruct['type'] = 'url';
701 elseif (preg_match('/^\{(' . $_categoryString . ')\.(\w+)\}$/', $token, $matches)) {
702 $funcStruct['type'] = $matches[1];
703 $funcStruct['token'] = $matches[2];
705 elseif (preg_match('/\\\\\{(\w+\.\w+)\\\\\}|\{\{(\w+\.\w+)\}\}/', $token, $matches)) {
706 // we are an escaped token
707 // so remove the escape chars
708 $unescaped_token = preg_replace('/\{\{|\}\}|\\\\\{|\\\\\}/', '', $matches[0]);
709 $funcStruct['token'] = '{' . $unescaped_token . '}';
716 * Prepares the text and html templates
717 * for generating the emails and returns a copy of the
720 private function getPreparedTemplates() {
721 if (!$this->preparedTemplates
) {
722 $patterns['html'] = $this->getPatterns(TRUE);
723 $patterns['subject'] = $patterns['text'] = $this->getPatterns();
724 $templates = $this->getTemplates();
726 $this->preparedTemplates
= array();
733 if (!isset($templates[$key])) {
739 $split_template = array();
741 $email = $templates[$key];
742 preg_match_all($patterns[$key], $email, $matches, PREG_PATTERN_ORDER
);
743 foreach ($matches[0] as $idx => $token) {
744 $preg_token = '/' . preg_quote($token, '/') . '/im';
745 list($split_template[], $email) = preg_split($preg_token, $email, 2);
746 array_push($tokens, $this->getDataFunc($token));
749 $split_template[] = $email;
751 $this->preparedTemplates
[$key]['template'] = $split_template;
752 $this->preparedTemplates
[$key]['tokens'] = $tokens;
755 return ($this->preparedTemplates
);
759 * Retrieve a ref to an array that holds the email and text templates for this email
760 * assembles the complete template including the header and footer
761 * that the user has uploaded or declared (if they have done that)
764 * reference to an assoc array
766 public function getTemplates() {
767 if (!$this->templates
) {
768 $this->getHeaderFooter();
769 $this->templates
= array();
770 if ($this->body_text ||
!empty($this->header
)) {
772 if (!empty($this->header
->body_text
)) {
773 $template[] = $this->header
->body_text
;
775 elseif (!empty($this->header
->body_html
)) {
776 $template[] = CRM_Utils_String
::htmlToText($this->header
->body_html
);
779 if ($this->body_text
) {
780 $template[] = $this->body_text
;
783 $template[] = CRM_Utils_String
::htmlToText($this->body_html
);
786 if (!empty($this->footer
->body_text
)) {
787 $template[] = $this->footer
->body_text
;
789 elseif (!empty($this->footer
->body_html
)) {
790 $template[] = CRM_Utils_String
::htmlToText($this->footer
->body_html
);
793 $this->templates
['text'] = implode("\n", $template);
796 // To check for an html part strip tags
797 if (trim(strip_tags($this->body_html
))) {
801 $template[] = $this->header
->body_html
;
804 $template[] = $this->body_html
;
807 $template[] = $this->footer
->body_html
;
810 $this->templates
['html'] = implode("\n", $template);
812 // this is where we create a text template from the html template if the text template did not exist
813 // this way we ensure that every recipient will receive an email even if the pref is set to text and the
814 // user uploads an html email only
815 if (empty($this->templates
['text'])) {
816 $this->templates
['text'] = CRM_Utils_String
::htmlToText($this->templates
['html']);
820 if ($this->subject
) {
822 $template[] = $this->subject
;
823 $this->templates
['subject'] = implode("\n", $template);
826 CRM_Utils_Hook
::alterMailContent($this->templates
);
828 return $this->templates
;
833 * Retrieve a ref to an array that holds all of the tokens in the email body
834 * where the keys are the type of token and the values are ordinal arrays
835 * that hold the token names (even repeated tokens) in the order in which
836 * they appear in the body of the email.
838 * note: the real work is done in the _getTokens() function
840 * this function needs to have some sort of a body assigned
841 * either text or html for this to have any meaningful impact
844 * reference to an assoc array
846 public function &getTokens() {
847 if (!$this->tokens
) {
849 $this->tokens
= array('html' => array(), 'text' => array(), 'subject' => array());
851 if ($this->body_html
) {
852 $this->_getTokens('html');
853 if (!$this->body_text
) {
854 // Since the text template was created from html, use the html tokens.
855 // @see CRM_Mailing_BAO_Mailing::getTemplates()
856 $this->tokens
['text'] = $this->tokens
['html'];
860 if ($this->body_text
) {
861 $this->_getTokens('text');
864 if ($this->subject
) {
865 $this->_getTokens('subject');
869 return $this->tokens
;
873 * Returns the token set for all 3 parts as one set. This allows it to be sent to the
874 * hook in one call and standardizes it across other token workflows
877 * reference to an assoc array
879 public function &getFlattenedTokens() {
880 if (!$this->flattenedTokens
) {
881 $tokens = $this->getTokens();
883 $this->flattenedTokens
= CRM_Utils_Token
::flattenTokens($tokens);
886 return $this->flattenedTokens
;
891 * _getTokens parses out all of the tokens that have been
892 * included in the html and text bodies of the email
893 * we get the tokens and then separate them into an
894 * internal structure named tokens that has the same
895 * form as the static tokens property(?) of the CRM_Utils_Token class.
896 * The difference is that there might be repeated token names as we want the
897 * structures to represent the order in which tokens were found from left to right, top to bottom.
900 * @param string $prop name of the property that holds the text that we want to scan for tokens (html, text).
901 * Name of the property that holds the text that we want to scan for tokens (html, text).
905 private function _getTokens($prop) {
906 $templates = $this->getTemplates();
908 $newTokens = CRM_Utils_Token
::getTokens($templates[$prop]);
910 foreach ($newTokens as $type => $names) {
911 if (!isset($this->tokens
[$prop][$type])) {
912 $this->tokens
[$prop][$type] = array();
914 foreach ($names as $key => $name) {
915 $this->tokens
[$prop][$type][] = $name;
921 * Generate an event queue for a test job.
923 * @param array $testParams
924 * Contains form values.
928 public function getTestRecipients($testParams) {
929 if (!empty($testParams['test_group']) && array_key_exists($testParams['test_group'], CRM_Core_PseudoConstant
::group())) {
930 $contacts = civicrm_api('contact', 'get', array(
932 'group' => $testParams['test_group'],
935 'limit' => 100000000000,
940 foreach (array_keys($contacts['values']) as $groupContact) {
942 SELECT civicrm_email.id AS email_id,
943 civicrm_email.is_primary as is_primary,
944 civicrm_email.is_bulkmail as is_bulkmail
946 INNER JOIN civicrm_contact ON civicrm_email.contact_id = civicrm_contact.id
947 WHERE (civicrm_email.is_bulkmail = 1 OR civicrm_email.is_primary = 1)
948 AND civicrm_contact.id = {$groupContact}
949 AND civicrm_contact.do_not_email = 0
950 AND civicrm_contact.is_deceased <> 1
951 AND civicrm_email.on_hold = 0
952 AND civicrm_contact.is_opt_out = 0
953 GROUP BY civicrm_email.id
954 ORDER BY civicrm_email.is_bulkmail DESC
956 $dao = CRM_Core_DAO
::executeQuery($query);
959 'job_id' => $testParams['job_id'],
960 'email_id' => $dao->email_id
,
961 'contact_id' => $groupContact,
963 CRM_Mailing_Event_BAO_Queue
::create($params);
970 * Load this->header and this->footer.
972 private function getHeaderFooter() {
973 if (!$this->header
and $this->header_id
) {
974 $this->header
= new CRM_Mailing_BAO_Component();
975 $this->header
->id
= $this->header_id
;
976 $this->header
->find(TRUE);
977 $this->header
->free();
980 if (!$this->footer
and $this->footer_id
) {
981 $this->footer
= new CRM_Mailing_BAO_Component();
982 $this->footer
->id
= $this->footer_id
;
983 $this->footer
->find(TRUE);
984 $this->footer
->free();
989 * Given and array of headers and a prefix, job ID, event queue ID, and hash,
990 * add a Message-ID header if needed.
992 * i.e. if the global includeMessageId is set and there isn't already a
993 * Message-ID in the array.
994 * The message ID is structured the same way as a verp. However no interpretation
995 * is placed on the values received, so they do not need to follow the verp
998 * @param array $headers
999 * Array of message headers to update, in-out.
1000 * @param string $prefix
1001 * Prefix for the message ID, use same prefixes as verp.
1003 * @param string $job_id
1004 * Job ID component of the generated message ID.
1005 * @param string $event_queue_id
1006 * Event Queue ID component of the generated message ID.
1007 * @param string $hash
1008 * Hash component of the generated message ID.
1012 public static function addMessageIdHeader(&$headers, $prefix, $job_id, $event_queue_id, $hash) {
1013 $config = CRM_Core_Config
::singleton();
1014 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
1015 $emailDomain = CRM_Core_BAO_MailSettings
::defaultDomain();
1016 $includeMessageId = CRM_Core_BAO_MailSettings
::includeMessageId();
1018 $fields[] = 'Message-ID';
1019 // CRM-17754 check if Resent-Message-id is set also if not add it in when re-laying reply email
1020 if ($prefix == 'r') {
1021 $fields[] = 'Resent-Message-ID';
1023 foreach ($fields as $field) {
1024 if ($includeMessageId && (!array_key_exists($field, $headers))) {
1025 $headers[$field] = '<' . implode($config->verpSeparator
,
1027 $localpart . $prefix,
1032 ) . "@{$emailDomain}>";
1039 * Static wrapper for getting verp and urls.
1041 * @param int $job_id
1042 * ID of the Job associated with this message.
1043 * @param int $event_queue_id
1044 * ID of the EventQueue.
1045 * @param string $hash
1046 * Hash of the EventQueue.
1047 * @param string $email
1048 * Destination address.
1051 * (reference) array array ref that hold array refs to the verp info and urls
1053 public static function getVerpAndUrls($job_id, $event_queue_id, $hash, $email) {
1054 // create a skeleton object and set its properties that are required by getVerpAndUrlsAndHeaders()
1055 $config = CRM_Core_Config
::singleton();
1056 $bao = new CRM_Mailing_BAO_Mailing();
1057 $bao->_domain
= CRM_Core_BAO_Domain
::getDomain();
1058 $bao->from_name
= $bao->from_email
= $bao->subject
= '';
1060 // use $bao's instance method to get verp and urls
1061 list($verp, $urls, $_) = $bao->getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email);
1062 return array($verp, $urls);
1066 * Get verp, urls and headers
1068 * @param int $job_id
1069 * ID of the Job associated with this message.
1070 * @param int $event_queue_id
1071 * ID of the EventQueue.
1072 * @param string $hash
1073 * Hash of the EventQueue.
1074 * @param string $email
1075 * Destination address.
1077 * @param bool $isForward
1080 * array ref that hold array refs to the verp info, urls, and headers
1082 public function getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email, $isForward = FALSE) {
1083 $config = CRM_Core_Config
::singleton();
1086 * Inbound VERP keys:
1087 * reply: user replied to mailing
1088 * bounce: email address bounced
1089 * unsubscribe: contact opts out of all target lists for the mailing
1090 * resubscribe: contact opts back into all target lists for the mailing
1091 * optOut: contact unsubscribes from the domain
1094 $verpTokens = array(
1097 'unsubscribe' => 'u',
1098 'resubscribe' => 'e',
1102 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
1103 $emailDomain = CRM_Core_BAO_MailSettings
::defaultDomain();
1104 // 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
1105 if (empty($emailDomain)) {
1106 CRM_Core_Error
::debug_log_message('Error setting verp parameters, defaultDomain is NULL. Did you configure the bounce processing account for this domain?');
1109 foreach ($verpTokens as $key => $value) {
1110 $verp[$key] = implode($config->verpSeparator
,
1112 $localpart . $value,
1117 ) . "@$emailDomain";
1120 //handle should override VERP address.
1121 $skipEncode = FALSE;
1124 self
::overrideVerp($job_id)
1126 $verp['reply'] = "\"{$this->from_name}\" <{$this->from_email}>";
1130 'forward' => CRM_Utils_System
::url('civicrm/mailing/forward',
1131 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1132 TRUE, NULL, TRUE, TRUE
1134 'unsubscribeUrl' => CRM_Utils_System
::url('civicrm/mailing/unsubscribe',
1135 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1136 TRUE, NULL, TRUE, TRUE
1138 'resubscribeUrl' => CRM_Utils_System
::url('civicrm/mailing/resubscribe',
1139 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1140 TRUE, NULL, TRUE, TRUE
1142 'optOutUrl' => CRM_Utils_System
::url('civicrm/mailing/optout',
1143 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1144 TRUE, NULL, TRUE, TRUE
1146 'subscribeUrl' => CRM_Utils_System
::url('civicrm/mailing/subscribe',
1148 TRUE, NULL, TRUE, TRUE
1153 'Reply-To' => $verp['reply'],
1154 'Return-Path' => $verp['bounce'],
1155 'From' => "\"{$this->from_name}\" <{$this->from_email}>",
1156 'Subject' => $this->subject
,
1157 'List-Unsubscribe' => "<mailto:{$verp['unsubscribe']}>",
1159 self
::addMessageIdHeader($headers, 'm', $job_id, $event_queue_id, $hash);
1161 $headers['Subject'] = "[Fwd:{$this->subject}]";
1163 return array(&$verp, &$urls, &$headers);
1167 * Compose a message.
1169 * @param int $job_id
1170 * ID of the Job associated with this message.
1171 * @param int $event_queue_id
1172 * ID of the EventQueue.
1173 * @param string $hash
1174 * Hash of the EventQueue.
1175 * @param string $contactId
1176 * ID of the Contact.
1177 * @param string $email
1178 * Destination address.
1179 * @param string $recipient
1180 * To: of the recipient.
1182 * Is this mailing a test?.
1183 * @param $contactDetails
1184 * @param $attachments
1185 * @param bool $isForward
1186 * Is this mailing compose for forward?.
1187 * @param string $fromEmail
1188 * Email address of who is forwardinf it.
1190 * @param null $replyToEmail
1192 * @return Mail_mime The mail object
1194 public function compose(
1195 $job_id, $event_queue_id, $hash, $contactId,
1196 $email, &$recipient, $test,
1197 $contactDetails, &$attachments, $isForward = FALSE,
1198 $fromEmail = NULL, $replyToEmail = NULL
1200 $config = CRM_Core_Config
::singleton();
1203 if ($this->_domain
== NULL) {
1204 $this->_domain
= CRM_Core_BAO_Domain
::getDomain();
1207 list($verp, $urls, $headers) = $this->getVerpAndUrlsAndHeaders(
1215 //set from email who is forwarding it and not original one.
1217 unset($headers['From']);
1218 $headers['From'] = "<{$fromEmail}>";
1221 if ($replyToEmail && ($fromEmail != $replyToEmail)) {
1222 $headers['Reply-To'] = "{$replyToEmail}";
1225 if ($contactDetails) {
1226 $contact = $contactDetails;
1228 elseif ($contactId === 0) {
1231 CRM_Utils_Hook
::tokenValues($contact, $contactId, $job_id);
1234 $params = array(array('contact_id', '=', $contactId, 0, 0));
1235 list($contact) = CRM_Contact_BAO_Query
::apiQuery($params);
1238 $contact = reset($contact);
1240 if (!$contact ||
is_a($contact, 'CRM_Core_Error')) {
1241 CRM_Core_Error
::debug_log_message(ts('CiviMail will not send email to a non-existent contact: %1',
1242 array(1 => $contactId)
1244 // setting this because function is called by reference
1245 //@todo test not calling function by reference
1250 // also call the hook to get contact details
1251 CRM_Utils_Hook
::tokenValues($contact, $contactId, $job_id);
1254 $pTemplates = $this->getPreparedTemplates();
1257 foreach ($pTemplates as $type => $pTemplate) {
1258 $html = ($type == 'html') ?
TRUE : FALSE;
1259 $pEmails[$type] = array();
1260 $pEmail = &$pEmails[$type];
1261 $template = &$pTemplates[$type]['template'];
1262 $tokens = &$pTemplates[$type]['tokens'];
1264 if (!empty($tokens)) {
1265 foreach ($tokens as $idx => $token) {
1266 $token_data = $this->getTokenData($token, $html, $contact, $verp, $urls, $event_queue_id);
1267 array_push($pEmail, $template[$idx]);
1268 array_push($pEmail, $token_data);
1272 array_push($pEmail, $template[$idx]);
1275 if (isset($template[($idx +
1)])) {
1276 array_push($pEmail, $template[($idx +
1)]);
1281 if (isset($pEmails['html']) && is_array($pEmails['html']) && count($pEmails['html'])) {
1282 $html = &$pEmails['html'];
1286 if (isset($pEmails['text']) && is_array($pEmails['text']) && count($pEmails['text'])) {
1287 $text = &$pEmails['text'];
1290 // push the tracking url on to the html email if necessary
1291 if ($this->open_tracking
&& $html) {
1292 array_push($html, "\n" . '<img src="' . $config->userFrameworkResourceURL
.
1293 "extern/open.php?q=$event_queue_id\" width='1' height='1' alt='' border='0'>"
1297 $message = new Mail_mime("\n");
1299 $useSmarty = defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY ?
TRUE : FALSE;
1301 $smarty = CRM_Core_Smarty
::singleton();
1302 // also add the contact tokens to the template
1303 $smarty->assign_by_ref('contact', $contact);
1306 $mailParams = $headers;
1307 if ($text && ($test ||
$contact['preferred_mail_format'] == 'Text' ||
1308 $contact['preferred_mail_format'] == 'Both' ||
1309 ($contact['preferred_mail_format'] == 'HTML' && !array_key_exists('html', $pEmails))
1312 $textBody = implode('', $text);
1314 $textBody = $smarty->fetch("string:$textBody");
1316 $mailParams['text'] = $textBody;
1319 if ($html && ($test ||
($contact['preferred_mail_format'] == 'HTML' ||
1320 $contact['preferred_mail_format'] == 'Both'
1323 $htmlBody = implode('', $html);
1325 $htmlBody = $smarty->fetch("string:$htmlBody");
1327 $mailParams['html'] = $htmlBody;
1330 if (empty($mailParams['text']) && empty($mailParams['html'])) {
1332 // something went wrong, lets log it and return null (by reference)
1333 CRM_Core_Error
::debug_log_message(ts('CiviMail will not send an empty mail body, Skipping: %1',
1340 $mailParams['attachments'] = $attachments;
1342 $mailParams['Subject'] = CRM_Utils_Array
::value('subject', $pEmails);
1343 if (is_array($mailParams['Subject'])) {
1344 $mailParams['Subject'] = implode('', $mailParams['Subject']);
1347 $mailParams['toName'] = CRM_Utils_Array
::value('display_name',
1350 $mailParams['toEmail'] = $email;
1352 // Add job ID to mailParams for external email delivery service to utilise
1353 $mailParams['job_id'] = $job_id;
1355 CRM_Utils_Hook
::alterMailParams($mailParams, 'civimail');
1357 // CRM-10699 support custom email headers
1358 if (!empty($mailParams['headers'])) {
1359 $headers = array_merge($headers, $mailParams['headers']);
1361 //cycle through mailParams and set headers array
1362 foreach ($mailParams as $paramKey => $paramValue) {
1363 //exclude values not intended for the header
1364 if (!in_array($paramKey, array(
1372 $headers[$paramKey] = $paramValue;
1376 if (!empty($mailParams['text'])) {
1377 $message->setTxtBody($mailParams['text']);
1380 if (!empty($mailParams['html'])) {
1381 $message->setHTMLBody($mailParams['html']);
1384 if (!empty($mailParams['attachments'])) {
1385 foreach ($mailParams['attachments'] as $fileID => $attach) {
1386 $message->addAttachment($attach['fullPath'],
1387 $attach['mime_type'],
1388 $attach['cleanName']
1393 //pickup both params from mail params.
1394 $toName = trim($mailParams['toName']);
1395 $toEmail = trim($mailParams['toEmail']);
1396 if ($toName == $toEmail ||
1397 strpos($toName, '@') !== FALSE
1402 $toName = CRM_Utils_Mail
::formatRFC2822Name($toName);
1405 $headers['To'] = "$toName <$toEmail>";
1407 $headers['Precedence'] = 'bulk';
1408 // Will test in the mail processor if the X-VERP is set in the bounced email.
1409 // (As an option to replace real VERP for those that can't set it up)
1410 $headers['X-CiviMail-Bounce'] = $verp['bounce'];
1413 //token replacement of subject
1414 $headers['Subject'] = $mailParams['Subject'];
1416 CRM_Utils_Mail
::setMimeParams($message);
1417 $headers = $message->headers($headers);
1419 //get formatted recipient
1420 $recipient = $headers['To'];
1422 // make sure we unset a lot of stuff
1435 * Get mailing object and replaces subscribeInvite, domain and mailing tokens.
1437 * @param CRM_Mailing_BAO_Mailing $mailing
1439 public static function tokenReplace(&$mailing) {
1440 $domain = CRM_Core_BAO_Domain
::getDomain();
1442 foreach (array('text', 'html') as $type) {
1443 $tokens = $mailing->getTokens();
1444 if (isset($mailing->templates
[$type])) {
1445 $mailing->templates
[$type] = CRM_Utils_Token
::replaceSubscribeInviteTokens($mailing->templates
[$type]);
1446 $mailing->templates
[$type] = CRM_Utils_Token
::replaceDomainTokens(
1447 $mailing->templates
[$type],
1449 $type == 'html' ?
TRUE : FALSE,
1452 $mailing->templates
[$type] = CRM_Utils_Token
::replaceMailingTokens($mailing->templates
[$type], $mailing, NULL, $tokens[$type]);
1458 * Get data to resolve tokens.
1460 * @param array $token_a
1462 * Whether to encode the token result for use in HTML email
1463 * @param array $contact
1464 * @param string $verp
1465 * @param array $urls
1466 * @param int $event_queue_id
1468 * @return bool|mixed|null|string
1470 private function getTokenData(&$token_a, $html = FALSE, &$contact, &$verp, &$urls, $event_queue_id) {
1471 $type = $token_a['type'];
1472 $token = $token_a['token'];
1475 $useSmarty = defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY ?
TRUE : FALSE;
1477 if ($type == 'embedded_url') {
1478 $embed_data = array();
1479 foreach ($token as $t) {
1480 $embed_data[] = $this->getTokenData($t, $html, $contact, $verp, $urls, $event_queue_id);
1482 $numSlices = count($embed_data);
1484 for ($i = 0; $i < $numSlices; $i++
) {
1485 $url .= "{$token_a['embed_parts'][$i]}{$embed_data[$i]}";
1487 if (isset($token_a['embed_parts'][$numSlices])) {
1488 $url .= $token_a['embed_parts'][$numSlices];
1490 // add trailing quote since we've gobbled it up in a previous regex
1491 // function getPatterns, line 431
1492 if (preg_match('/^href[ ]*=[ ]*\'/', $url)) {
1495 elseif (preg_match('/^href[ ]*=[ ]*\"/', $url)) {
1499 // CRM-20206 Fix ampersand encoding in plain text emails
1501 $data = CRM_Utils_String
::unstupifyUrl($data);
1504 elseif ($type == 'url') {
1505 if ($this->url_tracking
) {
1506 $data = CRM_Mailing_BAO_TrackableURL
::getTrackerURL($token, $this->id
, $event_queue_id);
1507 if (!empty($html)) {
1508 $data = htmlentities($data, ENT_NOQUOTES
);
1515 elseif ($type == 'contact') {
1516 $data = CRM_Utils_Token
::getContactTokenReplacement($token, $contact, FALSE, FALSE, $useSmarty);
1518 elseif ($type == 'action') {
1519 $data = CRM_Utils_Token
::getActionTokenReplacement($token, $verp, $urls, $html);
1521 elseif ($type == 'domain') {
1522 $domain = CRM_Core_BAO_Domain
::getDomain();
1523 $data = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain, $html);
1525 elseif ($type == 'mailing') {
1526 if ($token == 'name') {
1527 $data = $this->name
;
1529 elseif ($token == 'group') {
1530 $groups = $this->getGroupNames();
1531 $data = implode(', ', $groups);
1535 $data = CRM_Utils_Array
::value("{$type}.{$token}", $contact);
1541 * Return a list of group names for this mailing. Does not work with
1542 * prior-mailing targets.
1545 * Names of groups receiving this mailing
1547 public function &getGroupNames() {
1548 if (!isset($this->id
)) {
1551 $mg = new CRM_Mailing_DAO_MailingGroup();
1552 $mgtable = CRM_Mailing_DAO_MailingGroup
::getTableName();
1553 $group = CRM_Contact_BAO_Group
::getTableName();
1555 $mg->query("SELECT $group.title as name FROM $mgtable
1556 INNER JOIN $group ON $mgtable.entity_id = $group.id
1557 WHERE $mgtable.mailing_id = {$this->id}
1558 AND $mgtable.entity_table = '$group'
1559 AND $mgtable.group_type = 'Include'
1560 ORDER BY $group.name");
1563 while ($mg->fetch()) {
1564 $groups[] = $mg->name
;
1573 * @param array $params
1574 * Reference array contains the values submitted by the form.
1576 * Reference array contains the id.
1579 * @return CRM_Mailing_DAO_Mailing
1581 public static function add(&$params, $ids = array()) {
1582 $id = CRM_Utils_Array
::value('mailing_id', $ids, CRM_Utils_Array
::value('id', $params));
1585 CRM_Utils_Hook
::pre('edit', 'Mailing', $id, $params);
1588 CRM_Utils_Hook
::pre('create', 'Mailing', NULL, $params);
1591 $mailing = new static();
1594 $mailing->find(TRUE);
1596 $mailing->domain_id
= CRM_Utils_Array
::value('domain_id', $params, CRM_Core_Config
::domainID());
1598 if (!isset($params['replyto_email']) &&
1599 isset($params['from_email'])
1601 $params['replyto_email'] = $params['from_email'];
1603 $mailing->copyValues($params);
1605 // CRM-20892 Unset Modifed Date here so that MySQL can correctly set an updated modfied date.
1606 unset($mailing->modified_date
);
1607 $result = $mailing->save();
1609 // CRM-20892 Re find record after saing so we can set the updated modified date in the result.
1610 $mailing->find(TRUE);
1612 if (isset($mailing->modified_date
)) {
1613 $result->modified_date
= $mailing->modified_date
;
1616 if (!empty($ids['mailing'])) {
1617 CRM_Utils_Hook
::post('edit', 'Mailing', $mailing->id
, $mailing);
1620 CRM_Utils_Hook
::post('create', 'Mailing', $mailing->id
, $mailing);
1627 * Construct a new mailing object, along with job and mailing_group
1628 * objects, from the form values of the create mailing wizard.
1630 * This function is a bit evil. It not only merges $params and saves
1631 * the mailing -- it also schedules the mailing and chooses the recipients.
1632 * Since it merges $params, it's also the only place to correctly trigger
1633 * multi-field validation. It should be broken up.
1635 * In the mean time, use-cases which break under the weight of this
1636 * evil may find reprieve in these extra evil params:
1638 * - _skip_evil_bao_auto_recipients_: bool
1639 * - _skip_evil_bao_auto_schedule_: bool
1640 * - _evil_bao_validator_: string|callable
1642 * </twowrongsmakesaright>
1644 * @params array $params
1647 * @param array $params
1651 * $mailing The new mailing object
1652 * @throws \Exception
1654 public static function create(&$params, $ids = array()) {
1656 if (empty($ids) && isset($params['id'])) {
1657 $ids['mailing_id'] = $ids['id'] = $params['id'];
1661 // Do the below only for an insert
1662 // for an update, we should not set the defaults
1663 if (!isset($ids['id']) && !isset($ids['mailing_id'])) {
1664 // Retrieve domain email and name for default sender
1665 $domain = civicrm_api(
1670 'current_domain' => 1,
1674 if (isset($domain['from_email'])) {
1675 $domain_email = $domain['from_email'];
1676 $domain_name = $domain['from_name'];
1679 $domain_email = 'info@EXAMPLE.ORG';
1680 $domain_name = 'EXAMPLE.ORG';
1682 if (!isset($params['created_id'])) {
1683 $session =& CRM_Core_Session
::singleton();
1684 $params['created_id'] = $session->get('userID');
1687 // load the default config settings for each
1688 // eg reply_id, unsubscribe_id need to use
1689 // correct template IDs here
1690 'override_verp' => TRUE,
1691 'forward_replies' => FALSE,
1692 'open_tracking' => TRUE,
1693 'url_tracking' => TRUE,
1694 'visibility' => 'Public Pages',
1695 'replyto_email' => $domain_email,
1696 'header_id' => CRM_Mailing_PseudoConstant
::defaultComponent('header_id', ''),
1697 'footer_id' => CRM_Mailing_PseudoConstant
::defaultComponent('footer_id', ''),
1698 'from_email' => $domain_email,
1699 'from_name' => $domain_name,
1700 'msg_template_id' => NULL,
1701 'created_id' => $params['created_id'],
1702 'approver_id' => NULL,
1703 'auto_responder' => 0,
1704 'created_date' => date('YmdHis'),
1705 'scheduled_date' => NULL,
1706 'approval_date' => NULL,
1709 // Get the default from email address, if not provided.
1710 if (empty($defaults['from_email'])) {
1711 $defaultAddress = CRM_Core_OptionGroup
::values('from_email_address', NULL, NULL, NULL, ' AND is_default = 1');
1712 foreach ($defaultAddress as $id => $value) {
1713 if (preg_match('/"(.*)" <(.*)>/', $value, $match)) {
1714 $defaults['from_email'] = $match[2];
1715 $defaults['from_name'] = $match[1];
1720 $params = array_merge($defaults, $params);
1724 * Could check and warn for the following cases:
1726 * - groups OR mailings should be populated.
1727 * - body html OR body text should be populated.
1730 $transaction = new CRM_Core_Transaction();
1732 $mailing = self
::add($params, $ids);
1734 if (is_a($mailing, 'CRM_Core_Error')) {
1735 $transaction->rollback();
1738 // update mailings with hash values
1739 CRM_Contact_BAO_Contact_Utils
::generateChecksum($mailing->id
, NULL, NULL, NULL, 'mailing', 16);
1741 $groupTableName = CRM_Contact_BAO_Group
::getTableName();
1742 $mailingTableName = CRM_Mailing_BAO_Mailing
::getTableName();
1744 /* Create the mailing group record */
1745 $mg = new CRM_Mailing_DAO_MailingGroup();
1746 $groupTypes = array('include' => 'Include', 'exclude' => 'Exclude', 'base' => 'Base');
1747 foreach (array('groups', 'mailings') as $entity) {
1748 foreach (array('include', 'exclude', 'base') as $type) {
1749 if (isset($params[$entity][$type])) {
1750 self
::replaceGroups($mailing->id
, $groupTypes[$type], $entity, $params[$entity][$type]);
1755 if (!empty($params['search_id']) && !empty($params['group_id'])) {
1757 $mg->mailing_id
= $mailing->id
;
1758 $mg->entity_table
= $groupTableName;
1759 $mg->entity_id
= $params['group_id'];
1760 $mg->search_id
= $params['search_id'];
1761 $mg->search_args
= $params['search_args'];
1762 $mg->group_type
= 'Include';
1766 // check and attach and files as needed
1767 CRM_Core_BAO_File
::processAttachment($params, 'civicrm_mailing', $mailing->id
);
1769 // If we're going to autosend, then check validity before saving.
1770 if (!empty($params['scheduled_date']) && $params['scheduled_date'] != 'null' && !empty($params['_evil_bao_validator_'])) {
1771 $cb = Civi\Core\Resolver
::singleton()->get($params['_evil_bao_validator_']);
1772 $errors = call_user_func($cb, $mailing);
1773 if (!empty($errors)) {
1774 $fields = implode(',', array_keys($errors));
1775 throw new CRM_Core_Exception("Mailing cannot be sent. There are missing or invalid fields ($fields).", 'cannot-send', $errors);
1779 $transaction->commit();
1781 // Create parent job if not yet created.
1782 // Condition on the existence of a scheduled date.
1783 if (!empty($params['scheduled_date']) && $params['scheduled_date'] != 'null' && empty($params['_skip_evil_bao_auto_schedule_'])) {
1784 $job = new CRM_Mailing_BAO_MailingJob();
1785 $job->mailing_id
= $mailing->id
;
1786 $job->status
= 'Scheduled';
1789 if (!$job->find(TRUE)) {
1790 // Don't schedule job until we populate the recipients.
1791 $job->scheduled_date
= NULL;
1795 // Populate the recipients.
1796 if (empty($params['_skip_evil_bao_auto_recipients_'])) {
1797 // check if it's sms
1798 $mode = $mailing->sms_provider_id
&& $mailing->sms_provider_id
!= 'null' ?
'sms' : NULL;
1799 self
::getRecipients($job->id
, $mailing->id
, TRUE, $mailing->dedupe_email
, $mode);
1801 // Schedule the job now that it has recipients.
1802 $job->scheduled_date
= $params['scheduled_date'];
1810 * @param CRM_Mailing_DAO_Mailing $mailing
1811 * The mailing which may or may not be sendable.
1813 * List of error messages.
1815 public static function checkSendable($mailing) {
1817 foreach (array('subject', 'name', 'from_name', 'from_email') as $field) {
1818 if (empty($mailing->{$field})) {
1819 $errors[$field] = ts('Field "%1" is required.', array(
1824 if (empty($mailing->body_html
) && empty($mailing->body_text
)) {
1825 $errors['body'] = ts('Field "body_html" or "body_text" is required.');
1828 if (!Civi
::settings()->get('disable_mandatory_tokens_check')) {
1829 $header = $mailing->header_id
&& $mailing->header_id
!= 'null' ? CRM_Mailing_BAO_Component
::findById($mailing->header_id
) : NULL;
1830 $footer = $mailing->footer_id
&& $mailing->footer_id
!= 'null' ? CRM_Mailing_BAO_Component
::findById($mailing->footer_id
) : NULL;
1831 foreach (array('body_html', 'body_text') as $field) {
1832 if (empty($mailing->{$field})) {
1835 $str = ($header ?
$header->{$field} : '') . $mailing->{$field} . ($footer ?
$footer->{$field} : '');
1836 $err = CRM_Utils_Token
::requiredTokens($str);
1837 if ($err !== TRUE) {
1838 foreach ($err as $token => $desc) {
1839 $errors["{$field}:{$token}"] = ts('This message is missing a required token - {%1}: %2',
1840 array(1 => $token, 2 => $desc)
1851 * Replace the list of recipients on a given mailing.
1853 * @param int $mailingId
1854 * @param string $type
1855 * 'include' or 'exclude'.
1856 * @param string $entity
1857 * 'groups' or 'mailings'.
1858 * @param array <int> $entityIds
1859 * @throws CiviCRM_API3_Exception
1861 public static function replaceGroups($mailingId, $type, $entity, $entityIds) {
1863 foreach ($entityIds as $entityId) {
1864 $values[] = array('entity_id' => $entityId);
1866 civicrm_api3('mailing_group', 'replace', array(
1867 'mailing_id' => $mailingId,
1868 'group_type' => $type,
1869 'entity_table' => ($entity == 'groups') ? CRM_Contact_BAO_Group
::getTableName() : CRM_Mailing_BAO_Mailing
::getTableName(),
1870 'values' => $values,
1875 * Get hash value of the mailing.
1879 * @return null|string
1881 public static function getMailingHash($id) {
1883 if (Civi
::settings()->get('hash_mailing_url')) {
1884 $hash = CRM_Core_DAO
::getFieldValue('CRM_Mailing_BAO_Mailing', $id, 'hash', 'id');
1890 * Generate a report. Fetch event count information, mailing data, and job
1894 * The mailing id to report.
1895 * @param bool $skipDetails
1896 * Whether return all detailed report.
1898 * @param bool $isSMS
1901 * Associative array of reporting data
1903 public static function &report($id, $skipDetails = FALSE, $isSMS = FALSE) {
1904 $mailing_id = CRM_Utils_Type
::escape($id, 'Integer');
1906 $mailing = new CRM_Mailing_BAO_Mailing();
1909 'mailing' => self
::getTableName(),
1910 'mailing_group' => CRM_Mailing_DAO_MailingGroup
::getTableName(),
1911 'group' => CRM_Contact_BAO_Group
::getTableName(),
1912 'job' => CRM_Mailing_BAO_MailingJob
::getTableName(),
1913 'queue' => CRM_Mailing_Event_BAO_Queue
::getTableName(),
1914 'delivered' => CRM_Mailing_Event_BAO_Delivered
::getTableName(),
1915 'opened' => CRM_Mailing_Event_BAO_Opened
::getTableName(),
1916 'reply' => CRM_Mailing_Event_BAO_Reply
::getTableName(),
1917 'unsubscribe' => CRM_Mailing_Event_BAO_Unsubscribe
::getTableName(),
1918 'bounce' => CRM_Mailing_Event_BAO_Bounce
::getTableName(),
1919 'forward' => CRM_Mailing_Event_BAO_Forward
::getTableName(),
1920 'url' => CRM_Mailing_BAO_TrackableURL
::getTableName(),
1921 'urlopen' => CRM_Mailing_Event_BAO_TrackableURLOpen
::getTableName(),
1922 'component' => CRM_Mailing_BAO_Component
::getTableName(),
1923 'spool' => CRM_Mailing_BAO_Spool
::getTableName(),
1927 $additionalWhereClause = " AND ";
1929 $additionalWhereClause .= " {$t['mailing']}.sms_provider_id IS NULL ";
1932 $additionalWhereClause .= " {$t['mailing']}.sms_provider_id IS NOT NULL ";
1935 /* Get the mailing info */
1938 SELECT {$t['mailing']}.*
1939 FROM {$t['mailing']}
1940 WHERE {$t['mailing']}.id = $mailing_id {$additionalWhereClause}");
1944 $report['mailing'] = array();
1945 foreach (array_keys(self
::fields()) as $field) {
1946 $report['mailing'][$field] = $mailing->$field;
1950 if ($campaignId = CRM_Utils_Array
::value('campaign_id', $report['mailing'])) {
1951 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1952 $report['mailing']['campaign'] = $campaigns[$campaignId];
1955 //mailing report is called by activity
1956 //we dont need all detail report
1961 /* Get the component info */
1965 $components = array(
1966 'header' => ts('Header'),
1967 'footer' => ts('Footer'),
1968 'reply' => ts('Reply'),
1969 'optout' => ts('Opt-Out'),
1970 'resubscribe' => ts('Resubscribe'),
1971 'unsubscribe' => ts('Unsubscribe'),
1973 foreach (array_keys($components) as $type) {
1974 $query[] = "SELECT {$t['component']}.name as name,
1976 {$t['component']}.id as id
1977 FROM {$t['component']}
1978 INNER JOIN {$t['mailing']}
1979 ON {$t['mailing']}.{$type}_id =
1980 {$t['component']}.id
1981 WHERE {$t['mailing']}.id = $mailing_id";
1983 $q = '(' . implode(') UNION (', $query) . ')';
1984 $mailing->query($q);
1986 $report['component'] = array();
1987 while ($mailing->fetch()) {
1988 $report['component'][] = array(
1989 'type' => $components[$mailing->type
],
1990 'name' => $mailing->name
,
1991 'link' => CRM_Utils_System
::url('civicrm/mailing/component',
1992 "reset=1&action=update&id={$mailing->id}"
1997 /* Get the recipient group info */
2000 SELECT {$t['mailing_group']}.group_type as group_type,
2001 {$t['group']}.id as group_id,
2002 {$t['group']}.title as group_title,
2003 {$t['group']}.is_hidden as group_hidden,
2004 {$t['mailing']}.id as mailing_id,
2005 {$t['mailing']}.name as mailing_name
2006 FROM {$t['mailing_group']}
2007 LEFT JOIN {$t['group']}
2008 ON {$t['mailing_group']}.entity_id = {$t['group']}.id
2009 AND {$t['mailing_group']}.entity_table =
2011 LEFT JOIN {$t['mailing']}
2012 ON {$t['mailing_group']}.entity_id =
2014 AND {$t['mailing_group']}.entity_table =
2017 WHERE {$t['mailing_group']}.mailing_id = $mailing_id
2020 $report['group'] = array('include' => array(), 'exclude' => array(), 'base' => array());
2021 while ($mailing->fetch()) {
2023 if (isset($mailing->group_id
)) {
2024 $row['id'] = $mailing->group_id
;
2025 $row['name'] = $mailing->group_title
;
2026 $row['link'] = CRM_Utils_System
::url('civicrm/group/search',
2027 "reset=1&force=1&context=smog&gid={$row['id']}"
2031 $row['id'] = $mailing->mailing_id
;
2032 $row['name'] = $mailing->mailing_name
;
2033 $row['mailing'] = TRUE;
2034 $row['link'] = CRM_Utils_System
::url('civicrm/mailing/report',
2039 /* Rename hidden groups */
2041 if ($mailing->group_hidden
== 1) {
2042 $row['name'] = "Search Results";
2045 if ($mailing->group_type
== 'Include') {
2046 $report['group']['include'][] = $row;
2048 elseif ($mailing->group_type
== 'Base') {
2049 $report['group']['base'][] = $row;
2052 $report['group']['exclude'][] = $row;
2056 /* Get the event totals, grouped by job (retries) */
2059 SELECT {$t['job']}.*,
2060 COUNT(DISTINCT {$t['queue']}.id) as queue,
2061 COUNT(DISTINCT {$t['delivered']}.id) as delivered,
2062 COUNT(DISTINCT {$t['reply']}.id) as reply,
2063 COUNT(DISTINCT {$t['forward']}.id) as forward,
2064 COUNT(DISTINCT {$t['bounce']}.id) as bounce,
2065 COUNT(DISTINCT {$t['urlopen']}.id) as url,
2066 COUNT(DISTINCT {$t['spool']}.id) as spool
2068 LEFT JOIN {$t['queue']}
2069 ON {$t['queue']}.job_id = {$t['job']}.id
2070 LEFT JOIN {$t['reply']}
2071 ON {$t['reply']}.event_queue_id = {$t['queue']}.id
2072 LEFT JOIN {$t['forward']}
2073 ON {$t['forward']}.event_queue_id = {$t['queue']}.id
2074 LEFT JOIN {$t['bounce']}
2075 ON {$t['bounce']}.event_queue_id = {$t['queue']}.id
2076 LEFT JOIN {$t['delivered']}
2077 ON {$t['delivered']}.event_queue_id = {$t['queue']}.id
2078 AND {$t['bounce']}.id IS null
2079 LEFT JOIN {$t['urlopen']}
2080 ON {$t['urlopen']}.event_queue_id = {$t['queue']}.id
2081 LEFT JOIN {$t['spool']}
2082 ON {$t['spool']}.job_id = {$t['job']}.id
2083 WHERE {$t['job']}.mailing_id = $mailing_id
2084 AND {$t['job']}.is_test = 0
2085 GROUP BY {$t['job']}.id");
2087 $report['jobs'] = array();
2088 $report['event_totals'] = array();
2103 // initialize various counters
2104 foreach ($elements as $field) {
2105 $report['event_totals'][$field] = 0;
2108 while ($mailing->fetch()) {
2110 foreach ($elements as $field) {
2111 if (isset($mailing->$field)) {
2112 $row[$field] = $mailing->$field;
2113 $report['event_totals'][$field] +
= $mailing->$field;
2117 // compute open total separately to discount duplicates
2119 $row['opened'] = CRM_Mailing_Event_BAO_Opened
::getTotalCount($mailing_id, $mailing->id
, TRUE);
2120 $report['event_totals']['opened'] +
= $row['opened'];
2121 $row['total_opened'] = CRM_Mailing_Event_BAO_Opened
::getTotalCount($mailing_id, $mailing->id
);
2122 $report['event_totals']['total_opened'] +
= $row['total_opened'];
2124 // compute unsub total separately to discount duplicates
2126 $row['unsubscribe'] = CRM_Mailing_Event_BAO_Unsubscribe
::getTotalCount($mailing_id, $mailing->id
, TRUE, TRUE);
2127 $report['event_totals']['unsubscribe'] +
= $row['unsubscribe'];
2129 $row['optout'] = CRM_Mailing_Event_BAO_Unsubscribe
::getTotalCount($mailing_id, $mailing->id
, TRUE, FALSE);
2130 $report['event_totals']['optout'] +
= $row['optout'];
2132 foreach (array_keys(CRM_Mailing_BAO_MailingJob
::fields()) as $field) {
2133 $row[$field] = $mailing->$field;
2136 if ($mailing->queue
) {
2137 $row['delivered_rate'] = (100.0 * $mailing->delivered
) / $mailing->queue
;
2138 $row['bounce_rate'] = (100.0 * $mailing->bounce
) / $mailing->queue
;
2139 $row['unsubscribe_rate'] = (100.0 * $row['unsubscribe']) / $mailing->queue
;
2140 $row['optout_rate'] = (100.0 * $row['optout']) / $mailing->queue
;
2143 $row['delivered_rate'] = 0;
2144 $row['bounce_rate'] = 0;
2145 $row['unsubscribe_rate'] = 0;
2146 $row['optout_rate'] = 0;
2149 $row['links'] = array(
2150 'clicks' => CRM_Utils_System
::url(
2151 'civicrm/mailing/report/event',
2152 "reset=1&event=click&mid=$mailing_id&jid={$mailing->id}"
2154 'queue' => CRM_Utils_System
::url(
2155 'civicrm/mailing/report/event',
2156 "reset=1&event=queue&mid=$mailing_id&jid={$mailing->id}"
2158 'delivered' => CRM_Utils_System
::url(
2159 'civicrm/mailing/report/event',
2160 "reset=1&event=delivered&mid=$mailing_id&jid={$mailing->id}"
2162 'bounce' => CRM_Utils_System
::url(
2163 'civicrm/mailing/report/event',
2164 "reset=1&event=bounce&mid=$mailing_id&jid={$mailing->id}"
2166 'unsubscribe' => CRM_Utils_System
::url(
2167 'civicrm/mailing/report/event',
2168 "reset=1&event=unsubscribe&mid=$mailing_id&jid={$mailing->id}"
2170 'forward' => CRM_Utils_System
::url(
2171 'civicrm/mailing/report/event',
2172 "reset=1&event=forward&mid=$mailing_id&jid={$mailing->id}"
2174 'reply' => CRM_Utils_System
::url(
2175 'civicrm/mailing/report/event',
2176 "reset=1&event=reply&mid=$mailing_id&jid={$mailing->id}"
2178 'opened' => CRM_Utils_System
::url(
2179 'civicrm/mailing/report/event',
2180 "reset=1&event=opened&mid=$mailing_id&jid={$mailing->id}"
2189 $row[$key] = CRM_Utils_Date
::customFormat($row[$key]);
2191 $report['jobs'][] = $row;
2194 $newTableSize = CRM_Mailing_BAO_Recipients
::mailingSize($mailing_id);
2196 // we need to do this for backward compatibility, since old mailings did not
2197 // use the mailing_recipients table
2198 if ($newTableSize > 0) {
2199 $report['event_totals']['queue'] = $newTableSize;
2202 $report['event_totals']['queue'] = self
::getRecipientsCount($mailing_id, $mailing_id);
2205 if (!empty($report['event_totals']['queue'])) {
2206 $report['event_totals']['delivered_rate'] = (100.0 * $report['event_totals']['delivered']) / $report['event_totals']['queue'];
2207 $report['event_totals']['bounce_rate'] = (100.0 * $report['event_totals']['bounce']) / $report['event_totals']['queue'];
2208 $report['event_totals']['unsubscribe_rate'] = (100.0 * $report['event_totals']['unsubscribe']) / $report['event_totals']['queue'];
2209 $report['event_totals']['optout_rate'] = (100.0 * $report['event_totals']['optout']) / $report['event_totals']['queue'];
2212 $report['event_totals']['delivered_rate'] = 0;
2213 $report['event_totals']['bounce_rate'] = 0;
2214 $report['event_totals']['unsubscribe_rate'] = 0;
2215 $report['event_totals']['optout_rate'] = 0;
2218 /* Get the click-through totals, grouped by URL */
2221 SELECT {$t['url']}.url,
2223 COUNT({$t['urlopen']}.id) as clicks,
2224 COUNT(DISTINCT {$t['queue']}.id) as unique_clicks
2226 LEFT JOIN {$t['urlopen']}
2227 ON {$t['urlopen']}.trackable_url_id = {$t['url']}.id
2228 LEFT JOIN {$t['queue']}
2229 ON {$t['urlopen']}.event_queue_id = {$t['queue']}.id
2230 LEFT JOIN {$t['job']}
2231 ON {$t['queue']}.job_id = {$t['job']}.id
2232 WHERE {$t['url']}.mailing_id = $mailing_id
2233 AND {$t['job']}.is_test = 0
2234 GROUP BY {$t['url']}.id");
2236 $report['click_through'] = array();
2238 while ($mailing->fetch()) {
2239 $report['click_through'][] = array(
2240 'url' => $mailing->url
,
2241 'link' => CRM_Utils_System
::url(
2242 'civicrm/mailing/report/event',
2243 "reset=1&event=click&mid=$mailing_id&uid={$mailing->id}"
2245 'link_unique' => CRM_Utils_System
::url(
2246 'civicrm/mailing/report/event',
2247 "reset=1&event=click&mid=$mailing_id&uid={$mailing->id}&distinct=1"
2249 'clicks' => $mailing->clicks
,
2250 'unique' => $mailing->unique_clicks
,
2251 'rate' => CRM_Utils_Array
::value('delivered', $report['event_totals']) ?
(100.0 * $mailing->unique_clicks
) / $report['event_totals']['delivered'] : 0,
2252 'report' => CRM_Report_Utils_Report
::getNextUrl('mailing/clicks', "reset=1&mailing_id_value={$mailing_id}&url_value={$mailing->url}", FALSE, TRUE),
2256 $report['event_totals']['links'] = array(
2257 'clicks' => CRM_Utils_System
::url(
2258 'civicrm/mailing/report/event',
2259 "reset=1&event=click&mid=$mailing_id"
2261 'clicks_unique' => CRM_Utils_System
::url(
2262 'civicrm/mailing/report/event',
2263 "reset=1&event=click&mid=$mailing_id&distinct=1"
2265 'queue' => CRM_Utils_System
::url(
2266 'civicrm/mailing/report/event',
2267 "reset=1&event=queue&mid=$mailing_id"
2269 'delivered' => CRM_Utils_System
::url(
2270 'civicrm/mailing/report/event',
2271 "reset=1&event=delivered&mid=$mailing_id"
2273 'bounce' => CRM_Utils_System
::url(
2274 'civicrm/mailing/report/event',
2275 "reset=1&event=bounce&mid=$mailing_id"
2277 'unsubscribe' => CRM_Utils_System
::url(
2278 'civicrm/mailing/report/event',
2279 "reset=1&event=unsubscribe&mid=$mailing_id"
2281 'optout' => CRM_Utils_System
::url(
2282 'civicrm/mailing/report/event',
2283 "reset=1&event=optout&mid=$mailing_id"
2285 'forward' => CRM_Utils_System
::url(
2286 'civicrm/mailing/report/event',
2287 "reset=1&event=forward&mid=$mailing_id"
2289 'reply' => CRM_Utils_System
::url(
2290 'civicrm/mailing/report/event',
2291 "reset=1&event=reply&mid=$mailing_id"
2293 'opened' => CRM_Utils_System
::url(
2294 'civicrm/mailing/report/event',
2295 "reset=1&event=opened&mid=$mailing_id"
2299 $actionLinks = array(CRM_Core_Action
::VIEW
=> array('name' => ts('Report')));
2300 if (CRM_Core_Permission
::check('view all contacts')) {
2301 $actionLinks[CRM_Core_Action
::ADVANCED
] = array(
2302 'name' => ts('Advanced Search'),
2303 'url' => 'civicrm/contact/search/advanced',
2306 $action = array_sum(array_keys($actionLinks));
2308 $report['event_totals']['actionlinks'] = array();
2321 $url = 'mailing/detail';
2322 $reportFilter = "reset=1&mailing_id_value={$mailing_id}";
2323 $searchFilter = "force=1&mailing_id=%%mid%%";
2326 $reportFilter .= "&delivery_status_value=successful";
2327 $searchFilter .= "&mailing_delivery_status=Y";
2331 $url = "mailing/bounce";
2332 $searchFilter .= "&mailing_delivery_status=N";
2336 $reportFilter .= "&is_forwarded_value=1";
2337 $searchFilter .= "&mailing_forward=1";
2341 $reportFilter .= "&is_replied_value=1";
2342 $searchFilter .= "&mailing_reply_status=Y";
2346 $reportFilter .= "&is_unsubscribed_value=1";
2347 $searchFilter .= "&mailing_unsubscribe=1";
2351 $reportFilter .= "&is_optout_value=1";
2352 $searchFilter .= "&mailing_optout=1";
2356 $url = "mailing/opened";
2357 $searchFilter .= "&mailing_open_status=Y";
2361 case 'clicks_unique':
2362 $url = "mailing/clicks";
2363 $searchFilter .= "&mailing_click_status=Y";
2366 $actionLinks[CRM_Core_Action
::VIEW
]['url'] = CRM_Report_Utils_Report
::getNextUrl($url, $reportFilter, FALSE, TRUE);
2367 if (array_key_exists(CRM_Core_Action
::ADVANCED
, $actionLinks)) {
2368 $actionLinks[CRM_Core_Action
::ADVANCED
]['qs'] = $searchFilter;
2370 $report['event_totals']['actionlinks'][$key] = CRM_Core_Action
::formLink(
2373 array('mid' => $mailing_id),
2376 'mailing.report.action',
2386 * Get the count of mailings.
2393 public function getCount() {
2395 $this->selectAdd('COUNT(id) as count');
2397 $session = CRM_Core_Session
::singleton();
2400 return $this->count
;
2408 public static function checkPermission($id) {
2413 $mailingIDs = self
::mailingACLIDs();
2414 if ($mailingIDs === TRUE) {
2418 if (!in_array($id, $mailingIDs)) {
2419 CRM_Core_Error
::fatal(ts('You do not have permission to access this mailing report'));
2424 * @param null $alias
2428 public static function mailingACL($alias = NULL) {
2429 $mailingACL = " ( 0 ) ";
2431 $mailingIDs = self
::mailingACLIDs();
2432 if ($mailingIDs === TRUE) {
2436 if (!empty($mailingIDs)) {
2437 $mailingIDs = implode(',', $mailingIDs);
2438 $tableName = !$alias ? self
::getTableName() : $alias;
2439 $mailingACL = " $tableName.id IN ( $mailingIDs ) ";
2445 * Returns all the mailings that this user can access. This is dependent on
2446 * all the groups that the user has access to.
2447 * However since most civi installs dont use ACL's we special case the condition
2448 * where the user has access to ALL groups, and hence ALL mailings and return a
2449 * value of TRUE (to avoid the downstream where clause with a list of mailing list IDs
2451 * @return bool|array
2452 * TRUE if the user has access to all mailings, else array of mailing IDs (possibly empty).
2454 public static function mailingACLIDs() {
2456 // optimize common case where admin has access
2459 CRM_Core_Permission
::check('view all contacts') ||
2460 CRM_Core_Permission
::check('edit all contacts')
2465 $mailingIDs = array();
2467 // get all the groups that this user can access
2468 // if they dont have universal access
2469 $groupNames = civicrm_api3('Group', 'get', array(
2471 'check_permissions' => TRUE,
2472 'return' => array('title', 'id'),
2473 'options' => array('limit' => 0),
2475 foreach ($groupNames['values'] as $group) {
2476 $groups[$group['id']] = $group['title'];
2478 if (!empty($groups)) {
2479 $groupIDs = implode(',', array_keys($groups));
2480 $domain_id = CRM_Core_Config
::domainID();
2482 // get all the mailings that are in this subset of groups
2484 SELECT DISTINCT( m.id ) as id
2485 FROM civicrm_mailing m
2486 LEFT JOIN civicrm_mailing_group g ON g.mailing_id = m.id
2487 WHERE ( ( g.entity_table like 'civicrm_group%' AND g.entity_id IN ( $groupIDs ) )
2488 OR ( g.entity_table IS NULL AND g.entity_id IS NULL AND m.domain_id = $domain_id ) )
2490 $dao = CRM_Core_DAO
::executeQuery($query);
2492 $mailingIDs = array();
2493 while ($dao->fetch()) {
2494 $mailingIDs[] = $dao->id
;
2496 //CRM-18181 Get all mailings that use the mailings found earlier as receipients
2497 if (!empty($mailingIDs)) {
2498 $mailings = implode(',', $mailingIDs);
2500 SELECT DISTINCT ( m.id ) as id
2501 FROM civicrm_mailing m
2502 LEFT JOIN civicrm_mailing_group g ON g.mailing_id = m.id
2503 WHERE g.entity_table like 'civicrm_mailing%' AND g.entity_id IN ($mailings)";
2504 $mailingDao = CRM_Core_DAO
::executeQuery($mailingQuery);
2505 while ($mailingDao->fetch()) {
2506 $mailingIDs[] = $mailingDao->id
;
2515 * Get the rows for a browse operation.
2517 * @param int $offset
2518 * The row number to start from.
2519 * @param int $rowCount
2520 * The nmber of rows to return.
2521 * @param string $sort
2522 * The sql string that describes the sort order.
2524 * @param null $additionalClause
2525 * @param array $additionalParams
2530 public function &getRows($offset, $rowCount, $sort, $additionalClause = NULL, $additionalParams = NULL) {
2531 $mailing = self
::getTableName();
2532 $job = CRM_Mailing_BAO_MailingJob
::getTableName();
2533 $group = CRM_Mailing_DAO_MailingGroup
::getTableName();
2534 $session = CRM_Core_Session
::singleton();
2536 $mailingACL = self
::mailingACL();
2538 //get all campaigns.
2539 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
2541 "$mailing.id", "$mailing.name", "$job.status",
2542 "$mailing.approval_status_id", "createdContact.sort_name as created_by", "scheduledContact.sort_name as scheduled_by",
2543 "$mailing.created_id as created_id", "$mailing.scheduled_id as scheduled_id", "$mailing.is_archived as archived",
2544 "$mailing.created_date as created_date", "campaign_id", "$mailing.sms_provider_id as sms_provider_id",
2545 "$mailing.language",
2548 // we only care about parent jobs, since that holds all the info on
2550 $selectClause = implode(', ', $select);
2551 $groupFromSelect = CRM_Contact_BAO_Query
::getGroupByFromSelectColumns($select, "$mailing.id");
2553 SELECT {$selectClause},
2554 MIN($job.scheduled_date) as scheduled_date,
2555 MIN($job.start_date) as start_date,
2556 MAX($job.end_date) as end_date
2558 LEFT JOIN $job ON ( $job.mailing_id = $mailing.id AND $job.is_test = 0 AND $job.parent_id IS NULL )
2559 LEFT JOIN civicrm_contact createdContact ON ( civicrm_mailing.created_id = createdContact.id )
2560 LEFT JOIN civicrm_contact scheduledContact ON ( civicrm_mailing.scheduled_id = scheduledContact.id )
2561 WHERE $mailingACL $additionalClause";
2563 if (!empty($groupFromSelect)) {
2564 $query .= $groupFromSelect;
2568 $orderBy = trim($sort->orderBy());
2569 if (!empty($orderBy)) {
2570 $query .= " ORDER BY $orderBy";
2575 $offset = CRM_Utils_Type
::escape($offset, 'Int');
2576 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
2578 $query .= " LIMIT $offset, $rowCount ";
2581 if (!$additionalParams) {
2582 $additionalParams = array();
2585 $dao = CRM_Core_DAO
::executeQuery($query, $additionalParams);
2588 while ($dao->fetch()) {
2591 'name' => $dao->name
,
2592 'status' => $dao->status ?
$dao->status
: 'Not scheduled',
2593 'created_date' => CRM_Utils_Date
::customFormat($dao->created_date
),
2594 'scheduled' => CRM_Utils_Date
::customFormat($dao->scheduled_date
),
2595 'scheduled_iso' => $dao->scheduled_date
,
2596 'start' => CRM_Utils_Date
::customFormat($dao->start_date
),
2597 'end' => CRM_Utils_Date
::customFormat($dao->end_date
),
2598 'created_by' => $dao->created_by
,
2599 'scheduled_by' => $dao->scheduled_by
,
2600 'created_id' => $dao->created_id
,
2601 'scheduled_id' => $dao->scheduled_id
,
2602 'archived' => $dao->archived
,
2603 'approval_status_id' => $dao->approval_status_id
,
2604 'campaign_id' => $dao->campaign_id
,
2605 'campaign' => empty($dao->campaign_id
) ?
NULL : $allCampaigns[$dao->campaign_id
],
2606 'sms_provider_id' => $dao->sms_provider_id
,
2607 'language' => $dao->language
,
2614 * Show detail Mailing report.
2620 public static function showEmailDetails($id) {
2621 return CRM_Utils_System
::url('civicrm/mailing/report', "mid=$id");
2625 * Delete Mails and all its associated records.
2628 * Id of the mail to delete.
2632 public static function del($id) {
2634 CRM_Core_Error
::fatal();
2637 CRM_Utils_Hook
::pre('delete', 'Mailing', $id, CRM_Core_DAO
::$_nullArray);
2639 // delete all file attachments
2640 CRM_Core_BAO_File
::deleteEntityFile('civicrm_mailing',
2644 $dao = new CRM_Mailing_DAO_Mailing();
2648 CRM_Core_Session
::setStatus(ts('Selected mailing has been deleted.'), ts('Deleted'), 'success');
2650 CRM_Utils_Hook
::post('delete', 'Mailing', $id, $dao);
2654 * Delete Jobss and all its associated records
2655 * related to test Mailings
2658 * Id of the Job to delete.
2662 public static function delJob($id) {
2664 CRM_Core_Error
::fatal();
2667 $dao = new CRM_Mailing_BAO_MailingJob();
2675 public function getReturnProperties() {
2676 $tokens = &$this->getTokens();
2678 $properties = array();
2679 if (isset($tokens['html']) &&
2680 isset($tokens['html']['contact'])
2682 $properties = array_merge($properties, $tokens['html']['contact']);
2685 if (isset($tokens['text']) &&
2686 isset($tokens['text']['contact'])
2688 $properties = array_merge($properties, $tokens['text']['contact']);
2691 if (isset($tokens['subject']) &&
2692 isset($tokens['subject']['contact'])
2694 $properties = array_merge($properties, $tokens['subject']['contact']);
2697 $returnProperties = array();
2698 $returnProperties['display_name'] = $returnProperties['contact_id'] = $returnProperties['preferred_mail_format'] = $returnProperties['hash'] = 1;
2700 foreach ($properties as $p) {
2701 $returnProperties[$p] = 1;
2704 return $returnProperties;
2708 * Build the compose mail form.
2710 * @param CRM_Core_Form $form
2714 public static function commonCompose(&$form) {
2718 if (method_exists($form, 'listTokens')) {
2719 $tokens = array_merge($form->listTokens(), $tokens);
2722 //sorted in ascending order tokens by ignoring word case
2723 $form->assign('tokens', CRM_Utils_Token
::formatTokensForDisplay($tokens));
2725 $templates = array();
2727 $textFields = array('text_message' => ts('HTML Format'), 'sms_text_message' => ts('SMS Message'));
2728 $modePrefixes = array('Mail' => NULL, 'SMS' => 'SMS');
2730 $className = CRM_Utils_System
::getClassName($form);
2732 if ($className != 'CRM_SMS_Form_Upload' && $className != 'CRM_Contact_Form_Task_SMS' &&
2733 $className != 'CRM_Contact_Form_Task_SMS'
2735 $form->add('wysiwyg', 'html_message',
2736 strstr($className, 'PDF') ?
ts('Document Body') : ts('HTML Format'),
2740 'onkeyup' => "return verify(this)",
2744 if ($className != 'CRM_Admin_Form_ScheduleReminders') {
2745 unset($modePrefixes['SMS']);
2749 unset($textFields['text_message']);
2750 unset($modePrefixes['Mail']);
2753 //insert message Text by selecting "Select Template option"
2754 foreach ($textFields as $id => $label) {
2756 if ($id == 'sms_text_message') {
2758 $form->assign('max_sms_length', CRM_SMS_Provider
::MAX_SMS_CHAR
);
2760 $form->add('textarea', $id, $label,
2764 'onkeyup' => "return verify(this, '{$prefix}')",
2769 foreach ($modePrefixes as $prefix) {
2770 if ($prefix == 'SMS') {
2771 $templates[$prefix] = CRM_Core_BAO_MessageTemplate
::getMessageTemplates(FALSE, TRUE);
2774 $templates[$prefix] = CRM_Core_BAO_MessageTemplate
::getMessageTemplates(FALSE);
2776 if (!empty($templates[$prefix])) {
2777 $form->assign('templates', TRUE);
2779 $form->add('select', "{$prefix}template", ts('Use Template'),
2780 array('' => ts('- select -')) +
$templates[$prefix], FALSE,
2781 array('onChange' => "selectValue( this.value, '{$prefix}');")
2784 $form->add('checkbox', "{$prefix}updateTemplate", ts('Update Template'), NULL);
2786 $form->add('checkbox', "{$prefix}saveTemplate", ts('Save As New Template'), NULL, FALSE,
2787 array('onclick' => "showSaveDetails(this, '{$prefix}');")
2789 $form->add('text', "{$prefix}saveTemplateName", ts('Template Title'));
2792 // I'm not sure this is ever called.
2793 $action = CRM_Utils_Request
::retrieve('action', 'String', $form, FALSE);
2794 if ((CRM_Utils_System
::getClassName($form) == 'CRM_Contact_Form_Task_PDF') &&
2795 $action == CRM_Core_Action
::VIEW
2797 $form->freeze('html_message');
2802 * Get the search based mailing Ids.
2805 * , searched base mailing ids.
2807 public function searchMailingIDs() {
2808 $group = CRM_Mailing_DAO_MailingGroup
::getTableName();
2809 $mailing = self
::getTableName();
2812 SELECT $mailing.id as mailing_id
2813 FROM $mailing, $group
2814 WHERE $group.mailing_id = $mailing.id
2815 AND $group.group_type = 'Base'";
2817 $searchDAO = CRM_Core_DAO
::executeQuery($query);
2818 $mailingIDs = array();
2819 while ($searchDAO->fetch()) {
2820 $mailingIDs[] = $searchDAO->mailing_id
;
2827 * Get the content/components of mailing based on mailing Id
2829 * @param array $report
2830 * of mailing report.
2833 * Reference of this.
2835 * @param bool $isSMS
2838 * array content/component.
2840 public static function getMailingContent(&$report, &$form, $isSMS = FALSE) {
2841 $htmlHeader = $textHeader = NULL;
2842 $htmlFooter = $textFooter = NULL;
2845 if ($report['mailing']['header_id']) {
2846 $header = new CRM_Mailing_BAO_Component();
2847 $header->id
= $report['mailing']['header_id'];
2848 $header->find(TRUE);
2849 $htmlHeader = $header->body_html
;
2850 $textHeader = $header->body_text
;
2853 if ($report['mailing']['footer_id']) {
2854 $footer = new CRM_Mailing_BAO_Component();
2855 $footer->id
= $report['mailing']['footer_id'];
2856 $footer->find(TRUE);
2857 $htmlFooter = $footer->body_html
;
2858 $textFooter = $footer->body_text
;
2862 $mailingKey = $form->_mailing_id
;
2864 if ($hash = CRM_Mailing_BAO_Mailing
::getMailingHash($mailingKey)) {
2865 $mailingKey = $hash;
2869 if (!empty($report['mailing']['body_text'])) {
2870 $url = CRM_Utils_System
::url('civicrm/mailing/view', 'reset=1&text=1&id=' . $mailingKey);
2871 $form->assign('textViewURL', $url);
2875 if (!empty($report['mailing']['body_html'])) {
2876 $url = CRM_Utils_System
::url('civicrm/mailing/view', 'reset=1&id=' . $mailingKey);
2877 $form->assign('htmlViewURL', $url);
2882 $report['mailing']['attachment'] = CRM_Core_BAO_File
::attachmentInfo('civicrm_mailing', $form->_mailing_id
);
2892 public static function overrideVerp($jobID) {
2893 static $_cache = array();
2895 if (!isset($_cache[$jobID])) {
2897 SELECT override_verp
2898 FROM civicrm_mailing
2899 INNER JOIN civicrm_mailing_job ON civicrm_mailing.id = civicrm_mailing_job.mailing_id
2900 WHERE civicrm_mailing_job.id = %1
2902 $params = array(1 => array($jobID, 'Integer'));
2903 $_cache[$jobID] = CRM_Core_DAO
::singleValueQuery($query, $params);
2905 return $_cache[$jobID];
2914 public static function processQueue($mode = NULL) {
2915 $config = CRM_Core_Config
::singleton();
2917 if ($mode == NULL && CRM_Core_BAO_MailSettings
::defaultDomain() == "EXAMPLE.ORG") {
2918 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 user and administrator guide</a>', array(
2919 1 => CRM_Utils_System
::url('civicrm/admin/mailSettings', 'reset=1'),
2920 2 => "http://book.civicrm.org/user/advanced-configuration/email-system-configuration/",
2924 // check if we are enforcing number of parallel cron jobs
2926 $gotCronLock = FALSE;
2928 $mailerJobsMax = Civi
::settings()->get('mailerJobsMax');
2929 if (is_numeric($mailerJobsMax) && $mailerJobsMax > 0) {
2930 $lockArray = range(1, $mailerJobsMax);
2932 // Shuffle the array to improve chances of quickly finding an open thread
2933 shuffle($lockArray);
2935 // Check if we are using global locks
2936 foreach ($lockArray as $lockID) {
2937 $cronLock = Civi
::lockManager()->acquire("worker.mailing.send.{$lockID}");
2938 if ($cronLock->isAcquired()) {
2939 $gotCronLock = TRUE;
2944 // Exit here since we have enough mailing processes running
2945 if (!$gotCronLock) {
2946 CRM_Core_Error
::debug_log_message('Returning early, since the maximum number of mailing processes are running');
2950 if (getenv('CIVICRM_CRON_HOLD')) {
2951 // In testing, we may need to simulate some slow activities.
2952 sleep(getenv('CIVICRM_CRON_HOLD'));
2956 // Split up the parent jobs into multiple child jobs
2957 $mailerJobSize = Civi
::settings()->get('mailerJobSize');
2958 CRM_Mailing_BAO_MailingJob
::runJobs_pre($mailerJobSize, $mode);
2959 CRM_Mailing_BAO_MailingJob
::runJobs(NULL, $mode);
2960 CRM_Mailing_BAO_MailingJob
::runJobs_post($mode);
2962 // Release the global lock if we do have one
2964 $cronLock->release();
2971 * @param int $mailingID
2973 private static function addMultipleEmails($mailingID) {
2975 INSERT INTO civicrm_mailing_recipients
2976 (mailing_id, email_id, contact_id)
2977 SELECT %1, e.id, e.contact_id FROM civicrm_email e
2979 AND e.is_bulkmail = 1
2981 ( SELECT contact_id FROM civicrm_mailing_recipients mr WHERE mailing_id = %1 )
2982 AND e.id NOT IN ( SELECT email_id FROM civicrm_mailing_recipients mr WHERE mailing_id = %1 )
2984 $params = array(1 => array($mailingID, 'Integer'));
2986 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2990 * @param bool $isSMS
2994 public static function getMailingsList($isSMS = FALSE) {
2995 static $list = array();
2998 $where .= " civicrm_mailing.sms_provider_id IS NULL ";
3001 $where .= " civicrm_mailing.sms_provider_id IS NOT NULL ";
3006 SELECT civicrm_mailing.id, civicrm_mailing.name, civicrm_mailing_job.end_date
3007 FROM civicrm_mailing
3008 INNER JOIN civicrm_mailing_job ON civicrm_mailing.id = civicrm_mailing_job.mailing_id {$where}
3009 ORDER BY civicrm_mailing.name";
3010 $mailing = CRM_Core_DAO
::executeQuery($query);
3012 while ($mailing->fetch()) {
3013 $list[$mailing->id
] = "{$mailing->name} :: {$mailing->end_date}";
3023 * @return null|string
3025 public static function hiddenMailingGroup($mid) {
3028 FROM civicrm_mailing m
3029 INNER JOIN civicrm_mailing_group mg ON mg.mailing_id = m.id
3030 INNER JOIN civicrm_group g ON mg.entity_id = g.id AND mg.entity_table = 'civicrm_group'
3031 WHERE g.is_hidden = 1
3032 AND mg.group_type = 'Include'
3035 $params = array(1 => array($mid, 'Integer'));
3036 return CRM_Core_DAO
::singleValueQuery($sql, $params);
3040 * wrapper for ajax activity selector.
3042 * @param array $params
3043 * Associated array for params record id.
3046 * associated array of contact activities
3048 public static function getContactMailingSelector(&$params) {
3049 // format the params
3050 $params['offset'] = ($params['page'] - 1) * $params['rp'];
3051 $params['rowCount'] = $params['rp'];
3052 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
3053 $params['caseId'] = NULL;
3055 // get contact mailings
3056 $mailings = CRM_Mailing_BAO_Mailing
::getContactMailings($params);
3059 $params['total'] = CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
3062 if (!empty($mailings)) {
3063 $openCounts = CRM_Mailing_Event_BAO_Opened
::getMailingContactCount(array_keys($mailings), $params['contact_id']);
3064 $clickCounts = CRM_Mailing_Event_BAO_TrackableURLOpen
::getMailingContactCount(array_keys($mailings), $params['contact_id']);
3067 // format params and add links
3068 $contactMailings = array();
3069 foreach ($mailings as $mailingId => $values) {
3071 $mailing['subject'] = $values['subject'];
3072 $mailing['creator_name'] = CRM_Utils_System
::href(
3073 $values['creator_name'],
3074 'civicrm/contact/view',
3075 "reset=1&cid={$values['creator_id']}");
3076 $mailing['recipients'] = CRM_Utils_System
::href(ts('(recipients)'), 'civicrm/mailing/report/event',
3077 "mid={$values['mailing_id']}&reset=1&cid={$params['contact_id']}&event=queue&context=mailing");
3078 $mailing['start_date'] = CRM_Utils_Date
::customFormat($values['start_date']);
3080 $mailing['openstats'] = "Opens: " .
3081 CRM_Utils_Array
::value($values['mailing_id'], $openCounts, 0) .
3083 CRM_Utils_Array
::value($values['mailing_id'], $clickCounts, 0);
3085 $actionLinks = array(
3086 CRM_Core_Action
::VIEW
=> array(
3087 'name' => ts('View'),
3088 'url' => 'civicrm/mailing/view',
3089 'qs' => "reset=1&id=%%mkey%%",
3090 'title' => ts('View Mailing'),
3091 'class' => 'crm-popup',
3093 CRM_Core_Action
::BROWSE
=> array(
3094 'name' => ts('Mailing Report'),
3095 'url' => 'civicrm/mailing/report',
3096 'qs' => "mid=%%mid%%&reset=1&cid=%%cid%%&context=mailing",
3097 'title' => ts('View Mailing Report'),
3101 $mailingKey = $values['mailing_id'];
3102 if ($hash = CRM_Mailing_BAO_Mailing
::getMailingHash($mailingKey)) {
3103 $mailingKey = $hash;
3106 $mailing['links'] = CRM_Core_Action
::formLink(
3110 'mid' => $values['mailing_id'],
3111 'cid' => $params['contact_id'],
3112 'mkey' => $mailingKey,
3116 'mailing.contact.action',
3118 $values['mailing_id']
3121 array_push($contactMailings, $mailing);
3124 $contactMailingsDT = array();
3125 $contactMailingsDT['data'] = $contactMailings;
3126 $contactMailingsDT['recordsTotal'] = $params['total'];
3127 $contactMailingsDT['recordsFiltered'] = $params['total'];
3129 return $contactMailingsDT;
3133 * Retrieve contact mailing.
3135 * @param array $params
3138 * Array of mailings for a contact
3141 static public function getContactMailings(&$params) {
3142 $params['version'] = 3;
3143 $params['offset'] = ($params['page'] - 1) * $params['rp'];
3144 $params['limit'] = $params['rp'];
3145 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
3147 $result = civicrm_api('MailingContact', 'get', $params);
3148 return $result['values'];
3152 * Retrieve contact mailing count.
3154 * @param array $params
3157 * count of mailings for a contact
3160 static public function getContactMailingsCount(&$params) {
3161 $params['version'] = 3;
3162 return civicrm_api('MailingContact', 'getcount', $params);
3166 * Get a list of permissions required for CRUD'ing each field
3167 * (when workflow is enabled).
3170 * Array (string $fieldName => string $permName)
3172 public static function getWorkflowFieldPerms() {
3173 $fieldNames = array_keys(CRM_Mailing_DAO_Mailing
::fields());
3174 $fieldPerms = array();
3175 foreach ($fieldNames as $fieldName) {
3176 if ($fieldName == 'id') {
3177 $fieldPerms[$fieldName] = array(
3178 array('access CiviMail', 'schedule mailings', 'approve mailings', 'create mailings'), // OR
3181 elseif (in_array($fieldName, array('scheduled_date', 'scheduled_id'))) {
3182 $fieldPerms[$fieldName] = array(
3183 array('access CiviMail', 'schedule mailings'), // OR
3186 elseif (in_array($fieldName, array('approval_date', 'approver_id', 'approval_status_id', 'approval_note'))) {
3187 $fieldPerms[$fieldName] = array(
3188 array('access CiviMail', 'approve mailings'), // OR
3192 $fieldPerms[$fieldName] = array(
3193 array('access CiviMail', 'create mailings'), // OR
3201 * White-list of possible values for the entity_table field.
3205 public static function mailingGroupEntityTables() {
3207 CRM_Contact_BAO_Group
::getTableName() => 'Group',
3208 CRM_Mailing_BAO_Mailing
::getTableName() => 'Mailing',
3213 * Get the public view url.
3216 * @param bool $absolute
3220 public static function getPublicViewUrl($id, $absolute = TRUE) {
3221 if ((civicrm_api3('Mailing', 'getvalue', array('id' => $id, 'return' => 'visibility'))) === 'Public Pages') {
3222 return CRM_Utils_System
::url('civicrm/mailing/view', array('id' => $id), $absolute, NULL, TRUE, TRUE);
3227 * Get a list of template types which can be used as `civicrm_mailing.template_type`.
3230 * A list of template-types, keyed numerically. Each defines:
3231 * - name: string, a short symbolic name
3232 * - editorUrl: string, Angular template name
3234 * Ex: $templateTypes[0] === array('name' => 'mosaico', 'editorUrl' => '~/crmMosaico/editor.html').
3236 public static function getTemplateTypes() {
3237 if (!isset(Civi
::$statics[__CLASS__
]['templateTypes'])) {
3240 'name' => 'traditional',
3241 'editorUrl' => CRM_Mailing_Info
::workflowEnabled() ?
'~/crmMailing/EditMailingCtrl/workflow.html' : '~/crmMailing/EditMailingCtrl/2step.html',
3245 CRM_Utils_Hook
::mailingTemplateTypes($types);
3247 $defaults = array('weight' => 0);
3248 foreach (array_keys($types) as $typeName) {
3249 $types[$typeName] = array_merge($defaults, $types[$typeName]);
3251 usort($types, function ($a, $b) {
3252 if ($a['weight'] === $b['weight']) {
3255 return $a['weight'] < $b['weight'] ?
-1 : 1;
3258 Civi
::$statics[__CLASS__
]['templateTypes'] = $types;
3261 return Civi
::$statics[__CLASS__
]['templateTypes'];
3265 * Get a list of template types.
3268 * Array(string $name => string $label).
3270 public static function getTemplateTypeNames() {
3272 foreach (self
::getTemplateTypes() as $type) {
3273 $r[$type['name']] = $type['name'];