3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.6 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
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-2014
35 require_once 'Mail/mime.php';
38 * Class CRM_Mailing_BAO_Mailing
40 class CRM_Mailing_BAO_Mailing
extends CRM_Mailing_DAO_Mailing
{
43 * An array that holds the complete templates
44 * including any headers or footers that need to be prepended
45 * or appended to the body
47 private $preparedTemplates = NULL;
50 * An array that holds the complete templates
51 * including any headers or footers that need to be prepended
52 * or appended to the body
54 private $templates = NULL;
57 * An array that holds the tokens that are specifically found in our text and html bodies
59 private $tokens = NULL;
62 * An array that holds the tokens that are specifically found in our text and html bodies
64 private $flattenedTokens = NULL;
67 * The header associated with this mailing
69 private $header = NULL;
72 * The footer associated with this mailing
74 private $footer = NULL;
77 * The HTML content of the message
82 * The text content of the message
87 * Cached BAO for the domain
89 private $_domain = NULL;
94 public function __construct() {
95 parent
::__construct();
100 * @param int $mailing_id
105 public static function &getRecipientsCount($job_id, $mailing_id = NULL, $mode = NULL) {
106 // need this for backward compatibility, so we can get count for old mailings
107 // please do not use this function if possible
108 $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
116 * (misnomer) a nonce value used to name temporary tables.
117 * @param int $mailing_id
118 * @param null $offset
120 * @param bool $storeRecipients
121 * @param bool $dedupeEmail
124 * @return CRM_Mailing_Event_BAO_Queue|string
126 static function &getRecipients(
131 $storeRecipients = FALSE,
132 $dedupeEmail = FALSE,
134 $mailingGroup = new CRM_Mailing_DAO_MailingGroup();
136 $mailing = CRM_Mailing_BAO_Mailing
::getTableName();
137 $job = CRM_Mailing_BAO_MailingJob
::getTableName();
138 $mg = CRM_Mailing_DAO_MailingGroup
::getTableName();
139 $eq = CRM_Mailing_Event_DAO_Queue
::getTableName();
140 $ed = CRM_Mailing_Event_DAO_Delivered
::getTableName();
141 $eb = CRM_Mailing_Event_DAO_Bounce
::getTableName();
143 $email = CRM_Core_DAO_Email
::getTableName();
144 if ($mode == 'sms') {
145 $phone = CRM_Core_DAO_Phone
::getTableName();
147 $contact = CRM_Contact_DAO_Contact
::getTableName();
149 $group = CRM_Contact_DAO_Group
::getTableName();
150 $g2contact = CRM_Contact_DAO_GroupContact
::getTableName();
152 $m = new CRM_Mailing_DAO_Mailing();
153 $m->id
= $mailing_id;
156 $email_selection_method = $m->email_selection_method
;
157 $location_type_id = $m->location_type_id
;
159 // Note: When determining the ORDER that results are returned, it's
160 // the record that comes last that counts. That's because we are
161 // INSERT'ing INTO a table with a primary id so that last record
162 // over writes any previous record.
163 switch ($email_selection_method) {
164 case 'location-exclude':
165 $location_filter = "($email.location_type_id != $location_type_id)";
166 // If there is more than one email that doesn't match the location,
167 // prefer the one marked is_bulkmail, followed by is_primary.
168 $order_by = "ORDER BY $email.is_bulkmail, $email.is_primary";
171 case 'location-only':
172 $location_filter = "($email.location_type_id = $location_type_id)";
173 // If there is more than one email of the desired location, prefer
174 // the one marked is_bulkmail, followed by is_primary.
175 $order_by = "ORDER BY $email.is_bulkmail, $email.is_primary";
178 case 'location-prefer':
179 $location_filter = "($email.is_bulkmail = 1 OR $email.is_primary = 1 OR $email.location_type_id = $location_type_id)";
181 // ORDER BY is more complicated because we have to set an arbitrary
182 // order that prefers the location that we want. We do that using
183 // the FIELD function. For more info, see:
184 // https://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_field
185 // We assign the location type we want the value "1" by putting it
186 // in the first position after we name the field. All other location
187 // types are left out, so they will be assigned the value 0. That
188 // means, they will all be equally tied for first place, with our
189 // location being last.
190 $order_by = "ORDER BY FIELD($email.location_type_id, $location_type_id), $email.is_bulkmail, $email.is_primary";
194 // fall through to default
196 $location_filter = "($email.is_bulkmail = 1 OR $email.is_primary = 1)";
197 $order_by = "ORDER BY $email.is_bulkmail";
200 /* Create a temp table for contact exclusion */
201 $mailingGroup->query(
202 "CREATE TEMPORARY TABLE X_$job_id
203 (contact_id int primary key)
207 /* Add all the members of groups excluded from this mailing to the temp
210 $excludeSubGroup = "INSERT INTO X_$job_id (contact_id)
211 SELECT DISTINCT $g2contact.contact_id
214 ON $g2contact.group_id = $mg.entity_id AND $mg.entity_table = '$group'
216 $mg.mailing_id = {$mailing_id}
217 AND $g2contact.status = 'Added'
218 AND $mg.group_type = 'Exclude'";
219 $mailingGroup->query($excludeSubGroup);
221 /* Add all unsubscribe members of base group from this mailing to the temp
224 $unSubscribeBaseGroup = "INSERT INTO X_$job_id (contact_id)
225 SELECT DISTINCT $g2contact.contact_id
228 ON $g2contact.group_id = $mg.entity_id AND $mg.entity_table = '$group'
230 $mg.mailing_id = {$mailing_id}
231 AND $g2contact.status = 'Removed'
232 AND $mg.group_type = 'Base'";
233 $mailingGroup->query($unSubscribeBaseGroup);
235 /* Add all the (intended) recipients of an excluded prior mailing to
238 $excludeSubMailing = "INSERT IGNORE INTO X_$job_id (contact_id)
239 SELECT DISTINCT $eq.contact_id
242 ON $eq.job_id = $job.id
244 ON $job.mailing_id = $mg.entity_id AND $mg.entity_table = '$mailing'
246 $mg.mailing_id = {$mailing_id}
247 AND $mg.group_type = 'Exclude'";
248 $mailingGroup->query($excludeSubMailing);
250 // get all the saved searches AND hierarchical groups
251 // and load them in the cache
253 SELECT $group.id, $group.cache_date, $group.saved_search_id, $group.children
255 INNER JOIN $mg ON $mg.entity_id = $group.id
256 WHERE $mg.entity_table = '$group'
257 AND $mg.group_type = 'Exclude'
258 AND $mg.mailing_id = {$mailing_id}
259 AND ( saved_search_id != 0
260 OR saved_search_id IS NOT NULL
261 OR children IS NOT NULL )
264 $groupDAO = CRM_Core_DAO
::executeQuery($sql);
265 while ($groupDAO->fetch()) {
266 if ($groupDAO->cache_date
== NULL) {
267 CRM_Contact_BAO_GroupContactCache
::load($groupDAO);
270 $smartGroupExclude = "
271 INSERT IGNORE INTO X_$job_id (contact_id)
273 FROM civicrm_group_contact_cache c
274 WHERE c.group_id = {$groupDAO->id}
276 $mailingGroup->query($smartGroupExclude);
279 $tempColumn = 'email_id';
280 if ($mode == 'sms') {
281 $tempColumn = 'phone_id';
284 /* Get all the group contacts we want to include */
286 $mailingGroup->query(
287 "CREATE TEMPORARY TABLE I_$job_id
288 ($tempColumn int, contact_id int primary key)
292 /* Get the group contacts, but only those which are not in the
293 * exclusion temp table */
295 $query = "REPLACE INTO I_$job_id (email_id, contact_id)
297 SELECT DISTINCT $email.id as email_id,
298 $contact.id as contact_id
301 ON $email.contact_id = $contact.id
302 INNER JOIN $g2contact
303 ON $contact.id = $g2contact.contact_id
305 ON $g2contact.group_id = $mg.entity_id
306 AND $mg.entity_table = '$group'
308 ON $contact.id = X_$job_id.contact_id
310 ($mg.group_type = 'Include')
311 AND $mg.search_id IS NULL
312 AND $g2contact.status = 'Added'
313 AND $contact.do_not_email = 0
314 AND $contact.is_opt_out = 0
315 AND $contact.is_deceased = 0
317 AND $email.email IS NOT NULL
318 AND $email.email != ''
319 AND $email.on_hold = 0
320 AND $mg.mailing_id = {$mailing_id}
321 AND X_$job_id.contact_id IS null
324 if ($mode == 'sms') {
325 $phoneTypes = CRM_Core_OptionGroup
::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
326 $query = "REPLACE INTO I_$job_id (phone_id, contact_id)
328 SELECT DISTINCT $phone.id as phone_id,
329 $contact.id as contact_id
332 ON $phone.contact_id = $contact.id
333 INNER JOIN $g2contact
334 ON $contact.id = $g2contact.contact_id
336 ON $g2contact.group_id = $mg.entity_id
337 AND $mg.entity_table = '$group'
339 ON $contact.id = X_$job_id.contact_id
341 ($mg.group_type = 'Include')
342 AND $mg.search_id IS NULL
343 AND $g2contact.status = 'Added'
344 AND $contact.do_not_sms = 0
345 AND $contact.is_opt_out = 0
346 AND $contact.is_deceased = 0
347 AND $phone.phone_type_id = {$phoneTypes['Mobile']}
348 AND $phone.phone IS NOT NULL
349 AND $phone.phone != ''
350 AND $mg.mailing_id = {$mailing_id}
351 AND X_$job_id.contact_id IS null";
353 $mailingGroup->query($query);
355 /* Query prior mailings */
357 $query = "REPLACE INTO I_$job_id (email_id, contact_id)
358 SELECT DISTINCT $email.id as email_id,
359 $contact.id as contact_id
362 ON $email.contact_id = $contact.id
364 ON $eq.contact_id = $contact.id
366 ON $eq.job_id = $job.id
368 ON $job.mailing_id = $mg.entity_id AND $mg.entity_table = '$mailing'
370 ON $contact.id = X_$job_id.contact_id
372 ($mg.group_type = 'Include')
373 AND $contact.do_not_email = 0
374 AND $contact.is_opt_out = 0
375 AND $contact.is_deceased = 0
377 AND $email.on_hold = 0
378 AND $mg.mailing_id = {$mailing_id}
379 AND X_$job_id.contact_id IS null
382 if ($mode == 'sms') {
383 $query = "REPLACE INTO I_$job_id (phone_id, contact_id)
384 SELECT DISTINCT $phone.id as phone_id,
385 $contact.id as contact_id
388 ON $phone.contact_id = $contact.id
390 ON $eq.contact_id = $contact.id
392 ON $eq.job_id = $job.id
394 ON $job.mailing_id = $mg.entity_id AND $mg.entity_table = '$mailing'
396 ON $contact.id = X_$job_id.contact_id
398 ($mg.group_type = 'Include')
399 AND $contact.do_not_sms = 0
400 AND $contact.is_opt_out = 0
401 AND $contact.is_deceased = 0
402 AND $phone.phone_type_id = {$phoneTypes['Mobile']}
403 AND $mg.mailing_id = {$mailing_id}
404 AND X_$job_id.contact_id IS null";
406 $mailingGroup->query($query);
409 SELECT $group.id, $group.cache_date, $group.saved_search_id, $group.children
411 INNER JOIN $mg ON $mg.entity_id = $group.id
412 WHERE $mg.entity_table = '$group'
413 AND $mg.group_type = 'Include'
414 AND $mg.search_id IS NULL
415 AND $mg.mailing_id = {$mailing_id}
416 AND ( saved_search_id != 0
417 OR saved_search_id IS NOT NULL
418 OR children IS NOT NULL )
421 $groupDAO = CRM_Core_DAO
::executeQuery($sql);
422 while ($groupDAO->fetch()) {
423 if ($groupDAO->cache_date
== NULL) {
424 CRM_Contact_BAO_GroupContactCache
::load($groupDAO);
427 $smartGroupInclude = "
428 INSERT IGNORE INTO I_$job_id (email_id, contact_id)
429 SELECT civicrm_email.id as email_id, c.id as contact_id
430 FROM civicrm_contact c
431 INNER JOIN civicrm_email ON civicrm_email.contact_id = c.id
432 INNER JOIN civicrm_group_contact_cache gc ON gc.contact_id = c.id
433 LEFT JOIN X_$job_id ON X_$job_id.contact_id = c.id
434 WHERE gc.group_id = {$groupDAO->id}
435 AND c.do_not_email = 0
437 AND c.is_deceased = 0
439 AND civicrm_email.on_hold = 0
440 AND X_$job_id.contact_id IS null
443 if ($mode == 'sms') {
444 $smartGroupInclude = "
445 INSERT IGNORE INTO I_$job_id (phone_id, contact_id)
446 SELECT p.id as phone_id, c.id as contact_id
447 FROM civicrm_contact c
448 INNER JOIN civicrm_phone p ON p.contact_id = c.id
449 INNER JOIN civicrm_group_contact_cache gc ON gc.contact_id = c.id
450 LEFT JOIN X_$job_id ON X_$job_id.contact_id = c.id
451 WHERE gc.group_id = {$groupDAO->id}
454 AND c.is_deceased = 0
455 AND p.phone_type_id = {$phoneTypes['Mobile']}
456 AND X_$job_id.contact_id IS null";
458 $mailingGroup->query($smartGroupInclude);
462 * Construct the filtered search queries
465 SELECT search_id, search_args, entity_id
467 WHERE $mg.search_id IS NOT NULL
468 AND $mg.mailing_id = {$mailing_id}
470 $dao = CRM_Core_DAO
::executeQuery($query);
471 while ($dao->fetch()) {
472 $customSQL = CRM_Contact_BAO_SearchCustom
::civiMailSQL($dao->search_id
,
476 $query = "REPLACE INTO I_$job_id ({$tempColumn}, contact_id)
478 $mailingGroup->query($query);
481 /* Get the emails with only location override */
483 $query = "REPLACE INTO I_$job_id (email_id, contact_id)
484 SELECT DISTINCT $email.id as local_email_id,
485 $contact.id as contact_id
488 ON $email.contact_id = $contact.id
489 INNER JOIN $g2contact
490 ON $contact.id = $g2contact.contact_id
492 ON $g2contact.group_id = $mg.entity_id
494 ON $contact.id = X_$job_id.contact_id
496 $mg.entity_table = '$group'
497 AND $mg.group_type = 'Include'
498 AND $g2contact.status = 'Added'
499 AND $contact.do_not_email = 0
500 AND $contact.is_opt_out = 0
501 AND $contact.is_deceased = 0
503 AND $email.on_hold = 0
504 AND $mg.mailing_id = {$mailing_id}
505 AND X_$job_id.contact_id IS null
507 if ($mode == "sms") {
508 $query = "REPLACE INTO I_$job_id (phone_id, contact_id)
509 SELECT DISTINCT $phone.id as phone_id,
510 $contact.id as contact_id
513 ON $phone.contact_id = $contact.id
514 INNER JOIN $g2contact
515 ON $contact.id = $g2contact.contact_id
517 ON $g2contact.group_id = $mg.entity_id
519 ON $contact.id = X_$job_id.contact_id
521 $mg.entity_table = '$group'
522 AND $mg.group_type = 'Include'
523 AND $g2contact.status = 'Added'
524 AND $contact.do_not_sms = 0
525 AND $contact.is_opt_out = 0
526 AND $contact.is_deceased = 0
527 AND $phone.phone_type_id = {$phoneTypes['Mobile']}
528 AND $mg.mailing_id = {$mailing_id}
529 AND X_$job_id.contact_id IS null";
531 $mailingGroup->query($query);
535 $eq = new CRM_Mailing_Event_BAO_Queue();
537 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause();
538 $aclWhere = $aclWhere ?
"WHERE {$aclWhere}" : '';
540 if ($limit && $offset !== NULL) {
541 $offset = CRM_Utils_Type
::escape($offset, 'Int');
542 $limit = CRM_Utils_Type
::escape($limit, 'Int');
544 $limitString = "LIMIT $offset, $limit";
547 if ($storeRecipients && $mailing_id) {
550 FROM civicrm_mailing_recipients
551 WHERE mailing_id = %1
553 $params = array(1 => array($mailing_id, 'Integer'));
554 CRM_Core_DAO
::executeQuery($sql, $params);
557 $groupBy = $groupJoin = '';
559 $groupJoin = " INNER JOIN civicrm_email e ON e.id = i.email_id";
560 $groupBy = " GROUP BY e.email ";
564 INSERT INTO civicrm_mailing_recipients ( mailing_id, contact_id, {$tempColumn} )
565 SELECT %1, i.contact_id, i.{$tempColumn}
566 FROM civicrm_contact contact_a
567 INNER JOIN I_$job_id i ON contact_a.id = i.contact_id
572 ORDER BY i.contact_id, i.{$tempColumn}
575 CRM_Core_DAO
::executeQuery($sql, $params);
577 // if we need to add all emails marked bulk, do it as a post filter
578 // on the mailing recipients table
579 if (CRM_Core_BAO_Email
::isMultipleBulkMail()) {
580 self
::addMultipleEmails($mailing_id);
584 /* Delete the temp table */
586 $mailingGroup->reset();
587 $mailingGroup->query("DROP TEMPORARY TABLE X_$job_id");
588 $mailingGroup->query("DROP TEMPORARY TABLE I_$job_id");
594 * @param string $type
598 private function _getMailingGroupIds($type = 'Include') {
599 $mailingGroup = new CRM_Mailing_DAO_MailingGroup();
600 $group = CRM_Contact_DAO_Group
::getTableName();
601 if (!isset($this->id
)) {
602 // we're just testing tokens, so return any group
603 $query = "SELECT id AS entity_id
609 $query = "SELECT entity_id
611 WHERE mailing_id = {$this->id}
612 AND group_type = '$type'
613 AND entity_table = '$group'";
615 $mailingGroup->query($query);
618 while ($mailingGroup->fetch()) {
619 $groupIds[] = $mailingGroup->entity_id
;
627 * Returns the regex patterns that are used for preparing the text and html templates
631 private function &getPatterns($onlyHrefs = FALSE) {
635 $protos = '(https?|ftp)';
637 $gunk = '\{\}/#~:.?+=&;%@!\,\-';
639 $any = "{$letters}{$gunk}{$punc}";
641 $pattern = "\\bhref[ ]*=[ ]*([\"'])?(($protos:[$any]+?(?=[$punc]*[^$any]|$)))([\"'])?";
644 $pattern = "\\b($protos:[$any]+?(?=[$punc]*[^$any]|$))";
647 $patterns[] = $pattern;
648 $patterns[] = '\\\\\{\w+\.\w+\\\\\}|\{\{\w+\.\w+\}\}';
649 $patterns[] = '\{\w+\.\w+\}';
651 $patterns = '{' . join('|', $patterns) . '}im';
657 * returns an array that denotes the type of token that we are dealing with
658 * we use the type later on when we are doing a token replcement lookup
660 * @param string $token The token for which we will be doing adata lookup
662 * @return array $funcStruct An array that holds the token itself and the type.
663 * the type will tell us which function to use for the data lookup
664 * if we need to do a lookup at all
666 public function &getDataFunc($token) {
667 static $_categories = NULL;
668 static $_categoryString = NULL;
670 $_categories = array(
677 CRM_Utils_Hook
::tokens($_categories);
678 $_categoryString = implode('|', array_keys($_categories));
681 $funcStruct = array('type' => NULL, 'token' => $token);
683 if ((preg_match('/^href/i', $token) ||
preg_match('/^http/i', $token))) {
684 // it is a url so we need to check to see if there are any tokens embedded
685 // if so then call this function again to get the token dataFunc
686 // and assign the type 'embedded' so that the data retrieving function
687 // will know what how to handle this token.
688 if (preg_match_all('/(\{\w+\.\w+\})/', $token, $matches)) {
689 $funcStruct['type'] = 'embedded_url';
690 $funcStruct['embed_parts'] = $funcStruct['token'] = array();
691 foreach ($matches[1] as $match) {
692 $preg_token = '/' . preg_quote($match, '/') . '/';
693 $list = preg_split($preg_token, $token, 2);
694 $funcStruct['embed_parts'][] = $list[0];
696 $funcStruct['token'][] = $this->getDataFunc($match);
698 // fixed truncated url, CRM-7113
700 $funcStruct['embed_parts'][] = $token;
704 $funcStruct['type'] = 'url';
707 elseif (preg_match('/^\{(' . $_categoryString . ')\.(\w+)\}$/', $token, $matches)) {
708 $funcStruct['type'] = $matches[1];
709 $funcStruct['token'] = $matches[2];
711 elseif (preg_match('/\\\\\{(\w+\.\w+)\\\\\}|\{\{(\w+\.\w+)\}\}/', $token, $matches)) {
712 // we are an escaped token
713 // so remove the escape chars
714 $unescaped_token = preg_replace('/\{\{|\}\}|\\\\\{|\\\\\}/', '', $matches[0]);
715 $funcStruct['token'] = '{' . $unescaped_token . '}';
722 * Prepares the text and html templates
723 * for generating the emails and returns a copy of the
728 private function getPreparedTemplates() {
729 if (!$this->preparedTemplates
) {
730 $patterns['html'] = $this->getPatterns(TRUE);
731 $patterns['subject'] = $patterns['text'] = $this->getPatterns();
732 $templates = $this->getTemplates();
734 $this->preparedTemplates
= array();
737 'html', 'text', 'subject') as $key) {
738 if (!isset($templates[$key])) {
744 $split_template = array();
746 $email = $templates[$key];
747 preg_match_all($patterns[$key], $email, $matches, PREG_PATTERN_ORDER
);
748 foreach ($matches[0] as $idx => $token) {
749 $preg_token = '/' . preg_quote($token, '/') . '/im';
750 list($split_template[], $email) = preg_split($preg_token, $email, 2);
751 array_push($tokens, $this->getDataFunc($token));
754 $split_template[] = $email;
756 $this->preparedTemplates
[$key]['template'] = $split_template;
757 $this->preparedTemplates
[$key]['tokens'] = $tokens;
760 return ($this->preparedTemplates
);
765 * Retrieve a ref to an array that holds the email and text templates for this email
766 * assembles the complete template including the header and footer
767 * that the user has uploaded or declared (if they have dome that)
770 * @return array reference to an assoc array
773 private function &getTemplates() {
774 if (!$this->templates
) {
775 $this->getHeaderFooter();
776 $this->templates
= array();
778 if ($this->body_text
) {
781 $template[] = $this->header
->body_text
;
784 $template[] = $this->body_text
;
787 $template[] = $this->footer
->body_text
;
790 $this->templates
['text'] = join("\n", $template);
793 if ($this->body_html
) {
797 $template[] = $this->header
->body_html
;
800 $template[] = $this->body_html
;
803 $template[] = $this->footer
->body_html
;
806 $this->templates
['html'] = join("\n", $template);
808 // this is where we create a text template from the html template if the text template did not exist
809 // this way we ensure that every recipient will receive an email even if the pref is set to text and the
810 // user uploads an html email only
811 if (!$this->body_text
) {
812 $this->templates
['text'] = CRM_Utils_String
::htmlToText($this->templates
['html']);
816 if ($this->subject
) {
818 $template[] = $this->subject
;
819 $this->templates
['subject'] = join("\n", $template);
822 return $this->templates
;
827 * Retrieve a ref to an array that holds all of the tokens in the email body
828 * where the keys are the type of token and the values are ordinal arrays
829 * that hold the token names (even repeated tokens) in the order in which
830 * they appear in the body of the email.
832 * note: the real work is done in the _getTokens() function
834 * this function needs to have some sort of a body assigned
835 * either text or html for this to have any meaningful impact
837 * @return array reference to an assoc array
840 public function &getTokens() {
841 if (!$this->tokens
) {
843 $this->tokens
= array('html' => array(), 'text' => array(), 'subject' => array());
845 if ($this->body_html
) {
846 $this->_getTokens('html');
847 if (!$this->body_text
) {
848 // Since the text template was created from html, use the html tokens.
849 // @see CRM_Mailing_BAO_Mailing::getTemplates()
850 $this->tokens
['text'] = $this->tokens
['html'];
854 if ($this->body_text
) {
855 $this->_getTokens('text');
858 if ($this->subject
) {
859 $this->_getTokens('subject');
863 return $this->tokens
;
867 * Returns the token set for all 3 parts as one set. This allows it to be sent to the
868 * hook in one call and standardizes it across other token workflows
870 * @return array reference to an assoc array
873 public function &getFlattenedTokens() {
874 if (!$this->flattenedTokens
) {
875 $tokens = $this->getTokens();
877 $this->flattenedTokens
= CRM_Utils_Token
::flattenTokens($tokens);
880 return $this->flattenedTokens
;
885 * _getTokens parses out all of the tokens that have been
886 * included in the html and text bodies of the email
887 * we get the tokens and then separate them into an
888 * internal structure named tokens that has the same
889 * form as the static tokens property(?) of the CRM_Utils_Token class.
890 * The difference is that there might be repeated token names as we want the
891 * structures to represent the order in which tokens were found from left to right, top to bottom.
894 * @param string $propName of the property that holds the text that we want to scan for tokens (html, text).
895 * Name of the property that holds the text that we want to scan for tokens (html, text).
899 private function _getTokens($prop) {
900 $templates = $this->getTemplates();
902 $newTokens = CRM_Utils_Token
::getTokens($templates[$prop]);
904 foreach ($newTokens as $type => $names) {
905 if (!isset($this->tokens
[$prop][$type])) {
906 $this->tokens
[$prop][$type] = array();
908 foreach ($names as $key => $name) {
909 $this->tokens
[$prop][$type][] = $name;
915 * Generate an event queue for a test job
917 * @param array $testParams
918 * Contains form values.
922 public function getTestRecipients($testParams) {
923 if (array_key_exists($testParams['test_group'], CRM_Core_PseudoConstant
::group())) {
924 $contacts = civicrm_api('contact', 'get', array(
926 'group' => $testParams['test_group'],
928 'options' => array('limit' => 100000000000,
932 foreach (array_keys($contacts['values']) as $groupContact) {
934 SELECT civicrm_email.id AS email_id,
935 civicrm_email.is_primary as is_primary,
936 civicrm_email.is_bulkmail as is_bulkmail
938 INNER JOIN civicrm_contact ON civicrm_email.contact_id = civicrm_contact.id
939 WHERE (civicrm_email.is_bulkmail = 1 OR civicrm_email.is_primary = 1)
940 AND civicrm_contact.id = {$groupContact}
941 AND civicrm_contact.do_not_email = 0
942 AND civicrm_contact.is_deceased = 0
943 AND civicrm_email.on_hold = 0
944 AND civicrm_contact.is_opt_out = 0
945 GROUP BY civicrm_email.id
946 ORDER BY civicrm_email.is_bulkmail DESC
948 $dao = CRM_Core_DAO
::executeQuery($query);
951 'job_id' => $testParams['job_id'],
952 'email_id' => $dao->email_id
,
953 'contact_id' => $groupContact,
955 CRM_Mailing_Event_BAO_Queue
::create($params);
962 * Retrieve the header and footer for this mailing
968 private function getHeaderFooter() {
969 if (!$this->header
and $this->header_id
) {
970 $this->header
= new CRM_Mailing_BAO_Component();
971 $this->header
->id
= $this->header_id
;
972 $this->header
->find(TRUE);
973 $this->header
->free();
976 if (!$this->footer
and $this->footer_id
) {
977 $this->footer
= new CRM_Mailing_BAO_Component();
978 $this->footer
->id
= $this->footer_id
;
979 $this->footer
->find(TRUE);
980 $this->footer
->free();
985 * Given and array of headers and a prefix, job ID, event queue ID, and hash,
986 * add a Message-ID header if needed.
988 * i.e. if the global includeMessageId is set and there isn't already a
989 * Message-ID in the array.
990 * The message ID is structured the same way as a verp. However no interpretation
991 * is placed on the values received, so they do not need to follow the verp
994 * @param array $headers
995 * Array of message headers to update, in-out.
996 * @param string $prefix
997 * Prefix for the message ID, use same prefixes as verp.
999 * @param string $job_id
1000 * Job ID component of the generated message ID.
1001 * @param string $event_queue_id
1002 * Event Queue ID component of the generated message ID.
1003 * @param string $hash
1004 * Hash component of the generated message ID.
1008 public static function addMessageIdHeader(&$headers, $prefix, $job_id, $event_queue_id, $hash) {
1009 $config = CRM_Core_Config
::singleton();
1010 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
1011 $emailDomain = CRM_Core_BAO_MailSettings
::defaultDomain();
1012 $includeMessageId = CRM_Core_BAO_MailSettings
::includeMessageId();
1014 if ($includeMessageId && (!array_key_exists('Message-ID', $headers))) {
1015 $headers['Message-ID'] = '<' . implode($config->verpSeparator
,
1017 $localpart . $prefix,
1022 ) . "@{$emailDomain}>";
1027 * Static wrapper for getting verp and urls
1029 * @param int $job_id
1030 * ID of the Job associated with this message.
1031 * @param int $event_queue_id
1032 * ID of the EventQueue.
1033 * @param string $hash
1034 * Hash of the EventQueue.
1035 * @param string $email
1036 * Destination address.
1038 * @return array (reference) array array ref that hold array refs to the verp info and urls
1040 public static function getVerpAndUrls($job_id, $event_queue_id, $hash, $email) {
1041 // create a skeleton object and set its properties that are required by getVerpAndUrlsAndHeaders()
1042 $config = CRM_Core_Config
::singleton();
1043 $bao = new CRM_Mailing_BAO_Mailing();
1044 $bao->_domain
= CRM_Core_BAO_Domain
::getDomain();
1045 $bao->from_name
= $bao->from_email
= $bao->subject
= '';
1047 // use $bao's instance method to get verp and urls
1048 list($verp, $urls, $_) = $bao->getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email);
1049 return array($verp, $urls);
1053 * Get verp, urls and headers
1055 * @param int $job_id
1056 * ID of the Job associated with this message.
1057 * @param int $event_queue_id
1058 * ID of the EventQueue.
1059 * @param string $hash
1060 * Hash of the EventQueue.
1061 * @param string $email
1062 * Destination address.
1064 * @param bool $isForward
1066 * @return array (reference) array array ref that hold array refs to the verp info, urls, and headers
1069 private function getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email, $isForward = FALSE) {
1070 $config = CRM_Core_Config
::singleton();
1073 * Inbound VERP keys:
1074 * reply: user replied to mailing
1075 * bounce: email address bounced
1076 * unsubscribe: contact opts out of all target lists for the mailing
1077 * resubscribe: contact opts back into all target lists for the mailing
1078 * optOut: contact unsubscribes from the domain
1081 $verpTokens = array(
1084 'unsubscribe' => 'u',
1085 'resubscribe' => 'e',
1089 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
1090 $emailDomain = CRM_Core_BAO_MailSettings
::defaultDomain();
1092 foreach ($verpTokens as $key => $value) {
1093 $verp[$key] = implode($config->verpSeparator
,
1095 $localpart . $value,
1100 ) . "@$emailDomain";
1103 //handle should override VERP address.
1104 $skipEncode = FALSE;
1107 self
::overrideVerp($job_id)
1109 $verp['reply'] = "\"{$this->from_name}\" <{$this->from_email}>";
1113 'forward' => CRM_Utils_System
::url('civicrm/mailing/forward',
1114 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1115 TRUE, NULL, TRUE, TRUE
1117 'unsubscribeUrl' => CRM_Utils_System
::url('civicrm/mailing/unsubscribe',
1118 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1119 TRUE, NULL, TRUE, TRUE
1121 'resubscribeUrl' => CRM_Utils_System
::url('civicrm/mailing/resubscribe',
1122 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1123 TRUE, NULL, TRUE, TRUE
1125 'optOutUrl' => CRM_Utils_System
::url('civicrm/mailing/optout',
1126 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1127 TRUE, NULL, TRUE, TRUE
1129 'subscribeUrl' => CRM_Utils_System
::url('civicrm/mailing/subscribe',
1131 TRUE, NULL, TRUE, TRUE
1136 'Reply-To' => $verp['reply'],
1137 'Return-Path' => $verp['bounce'],
1138 'From' => "\"{$this->from_name}\" <{$this->from_email}>",
1139 'Subject' => $this->subject
,
1140 'List-Unsubscribe' => "<mailto:{$verp['unsubscribe']}>",
1142 self
::addMessageIdHeader($headers, 'm', $job_id, $event_queue_id, $hash);
1144 $headers['Subject'] = "[Fwd:{$this->subject}]";
1146 return array(&$verp, &$urls, &$headers);
1152 * @param int $job_id
1153 * ID of the Job associated with this message.
1154 * @param int $event_queue_id
1155 * ID of the EventQueue.
1156 * @param string $hash
1157 * Hash of the EventQueue.
1158 * @param string $contactId
1159 * ID of the Contact.
1160 * @param string $email
1161 * Destination address.
1162 * @param string $recipient
1163 * To: of the recipient.
1165 * Is this mailing a test?.
1166 * @param $contactDetails
1167 * @param $attachments
1168 * @param bool $isForward
1169 * Is this mailing compose for forward?.
1170 * @param string $fromEmail
1171 * Email address of who is forwardinf it.
1173 * @param null $replyToEmail
1175 * @return Mail_mime The mail object
1177 public function &compose(
1178 $job_id, $event_queue_id, $hash, $contactId,
1179 $email, &$recipient, $test,
1180 $contactDetails, &$attachments, $isForward = FALSE,
1181 $fromEmail = NULL, $replyToEmail = NULL
1183 $config = CRM_Core_Config
::singleton();
1184 $knownTokens = $this->getTokens();
1186 if ($this->_domain
== NULL) {
1187 $this->_domain
= CRM_Core_BAO_Domain
::getDomain();
1190 list($verp, $urls, $headers) = $this->getVerpAndUrlsAndHeaders(
1198 //set from email who is forwarding it and not original one.
1200 unset($headers['From']);
1201 $headers['From'] = "<{$fromEmail}>";
1204 if ($replyToEmail && ($fromEmail != $replyToEmail)) {
1205 $headers['Reply-To'] = "{$replyToEmail}";
1208 if ($contactDetails) {
1209 $contact = $contactDetails;
1211 elseif ($contactId === 0) {
1214 CRM_Utils_Hook
::tokenValues($contact, $contactId, $job_id);
1217 $params = array(array('contact_id', '=', $contactId, 0, 0));
1218 list($contact, $_) = CRM_Contact_BAO_Query
::apiQuery($params);
1221 $contact = reset($contact);
1223 if (!$contact ||
is_a($contact, 'CRM_Core_Error')) {
1224 CRM_Core_Error
::debug_log_message(ts('CiviMail will not send email to a non-existent contact: %1',
1225 array(1 => $contactId)
1227 // setting this because function is called by reference
1228 //@todo test not calling function by reference
1233 // also call the hook to get contact details
1234 CRM_Utils_Hook
::tokenValues($contact, $contactId, $job_id);
1237 $pTemplates = $this->getPreparedTemplates();
1240 foreach ($pTemplates as $type => $pTemplate) {
1241 $html = ($type == 'html') ?
TRUE : FALSE;
1242 $pEmails[$type] = array();
1243 $pEmail = &$pEmails[$type];
1244 $template = &$pTemplates[$type]['template'];
1245 $tokens = &$pTemplates[$type]['tokens'];
1247 if (!empty($tokens)) {
1248 foreach ($tokens as $idx => $token) {
1249 $token_data = $this->getTokenData($token, $html, $contact, $verp, $urls, $event_queue_id);
1250 array_push($pEmail, $template[$idx]);
1251 array_push($pEmail, $token_data);
1255 array_push($pEmail, $template[$idx]);
1258 if (isset($template[($idx +
1)])) {
1259 array_push($pEmail, $template[($idx +
1)]);
1264 if (isset($pEmails['html']) && is_array($pEmails['html']) && count($pEmails['html'])) {
1265 $html = &$pEmails['html'];
1269 if (isset($pEmails['text']) && is_array($pEmails['text']) && count($pEmails['text'])) {
1270 $text = &$pEmails['text'];
1273 // push the tracking url on to the html email if necessary
1274 if ($this->open_tracking
&& $html) {
1275 array_push($html, "\n" . '<img src="' . $config->userFrameworkResourceURL
.
1276 "extern/open.php?q=$event_queue_id\" width='1' height='1' alt='' border='0'>"
1280 $message = new Mail_mime("\n");
1282 $useSmarty = defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY ?
TRUE : FALSE;
1284 $smarty = CRM_Core_Smarty
::singleton();
1285 // also add the contact tokens to the template
1286 $smarty->assign_by_ref('contact', $contact);
1289 $mailParams = $headers;
1290 if ($text && ($test ||
$contact['preferred_mail_format'] == 'Text' ||
1291 $contact['preferred_mail_format'] == 'Both' ||
1292 ($contact['preferred_mail_format'] == 'HTML' && !array_key_exists('html', $pEmails))
1294 $textBody = join('', $text);
1296 $textBody = $smarty->fetch("string:$textBody");
1298 $mailParams['text'] = $textBody;
1301 if ($html && ($test ||
($contact['preferred_mail_format'] == 'HTML' ||
1302 $contact['preferred_mail_format'] == 'Both'
1304 $htmlBody = join('', $html);
1306 $htmlBody = $smarty->fetch("string:$htmlBody");
1308 $mailParams['html'] = $htmlBody;
1311 if (empty($mailParams['text']) && empty($mailParams['html'])) {
1313 // something went wrong, lets log it and return null (by reference)
1314 CRM_Core_Error
::debug_log_message(ts('CiviMail will not send an empty mail body, Skipping: %1',
1321 $mailParams['attachments'] = $attachments;
1323 $mailingSubject = CRM_Utils_Array
::value('subject', $pEmails);
1324 if (is_array($mailingSubject)) {
1325 $mailingSubject = join('', $mailingSubject);
1327 $mailParams['Subject'] = $mailingSubject;
1329 $mailParams['toName'] = CRM_Utils_Array
::value('display_name',
1332 $mailParams['toEmail'] = $email;
1334 CRM_Utils_Hook
::alterMailParams($mailParams, 'civimail');
1336 // CRM-10699 support custom email headers
1337 if (!empty($mailParams['headers'])) {
1338 $headers = array_merge($headers, $mailParams['headers']);
1340 //cycle through mailParams and set headers array
1341 foreach ($mailParams as $paramKey => $paramValue) {
1342 //exclude values not intended for the header
1343 if (!in_array($paramKey, array(
1344 'text', 'html', 'attachments', 'toName', 'toEmail'))) {
1345 $headers[$paramKey] = $paramValue;
1349 if (!empty($mailParams['text'])) {
1350 $message->setTxtBody($mailParams['text']);
1353 if (!empty($mailParams['html'])) {
1354 $message->setHTMLBody($mailParams['html']);
1357 if (!empty($mailParams['attachments'])) {
1358 foreach ($mailParams['attachments'] as $fileID => $attach) {
1359 $message->addAttachment($attach['fullPath'],
1360 $attach['mime_type'],
1361 $attach['cleanName']
1366 //pickup both params from mail params.
1367 $toName = trim($mailParams['toName']);
1368 $toEmail = trim($mailParams['toEmail']);
1369 if ($toName == $toEmail ||
1370 strpos($toName, '@') !== FALSE
1375 $toName = CRM_Utils_Mail
::formatRFC2822Name($toName);
1378 $headers['To'] = "$toName <$toEmail>";
1380 $headers['Precedence'] = 'bulk';
1381 // Will test in the mail processor if the X-VERP is set in the bounced email.
1382 // (As an option to replace real VERP for those that can't set it up)
1383 $headers['X-CiviMail-Bounce'] = $verp['bounce'];
1386 //token replacement of subject
1387 $headers['Subject'] = $mailingSubject;
1389 CRM_Utils_Mail
::setMimeParams($message);
1390 $headers = $message->headers($headers);
1392 //get formatted recipient
1393 $recipient = $headers['To'];
1395 // make sure we unset a lot of stuff
1407 * get mailing object and replaces subscribeInvite,
1408 * domain and mailing tokens
1411 public static function tokenReplace(&$mailing) {
1412 $domain = CRM_Core_BAO_Domain
::getDomain();
1414 foreach (array('text', 'html') as $type) {
1415 $tokens = $mailing->getTokens();
1416 if (isset($mailing->templates
[$type])) {
1417 $mailing->templates
[$type] = CRM_Utils_Token
::replaceSubscribeInviteTokens($mailing->templates
[$type]);
1418 $mailing->templates
[$type] = CRM_Utils_Token
::replaceDomainTokens(
1419 $mailing->templates
[$type],
1421 $type == 'html' ?
TRUE : FALSE,
1424 $mailing->templates
[$type] = CRM_Utils_Token
::replaceMailingTokens($mailing->templates
[$type], $mailing, NULL, $tokens[$type]);
1431 * getTokenData receives a token from an email
1432 * and returns the appropriate data for the token
1435 private function getTokenData(&$token_a, $html = FALSE, &$contact, &$verp, &$urls, $event_queue_id) {
1436 $type = $token_a['type'];
1437 $token = $token_a['token'];
1440 $useSmarty = defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY ?
TRUE : FALSE;
1442 if ($type == 'embedded_url') {
1443 $embed_data = array();
1444 foreach ($token as $t) {
1445 $embed_data[] = $this->getTokenData($t, $html = FALSE, $contact, $verp, $urls, $event_queue_id);
1447 $numSlices = count($embed_data);
1449 for ($i = 0; $i < $numSlices; $i++
) {
1450 $url .= "{$token_a['embed_parts'][$i]}{$embed_data[$i]}";
1452 if (isset($token_a['embed_parts'][$numSlices])) {
1453 $url .= $token_a['embed_parts'][$numSlices];
1455 // add trailing quote since we've gobbled it up in a previous regex
1456 // function getPatterns, line 431
1457 if (preg_match('/^href[ ]*=[ ]*\'/', $url)) {
1460 elseif (preg_match('/^href[ ]*=[ ]*\"/', $url)) {
1465 elseif ($type == 'url') {
1466 if ($this->url_tracking
) {
1467 $data = CRM_Mailing_BAO_TrackableURL
::getTrackerURL($token, $this->id
, $event_queue_id);
1468 if (!empty($html)) {
1469 $data = htmlentities($data);
1476 elseif ($type == 'contact') {
1477 $data = CRM_Utils_Token
::getContactTokenReplacement($token, $contact, FALSE, FALSE, $useSmarty);
1479 elseif ($type == 'action') {
1480 $data = CRM_Utils_Token
::getActionTokenReplacement($token, $verp, $urls, $html);
1482 elseif ($type == 'domain') {
1483 $domain = CRM_Core_BAO_Domain
::getDomain();
1484 $data = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain, $html);
1486 elseif ($type == 'mailing') {
1487 if ($token == 'name') {
1488 $data = $this->name
;
1490 elseif ($token == 'group') {
1491 $groups = $this->getGroupNames();
1492 $data = implode(', ', $groups);
1496 $data = CRM_Utils_Array
::value("{$type}.{$token}", $contact);
1502 * Return a list of group names for this mailing. Does not work with
1503 * prior-mailing targets.
1505 * @return array Names of groups receiving this mailing
1507 public function &getGroupNames() {
1508 if (!isset($this->id
)) {
1511 $mg = new CRM_Mailing_DAO_MailingGroup();
1512 $mgtable = CRM_Mailing_DAO_MailingGroup
::getTableName();
1513 $group = CRM_Contact_BAO_Group
::getTableName();
1515 $mg->query("SELECT $group.title as name FROM $mgtable
1516 INNER JOIN $group ON $mgtable.entity_id = $group.id
1517 WHERE $mgtable.mailing_id = {$this->id}
1518 AND $mgtable.entity_table = '$group'
1519 AND $mgtable.group_type = 'Include'
1520 ORDER BY $group.name");
1523 while ($mg->fetch()) {
1524 $groups[] = $mg->name
;
1533 * @param array $params
1534 * Reference array contains the values submitted by the form.
1536 * Reference array contains the id.
1542 public static function add(&$params, $ids = array()) {
1543 $id = CRM_Utils_Array
::value('mailing_id', $ids, CRM_Utils_Array
::value('id', $params));
1546 CRM_Utils_Hook
::pre('edit', 'Mailing', $id, $params);
1549 CRM_Utils_Hook
::pre('create', 'Mailing', NULL, $params);
1552 $mailing = new static();
1554 $mailing->domain_id
= CRM_Utils_Array
::value('domain_id', $params, CRM_Core_Config
::domainID());
1556 if (!isset($params['replyto_email']) &&
1557 isset($params['from_email'])
1559 $params['replyto_email'] = $params['from_email'];
1562 $mailing->copyValues($params);
1564 $result = $mailing->save();
1566 if (!empty($ids['mailing'])) {
1567 CRM_Utils_Hook
::post('edit', 'Mailing', $mailing->id
, $mailing);
1570 CRM_Utils_Hook
::post('create', 'Mailing', $mailing->id
, $mailing);
1577 * Construct a new mailing object, along with job and mailing_group
1578 * objects, from the form values of the create mailing wizard.
1580 * @params array $params
1583 * @param array $params
1586 * @return object $mailing The new mailing object
1589 public static function create(&$params, $ids = array()) {
1592 // Do the below only for an insert
1593 // for an update, we should not set the defaults
1594 if (!isset($ids['id']) && !isset($ids['mailing_id'])) {
1595 // Retrieve domain email and name for default sender
1596 $domain = civicrm_api(
1601 'current_domain' => 1,
1605 if (isset($domain['from_email'])) {
1606 $domain_email = $domain['from_email'];
1607 $domain_name = $domain['from_name'];
1610 $domain_email = 'info@EXAMPLE.ORG';
1611 $domain_name = 'EXAMPLE.ORG';
1613 if (!isset($params['created_id'])) {
1614 $session =& CRM_Core_Session
::singleton();
1615 $params['created_id'] = $session->get('userID');
1618 // load the default config settings for each
1619 // eg reply_id, unsubscribe_id need to use
1620 // correct template IDs here
1621 'override_verp' => TRUE,
1622 'forward_replies' => FALSE,
1623 'open_tracking' => TRUE,
1624 'url_tracking' => TRUE,
1625 'visibility' => 'Public Pages',
1626 'replyto_email' => $domain_email,
1627 'header_id' => CRM_Mailing_PseudoConstant
::defaultComponent('header_id', ''),
1628 'footer_id' => CRM_Mailing_PseudoConstant
::defaultComponent('footer_id', ''),
1629 'from_email' => $domain_email,
1630 'from_name' => $domain_name,
1631 'msg_template_id' => NULL,
1632 'created_id' => $params['created_id'],
1633 'approver_id' => NULL,
1634 'auto_responder' => 0,
1635 'created_date' => date('YmdHis'),
1636 'scheduled_date' => NULL,
1637 'approval_date' => NULL,
1640 // Get the default from email address, if not provided.
1641 if (empty($defaults['from_email'])) {
1642 $defaultAddress = CRM_Core_OptionGroup
::values('from_email_address', NULL, NULL, NULL, ' AND is_default = 1');
1643 foreach ($defaultAddress as $id => $value) {
1644 if (preg_match('/"(.*)" <(.*)>/', $value, $match)) {
1645 $defaults['from_email'] = $match[2];
1646 $defaults['from_name'] = $match[1];
1651 $params = array_merge($defaults, $params);
1655 * Could check and warn for the following cases:
1657 * - groups OR mailings should be populated.
1658 * - body html OR body text should be populated.
1661 $transaction = new CRM_Core_Transaction();
1663 $mailing = self
::add($params, $ids);
1665 if (is_a($mailing, 'CRM_Core_Error')) {
1666 $transaction->rollback();
1669 // update mailings with hash values
1670 CRM_Contact_BAO_Contact_Utils
::generateChecksum($mailing->id
, NULL, NULL, NULL, 'mailing', 16);
1672 $groupTableName = CRM_Contact_BAO_Group
::getTableName();
1673 $mailingTableName = CRM_Mailing_BAO_Mailing
::getTableName();
1675 /* Create the mailing group record */
1676 $mg = new CRM_Mailing_DAO_MailingGroup();
1677 foreach (array('groups', 'mailings') as $entity) {
1678 foreach (array('include', 'exclude', 'base') as $type) {
1679 if (isset($params[$entity][$type])) {
1680 self
::replaceGroups($mailing->id
, $type, $entity, $params[$entity][$type]);
1685 if (!empty($params['search_id']) && !empty($params['group_id'])) {
1687 $mg->mailing_id
= $mailing->id
;
1688 $mg->entity_table
= $groupTableName;
1689 $mg->entity_id
= $params['group_id'];
1690 $mg->search_id
= $params['search_id'];
1691 $mg->search_args
= $params['search_args'];
1692 $mg->group_type
= 'Include';
1696 // check and attach and files as needed
1697 CRM_Core_BAO_File
::processAttachment($params, 'civicrm_mailing', $mailing->id
);
1699 $transaction->commit();
1702 * create parent job if not yet created
1703 * condition on the existence of a scheduled date
1705 if (!empty($params['scheduled_date']) && $params['scheduled_date'] != 'null') {
1706 $job = new CRM_Mailing_BAO_MailingJob();
1707 $job->mailing_id
= $mailing->id
;
1708 $job->status
= 'Scheduled';
1711 if (!$job->find(TRUE)) {
1712 $job->scheduled_date
= $params['scheduled_date'];
1716 // Populate the recipients.
1717 if (empty($params['_skip_evil_bao_auto_recipients_'])) {
1718 self
::getRecipients($job->id
, $mailing->id
, NULL, NULL, TRUE, FALSE);
1726 * Replace the list of recipients on a given mailing
1728 * @param int $mailingId
1729 * @param string $type
1730 * 'include' or 'exclude'.
1731 * @param string $entity
1732 * 'groups' or 'mailings'.
1733 * @param array<int> $entityIds
1734 * @throws CiviCRM_API3_Exception
1736 public static function replaceGroups($mailingId, $type, $entity, $entityIds) {
1738 foreach ($entityIds as $entityId) {
1739 $values[] = array('entity_id' => $entityId);
1741 civicrm_api3('mailing_group', 'replace', array(
1742 'mailing_id' => $mailingId,
1743 'group_type' => $type,
1744 'entity_table' => ($entity == 'groups') ? CRM_Contact_BAO_Group
::getTableName() : CRM_Mailing_BAO_Mailing
::getTableName(),
1745 'values' => $values,
1750 * Get hash value of the mailing
1752 public static function getMailingHash($id) {
1754 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
, 'hash_mailing_url')) {
1755 $hash = CRM_Core_DAO
::getFieldValue('CRM_Mailing_BAO_Mailing', $id, 'hash', 'id');
1761 * Generate a report. Fetch event count information, mailing data, and job
1765 * The mailing id to report.
1766 * @param bool $skipDetails
1767 * Whether return all detailed report.
1769 * @param bool $isSMS
1771 * @return array Associative array of reporting data
1774 public static function &report($id, $skipDetails = FALSE, $isSMS = FALSE) {
1775 $mailing_id = CRM_Utils_Type
::escape($id, 'Integer');
1777 $mailing = new CRM_Mailing_BAO_Mailing();
1780 'mailing' => self
::getTableName(),
1781 'mailing_group' => CRM_Mailing_DAO_MailingGroup
::getTableName(),
1782 'group' => CRM_Contact_BAO_Group
::getTableName(),
1783 'job' => CRM_Mailing_BAO_MailingJob
::getTableName(),
1784 'queue' => CRM_Mailing_Event_BAO_Queue
::getTableName(),
1785 'delivered' => CRM_Mailing_Event_BAO_Delivered
::getTableName(),
1786 'opened' => CRM_Mailing_Event_BAO_Opened
::getTableName(),
1787 'reply' => CRM_Mailing_Event_BAO_Reply
::getTableName(),
1788 'unsubscribe' => CRM_Mailing_Event_BAO_Unsubscribe
::getTableName(),
1789 'bounce' => CRM_Mailing_Event_BAO_Bounce
::getTableName(),
1790 'forward' => CRM_Mailing_Event_BAO_Forward
::getTableName(),
1791 'url' => CRM_Mailing_BAO_TrackableURL
::getTableName(),
1793 CRM_Mailing_Event_BAO_TrackableURLOpen
::getTableName(),
1794 'component' => CRM_Mailing_BAO_Component
::getTableName(),
1795 'spool' => CRM_Mailing_BAO_Spool
::getTableName(),
1799 $additionalWhereClause = " AND ";
1801 $additionalWhereClause .= " {$t['mailing']}.sms_provider_id IS NULL ";
1804 $additionalWhereClause .= " {$t['mailing']}.sms_provider_id IS NOT NULL ";
1807 /* Get the mailing info */
1810 SELECT {$t['mailing']}.*
1811 FROM {$t['mailing']}
1812 WHERE {$t['mailing']}.id = $mailing_id {$additionalWhereClause}");
1816 $report['mailing'] = array();
1817 foreach (array_keys(self
::fields()) as $field) {
1818 $report['mailing'][$field] = $mailing->$field;
1822 if ($campaignId = CRM_Utils_Array
::value('campaign_id', $report['mailing'])) {
1823 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1824 $report['mailing']['campaign'] = $campaigns[$campaignId];
1827 //mailing report is called by activity
1828 //we dont need all detail report
1833 /* Get the component info */
1837 $components = array(
1838 'header' => ts('Header'),
1839 'footer' => ts('Footer'),
1840 'reply' => ts('Reply'),
1841 'unsubscribe' => ts('Unsubscribe'),
1842 'optout' => ts('Opt-Out'),
1844 foreach (array_keys($components) as $type) {
1845 $query[] = "SELECT {$t['component']}.name as name,
1847 {$t['component']}.id as id
1848 FROM {$t['component']}
1849 INNER JOIN {$t['mailing']}
1850 ON {$t['mailing']}.{$type}_id =
1851 {$t['component']}.id
1852 WHERE {$t['mailing']}.id = $mailing_id";
1854 $q = '(' . implode(') UNION (', $query) . ')';
1855 $mailing->query($q);
1857 $report['component'] = array();
1858 while ($mailing->fetch()) {
1859 $report['component'][] = array(
1860 'type' => $components[$mailing->type
],
1861 'name' => $mailing->name
,
1863 CRM_Utils_System
::url('civicrm/mailing/component',
1864 "reset=1&action=update&id={$mailing->id}"
1869 /* Get the recipient group info */
1872 SELECT {$t['mailing_group']}.group_type as group_type,
1873 {$t['group']}.id as group_id,
1874 {$t['group']}.title as group_title,
1875 {$t['group']}.is_hidden as group_hidden,
1876 {$t['mailing']}.id as mailing_id,
1877 {$t['mailing']}.name as mailing_name
1878 FROM {$t['mailing_group']}
1879 LEFT JOIN {$t['group']}
1880 ON {$t['mailing_group']}.entity_id = {$t['group']}.id
1881 AND {$t['mailing_group']}.entity_table =
1883 LEFT JOIN {$t['mailing']}
1884 ON {$t['mailing_group']}.entity_id =
1886 AND {$t['mailing_group']}.entity_table =
1889 WHERE {$t['mailing_group']}.mailing_id = $mailing_id
1892 $report['group'] = array('include' => array(), 'exclude' => array(), 'base' => array());
1893 while ($mailing->fetch()) {
1895 if (isset($mailing->group_id
)) {
1896 $row['id'] = $mailing->group_id
;
1897 $row['name'] = $mailing->group_title
;
1898 $row['link'] = CRM_Utils_System
::url('civicrm/group/search',
1899 "reset=1&force=1&context=smog&gid={$row['id']}"
1903 $row['id'] = $mailing->mailing_id
;
1904 $row['name'] = $mailing->mailing_name
;
1905 $row['mailing'] = TRUE;
1906 $row['link'] = CRM_Utils_System
::url('civicrm/mailing/report',
1911 /* Rename hidden groups */
1913 if ($mailing->group_hidden
== 1) {
1914 $row['name'] = "Search Results";
1917 if ($mailing->group_type
== 'Include') {
1918 $report['group']['include'][] = $row;
1920 elseif ($mailing->group_type
== 'Base') {
1921 $report['group']['base'][] = $row;
1924 $report['group']['exclude'][] = $row;
1928 /* Get the event totals, grouped by job (retries) */
1931 SELECT {$t['job']}.*,
1932 COUNT(DISTINCT {$t['queue']}.id) as queue,
1933 COUNT(DISTINCT {$t['delivered']}.id) as delivered,
1934 COUNT(DISTINCT {$t['reply']}.id) as reply,
1935 COUNT(DISTINCT {$t['forward']}.id) as forward,
1936 COUNT(DISTINCT {$t['bounce']}.id) as bounce,
1937 COUNT(DISTINCT {$t['urlopen']}.id) as url,
1938 COUNT(DISTINCT {$t['spool']}.id) as spool
1940 LEFT JOIN {$t['queue']}
1941 ON {$t['queue']}.job_id = {$t['job']}.id
1942 LEFT JOIN {$t['reply']}
1943 ON {$t['reply']}.event_queue_id = {$t['queue']}.id
1944 LEFT JOIN {$t['forward']}
1945 ON {$t['forward']}.event_queue_id = {$t['queue']}.id
1946 LEFT JOIN {$t['bounce']}
1947 ON {$t['bounce']}.event_queue_id = {$t['queue']}.id
1948 LEFT JOIN {$t['delivered']}
1949 ON {$t['delivered']}.event_queue_id = {$t['queue']}.id
1950 AND {$t['bounce']}.id IS null
1951 LEFT JOIN {$t['urlopen']}
1952 ON {$t['urlopen']}.event_queue_id = {$t['queue']}.id
1953 LEFT JOIN {$t['spool']}
1954 ON {$t['spool']}.job_id = {$t['job']}.id
1955 WHERE {$t['job']}.mailing_id = $mailing_id
1956 AND {$t['job']}.is_test = 0
1957 GROUP BY {$t['job']}.id");
1959 $report['jobs'] = array();
1960 $report['event_totals'] = array();
1962 'queue', 'delivered', 'url', 'forward',
1963 'reply', 'unsubscribe', 'optout', 'opened', 'bounce', 'spool',
1966 // initialize various counters
1967 foreach ($elements as $field) {
1968 $report['event_totals'][$field] = 0;
1971 while ($mailing->fetch()) {
1973 foreach ($elements as $field) {
1974 if (isset($mailing->$field)) {
1975 $row[$field] = $mailing->$field;
1976 $report['event_totals'][$field] +
= $mailing->$field;
1980 // compute open total separately to discount duplicates
1982 $row['opened'] = CRM_Mailing_Event_BAO_Opened
::getTotalCount($mailing_id, $mailing->id
, TRUE);
1983 $report['event_totals']['opened'] +
= $row['opened'];
1985 // compute unsub total separately to discount duplicates
1987 $row['unsubscribe'] = CRM_Mailing_Event_BAO_Unsubscribe
::getTotalCount($mailing_id, $mailing->id
, TRUE, TRUE);
1988 $report['event_totals']['unsubscribe'] +
= $row['unsubscribe'];
1990 $row['optout'] = CRM_Mailing_Event_BAO_Unsubscribe
::getTotalCount($mailing_id, $mailing->id
, TRUE, FALSE);
1991 $report['event_totals']['optout'] +
= $row['optout'];
1993 foreach (array_keys(CRM_Mailing_BAO_MailingJob
::fields()) as $field) {
1994 $row[$field] = $mailing->$field;
1997 if ($mailing->queue
) {
1998 $row['delivered_rate'] = (100.0 * $mailing->delivered
) / $mailing->queue
;
1999 $row['bounce_rate'] = (100.0 * $mailing->bounce
) / $mailing->queue
;
2000 $row['unsubscribe_rate'] = (100.0 * $row['unsubscribe']) / $mailing->queue
;
2001 $row['optout_rate'] = (100.0 * $row['optout']) / $mailing->queue
;
2004 $row['delivered_rate'] = 0;
2005 $row['bounce_rate'] = 0;
2006 $row['unsubscribe_rate'] = 0;
2007 $row['optout_rate'] = 0;
2010 $row['links'] = array(
2011 'clicks' => CRM_Utils_System
::url(
2012 'civicrm/mailing/report/event',
2013 "reset=1&event=click&mid=$mailing_id&jid={$mailing->id}"
2015 'queue' => CRM_Utils_System
::url(
2016 'civicrm/mailing/report/event',
2017 "reset=1&event=queue&mid=$mailing_id&jid={$mailing->id}"
2019 'delivered' => CRM_Utils_System
::url(
2020 'civicrm/mailing/report/event',
2021 "reset=1&event=delivered&mid=$mailing_id&jid={$mailing->id}"
2023 'bounce' => CRM_Utils_System
::url(
2024 'civicrm/mailing/report/event',
2025 "reset=1&event=bounce&mid=$mailing_id&jid={$mailing->id}"
2027 'unsubscribe' => CRM_Utils_System
::url(
2028 'civicrm/mailing/report/event',
2029 "reset=1&event=unsubscribe&mid=$mailing_id&jid={$mailing->id}"
2031 'forward' => CRM_Utils_System
::url(
2032 'civicrm/mailing/report/event',
2033 "reset=1&event=forward&mid=$mailing_id&jid={$mailing->id}"
2035 'reply' => CRM_Utils_System
::url(
2036 'civicrm/mailing/report/event',
2037 "reset=1&event=reply&mid=$mailing_id&jid={$mailing->id}"
2039 'opened' => CRM_Utils_System
::url(
2040 'civicrm/mailing/report/event',
2041 "reset=1&event=opened&mid=$mailing_id&jid={$mailing->id}"
2046 'scheduled_date', 'start_date', 'end_date') as $key) {
2047 $row[$key] = CRM_Utils_Date
::customFormat($row[$key]);
2049 $report['jobs'][] = $row;
2052 $newTableSize = CRM_Mailing_BAO_Recipients
::mailingSize($mailing_id);
2054 // we need to do this for backward compatibility, since old mailings did not
2055 // use the mailing_recipients table
2056 if ($newTableSize > 0) {
2057 $report['event_totals']['queue'] = $newTableSize;
2060 $report['event_totals']['queue'] = self
::getRecipientsCount($mailing_id, $mailing_id);
2063 if (!empty($report['event_totals']['queue'])) {
2064 $report['event_totals']['delivered_rate'] = (100.0 * $report['event_totals']['delivered']) / $report['event_totals']['queue'];
2065 $report['event_totals']['bounce_rate'] = (100.0 * $report['event_totals']['bounce']) / $report['event_totals']['queue'];
2066 $report['event_totals']['unsubscribe_rate'] = (100.0 * $report['event_totals']['unsubscribe']) / $report['event_totals']['queue'];
2067 $report['event_totals']['optout_rate'] = (100.0 * $report['event_totals']['optout']) / $report['event_totals']['queue'];
2070 $report['event_totals']['delivered_rate'] = 0;
2071 $report['event_totals']['bounce_rate'] = 0;
2072 $report['event_totals']['unsubscribe_rate'] = 0;
2073 $report['event_totals']['optout_rate'] = 0;
2076 /* Get the click-through totals, grouped by URL */
2079 SELECT {$t['url']}.url,
2081 COUNT({$t['urlopen']}.id) as clicks,
2082 COUNT(DISTINCT {$t['queue']}.id) as unique_clicks
2084 LEFT JOIN {$t['urlopen']}
2085 ON {$t['urlopen']}.trackable_url_id = {$t['url']}.id
2086 LEFT JOIN {$t['queue']}
2087 ON {$t['urlopen']}.event_queue_id = {$t['queue']}.id
2088 LEFT JOIN {$t['job']}
2089 ON {$t['queue']}.job_id = {$t['job']}.id
2090 WHERE {$t['url']}.mailing_id = $mailing_id
2091 AND {$t['job']}.is_test = 0
2092 GROUP BY {$t['url']}.id");
2094 $report['click_through'] = array();
2096 while ($mailing->fetch()) {
2097 $report['click_through'][] = array(
2098 'url' => $mailing->url
,
2100 CRM_Utils_System
::url(
2101 'civicrm/mailing/report/event',
2102 "reset=1&event=click&mid=$mailing_id&uid={$mailing->id}"
2105 CRM_Utils_System
::url(
2106 'civicrm/mailing/report/event',
2107 "reset=1&event=click&mid=$mailing_id&uid={$mailing->id}&distinct=1"
2109 'clicks' => $mailing->clicks
,
2110 'unique' => $mailing->unique_clicks
,
2111 'rate' => CRM_Utils_Array
::value('delivered', $report['event_totals']) ?
(100.0 * $mailing->unique_clicks
) / $report['event_totals']['delivered'] : 0,
2115 $report['event_totals']['links'] = array(
2116 'clicks' => CRM_Utils_System
::url(
2117 'civicrm/mailing/report/event',
2118 "reset=1&event=click&mid=$mailing_id"
2120 'clicks_unique' => CRM_Utils_System
::url(
2121 'civicrm/mailing/report/event',
2122 "reset=1&event=click&mid=$mailing_id&distinct=1"
2124 'queue' => CRM_Utils_System
::url(
2125 'civicrm/mailing/report/event',
2126 "reset=1&event=queue&mid=$mailing_id"
2128 'delivered' => CRM_Utils_System
::url(
2129 'civicrm/mailing/report/event',
2130 "reset=1&event=delivered&mid=$mailing_id"
2132 'bounce' => CRM_Utils_System
::url(
2133 'civicrm/mailing/report/event',
2134 "reset=1&event=bounce&mid=$mailing_id"
2136 'unsubscribe' => CRM_Utils_System
::url(
2137 'civicrm/mailing/report/event',
2138 "reset=1&event=unsubscribe&mid=$mailing_id"
2140 'optout' => CRM_Utils_System
::url(
2141 'civicrm/mailing/report/event',
2142 "reset=1&event=optout&mid=$mailing_id"
2144 'forward' => CRM_Utils_System
::url(
2145 'civicrm/mailing/report/event',
2146 "reset=1&event=forward&mid=$mailing_id"
2148 'reply' => CRM_Utils_System
::url(
2149 'civicrm/mailing/report/event',
2150 "reset=1&event=reply&mid=$mailing_id"
2152 'opened' => CRM_Utils_System
::url(
2153 'civicrm/mailing/report/event',
2154 "reset=1&event=opened&mid=$mailing_id"
2158 $actionLinks = array(CRM_Core_Action
::VIEW
=> array('name' => ts('Report')));
2159 if (CRM_Core_Permission
::check('view all contacts')) {
2160 $actionLinks[CRM_Core_Action
::ADVANCED
] =
2162 'name' => ts('Advanced Search'),
2163 'url' => 'civicrm/contact/search/advanced',
2166 $action = array_sum(array_keys($actionLinks));
2168 $report['event_totals']['actionlinks'] = array();
2170 'clicks', 'clicks_unique', 'queue', 'delivered', 'bounce', 'unsubscribe',
2171 'forward', 'reply', 'opened', 'optout',
2173 $url = 'mailing/detail';
2174 $reportFilter = "reset=1&mailing_id_value={$mailing_id}";
2175 $searchFilter = "force=1&mailing_id=%%mid%%";
2178 $reportFilter .= "&delivery_status_value=successful";
2179 $searchFilter .= "&mailing_delivery_status=Y";
2183 $url = "mailing/bounce";
2184 $searchFilter .= "&mailing_delivery_status=N";
2188 $reportFilter .= "&is_forwarded_value=1";
2189 $searchFilter .= "&mailing_forward=1";
2193 $reportFilter .= "&is_replied_value=1";
2194 $searchFilter .= "&mailing_reply_status=Y";
2198 $reportFilter .= "&is_unsubscribed_value=1";
2199 $searchFilter .= "&mailing_unsubscribe=1";
2203 $reportFilter .= "&is_optout_value=1";
2204 $searchFilter .= "&mailing_optout=1";
2208 $url = "mailing/opened";
2209 $searchFilter .= "&mailing_open_status=Y";
2213 case 'clicks_unique':
2214 $url = "mailing/clicks";
2215 $searchFilter .= "&mailing_click_status=Y";
2218 $actionLinks[CRM_Core_Action
::VIEW
]['url'] = CRM_Report_Utils_Report
::getNextUrl($url, $reportFilter, FALSE, TRUE);
2219 if (array_key_exists(CRM_Core_Action
::ADVANCED
, $actionLinks)) {
2220 $actionLinks[CRM_Core_Action
::ADVANCED
]['qs'] = $searchFilter;
2222 $report['event_totals']['actionlinks'][$key] = CRM_Core_Action
::formLink(
2225 array('mid' => $mailing_id),
2228 'mailing.report.action',
2238 * Get the count of mailings
2244 public function getCount() {
2246 $this->selectAdd('COUNT(id) as count');
2248 $session = CRM_Core_Session
::singleton();
2251 return $this->count
;
2259 public static function checkPermission($id) {
2264 $mailingIDs = self
::mailingACLIDs();
2265 if ($mailingIDs === TRUE) {
2269 if (!in_array($id, $mailingIDs)) {
2270 CRM_Core_Error
::fatal(ts('You do not have permission to access this mailing report'));
2276 * @param null $alias
2280 public static function mailingACL($alias = NULL) {
2281 $mailingACL = " ( 0 ) ";
2283 $mailingIDs = self
::mailingACLIDs();
2284 if ($mailingIDs === TRUE) {
2288 if (!empty($mailingIDs)) {
2289 $mailingIDs = implode(',', $mailingIDs);
2290 $tableName = !$alias ? self
::getTableName() : $alias;
2291 $mailingACL = " $tableName.id IN ( $mailingIDs ) ";
2297 * Returns all the mailings that this user can access. This is dependent on
2298 * all the groups that the user has access to.
2299 * However since most civi installs dont use ACL's we special case the condition
2300 * where the user has access to ALL groups, and hence ALL mailings and return a
2301 * value of TRUE (to avoid the downstream where clause with a list of mailing list IDs
2303 * @return boolean | array - TRUE if the user has access to all mailings, else array of mailing IDs (possibly empty)
2306 public static function mailingACLIDs() {
2308 // optimize common case where admin has access
2311 CRM_Core_Permission
::check('view all contacts') ||
2312 CRM_Core_Permission
::check('edit all contacts')
2317 $mailingIDs = array();
2319 // get all the groups that this user can access
2320 // if they dont have universal access
2321 $groups = CRM_Core_PseudoConstant
::group(NULL, FALSE);
2322 if (!empty($groups)) {
2323 $groupIDs = implode(',', array_keys($groups));
2325 // get all the mailings that are in this subset of groups
2327 SELECT DISTINCT( m.id ) as id
2328 FROM civicrm_mailing m
2329 LEFT JOIN civicrm_mailing_group g ON g.mailing_id = m.id
2330 WHERE ( ( g.entity_table like 'civicrm_group%' AND g.entity_id IN ( $groupIDs ) )
2331 OR ( g.entity_table IS NULL AND g.entity_id IS NULL ) )
2333 $dao = CRM_Core_DAO
::executeQuery($query);
2335 $mailingIDs = array();
2336 while ($dao->fetch()) {
2337 $mailingIDs[] = $dao->id
;
2345 * Get the rows for a browse operation
2347 * @param int $offset
2348 * The row number to start from.
2349 * @param int $rowCount
2350 * The nmber of rows to return.
2351 * @param string $sort
2352 * The sql string that describes the sort order.
2354 * @param null $additionalClause
2355 * @param array $additionalParams
2357 * @return array The rows
2359 public function &getRows($offset, $rowCount, $sort, $additionalClause = NULL, $additionalParams = NULL) {
2360 $mailing = self
::getTableName();
2361 $job = CRM_Mailing_BAO_MailingJob
::getTableName();
2362 $group = CRM_Mailing_DAO_MailingGroup
::getTableName();
2363 $session = CRM_Core_Session
::singleton();
2365 $mailingACL = self
::mailingACL();
2367 //get all campaigns.
2368 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
2370 // we only care about parent jobs, since that holds all the info on
2376 $mailing.approval_status_id,
2377 MIN($job.scheduled_date) as scheduled_date,
2378 MIN($job.start_date) as start_date,
2379 MAX($job.end_date) as end_date,
2380 createdContact.sort_name as created_by,
2381 scheduledContact.sort_name as scheduled_by,
2382 $mailing.created_id as created_id,
2383 $mailing.scheduled_id as scheduled_id,
2384 $mailing.is_archived as archived,
2385 $mailing.created_date as created_date,
2387 $mailing.sms_provider_id as sms_provider_id
2389 LEFT JOIN $job ON ( $job.mailing_id = $mailing.id AND $job.is_test = 0 AND $job.parent_id IS NULL )
2390 LEFT JOIN civicrm_contact createdContact ON ( civicrm_mailing.created_id = createdContact.id )
2391 LEFT JOIN civicrm_contact scheduledContact ON ( civicrm_mailing.scheduled_id = scheduledContact.id )
2392 WHERE $mailingACL $additionalClause
2393 GROUP BY $mailing.id ";
2396 $orderBy = trim($sort->orderBy());
2397 if (!empty($orderBy)) {
2398 $query .= " ORDER BY $orderBy";
2403 $offset = CRM_Utils_Type
::escape($offset, 'Int');
2404 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
2406 $query .= " LIMIT $offset, $rowCount ";
2409 if (!$additionalParams) {
2410 $additionalParams = array();
2413 $dao = CRM_Core_DAO
::executeQuery($query, $additionalParams);
2416 while ($dao->fetch()) {
2419 'name' => $dao->name
,
2420 'status' => $dao->status ?
$dao->status
: 'Not scheduled',
2421 'created_date' => CRM_Utils_Date
::customFormat($dao->created_date
),
2422 'scheduled' => CRM_Utils_Date
::customFormat($dao->scheduled_date
),
2423 'scheduled_iso' => $dao->scheduled_date
,
2424 'start' => CRM_Utils_Date
::customFormat($dao->start_date
),
2425 'end' => CRM_Utils_Date
::customFormat($dao->end_date
),
2426 'created_by' => $dao->created_by
,
2427 'scheduled_by' => $dao->scheduled_by
,
2428 'created_id' => $dao->created_id
,
2429 'scheduled_id' => $dao->scheduled_id
,
2430 'archived' => $dao->archived
,
2431 'approval_status_id' => $dao->approval_status_id
,
2432 'campaign_id' => $dao->campaign_id
,
2433 'campaign' => empty($dao->campaign_id
) ?
NULL : $allCampaigns[$dao->campaign_id
],
2434 'sms_provider_id' => $dao->sms_provider_id
,
2441 * Show detail Mailing report
2448 public static function showEmailDetails($id) {
2449 return CRM_Utils_System
::url('civicrm/mailing/report', "mid=$id");
2453 * Delete Mails and all its associated records
2456 * Id of the mail to delete.
2461 public static function del($id) {
2463 CRM_Core_Error
::fatal();
2466 CRM_Utils_Hook
::pre('delete', 'Mailing', $id, CRM_Core_DAO
::$_nullArray);
2468 // delete all file attachments
2469 CRM_Core_BAO_File
::deleteEntityFile('civicrm_mailing',
2473 $dao = new CRM_Mailing_DAO_Mailing();
2477 CRM_Core_Session
::setStatus(ts('Selected mailing has been deleted.'), ts('Deleted'), 'success');
2479 CRM_Utils_Hook
::post('delete', 'Mailing', $id, $dao);
2483 * Delete Jobss and all its associated records
2484 * related to test Mailings
2487 * Id of the Job to delete.
2492 public static function delJob($id) {
2494 CRM_Core_Error
::fatal();
2497 $dao = new CRM_Mailing_BAO_MailingJob();
2505 public function getReturnProperties() {
2506 $tokens = &$this->getTokens();
2508 $properties = array();
2509 if (isset($tokens['html']) &&
2510 isset($tokens['html']['contact'])
2512 $properties = array_merge($properties, $tokens['html']['contact']);
2515 if (isset($tokens['text']) &&
2516 isset($tokens['text']['contact'])
2518 $properties = array_merge($properties, $tokens['text']['contact']);
2521 if (isset($tokens['subject']) &&
2522 isset($tokens['subject']['contact'])
2524 $properties = array_merge($properties, $tokens['subject']['contact']);
2527 $returnProperties = array();
2528 $returnProperties['display_name'] = $returnProperties['contact_id'] = $returnProperties['preferred_mail_format'] = $returnProperties['hash'] = 1;
2530 foreach ($properties as $p) {
2531 $returnProperties[$p] = 1;
2534 return $returnProperties;
2538 * Build the compose mail form
2540 * @param CRM_Core_Form $form
2544 public static function commonCompose(&$form) {
2546 $tokens = CRM_Core_SelectValues
::contactTokens();
2548 $className = CRM_Utils_System
::getClassName($form);
2549 if ($className == 'CRM_Mailing_Form_Upload') {
2550 $tokens = array_merge(CRM_Core_SelectValues
::mailingTokens(), $tokens);
2552 elseif ($className == 'CRM_Admin_Form_ScheduleReminders') {
2553 $tokens = array_merge(CRM_Core_SelectValues
::activityTokens(), $tokens);
2554 $tokens = array_merge(CRM_Core_SelectValues
::eventTokens(), $tokens);
2555 $tokens = array_merge(CRM_Core_SelectValues
::membershipTokens(), $tokens);
2557 elseif ($className == 'CRM_Event_Form_ManageEvent_ScheduleReminders') {
2558 $tokens = array_merge(CRM_Core_SelectValues
::eventTokens(), $tokens);
2561 //sorted in ascending order tokens by ignoring word case
2562 $form->assign('tokens', CRM_Utils_Token
::formatTokensForDisplay($tokens));
2564 $templates = array();
2566 $textFields = array('text_message' => ts('HTML Format'), 'sms_text_message' => ts('SMS Message'));
2567 $modePrefixes = array('Mail' => NULL, 'SMS' => 'SMS');
2569 if ($className != 'CRM_SMS_Form_Upload' && $className != 'CRM_Contact_Form_Task_SMS' &&
2570 $className != 'CRM_Contact_Form_Task_SMS'
2572 $form->addWysiwyg('html_message',
2577 'onkeyup' => "return verify(this)",
2581 if ($className != 'CRM_Admin_Form_ScheduleReminders') {
2582 unset($modePrefixes['SMS']);
2586 unset($textFields['text_message']);
2587 unset($modePrefixes['Mail']);
2590 //insert message Text by selecting "Select Template option"
2591 foreach ($textFields as $id => $label) {
2593 if ($id == 'sms_text_message') {
2595 $form->assign('max_sms_length', CRM_SMS_Provider
::MAX_SMS_CHAR
);
2597 $form->add('textarea', $id, $label,
2601 'onkeyup' => "return verify(this, '{$prefix}')",
2606 foreach ($modePrefixes as $prefix) {
2607 if ($prefix == 'SMS') {
2608 $templates[$prefix] = CRM_Core_BAO_MessageTemplate
::getMessageTemplates(FALSE, TRUE);
2611 $templates[$prefix] = CRM_Core_BAO_MessageTemplate
::getMessageTemplates(FALSE);
2614 if (!empty($templates[$prefix])) {
2615 $form->assign('templates', TRUE);
2617 $form->add('select', "{$prefix}template", ts('Use Template'),
2618 array('' => ts('- select -')) +
$templates[$prefix], FALSE,
2619 array('onChange' => "selectValue( this.value, '{$prefix}');")
2622 $form->add('checkbox', "{$prefix}updateTemplate", ts('Update Template'), NULL);
2624 $form->add('checkbox', "{$prefix}saveTemplate", ts('Save As New Template'), NULL, FALSE,
2625 array('onclick' => "showSaveDetails(this, '{$prefix}');")
2627 $form->add('text', "{$prefix}saveTemplateName", ts('Template Title'));
2632 * Build the compose PDF letter form
2634 * @param CRM_Core_Form $form
2638 public static function commonLetterCompose(&$form) {
2640 $tokens = CRM_Core_SelectValues
::contactTokens();
2641 if (CRM_Utils_System
::getClassName($form) == 'CRM_Mailing_Form_Upload') {
2642 $tokens = array_merge(CRM_Core_SelectValues
::mailingTokens(), $tokens);
2644 //@todo move this fn onto the form
2645 if (CRM_Utils_System
::getClassName($form) == 'CRM_Contribute_Form_Task_PDFLetter') {
2646 $tokens = array_merge(CRM_Core_SelectValues
::contributionTokens(), $tokens);
2649 if (method_exists($form, 'listTokens')) {
2650 $tokens = array_merge($form->listTokens(), $tokens);
2653 $form->assign('tokens', CRM_Utils_Token
::formatTokensForDisplay($tokens));
2655 $form->_templates
= CRM_Core_BAO_MessageTemplate
::getMessageTemplates(FALSE);
2656 if (!empty($form->_templates
)) {
2657 $form->assign('templates', TRUE);
2658 $form->add('select', 'template', ts('Select Template'),
2660 '' => ts('- select -')) +
$form->_templates
, FALSE,
2661 array('onChange' => "selectValue( this.value,'' );")
2663 $form->add('checkbox', 'updateTemplate', ts('Update Template'), NULL);
2666 $form->add('checkbox', 'saveTemplate', ts('Save As New Template'), NULL, FALSE,
2667 array('onclick' => "showSaveDetails(this);")
2669 $form->add('text', 'saveTemplateName', ts('Template Title'));
2671 $form->addWysiwyg('html_message',
2676 'onkeyup' => "return verify(this)",
2679 $action = CRM_Utils_Request
::retrieve('action', 'String', $form, FALSE);
2680 if ((CRM_Utils_System
::getClassName($form) == 'CRM_Contact_Form_Task_PDF') &&
2681 $action == CRM_Core_Action
::VIEW
2683 $form->freeze('html_message');
2688 * Get the search based mailing Ids
2690 * @return array $mailingIDs, searched base mailing ids.
2692 public function searchMailingIDs() {
2693 $group = CRM_Mailing_DAO_MailingGroup
::getTableName();
2694 $mailing = self
::getTableName();
2697 SELECT $mailing.id as mailing_id
2698 FROM $mailing, $group
2699 WHERE $group.mailing_id = $mailing.id
2700 AND $group.group_type = 'Base'";
2702 $searchDAO = CRM_Core_DAO
::executeQuery($query);
2703 $mailingIDs = array();
2704 while ($searchDAO->fetch()) {
2705 $mailingIDs[] = $searchDAO->mailing_id
;
2712 * Get the content/components of mailing based on mailing Id
2714 * @param array $report
2715 * of mailing report.
2718 * Reference of this.
2720 * @param bool $isSMS
2722 * @return array $report array content/component.
2725 public static function getMailingContent(&$report, &$form, $isSMS = FALSE) {
2726 $htmlHeader = $textHeader = NULL;
2727 $htmlFooter = $textFooter = NULL;
2730 if ($report['mailing']['header_id']) {
2731 $header = new CRM_Mailing_BAO_Component();
2732 $header->id
= $report['mailing']['header_id'];
2733 $header->find(TRUE);
2734 $htmlHeader = $header->body_html
;
2735 $textHeader = $header->body_text
;
2738 if ($report['mailing']['footer_id']) {
2739 $footer = new CRM_Mailing_BAO_Component();
2740 $footer->id
= $report['mailing']['footer_id'];
2741 $footer->find(TRUE);
2742 $htmlFooter = $footer->body_html
;
2743 $textFooter = $footer->body_text
;
2747 $mailingKey = $form->_mailing_id
;
2749 if ($hash = CRM_Mailing_BAO_Mailing
::getMailingHash($mailingKey)) {
2750 $mailingKey = $hash;
2754 if (!empty($report['mailing']['body_text'])) {
2755 $url = CRM_Utils_System
::url('civicrm/mailing/view', 'reset=1&text=1&id=' . $mailingKey);
2756 $form->assign('textViewURL', $url);
2760 if (!empty($report['mailing']['body_html'])) {
2761 $url = CRM_Utils_System
::url('civicrm/mailing/view', 'reset=1&id=' . $mailingKey);
2762 $form->assign('htmlViewURL', $url);
2767 $report['mailing']['attachment'] = CRM_Core_BAO_File
::attachmentInfo('civicrm_mailing', $form->_mailing_id
);
2777 public static function overrideVerp($jobID) {
2778 static $_cache = array();
2780 if (!isset($_cache[$jobID])) {
2782 SELECT override_verp
2783 FROM civicrm_mailing
2784 INNER JOIN civicrm_mailing_job ON civicrm_mailing.id = civicrm_mailing_job.mailing_id
2785 WHERE civicrm_mailing_job.id = %1
2787 $params = array(1 => array($jobID, 'Integer'));
2788 $_cache[$jobID] = CRM_Core_DAO
::singleValueQuery($query, $params);
2790 return $_cache[$jobID];
2799 public static function processQueue($mode = NULL) {
2800 $config = &CRM_Core_Config
::singleton();
2802 if ($mode == NULL && CRM_Core_BAO_MailSettings
::defaultDomain() == "EXAMPLE.ORG") {
2803 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(1 => CRM_Utils_System
::url('civicrm/admin/mailSettings', 'reset=1'), 2 => "http://book.civicrm.org/user/advanced-configuration/email-system-configuration/")));
2806 // check if we are enforcing number of parallel cron jobs
2808 $gotCronLock = FALSE;
2810 if (property_exists($config, 'mailerJobsMax') && $config->mailerJobsMax
&& $config->mailerJobsMax
> 1) {
2811 $lockArray = range(1, $config->mailerJobsMax
);
2812 shuffle($lockArray);
2814 // check if we are using global locks
2815 $serverWideLock = CRM_Core_BAO_Setting
::getItem(
2816 CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
2817 'civimail_server_wide_lock'
2819 foreach ($lockArray as $lockID) {
2820 $cronLock = new CRM_Core_Lock("civimail.cronjob.{$lockID}", NULL, $serverWideLock);
2821 if ($cronLock->isAcquired()) {
2822 $gotCronLock = TRUE;
2827 // exit here since we have enuf cronjobs running
2828 if (!$gotCronLock) {
2829 CRM_Core_Error
::debug_log_message('Returning early, since max number of cronjobs running');
2834 // load bootstrap to call hooks
2836 // Split up the parent jobs into multiple child jobs
2837 $mailerJobSize = (property_exists($config, 'mailerJobSize')) ?
$config->mailerJobSize
: NULL;
2838 CRM_Mailing_BAO_MailingJob
::runJobs_pre($mailerJobSize, $mode);
2839 CRM_Mailing_BAO_MailingJob
::runJobs(NULL, $mode);
2840 CRM_Mailing_BAO_MailingJob
::runJobs_post($mode);
2842 // lets release the global cron lock if we do have one
2844 $cronLock->release();
2851 * @param int $mailingID
2853 private static function addMultipleEmails($mailingID) {
2855 INSERT INTO civicrm_mailing_recipients
2856 (mailing_id, email_id, contact_id)
2857 SELECT %1, e.id, e.contact_id FROM civicrm_email e
2859 AND e.is_bulkmail = 1
2861 ( SELECT contact_id FROM civicrm_mailing_recipients mr WHERE mailing_id = %1 )
2862 AND e.id NOT IN ( SELECT email_id FROM civicrm_mailing_recipients mr WHERE mailing_id = %1 )
2864 $params = array(1 => array($mailingID, 'Integer'));
2866 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2870 * @param bool $isSMS
2874 public static function getMailingsList($isSMS = FALSE) {
2875 static $list = array();
2878 $where .= " civicrm_mailing.sms_provider_id IS NULL ";
2881 $where .= " civicrm_mailing.sms_provider_id IS NOT NULL ";
2886 SELECT civicrm_mailing.id, civicrm_mailing.name, civicrm_mailing_job.end_date
2887 FROM civicrm_mailing
2888 INNER JOIN civicrm_mailing_job ON civicrm_mailing.id = civicrm_mailing_job.mailing_id {$where}
2889 ORDER BY civicrm_mailing.name";
2890 $mailing = CRM_Core_DAO
::executeQuery($query);
2892 while ($mailing->fetch()) {
2893 $list[$mailing->id
] = "{$mailing->name} :: {$mailing->end_date}";
2903 * @return null|string
2905 public static function hiddenMailingGroup($mid) {
2908 FROM civicrm_mailing m
2909 INNER JOIN civicrm_mailing_group mg ON mg.mailing_id = m.id
2910 INNER JOIN civicrm_group g ON mg.entity_id = g.id AND mg.entity_table = 'civicrm_group'
2911 WHERE g.is_hidden = 1
2912 AND mg.group_type = 'Include'
2915 $params = array(1 => array($mid, 'Integer'));
2916 return CRM_Core_DAO
::singleValueQuery($sql, $params);
2920 * This function is a wrapper for ajax activity selector
2922 * @param array $params
2923 * Associated array for params record id.
2925 * @return array $contactActivities associated array of contact activities
2927 public static function getContactMailingSelector(&$params) {
2928 // format the params
2929 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2930 $params['rowCount'] = $params['rp'];
2931 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
2932 $params['caseId'] = NULL;
2934 // get contact mailings
2935 $mailings = CRM_Mailing_BAO_Mailing
::getContactMailings($params);
2938 $params['total'] = CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2941 if (!empty($mailings)) {
2942 $openCounts = CRM_Mailing_Event_BAO_Opened
::getMailingContactCount(array_keys($mailings), $params['contact_id']);
2943 $clickCounts = CRM_Mailing_Event_BAO_TrackableURLOpen
::getMailingContactCount(array_keys($mailings), $params['contact_id']);
2946 // format params and add links
2947 $contactMailings = array();
2948 foreach ($mailings as $mailingId => $values) {
2949 $contactMailings[$mailingId]['subject'] = $values['subject'];
2950 $contactMailings[$mailingId]['start_date'] = CRM_Utils_Date
::customFormat($values['start_date']);
2951 $contactMailings[$mailingId]['recipients'] = CRM_Utils_System
::href(ts('(recipients)'), 'civicrm/mailing/report/event',
2952 "mid={$values['mailing_id']}&reset=1&cid={$params['contact_id']}&event=queue&context=mailing");
2954 $contactMailings[$mailingId]['mailing_creator'] = CRM_Utils_System
::href(
2955 $values['creator_name'],
2956 'civicrm/contact/view',
2957 "reset=1&cid={$values['creator_id']}");
2960 $contactMailings[$mailingId]['openstats'] = "Opens: " .
2961 CRM_Utils_Array
::value($values['mailing_id'], $openCounts, 0) .
2963 CRM_Utils_Array
::value($values['mailing_id'], $clickCounts, 0);
2965 $actionLinks = array(
2966 CRM_Core_Action
::VIEW
=> array(
2967 'name' => ts('View'),
2968 'url' => 'civicrm/mailing/view',
2969 'qs' => "reset=1&id=%%mkey%%",
2970 'title' => ts('View Mailing'),
2971 'class' => 'crm-popup',
2973 CRM_Core_Action
::BROWSE
=> array(
2974 'name' => ts('Mailing Report'),
2975 'url' => 'civicrm/mailing/report',
2976 'qs' => "mid=%%mid%%&reset=1&cid=%%cid%%&context=mailing",
2977 'title' => ts('View Mailing Report'),
2981 $mailingKey = $values['mailing_id'];
2982 if ($hash = CRM_Mailing_BAO_Mailing
::getMailingHash($mailingKey)) {
2983 $mailingKey = $hash;
2986 $contactMailings[$mailingId]['links'] = CRM_Core_Action
::formLink(
2990 'mid' => $values['mailing_id'],
2991 'cid' => $params['contact_id'],
2992 'mkey' => $mailingKey,
2996 'mailing.contact.action',
2998 $values['mailing_id']
3002 return $contactMailings;
3006 * Retrieve contact mailing
3008 * @param array $params
3011 * @return array of mailings for a contact
3015 static public function getContactMailings(&$params) {
3016 $params['version'] = 3;
3017 $params['offset'] = ($params['page'] - 1) * $params['rp'];
3018 $params['limit'] = $params['rp'];
3019 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
3021 $result = civicrm_api('MailingContact', 'get', $params);
3022 return $result['values'];
3026 * Retrieve contact mailing count
3028 * @param array $params
3031 * @return int count of mailings for a contact
3035 static public function getContactMailingsCount(&$params) {
3036 $params['version'] = 3;
3037 return civicrm_api('MailingContact', 'getcount', $params);