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 function __construct() {
95 parent
::__construct();
100 * @param int $mailing_id
105 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
115 * @param int $job_id (misnomer) a nonce value used to name temporary tables
116 * @param int $mailing_id
117 * @param null $offset
119 * @param bool $storeRecipients
120 * @param bool $dedupeEmail
123 * @return CRM_Mailing_Event_BAO_Queue|string
125 static function &getRecipients(
130 $storeRecipients = FALSE,
131 $dedupeEmail = FALSE,
133 $mailingGroup = new CRM_Mailing_DAO_MailingGroup();
135 $mailing = CRM_Mailing_BAO_Mailing
::getTableName();
136 $job = CRM_Mailing_BAO_MailingJob
::getTableName();
137 $mg = CRM_Mailing_DAO_MailingGroup
::getTableName();
138 $eq = CRM_Mailing_Event_DAO_Queue
::getTableName();
139 $ed = CRM_Mailing_Event_DAO_Delivered
::getTableName();
140 $eb = CRM_Mailing_Event_DAO_Bounce
::getTableName();
142 $email = CRM_Core_DAO_Email
::getTableName();
143 if ($mode == 'sms') {
144 $phone = CRM_Core_DAO_Phone
::getTableName();
146 $contact = CRM_Contact_DAO_Contact
::getTableName();
148 $group = CRM_Contact_DAO_Group
::getTableName();
149 $g2contact = CRM_Contact_DAO_GroupContact
::getTableName();
151 $m = new CRM_Mailing_DAO_Mailing();
152 $m->id
= $mailing_id;
155 $email_selection_method = $m->email_selection_method
;
156 $location_type_id = $m->location_type_id
;
158 // Note: When determining the ORDER that results are returned, it's
159 // the record that comes last that counts. That's because we are
160 // INSERT'ing INTO a table with a primary id so that last record
161 // over writes any previous record.
162 switch($email_selection_method) {
163 case 'location-exclude':
164 $location_filter = "($email.location_type_id != $location_type_id)";
165 // If there is more than one email that doesn't match the location,
166 // prefer the one marked is_bulkmail, followed by is_primary.
167 $order_by = "ORDER BY $email.is_bulkmail, $email.is_primary";
169 case 'location-only':
170 $location_filter = "($email.location_type_id = $location_type_id)";
171 // If there is more than one email of the desired location, prefer
172 // the one marked is_bulkmail, followed by is_primary.
173 $order_by = "ORDER BY $email.is_bulkmail, $email.is_primary";
175 case 'location-prefer':
176 $location_filter = "($email.is_bulkmail = 1 OR $email.is_primary = 1 OR $email.location_type_id = $location_type_id)";
178 // ORDER BY is more complicated because we have to set an arbitrary
179 // order that prefers the location that we want. We do that using
180 // the FIELD function. For more info, see:
181 // https://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_field
182 // We assign the location type we want the value "1" by putting it
183 // in the first position after we name the field. All other location
184 // types are left out, so they will be assigned the value 0. That
185 // means, they will all be equally tied for first place, with our
186 // location being last.
187 $order_by = "ORDER BY FIELD($email.location_type_id, $location_type_id), $email.is_bulkmail, $email.is_primary";
190 // fall through to default
192 $location_filter = "($email.is_bulkmail = 1 OR $email.is_primary = 1)";
193 $order_by = "ORDER BY $email.is_bulkmail";
196 /* Create a temp table for contact exclusion */
197 $mailingGroup->query(
198 "CREATE TEMPORARY TABLE X_$job_id
199 (contact_id int primary key)
203 /* Add all the members of groups excluded from this mailing to the temp
206 $excludeSubGroup = "INSERT INTO X_$job_id (contact_id)
207 SELECT DISTINCT $g2contact.contact_id
210 ON $g2contact.group_id = $mg.entity_id AND $mg.entity_table = '$group'
212 $mg.mailing_id = {$mailing_id}
213 AND $g2contact.status = 'Added'
214 AND $mg.group_type = 'Exclude'";
215 $mailingGroup->query($excludeSubGroup);
217 /* Add all unsubscribe members of base group from this mailing to the temp
220 $unSubscribeBaseGroup = "INSERT INTO X_$job_id (contact_id)
221 SELECT DISTINCT $g2contact.contact_id
224 ON $g2contact.group_id = $mg.entity_id AND $mg.entity_table = '$group'
226 $mg.mailing_id = {$mailing_id}
227 AND $g2contact.status = 'Removed'
228 AND $mg.group_type = 'Base'";
229 $mailingGroup->query($unSubscribeBaseGroup);
231 /* Add all the (intended) recipients of an excluded prior mailing to
234 $excludeSubMailing = "INSERT IGNORE INTO X_$job_id (contact_id)
235 SELECT DISTINCT $eq.contact_id
238 ON $eq.job_id = $job.id
240 ON $job.mailing_id = $mg.entity_id AND $mg.entity_table = '$mailing'
242 $mg.mailing_id = {$mailing_id}
243 AND $mg.group_type = 'Exclude'";
244 $mailingGroup->query($excludeSubMailing);
246 // get all the saved searches AND hierarchical groups
247 // and load them in the cache
249 SELECT $group.id, $group.cache_date, $group.saved_search_id, $group.children
251 INNER JOIN $mg ON $mg.entity_id = $group.id
252 WHERE $mg.entity_table = '$group'
253 AND $mg.group_type = 'Exclude'
254 AND $mg.mailing_id = {$mailing_id}
255 AND ( saved_search_id != 0
256 OR saved_search_id IS NOT NULL
257 OR children IS NOT NULL )
260 $groupDAO = CRM_Core_DAO
::executeQuery($sql);
261 while ($groupDAO->fetch()) {
262 if ($groupDAO->cache_date
== NULL) {
263 CRM_Contact_BAO_GroupContactCache
::load($groupDAO);
266 $smartGroupExclude = "
267 INSERT IGNORE INTO X_$job_id (contact_id)
269 FROM civicrm_group_contact_cache c
270 WHERE c.group_id = {$groupDAO->id}
272 $mailingGroup->query($smartGroupExclude);
275 $tempColumn = 'email_id';
276 if ($mode == 'sms') {
277 $tempColumn = 'phone_id';
280 /* Get all the group contacts we want to include */
282 $mailingGroup->query(
283 "CREATE TEMPORARY TABLE I_$job_id
284 ($tempColumn int, contact_id int primary key)
288 /* Get the group contacts, but only those which are not in the
289 * exclusion temp table */
291 $query = "REPLACE INTO I_$job_id (email_id, contact_id)
293 SELECT DISTINCT $email.id as email_id,
294 $contact.id as contact_id
297 ON $email.contact_id = $contact.id
298 INNER JOIN $g2contact
299 ON $contact.id = $g2contact.contact_id
301 ON $g2contact.group_id = $mg.entity_id
302 AND $mg.entity_table = '$group'
304 ON $contact.id = X_$job_id.contact_id
306 ($mg.group_type = 'Include')
307 AND $mg.search_id IS NULL
308 AND $g2contact.status = 'Added'
309 AND $contact.do_not_email = 0
310 AND $contact.is_opt_out = 0
311 AND $contact.is_deceased = 0
313 AND $email.email IS NOT NULL
314 AND $email.email != ''
315 AND $email.on_hold = 0
316 AND $mg.mailing_id = {$mailing_id}
317 AND X_$job_id.contact_id IS null
320 if ($mode == 'sms') {
321 $phoneTypes = CRM_Core_OptionGroup
::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
322 $query = "REPLACE INTO I_$job_id (phone_id, contact_id)
324 SELECT DISTINCT $phone.id as phone_id,
325 $contact.id as contact_id
328 ON $phone.contact_id = $contact.id
329 INNER JOIN $g2contact
330 ON $contact.id = $g2contact.contact_id
332 ON $g2contact.group_id = $mg.entity_id
333 AND $mg.entity_table = '$group'
335 ON $contact.id = X_$job_id.contact_id
337 ($mg.group_type = 'Include')
338 AND $mg.search_id IS NULL
339 AND $g2contact.status = 'Added'
340 AND $contact.do_not_sms = 0
341 AND $contact.is_opt_out = 0
342 AND $contact.is_deceased = 0
343 AND $phone.phone_type_id = {$phoneTypes['Mobile']}
344 AND $phone.phone IS NOT NULL
345 AND $phone.phone != ''
346 AND $mg.mailing_id = {$mailing_id}
347 AND X_$job_id.contact_id IS null";
349 $mailingGroup->query($query);
351 /* Query prior mailings */
353 $query = "REPLACE INTO I_$job_id (email_id, contact_id)
354 SELECT DISTINCT $email.id as email_id,
355 $contact.id as contact_id
358 ON $email.contact_id = $contact.id
360 ON $eq.contact_id = $contact.id
362 ON $eq.job_id = $job.id
364 ON $job.mailing_id = $mg.entity_id AND $mg.entity_table = '$mailing'
366 ON $contact.id = X_$job_id.contact_id
368 ($mg.group_type = 'Include')
369 AND $contact.do_not_email = 0
370 AND $contact.is_opt_out = 0
371 AND $contact.is_deceased = 0
373 AND $email.on_hold = 0
374 AND $mg.mailing_id = {$mailing_id}
375 AND X_$job_id.contact_id IS null
378 if ($mode == 'sms') {
379 $query = "REPLACE INTO I_$job_id (phone_id, contact_id)
380 SELECT DISTINCT $phone.id as phone_id,
381 $contact.id as contact_id
384 ON $phone.contact_id = $contact.id
386 ON $eq.contact_id = $contact.id
388 ON $eq.job_id = $job.id
390 ON $job.mailing_id = $mg.entity_id AND $mg.entity_table = '$mailing'
392 ON $contact.id = X_$job_id.contact_id
394 ($mg.group_type = 'Include')
395 AND $contact.do_not_sms = 0
396 AND $contact.is_opt_out = 0
397 AND $contact.is_deceased = 0
398 AND $phone.phone_type_id = {$phoneTypes['Mobile']}
399 AND $mg.mailing_id = {$mailing_id}
400 AND X_$job_id.contact_id IS null";
402 $mailingGroup->query($query);
405 SELECT $group.id, $group.cache_date, $group.saved_search_id, $group.children
407 INNER JOIN $mg ON $mg.entity_id = $group.id
408 WHERE $mg.entity_table = '$group'
409 AND $mg.group_type = 'Include'
410 AND $mg.search_id IS NULL
411 AND $mg.mailing_id = {$mailing_id}
412 AND ( saved_search_id != 0
413 OR saved_search_id IS NOT NULL
414 OR children IS NOT NULL )
417 $groupDAO = CRM_Core_DAO
::executeQuery($sql);
418 while ($groupDAO->fetch()) {
419 if ($groupDAO->cache_date
== NULL) {
420 CRM_Contact_BAO_GroupContactCache
::load($groupDAO);
423 $smartGroupInclude = "
424 INSERT IGNORE INTO I_$job_id (email_id, contact_id)
425 SELECT civicrm_email.id as email_id, c.id as contact_id
426 FROM civicrm_contact c
427 INNER JOIN civicrm_email ON civicrm_email.contact_id = c.id
428 INNER JOIN civicrm_group_contact_cache gc ON gc.contact_id = c.id
429 LEFT JOIN X_$job_id ON X_$job_id.contact_id = c.id
430 WHERE gc.group_id = {$groupDAO->id}
431 AND c.do_not_email = 0
433 AND c.is_deceased = 0
435 AND civicrm_email.on_hold = 0
436 AND X_$job_id.contact_id IS null
439 if ($mode == 'sms') {
440 $smartGroupInclude = "
441 INSERT IGNORE INTO I_$job_id (phone_id, contact_id)
442 SELECT p.id as phone_id, c.id as contact_id
443 FROM civicrm_contact c
444 INNER JOIN civicrm_phone p ON p.contact_id = c.id
445 INNER JOIN civicrm_group_contact_cache gc ON gc.contact_id = c.id
446 LEFT JOIN X_$job_id ON X_$job_id.contact_id = c.id
447 WHERE gc.group_id = {$groupDAO->id}
450 AND c.is_deceased = 0
451 AND p.phone_type_id = {$phoneTypes['Mobile']}
452 AND X_$job_id.contact_id IS null";
454 $mailingGroup->query($smartGroupInclude);
458 * Construct the filtered search queries
461 SELECT search_id, search_args, entity_id
463 WHERE $mg.search_id IS NOT NULL
464 AND $mg.mailing_id = {$mailing_id}
466 $dao = CRM_Core_DAO
::executeQuery($query);
467 while ($dao->fetch()) {
468 $customSQL = CRM_Contact_BAO_SearchCustom
::civiMailSQL($dao->search_id
,
472 $query = "REPLACE INTO I_$job_id ({$tempColumn}, contact_id)
474 $mailingGroup->query($query);
477 /* Get the emails with only location override */
479 $query = "REPLACE INTO I_$job_id (email_id, contact_id)
480 SELECT DISTINCT $email.id as local_email_id,
481 $contact.id as contact_id
484 ON $email.contact_id = $contact.id
485 INNER JOIN $g2contact
486 ON $contact.id = $g2contact.contact_id
488 ON $g2contact.group_id = $mg.entity_id
490 ON $contact.id = X_$job_id.contact_id
492 $mg.entity_table = '$group'
493 AND $mg.group_type = 'Include'
494 AND $g2contact.status = 'Added'
495 AND $contact.do_not_email = 0
496 AND $contact.is_opt_out = 0
497 AND $contact.is_deceased = 0
499 AND $email.on_hold = 0
500 AND $mg.mailing_id = {$mailing_id}
501 AND X_$job_id.contact_id IS null
503 if ($mode == "sms") {
504 $query = "REPLACE INTO I_$job_id (phone_id, contact_id)
505 SELECT DISTINCT $phone.id as phone_id,
506 $contact.id as contact_id
509 ON $phone.contact_id = $contact.id
510 INNER JOIN $g2contact
511 ON $contact.id = $g2contact.contact_id
513 ON $g2contact.group_id = $mg.entity_id
515 ON $contact.id = X_$job_id.contact_id
517 $mg.entity_table = '$group'
518 AND $mg.group_type = 'Include'
519 AND $g2contact.status = 'Added'
520 AND $contact.do_not_sms = 0
521 AND $contact.is_opt_out = 0
522 AND $contact.is_deceased = 0
523 AND $phone.phone_type_id = {$phoneTypes['Mobile']}
524 AND $mg.mailing_id = {$mailing_id}
525 AND X_$job_id.contact_id IS null";
527 $mailingGroup->query($query);
531 $eq = new CRM_Mailing_Event_BAO_Queue();
533 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause();
534 $aclWhere = $aclWhere ?
"WHERE {$aclWhere}" : '';
536 if ($limit && $offset !== NULL) {
537 $offset = CRM_Utils_Type
::escape($offset, 'Int');
538 $limit = CRM_Utils_Type
::escape($limit, 'Int');
540 $limitString = "LIMIT $offset, $limit";
543 if ($storeRecipients && $mailing_id) {
546 FROM civicrm_mailing_recipients
547 WHERE mailing_id = %1
549 $params = array(1 => array($mailing_id, 'Integer'));
550 CRM_Core_DAO
::executeQuery($sql, $params);
553 $groupBy = $groupJoin = '';
555 $groupJoin = " INNER JOIN civicrm_email e ON e.id = i.email_id";
556 $groupBy = " GROUP BY e.email ";
560 INSERT INTO civicrm_mailing_recipients ( mailing_id, contact_id, {$tempColumn} )
561 SELECT %1, i.contact_id, i.{$tempColumn}
562 FROM civicrm_contact contact_a
563 INNER JOIN I_$job_id i ON contact_a.id = i.contact_id
568 ORDER BY i.contact_id, i.{$tempColumn}
571 CRM_Core_DAO
::executeQuery($sql, $params);
573 // if we need to add all emails marked bulk, do it as a post filter
574 // on the mailing recipients table
575 if (CRM_Core_BAO_Email
::isMultipleBulkMail()) {
576 self
::addMultipleEmails($mailing_id);
580 /* Delete the temp table */
582 $mailingGroup->reset();
583 $mailingGroup->query("DROP TEMPORARY TABLE X_$job_id");
584 $mailingGroup->query("DROP TEMPORARY TABLE I_$job_id");
590 * @param string $type
594 private function _getMailingGroupIds($type = 'Include') {
595 $mailingGroup = new CRM_Mailing_DAO_MailingGroup();
596 $group = CRM_Contact_DAO_Group
::getTableName();
597 if (!isset($this->id
)) {
598 // we're just testing tokens, so return any group
599 $query = "SELECT id AS entity_id
605 $query = "SELECT entity_id
607 WHERE mailing_id = {$this->id}
608 AND group_type = '$type'
609 AND entity_table = '$group'";
611 $mailingGroup->query($query);
614 while ($mailingGroup->fetch()) {
615 $groupIds[] = $mailingGroup->entity_id
;
623 * Returns the regex patterns that are used for preparing the text and html templates
628 private function &getPatterns($onlyHrefs = FALSE) {
632 $protos = '(https?|ftp)';
634 $gunk = '\{\}/#~:.?+=&;%@!\,\-';
636 $any = "{$letters}{$gunk}{$punc}";
638 $pattern = "\\bhref[ ]*=[ ]*([\"'])?(($protos:[$any]+?(?=[$punc]*[^$any]|$)))([\"'])?";
641 $pattern = "\\b($protos:[$any]+?(?=[$punc]*[^$any]|$))";
644 $patterns[] = $pattern;
645 $patterns[] = '\\\\\{\w+\.\w+\\\\\}|\{\{\w+\.\w+\}\}';
646 $patterns[] = '\{\w+\.\w+\}';
648 $patterns = '{' . join('|', $patterns) . '}im';
654 * returns an array that denotes the type of token that we are dealing with
655 * we use the type later on when we are doing a token replcement lookup
657 * @param string $token The token for which we will be doing adata lookup
659 * @return array $funcStruct An array that holds the token itself and the type.
660 * the type will tell us which function to use for the data lookup
661 * if we need to do a lookup at all
663 function &getDataFunc($token) {
664 static $_categories = NULL;
665 static $_categoryString = NULL;
667 $_categories = array(
674 CRM_Utils_Hook
::tokens($_categories);
675 $_categoryString = implode('|', array_keys($_categories));
678 $funcStruct = array('type' => NULL, 'token' => $token);
680 if ((preg_match('/^href/i', $token) ||
preg_match('/^http/i', $token))) {
681 // it is a url so we need to check to see if there are any tokens embedded
682 // if so then call this function again to get the token dataFunc
683 // and assign the type 'embedded' so that the data retrieving function
684 // will know what how to handle this token.
685 if (preg_match_all('/(\{\w+\.\w+\})/', $token, $matches)) {
686 $funcStruct['type'] = 'embedded_url';
687 $funcStruct['embed_parts'] = $funcStruct['token'] = array();
688 foreach ($matches[1] as $match) {
689 $preg_token = '/' . preg_quote($match, '/') . '/';
690 $list = preg_split($preg_token, $token, 2);
691 $funcStruct['embed_parts'][] = $list[0];
693 $funcStruct['token'][] = $this->getDataFunc($match);
695 // fixed truncated url, CRM-7113
697 $funcStruct['embed_parts'][] = $token;
701 $funcStruct['type'] = 'url';
704 elseif (preg_match('/^\{(' . $_categoryString . ')\.(\w+)\}$/', $token, $matches)) {
705 $funcStruct['type'] = $matches[1];
706 $funcStruct['token'] = $matches[2];
708 elseif (preg_match('/\\\\\{(\w+\.\w+)\\\\\}|\{\{(\w+\.\w+)\}\}/', $token, $matches)) {
709 // we are an escaped token
710 // so remove the escape chars
711 $unescaped_token = preg_replace('/\{\{|\}\}|\\\\\{|\\\\\}/', '', $matches[0]);
712 $funcStruct['token'] = '{' . $unescaped_token . '}';
719 * Prepares the text and html templates
720 * for generating the emails and returns a copy of the
726 private function getPreparedTemplates() {
727 if (!$this->preparedTemplates
) {
728 $patterns['html'] = $this->getPatterns(TRUE);
729 $patterns['subject'] = $patterns['text'] = $this->getPatterns();
730 $templates = $this->getTemplates();
732 $this->preparedTemplates
= array();
735 'html', 'text', 'subject') as $key) {
736 if (!isset($templates[$key])) {
742 $split_template = array();
744 $email = $templates[$key];
745 preg_match_all($patterns[$key], $email, $matches, PREG_PATTERN_ORDER
);
746 foreach ($matches[0] as $idx => $token) {
747 $preg_token = '/' . preg_quote($token, '/') . '/im';
748 list($split_template[], $email) = preg_split($preg_token, $email, 2);
749 array_push($tokens, $this->getDataFunc($token));
752 $split_template[] = $email;
754 $this->preparedTemplates
[$key]['template'] = $split_template;
755 $this->preparedTemplates
[$key]['tokens'] = $tokens;
758 return ($this->preparedTemplates
);
763 * Retrieve a ref to an array that holds the email and text templates for this email
764 * assembles the complete template including the header and footer
765 * that the user has uploaded or declared (if they have dome that)
768 * @return array reference to an assoc array
772 private function &getTemplates() {
773 if (!$this->templates
) {
774 $this->getHeaderFooter();
775 $this->templates
= array();
777 if ($this->body_text
) {
780 $template[] = $this->header
->body_text
;
783 $template[] = $this->body_text
;
786 $template[] = $this->footer
->body_text
;
789 $this->templates
['text'] = join("\n", $template);
792 if ($this->body_html
) {
796 $template[] = $this->header
->body_html
;
799 $template[] = $this->body_html
;
802 $template[] = $this->footer
->body_html
;
805 $this->templates
['html'] = join("\n", $template);
807 // this is where we create a text template from the html template if the text template did not exist
808 // this way we ensure that every recipient will receive an email even if the pref is set to text and the
809 // user uploads an html email only
810 if (!$this->body_text
) {
811 $this->templates
['text'] = CRM_Utils_String
::htmlToText($this->templates
['html']);
815 if ($this->subject
) {
817 $template[] = $this->subject
;
818 $this->templates
['subject'] = join("\n", $template);
821 return $this->templates
;
826 * Retrieve a ref to an array that holds all of the tokens in the email body
827 * where the keys are the type of token and the values are ordinal arrays
828 * that hold the token names (even repeated tokens) in the order in which
829 * they appear in the body of the email.
831 * note: the real work is done in the _getTokens() function
833 * this function needs to have some sort of a body assigned
834 * either text or html for this to have any meaningful impact
836 * @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
874 public function &getFlattenedTokens() {
875 if (!$this->flattenedTokens
) {
876 $tokens = $this->getTokens();
878 $this->flattenedTokens
= CRM_Utils_Token
::flattenTokens($tokens);
881 return $this->flattenedTokens
;
886 * _getTokens parses out all of the tokens that have been
887 * included in the html and text bodies of the email
888 * we get the tokens and then separate them into an
889 * internal structure named tokens that has the same
890 * form as the static tokens property(?) of the CRM_Utils_Token class.
891 * The difference is that there might be repeated token names as we want the
892 * structures to represent the order in which tokens were found from left to right, top to bottom.
895 * @param str $prop name of the property that holds the text that we want to scan for tokens (html, text)
900 private function _getTokens($prop) {
901 $templates = $this->getTemplates();
903 $newTokens = CRM_Utils_Token
::getTokens($templates[$prop]);
905 foreach ($newTokens as $type => $names) {
906 if (!isset($this->tokens
[$prop][$type])) {
907 $this->tokens
[$prop][$type] = array();
909 foreach ($names as $key => $name) {
910 $this->tokens
[$prop][$type][] = $name;
916 * Generate an event queue for a test job
918 * @param array $testParams contains form values
923 public function getTestRecipients($testParams) {
924 if (array_key_exists($testParams['test_group'], CRM_Core_PseudoConstant
::group())) {
925 $contacts = civicrm_api('contact','get', array(
927 'group' => $testParams['test_group'],
929 'options' => array('limit' => 100000000000,
933 foreach (array_keys($contacts['values']) as $groupContact) {
935 SELECT civicrm_email.id AS email_id,
936 civicrm_email.is_primary as is_primary,
937 civicrm_email.is_bulkmail as is_bulkmail
939 INNER JOIN civicrm_contact ON civicrm_email.contact_id = civicrm_contact.id
940 WHERE (civicrm_email.is_bulkmail = 1 OR civicrm_email.is_primary = 1)
941 AND civicrm_contact.id = {$groupContact}
942 AND civicrm_contact.do_not_email = 0
943 AND civicrm_contact.is_deceased = 0
944 AND civicrm_email.on_hold = 0
945 AND civicrm_contact.is_opt_out = 0
946 GROUP BY civicrm_email.id
947 ORDER BY civicrm_email.is_bulkmail DESC
949 $dao = CRM_Core_DAO
::executeQuery($query);
952 'job_id' => $testParams['job_id'],
953 'email_id' => $dao->email_id
,
954 'contact_id' => $groupContact,
956 CRM_Mailing_Event_BAO_Queue
::create($params);
963 * Retrieve the header and footer for this mailing
970 private function getHeaderFooter() {
971 if (!$this->header
and $this->header_id
) {
972 $this->header
= new CRM_Mailing_BAO_Component();
973 $this->header
->id
= $this->header_id
;
974 $this->header
->find(TRUE);
975 $this->header
->free();
978 if (!$this->footer
and $this->footer_id
) {
979 $this->footer
= new CRM_Mailing_BAO_Component();
980 $this->footer
->id
= $this->footer_id
;
981 $this->footer
->find(TRUE);
982 $this->footer
->free();
987 * Given and array of headers and a prefix, job ID, event queue ID, and hash,
988 * add a Message-ID header if needed.
990 * i.e. if the global includeMessageId is set and there isn't already a
991 * Message-ID in the array.
992 * The message ID is structured the same way as a verp. However no interpretation
993 * is placed on the values received, so they do not need to follow the verp
996 * @param array $headers Array of message headers to update, in-out
997 * @param string $prefix Prefix for the message ID, use same prefixes as verp
999 * @param string $job_id Job ID component of the generated message ID
1000 * @param string $event_queue_id Event Queue ID component of the generated message ID
1001 * @param string $hash Hash component of the generated message ID.
1005 static function addMessageIdHeader(&$headers, $prefix, $job_id, $event_queue_id, $hash) {
1006 $config = CRM_Core_Config
::singleton();
1007 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
1008 $emailDomain = CRM_Core_BAO_MailSettings
::defaultDomain();
1009 $includeMessageId = CRM_Core_BAO_MailSettings
::includeMessageId();
1011 if ($includeMessageId && (!array_key_exists('Message-ID', $headers))) {
1012 $headers['Message-ID'] = '<' . implode($config->verpSeparator
,
1014 $localpart . $prefix,
1019 ) . "@{$emailDomain}>";
1024 * Static wrapper for getting verp and urls
1026 * @param int $job_id ID of the Job associated with this message
1027 * @param int $event_queue_id ID of the EventQueue
1028 * @param string $hash Hash of the EventQueue
1029 * @param string $email Destination address
1031 * @return array (reference) array array ref that hold array refs to the verp info and urls
1033 static function getVerpAndUrls($job_id, $event_queue_id, $hash, $email) {
1034 // create a skeleton object and set its properties that are required by getVerpAndUrlsAndHeaders()
1035 $config = CRM_Core_Config
::singleton();
1036 $bao = new CRM_Mailing_BAO_Mailing();
1037 $bao->_domain
= CRM_Core_BAO_Domain
::getDomain();
1038 $bao->from_name
= $bao->from_email
= $bao->subject
= '';
1040 // use $bao's instance method to get verp and urls
1041 list($verp, $urls, $_) = $bao->getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email);
1042 return array($verp, $urls);
1046 * Get verp, urls and headers
1048 * @param int $job_id ID of the Job associated with this message
1049 * @param int $event_queue_id ID of the EventQueue
1050 * @param string $hash Hash of the EventQueue
1051 * @param string $email Destination address
1053 * @param bool $isForward
1055 * @return array (reference) array array ref that hold array refs to the verp info, urls, and headers@access private
1057 private function getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email, $isForward = FALSE) {
1058 $config = CRM_Core_Config
::singleton();
1061 * Inbound VERP keys:
1062 * reply: user replied to mailing
1063 * bounce: email address bounced
1064 * unsubscribe: contact opts out of all target lists for the mailing
1065 * resubscribe: contact opts back into all target lists for the mailing
1066 * optOut: contact unsubscribes from the domain
1069 $verpTokens = array(
1072 'unsubscribe' => 'u',
1073 'resubscribe' => 'e',
1077 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
1078 $emailDomain = CRM_Core_BAO_MailSettings
::defaultDomain();
1080 foreach ($verpTokens as $key => $value) {
1081 $verp[$key] = implode($config->verpSeparator
,
1083 $localpart . $value,
1088 ) . "@$emailDomain";
1091 //handle should override VERP address.
1092 $skipEncode = FALSE;
1095 self
::overrideVerp($job_id)
1097 $verp['reply'] = "\"{$this->from_name}\" <{$this->from_email}>";
1101 'forward' => CRM_Utils_System
::url('civicrm/mailing/forward',
1102 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1103 TRUE, NULL, TRUE, TRUE
1105 'unsubscribeUrl' => CRM_Utils_System
::url('civicrm/mailing/unsubscribe',
1106 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1107 TRUE, NULL, TRUE, TRUE
1109 'resubscribeUrl' => CRM_Utils_System
::url('civicrm/mailing/resubscribe',
1110 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1111 TRUE, NULL, TRUE, TRUE
1113 'optOutUrl' => CRM_Utils_System
::url('civicrm/mailing/optout',
1114 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1115 TRUE, NULL, TRUE, TRUE
1117 'subscribeUrl' => CRM_Utils_System
::url('civicrm/mailing/subscribe',
1119 TRUE, NULL, TRUE, TRUE
1124 'Reply-To' => $verp['reply'],
1125 'Return-Path' => $verp['bounce'],
1126 'From' => "\"{$this->from_name}\" <{$this->from_email}>",
1127 'Subject' => $this->subject
,
1128 'List-Unsubscribe' => "<mailto:{$verp['unsubscribe']}>",
1130 self
::addMessageIdHeader($headers, 'm', $job_id, $event_queue_id, $hash);
1132 $headers['Subject'] = "[Fwd:{$this->subject}]";
1134 return array(&$verp, &$urls, &$headers);
1140 * @param int $job_id ID of the Job associated with this message
1141 * @param int $event_queue_id ID of the EventQueue
1142 * @param string $hash Hash of the EventQueue
1143 * @param string $contactId ID of the Contact
1144 * @param string $email Destination address
1145 * @param string $recipient To: of the recipient
1146 * @param boolean $test Is this mailing a test?
1147 * @param $contactDetails
1148 * @param $attachments
1149 * @param boolean $isForward Is this mailing compose for forward?
1150 * @param string $fromEmail email address of who is forwardinf it.
1152 * @param null $replyToEmail
1154 * @return Mail_mime The mail object
1157 public function &compose($job_id, $event_queue_id, $hash, $contactId,
1158 $email, &$recipient, $test,
1159 $contactDetails, &$attachments, $isForward = FALSE,
1160 $fromEmail = NULL, $replyToEmail = NULL
1162 $config = CRM_Core_Config
::singleton();
1163 $knownTokens = $this->getTokens();
1165 if ($this->_domain
== NULL) {
1166 $this->_domain
= CRM_Core_BAO_Domain
::getDomain();
1169 list($verp, $urls, $headers) = $this->getVerpAndUrlsAndHeaders(
1177 //set from email who is forwarding it and not original one.
1179 unset($headers['From']);
1180 $headers['From'] = "<{$fromEmail}>";
1183 if ($replyToEmail && ($fromEmail != $replyToEmail)) {
1184 $headers['Reply-To'] = "{$replyToEmail}";
1187 if ($contactDetails) {
1188 $contact = $contactDetails;
1190 elseif ($contactId === 0) {
1193 CRM_Utils_Hook
::tokenValues($contact, $contactId, $job_id);
1196 $params = array(array('contact_id', '=', $contactId, 0, 0));
1197 list($contact, $_) = CRM_Contact_BAO_Query
::apiQuery($params);
1200 $contact = reset($contact);
1202 if (!$contact ||
is_a($contact, 'CRM_Core_Error')) {
1203 CRM_Core_Error
::debug_log_message(ts('CiviMail will not send email to a non-existent contact: %1',
1204 array(1 => $contactId)
1206 // setting this because function is called by reference
1207 //@todo test not calling function by reference
1212 // also call the hook to get contact details
1213 CRM_Utils_Hook
::tokenValues($contact, $contactId, $job_id);
1216 $pTemplates = $this->getPreparedTemplates();
1219 foreach ($pTemplates as $type => $pTemplate) {
1220 $html = ($type == 'html') ?
TRUE : FALSE;
1221 $pEmails[$type] = array();
1222 $pEmail = &$pEmails[$type];
1223 $template = &$pTemplates[$type]['template'];
1224 $tokens = &$pTemplates[$type]['tokens'];
1226 if (!empty($tokens)) {
1227 foreach ($tokens as $idx => $token) {
1228 $token_data = $this->getTokenData($token, $html, $contact, $verp, $urls, $event_queue_id);
1229 array_push($pEmail, $template[$idx]);
1230 array_push($pEmail, $token_data);
1234 array_push($pEmail, $template[$idx]);
1237 if (isset($template[($idx +
1)])) {
1238 array_push($pEmail, $template[($idx +
1)]);
1243 if (isset($pEmails['html']) && is_array($pEmails['html']) && count($pEmails['html'])) {
1244 $html = &$pEmails['html'];
1248 if (isset($pEmails['text']) && is_array($pEmails['text']) && count($pEmails['text'])) {
1249 $text = &$pEmails['text'];
1252 // push the tracking url on to the html email if necessary
1253 if ($this->open_tracking
&& $html) {
1254 array_push($html, "\n" . '<img src="' . $config->userFrameworkResourceURL
.
1255 "extern/open.php?q=$event_queue_id\" width='1' height='1' alt='' border='0'>"
1259 $message = new Mail_mime("\n");
1261 $useSmarty = defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY ?
TRUE : FALSE;
1263 $smarty = CRM_Core_Smarty
::singleton();
1264 // also add the contact tokens to the template
1265 $smarty->assign_by_ref('contact', $contact);
1268 $mailParams = $headers;
1269 if ($text && ($test ||
$contact['preferred_mail_format'] == 'Text' ||
1270 $contact['preferred_mail_format'] == 'Both' ||
1271 ($contact['preferred_mail_format'] == 'HTML' && !array_key_exists('html', $pEmails))
1273 $textBody = join('', $text);
1275 $textBody = $smarty->fetch("string:$textBody");
1277 $mailParams['text'] = $textBody;
1280 if ($html && ($test ||
($contact['preferred_mail_format'] == 'HTML' ||
1281 $contact['preferred_mail_format'] == 'Both'
1283 $htmlBody = join('', $html);
1285 $htmlBody = $smarty->fetch("string:$htmlBody");
1287 $mailParams['html'] = $htmlBody;
1290 if (empty($mailParams['text']) && empty($mailParams['html'])) {
1292 // something went wrong, lets log it and return null (by reference)
1293 CRM_Core_Error
::debug_log_message(ts('CiviMail will not send an empty mail body, Skipping: %1',
1300 $mailParams['attachments'] = $attachments;
1302 $mailingSubject = CRM_Utils_Array
::value('subject', $pEmails);
1303 if (is_array($mailingSubject)) {
1304 $mailingSubject = join('', $mailingSubject);
1306 $mailParams['Subject'] = $mailingSubject;
1308 $mailParams['toName'] = CRM_Utils_Array
::value('display_name',
1311 $mailParams['toEmail'] = $email;
1313 CRM_Utils_Hook
::alterMailParams($mailParams, 'civimail');
1315 // CRM-10699 support custom email headers
1316 if (!empty($mailParams['headers'])) {
1317 $headers = array_merge($headers, $mailParams['headers']);
1319 //cycle through mailParams and set headers array
1320 foreach ($mailParams as $paramKey => $paramValue) {
1321 //exclude values not intended for the header
1322 if (!in_array($paramKey, array(
1323 'text', 'html', 'attachments', 'toName', 'toEmail'))) {
1324 $headers[$paramKey] = $paramValue;
1328 if (!empty($mailParams['text'])) {
1329 $message->setTxtBody($mailParams['text']);
1332 if (!empty($mailParams['html'])) {
1333 $message->setHTMLBody($mailParams['html']);
1336 if (!empty($mailParams['attachments'])) {
1337 foreach ($mailParams['attachments'] as $fileID => $attach) {
1338 $message->addAttachment($attach['fullPath'],
1339 $attach['mime_type'],
1340 $attach['cleanName']
1345 //pickup both params from mail params.
1346 $toName = trim($mailParams['toName']);
1347 $toEmail = trim($mailParams['toEmail']);
1348 if ($toName == $toEmail ||
1349 strpos($toName, '@') !== FALSE
1354 $toName = CRM_Utils_Mail
::formatRFC2822Name($toName);
1357 $headers['To'] = "$toName <$toEmail>";
1359 $headers['Precedence'] = 'bulk';
1360 // Will test in the mail processor if the X-VERP is set in the bounced email.
1361 // (As an option to replace real VERP for those that can't set it up)
1362 $headers['X-CiviMail-Bounce'] = $verp['bounce'];
1365 //token replacement of subject
1366 $headers['Subject'] = $mailingSubject;
1368 CRM_Utils_Mail
::setMimeParams($message);
1369 $headers = $message->headers($headers);
1371 //get formatted recipient
1372 $recipient = $headers['To'];
1374 // make sure we unset a lot of stuff
1386 * get mailing object and replaces subscribeInvite,
1387 * domain and mailing tokens
1390 public static function tokenReplace(&$mailing) {
1391 $domain = CRM_Core_BAO_Domain
::getDomain();
1393 foreach (array('text', 'html') as $type) {
1394 $tokens = $mailing->getTokens();
1395 if (isset($mailing->templates
[$type])) {
1396 $mailing->templates
[$type] = CRM_Utils_Token
::replaceSubscribeInviteTokens($mailing->templates
[$type]);
1397 $mailing->templates
[$type] = CRM_Utils_Token
::replaceDomainTokens(
1398 $mailing->templates
[$type],
1400 $type == 'html' ?
TRUE : FALSE,
1403 $mailing->templates
[$type] = CRM_Utils_Token
::replaceMailingTokens($mailing->templates
[$type], $mailing, NULL, $tokens[$type]);
1410 * getTokenData receives a token from an email
1411 * and returns the appropriate data for the token
1414 private function getTokenData(&$token_a, $html = FALSE, &$contact, &$verp, &$urls, $event_queue_id) {
1415 $type = $token_a['type'];
1416 $token = $token_a['token'];
1419 $useSmarty = defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY ?
TRUE : FALSE;
1421 if ($type == 'embedded_url') {
1422 $embed_data = array();
1423 foreach ($token as $t) {
1424 $embed_data[] = $this->getTokenData($t, $html = FALSE, $contact, $verp, $urls, $event_queue_id);
1426 $numSlices = count($embed_data);
1428 for ($i = 0; $i < $numSlices; $i++
) {
1429 $url .= "{$token_a['embed_parts'][$i]}{$embed_data[$i]}";
1431 if (isset($token_a['embed_parts'][$numSlices])) {
1432 $url .= $token_a['embed_parts'][$numSlices];
1434 // add trailing quote since we've gobbled it up in a previous regex
1435 // function getPatterns, line 431
1436 if (preg_match('/^href[ ]*=[ ]*\'/', $url)) {
1439 elseif (preg_match('/^href[ ]*=[ ]*\"/', $url)) {
1444 elseif ($type == 'url') {
1445 if ($this->url_tracking
) {
1446 $data = CRM_Mailing_BAO_TrackableURL
::getTrackerURL($token, $this->id
, $event_queue_id);
1447 if (!empty($html)) {
1448 $data = htmlentities($data);
1455 elseif ($type == 'contact') {
1456 $data = CRM_Utils_Token
::getContactTokenReplacement($token, $contact, FALSE, FALSE, $useSmarty);
1458 elseif ($type == 'action') {
1459 $data = CRM_Utils_Token
::getActionTokenReplacement($token, $verp, $urls, $html);
1461 elseif ($type == 'domain') {
1462 $domain = CRM_Core_BAO_Domain
::getDomain();
1463 $data = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain, $html);
1465 elseif ($type == 'mailing') {
1466 if ($token == 'name') {
1467 $data = $this->name
;
1469 elseif ($token == 'group') {
1470 $groups = $this->getGroupNames();
1471 $data = implode(', ', $groups);
1475 $data = CRM_Utils_Array
::value("{$type}.{$token}", $contact);
1481 * Return a list of group names for this mailing. Does not work with
1482 * prior-mailing targets.
1484 * @return array Names of groups receiving this mailing
1487 public function &getGroupNames() {
1488 if (!isset($this->id
)) {
1491 $mg = new CRM_Mailing_DAO_MailingGroup();
1492 $mgtable = CRM_Mailing_DAO_MailingGroup
::getTableName();
1493 $group = CRM_Contact_BAO_Group
::getTableName();
1495 $mg->query("SELECT $group.title as name FROM $mgtable
1496 INNER JOIN $group ON $mgtable.entity_id = $group.id
1497 WHERE $mgtable.mailing_id = {$this->id}
1498 AND $mgtable.entity_table = '$group'
1499 AND $mgtable.group_type = 'Include'
1500 ORDER BY $group.name");
1503 while ($mg->fetch()) {
1504 $groups[] = $mg->name
;
1513 * @param array $params reference array contains the values submitted by the form
1514 * @param array $ids reference array contains the id
1521 static function add(&$params, $ids = array()) {
1522 $id = CRM_Utils_Array
::value('mailing_id', $ids, CRM_Utils_Array
::value('id', $params));
1525 CRM_Utils_Hook
::pre('edit', 'Mailing', $id, $params);
1528 CRM_Utils_Hook
::pre('create', 'Mailing', NULL, $params);
1531 $mailing = new static();
1533 $mailing->domain_id
= CRM_Utils_Array
::value('domain_id', $params, CRM_Core_Config
::domainID());
1535 if (!isset($params['replyto_email']) &&
1536 isset($params['from_email'])
1538 $params['replyto_email'] = $params['from_email'];
1541 $mailing->copyValues($params);
1543 $result = $mailing->save();
1545 if (!empty($ids['mailing'])) {
1546 CRM_Utils_Hook
::post('edit', 'Mailing', $mailing->id
, $mailing);
1549 CRM_Utils_Hook
::post('create', 'Mailing', $mailing->id
, $mailing);
1556 * Construct a new mailing object, along with job and mailing_group
1557 * objects, from the form values of the create mailing wizard.
1559 * @params array $params Form values
1561 * @param array $params
1564 * @return object $mailing The new mailing object
1568 public static function create(&$params, $ids = array()) {
1571 // Do the below only for an insert
1572 // for an update, we should not set the defaults
1573 if (!isset($ids['id']) && !isset($ids['mailing_id'])) {
1574 // Retrieve domain email and name for default sender
1575 $domain = civicrm_api(
1580 'current_domain' => 1,
1584 if (isset($domain['from_email'])) {
1585 $domain_email = $domain['from_email'];
1586 $domain_name = $domain['from_name'];
1589 $domain_email = 'info@EXAMPLE.ORG';
1590 $domain_name = 'EXAMPLE.ORG';
1592 if (!isset($params['created_id'])) {
1593 $session =& CRM_Core_Session
::singleton();
1594 $params['created_id'] = $session->get('userID');
1597 // load the default config settings for each
1598 // eg reply_id, unsubscribe_id need to use
1599 // correct template IDs here
1600 'override_verp' => TRUE,
1601 'forward_replies' => FALSE,
1602 'open_tracking' => TRUE,
1603 'url_tracking' => TRUE,
1604 'visibility' => 'Public Pages',
1605 'replyto_email' => $domain_email,
1606 'header_id' => CRM_Mailing_PseudoConstant
::defaultComponent('header_id', ''),
1607 'footer_id' => CRM_Mailing_PseudoConstant
::defaultComponent('footer_id', ''),
1608 'from_email' => $domain_email,
1609 'from_name' => $domain_name,
1610 'msg_template_id' => NULL,
1611 'created_id' => $params['created_id'],
1612 'approver_id' => NULL,
1613 'auto_responder' => 0,
1614 'created_date' => date('YmdHis'),
1615 'scheduled_date' => NULL,
1616 'approval_date' => NULL,
1619 // Get the default from email address, if not provided.
1620 if (empty($defaults['from_email'])) {
1621 $defaultAddress = CRM_Core_OptionGroup
::values('from_email_address', NULL, NULL, NULL, ' AND is_default = 1');
1622 foreach ($defaultAddress as $id => $value) {
1623 if (preg_match('/"(.*)" <(.*)>/', $value, $match)) {
1624 $defaults['from_email'] = $match[2];
1625 $defaults['from_name'] = $match[1];
1630 $params = array_merge($defaults, $params);
1634 * Could check and warn for the following cases:
1636 * - groups OR mailings should be populated.
1637 * - body html OR body text should be populated.
1640 $transaction = new CRM_Core_Transaction();
1642 $mailing = self
::add($params, $ids);
1644 if (is_a($mailing, 'CRM_Core_Error')) {
1645 $transaction->rollback();
1648 // update mailings with hash values
1649 CRM_Contact_BAO_Contact_Utils
::generateChecksum($mailing->id
, NULL, NULL, NULL, 'mailing', 16);
1651 $groupTableName = CRM_Contact_BAO_Group
::getTableName();
1652 $mailingTableName = CRM_Mailing_BAO_Mailing
::getTableName();
1654 /* Create the mailing group record */
1655 $mg = new CRM_Mailing_DAO_MailingGroup();
1656 foreach (array('groups', 'mailings') as $entity) {
1657 foreach (array('include', 'exclude', 'base') as $type) {
1658 if (isset($params[$entity][$type])) {
1659 self
::replaceGroups($mailing->id
, $type, $entity, $params[$entity][$type]);
1664 if (!empty($params['search_id']) && !empty($params['group_id'])) {
1666 $mg->mailing_id
= $mailing->id
;
1667 $mg->entity_table
= $groupTableName;
1668 $mg->entity_id
= $params['group_id'];
1669 $mg->search_id
= $params['search_id'];
1670 $mg->search_args
= $params['search_args'];
1671 $mg->group_type
= 'Include';
1675 // check and attach and files as needed
1676 CRM_Core_BAO_File
::processAttachment($params, 'civicrm_mailing', $mailing->id
);
1678 $transaction->commit();
1681 * create parent job if not yet created
1682 * condition on the existence of a scheduled date
1684 if (!empty($params['scheduled_date']) && $params['scheduled_date'] != 'null') {
1685 $job = new CRM_Mailing_BAO_MailingJob();
1686 $job->mailing_id
= $mailing->id
;
1687 $job->status
= 'Scheduled';
1690 if ( !$job->find(TRUE) ) {
1691 $job->scheduled_date
= $params['scheduled_date'];
1695 // Populate the recipients.
1696 if (empty($params['_skip_evil_bao_auto_recipients_'])) {
1697 self
::getRecipients($job->id
, $mailing->id
, NULL, NULL, TRUE, FALSE);
1705 * Replace the list of recipients on a given mailing
1707 * @param int $mailingId
1708 * @param string $type 'include' or 'exclude'
1709 * @param string $entity 'groups' or 'mailings'
1710 * @param array<int> $entityIds
1711 * @throws CiviCRM_API3_Exception
1713 public static function replaceGroups($mailingId, $type, $entity, $entityIds) {
1715 foreach ($entityIds as $entityId) {
1716 $values[] = array('entity_id' => $entityId);
1718 civicrm_api3('mailing_group', 'replace', array(
1719 'mailing_id' => $mailingId,
1720 'group_type' => $type,
1721 'entity_table' => ($entity == 'groups') ? CRM_Contact_BAO_Group
::getTableName() : CRM_Mailing_BAO_Mailing
::getTableName(),
1722 'values' => $values,
1727 * Get hash value of the mailing
1729 public static function getMailingHash($id) {
1731 if (CRM_Core_BAO_Setting
::getItem(CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
, 'hash_mailing_url')) {
1732 $hash = CRM_Core_DAO
::getFieldValue('CRM_Mailing_BAO_Mailing', $id, 'hash', 'id');
1738 * Generate a report. Fetch event count information, mailing data, and job
1741 * @param int $id The mailing id to report
1742 * @param boolean $skipDetails whether return all detailed report
1744 * @param bool $isSMS
1746 * @return array Associative array of reporting data
1750 public static function &report($id, $skipDetails = FALSE, $isSMS = FALSE) {
1751 $mailing_id = CRM_Utils_Type
::escape($id, 'Integer');
1753 $mailing = new CRM_Mailing_BAO_Mailing();
1756 'mailing' => self
::getTableName(),
1757 'mailing_group' => CRM_Mailing_DAO_MailingGroup
::getTableName(),
1758 'group' => CRM_Contact_BAO_Group
::getTableName(),
1759 'job' => CRM_Mailing_BAO_MailingJob
::getTableName(),
1760 'queue' => CRM_Mailing_Event_BAO_Queue
::getTableName(),
1761 'delivered' => CRM_Mailing_Event_BAO_Delivered
::getTableName(),
1762 'opened' => CRM_Mailing_Event_BAO_Opened
::getTableName(),
1763 'reply' => CRM_Mailing_Event_BAO_Reply
::getTableName(),
1764 'unsubscribe' => CRM_Mailing_Event_BAO_Unsubscribe
::getTableName(),
1765 'bounce' => CRM_Mailing_Event_BAO_Bounce
::getTableName(),
1766 'forward' => CRM_Mailing_Event_BAO_Forward
::getTableName(),
1767 'url' => CRM_Mailing_BAO_TrackableURL
::getTableName(),
1769 CRM_Mailing_Event_BAO_TrackableURLOpen
::getTableName(),
1770 'component' => CRM_Mailing_BAO_Component
::getTableName(),
1771 'spool' => CRM_Mailing_BAO_Spool
::getTableName(),
1776 $additionalWhereClause = " AND ";
1778 $additionalWhereClause .= " {$t['mailing']}.sms_provider_id IS NULL ";
1781 $additionalWhereClause .= " {$t['mailing']}.sms_provider_id IS NOT NULL ";
1784 /* Get the mailing info */
1787 SELECT {$t['mailing']}.*
1788 FROM {$t['mailing']}
1789 WHERE {$t['mailing']}.id = $mailing_id {$additionalWhereClause}");
1793 $report['mailing'] = array();
1794 foreach (array_keys(self
::fields()) as $field) {
1795 $report['mailing'][$field] = $mailing->$field;
1799 if ($campaignId = CRM_Utils_Array
::value('campaign_id', $report['mailing'])) {
1800 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1801 $report['mailing']['campaign'] = $campaigns[$campaignId];
1804 //mailing report is called by activity
1805 //we dont need all detail report
1810 /* Get the component info */
1814 $components = array(
1815 'header' => ts('Header'),
1816 'footer' => ts('Footer'),
1817 'reply' => ts('Reply'),
1818 'unsubscribe' => ts('Unsubscribe'),
1819 'optout' => ts('Opt-Out'),
1821 foreach (array_keys($components) as $type) {
1822 $query[] = "SELECT {$t['component']}.name as name,
1824 {$t['component']}.id as id
1825 FROM {$t['component']}
1826 INNER JOIN {$t['mailing']}
1827 ON {$t['mailing']}.{$type}_id =
1828 {$t['component']}.id
1829 WHERE {$t['mailing']}.id = $mailing_id";
1831 $q = '(' . implode(') UNION (', $query) . ')';
1832 $mailing->query($q);
1834 $report['component'] = array();
1835 while ($mailing->fetch()) {
1836 $report['component'][] = array(
1837 'type' => $components[$mailing->type
],
1838 'name' => $mailing->name
,
1840 CRM_Utils_System
::url('civicrm/mailing/component',
1841 "reset=1&action=update&id={$mailing->id}"
1846 /* Get the recipient group info */
1849 SELECT {$t['mailing_group']}.group_type as group_type,
1850 {$t['group']}.id as group_id,
1851 {$t['group']}.title as group_title,
1852 {$t['group']}.is_hidden as group_hidden,
1853 {$t['mailing']}.id as mailing_id,
1854 {$t['mailing']}.name as mailing_name
1855 FROM {$t['mailing_group']}
1856 LEFT JOIN {$t['group']}
1857 ON {$t['mailing_group']}.entity_id = {$t['group']}.id
1858 AND {$t['mailing_group']}.entity_table =
1860 LEFT JOIN {$t['mailing']}
1861 ON {$t['mailing_group']}.entity_id =
1863 AND {$t['mailing_group']}.entity_table =
1866 WHERE {$t['mailing_group']}.mailing_id = $mailing_id
1869 $report['group'] = array('include' => array(), 'exclude' => array(), 'base' => array());
1870 while ($mailing->fetch()) {
1872 if (isset($mailing->group_id
)) {
1873 $row['id'] = $mailing->group_id
;
1874 $row['name'] = $mailing->group_title
;
1875 $row['link'] = CRM_Utils_System
::url('civicrm/group/search',
1876 "reset=1&force=1&context=smog&gid={$row['id']}"
1880 $row['id'] = $mailing->mailing_id
;
1881 $row['name'] = $mailing->mailing_name
;
1882 $row['mailing'] = TRUE;
1883 $row['link'] = CRM_Utils_System
::url('civicrm/mailing/report',
1888 /* Rename hidden groups */
1890 if ($mailing->group_hidden
== 1) {
1891 $row['name'] = "Search Results";
1894 if ($mailing->group_type
== 'Include') {
1895 $report['group']['include'][] = $row;
1897 elseif ($mailing->group_type
== 'Base') {
1898 $report['group']['base'][] = $row;
1901 $report['group']['exclude'][] = $row;
1905 /* Get the event totals, grouped by job (retries) */
1908 SELECT {$t['job']}.*,
1909 COUNT(DISTINCT {$t['queue']}.id) as queue,
1910 COUNT(DISTINCT {$t['delivered']}.id) as delivered,
1911 COUNT(DISTINCT {$t['reply']}.id) as reply,
1912 COUNT(DISTINCT {$t['forward']}.id) as forward,
1913 COUNT(DISTINCT {$t['bounce']}.id) as bounce,
1914 COUNT(DISTINCT {$t['urlopen']}.id) as url,
1915 COUNT(DISTINCT {$t['spool']}.id) as spool
1917 LEFT JOIN {$t['queue']}
1918 ON {$t['queue']}.job_id = {$t['job']}.id
1919 LEFT JOIN {$t['reply']}
1920 ON {$t['reply']}.event_queue_id = {$t['queue']}.id
1921 LEFT JOIN {$t['forward']}
1922 ON {$t['forward']}.event_queue_id = {$t['queue']}.id
1923 LEFT JOIN {$t['bounce']}
1924 ON {$t['bounce']}.event_queue_id = {$t['queue']}.id
1925 LEFT JOIN {$t['delivered']}
1926 ON {$t['delivered']}.event_queue_id = {$t['queue']}.id
1927 AND {$t['bounce']}.id IS null
1928 LEFT JOIN {$t['urlopen']}
1929 ON {$t['urlopen']}.event_queue_id = {$t['queue']}.id
1930 LEFT JOIN {$t['spool']}
1931 ON {$t['spool']}.job_id = {$t['job']}.id
1932 WHERE {$t['job']}.mailing_id = $mailing_id
1933 AND {$t['job']}.is_test = 0
1934 GROUP BY {$t['job']}.id");
1936 $report['jobs'] = array();
1937 $report['event_totals'] = array();
1939 'queue', 'delivered', 'url', 'forward',
1940 'reply', 'unsubscribe', 'optout', 'opened', 'bounce', 'spool',
1943 // initialize various counters
1944 foreach ($elements as $field) {
1945 $report['event_totals'][$field] = 0;
1948 while ($mailing->fetch()) {
1950 foreach ($elements as $field) {
1951 if (isset($mailing->$field)) {
1952 $row[$field] = $mailing->$field;
1953 $report['event_totals'][$field] +
= $mailing->$field;
1957 // compute open total separately to discount duplicates
1959 $row['opened'] = CRM_Mailing_Event_BAO_Opened
::getTotalCount($mailing_id, $mailing->id
, TRUE);
1960 $report['event_totals']['opened'] +
= $row['opened'];
1962 // compute unsub total separately to discount duplicates
1964 $row['unsubscribe'] = CRM_Mailing_Event_BAO_Unsubscribe
::getTotalCount($mailing_id, $mailing->id
, TRUE, TRUE);
1965 $report['event_totals']['unsubscribe'] +
= $row['unsubscribe'];
1967 $row['optout'] = CRM_Mailing_Event_BAO_Unsubscribe
::getTotalCount($mailing_id, $mailing->id
, TRUE, FALSE);
1968 $report['event_totals']['optout'] +
= $row['optout'];
1970 foreach (array_keys(CRM_Mailing_BAO_MailingJob
::fields()) as $field) {
1971 $row[$field] = $mailing->$field;
1974 if ($mailing->queue
) {
1975 $row['delivered_rate'] = (100.0 * $mailing->delivered
) / $mailing->queue
;
1976 $row['bounce_rate'] = (100.0 * $mailing->bounce
) / $mailing->queue
;
1977 $row['unsubscribe_rate'] = (100.0 * $row['unsubscribe']) / $mailing->queue
;
1978 $row['optout_rate'] = (100.0 * $row['optout']) / $mailing->queue
;
1981 $row['delivered_rate'] = 0;
1982 $row['bounce_rate'] = 0;
1983 $row['unsubscribe_rate'] = 0;
1984 $row['optout_rate'] = 0;
1987 $row['links'] = array(
1988 'clicks' => CRM_Utils_System
::url(
1989 'civicrm/mailing/report/event',
1990 "reset=1&event=click&mid=$mailing_id&jid={$mailing->id}"
1992 'queue' => CRM_Utils_System
::url(
1993 'civicrm/mailing/report/event',
1994 "reset=1&event=queue&mid=$mailing_id&jid={$mailing->id}"
1996 'delivered' => CRM_Utils_System
::url(
1997 'civicrm/mailing/report/event',
1998 "reset=1&event=delivered&mid=$mailing_id&jid={$mailing->id}"
2000 'bounce' => CRM_Utils_System
::url(
2001 'civicrm/mailing/report/event',
2002 "reset=1&event=bounce&mid=$mailing_id&jid={$mailing->id}"
2004 'unsubscribe' => CRM_Utils_System
::url(
2005 'civicrm/mailing/report/event',
2006 "reset=1&event=unsubscribe&mid=$mailing_id&jid={$mailing->id}"
2008 'forward' => CRM_Utils_System
::url(
2009 'civicrm/mailing/report/event',
2010 "reset=1&event=forward&mid=$mailing_id&jid={$mailing->id}"
2012 'reply' => CRM_Utils_System
::url(
2013 'civicrm/mailing/report/event',
2014 "reset=1&event=reply&mid=$mailing_id&jid={$mailing->id}"
2016 'opened' => CRM_Utils_System
::url(
2017 'civicrm/mailing/report/event',
2018 "reset=1&event=opened&mid=$mailing_id&jid={$mailing->id}"
2023 'scheduled_date', 'start_date', 'end_date') as $key) {
2024 $row[$key] = CRM_Utils_Date
::customFormat($row[$key]);
2026 $report['jobs'][] = $row;
2029 $newTableSize = CRM_Mailing_BAO_Recipients
::mailingSize($mailing_id);
2031 // we need to do this for backward compatibility, since old mailings did not
2032 // use the mailing_recipients table
2033 if ($newTableSize > 0) {
2034 $report['event_totals']['queue'] = $newTableSize;
2037 $report['event_totals']['queue'] = self
::getRecipientsCount($mailing_id, $mailing_id);
2040 if (!empty($report['event_totals']['queue'])) {
2041 $report['event_totals']['delivered_rate'] = (100.0 * $report['event_totals']['delivered']) / $report['event_totals']['queue'];
2042 $report['event_totals']['bounce_rate'] = (100.0 * $report['event_totals']['bounce']) / $report['event_totals']['queue'];
2043 $report['event_totals']['unsubscribe_rate'] = (100.0 * $report['event_totals']['unsubscribe']) / $report['event_totals']['queue'];
2044 $report['event_totals']['optout_rate'] = (100.0 * $report['event_totals']['optout']) / $report['event_totals']['queue'];
2047 $report['event_totals']['delivered_rate'] = 0;
2048 $report['event_totals']['bounce_rate'] = 0;
2049 $report['event_totals']['unsubscribe_rate'] = 0;
2050 $report['event_totals']['optout_rate'] = 0;
2053 /* Get the click-through totals, grouped by URL */
2056 SELECT {$t['url']}.url,
2058 COUNT({$t['urlopen']}.id) as clicks,
2059 COUNT(DISTINCT {$t['queue']}.id) as unique_clicks
2061 LEFT JOIN {$t['urlopen']}
2062 ON {$t['urlopen']}.trackable_url_id = {$t['url']}.id
2063 LEFT JOIN {$t['queue']}
2064 ON {$t['urlopen']}.event_queue_id = {$t['queue']}.id
2065 LEFT JOIN {$t['job']}
2066 ON {$t['queue']}.job_id = {$t['job']}.id
2067 WHERE {$t['url']}.mailing_id = $mailing_id
2068 AND {$t['job']}.is_test = 0
2069 GROUP BY {$t['url']}.id");
2071 $report['click_through'] = array();
2073 while ($mailing->fetch()) {
2074 $report['click_through'][] = array(
2075 'url' => $mailing->url
,
2077 CRM_Utils_System
::url(
2078 'civicrm/mailing/report/event',
2079 "reset=1&event=click&mid=$mailing_id&uid={$mailing->id}"
2082 CRM_Utils_System
::url(
2083 'civicrm/mailing/report/event',
2084 "reset=1&event=click&mid=$mailing_id&uid={$mailing->id}&distinct=1"
2086 'clicks' => $mailing->clicks
,
2087 'unique' => $mailing->unique_clicks
,
2088 'rate' => CRM_Utils_Array
::value('delivered', $report['event_totals']) ?
(100.0 * $mailing->unique_clicks
) / $report['event_totals']['delivered'] : 0,
2092 $report['event_totals']['links'] = array(
2093 'clicks' => CRM_Utils_System
::url(
2094 'civicrm/mailing/report/event',
2095 "reset=1&event=click&mid=$mailing_id"
2097 'clicks_unique' => CRM_Utils_System
::url(
2098 'civicrm/mailing/report/event',
2099 "reset=1&event=click&mid=$mailing_id&distinct=1"
2101 'queue' => CRM_Utils_System
::url(
2102 'civicrm/mailing/report/event',
2103 "reset=1&event=queue&mid=$mailing_id"
2105 'delivered' => CRM_Utils_System
::url(
2106 'civicrm/mailing/report/event',
2107 "reset=1&event=delivered&mid=$mailing_id"
2109 'bounce' => CRM_Utils_System
::url(
2110 'civicrm/mailing/report/event',
2111 "reset=1&event=bounce&mid=$mailing_id"
2113 'unsubscribe' => CRM_Utils_System
::url(
2114 'civicrm/mailing/report/event',
2115 "reset=1&event=unsubscribe&mid=$mailing_id"
2117 'optout' => CRM_Utils_System
::url(
2118 'civicrm/mailing/report/event',
2119 "reset=1&event=optout&mid=$mailing_id"
2121 'forward' => CRM_Utils_System
::url(
2122 'civicrm/mailing/report/event',
2123 "reset=1&event=forward&mid=$mailing_id"
2125 'reply' => CRM_Utils_System
::url(
2126 'civicrm/mailing/report/event',
2127 "reset=1&event=reply&mid=$mailing_id"
2129 'opened' => CRM_Utils_System
::url(
2130 'civicrm/mailing/report/event',
2131 "reset=1&event=opened&mid=$mailing_id"
2136 $actionLinks = array(CRM_Core_Action
::VIEW
=> array('name' => ts('Report')));
2137 if (CRM_Core_Permission
::check('view all contacts')) {
2138 $actionLinks[CRM_Core_Action
::ADVANCED
] =
2140 'name' => ts('Advanced Search'),
2141 'url' => 'civicrm/contact/search/advanced',
2144 $action = array_sum(array_keys($actionLinks));
2146 $report['event_totals']['actionlinks'] = array();
2148 'clicks', 'clicks_unique', 'queue', 'delivered', 'bounce', 'unsubscribe',
2149 'forward', 'reply', 'opened', 'optout',
2151 $url = 'mailing/detail';
2152 $reportFilter = "reset=1&mailing_id_value={$mailing_id}";
2153 $searchFilter = "force=1&mailing_id=%%mid%%";
2156 $reportFilter .= "&delivery_status_value=successful";
2157 $searchFilter .= "&mailing_delivery_status=Y";
2161 $url = "mailing/bounce";
2162 $searchFilter .= "&mailing_delivery_status=N";
2166 $reportFilter .= "&is_forwarded_value=1";
2167 $searchFilter .= "&mailing_forward=1";
2171 $reportFilter .= "&is_replied_value=1";
2172 $searchFilter .= "&mailing_reply_status=Y";
2176 $reportFilter .= "&is_unsubscribed_value=1";
2177 $searchFilter .= "&mailing_unsubscribe=1";
2181 $reportFilter .= "&is_optout_value=1";
2182 $searchFilter .= "&mailing_optout=1";
2186 $url = "mailing/opened";
2187 $searchFilter .= "&mailing_open_status=Y";
2191 case 'clicks_unique':
2192 $url = "mailing/clicks";
2193 $searchFilter .= "&mailing_click_status=Y";
2196 $actionLinks[CRM_Core_Action
::VIEW
]['url'] = CRM_Report_Utils_Report
::getNextUrl($url, $reportFilter, FALSE, TRUE);
2197 if (array_key_exists(CRM_Core_Action
::ADVANCED
, $actionLinks)) {
2198 $actionLinks[CRM_Core_Action
::ADVANCED
]['qs'] = $searchFilter;
2200 $report['event_totals']['actionlinks'][$key] = CRM_Core_Action
::formLink(
2203 array('mid' => $mailing_id),
2206 'mailing.report.action',
2216 * Get the count of mailings
2223 public function getCount() {
2225 $this->selectAdd('COUNT(id) as count');
2227 $session = CRM_Core_Session
::singleton();
2230 return $this->count
;
2238 static function checkPermission($id) {
2243 $mailingIDs = self
::mailingACLIDs();
2244 if ($mailingIDs === TRUE) {
2248 if (!in_array($id, $mailingIDs)) {
2249 CRM_Core_Error
::fatal(ts('You do not have permission to access this mailing report'));
2255 * @param null $alias
2259 static function mailingACL($alias = NULL) {
2260 $mailingACL = " ( 0 ) ";
2262 $mailingIDs = self
::mailingACLIDs();
2263 if ($mailingIDs === TRUE) {
2267 if (!empty($mailingIDs)) {
2268 $mailingIDs = implode(',', $mailingIDs);
2269 $tableName = !$alias ? self
::getTableName() : $alias;
2270 $mailingACL = " $tableName.id IN ( $mailingIDs ) ";
2276 * Returns all the mailings that this user can access. This is dependent on
2277 * all the groups that the user has access to.
2278 * However since most civi installs dont use ACL's we special case the condition
2279 * where the user has access to ALL groups, and hence ALL mailings and return a
2280 * value of TRUE (to avoid the downstream where clause with a list of mailing list IDs
2282 * @return boolean | array - TRUE if the user has access to all mailings, else array of mailing IDs (possibly empty)
2285 static function mailingACLIDs() {
2287 // optimize common case where admin has access
2290 CRM_Core_Permission
::check('view all contacts') ||
2291 CRM_Core_Permission
::check('edit all contacts')
2296 $mailingIDs = array();
2298 // get all the groups that this user can access
2299 // if they dont have universal access
2300 $groups = CRM_Core_PseudoConstant
::group(NULL, FALSE);
2301 if (!empty($groups)) {
2302 $groupIDs = implode(',', array_keys($groups));
2304 // get all the mailings that are in this subset of groups
2306 SELECT DISTINCT( m.id ) as id
2307 FROM civicrm_mailing m
2308 LEFT JOIN civicrm_mailing_group g ON g.mailing_id = m.id
2309 WHERE ( ( g.entity_table like 'civicrm_group%' AND g.entity_id IN ( $groupIDs ) )
2310 OR ( g.entity_table IS NULL AND g.entity_id IS NULL ) )
2312 $dao = CRM_Core_DAO
::executeQuery($query);
2314 $mailingIDs = array();
2315 while ($dao->fetch()) {
2316 $mailingIDs[] = $dao->id
;
2324 * Get the rows for a browse operation
2326 * @param int $offset The row number to start from
2327 * @param int $rowCount The nmber of rows to return
2328 * @param string $sort The sql string that describes the sort order
2330 * @param null $additionalClause
2331 * @param array $additionalParams
2333 * @return array The rows
2336 public function &getRows($offset, $rowCount, $sort, $additionalClause = NULL, $additionalParams = NULL) {
2337 $mailing = self
::getTableName();
2338 $job = CRM_Mailing_BAO_MailingJob
::getTableName();
2339 $group = CRM_Mailing_DAO_MailingGroup
::getTableName();
2340 $session = CRM_Core_Session
::singleton();
2342 $mailingACL = self
::mailingACL();
2344 //get all campaigns.
2345 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
2347 // we only care about parent jobs, since that holds all the info on
2353 $mailing.approval_status_id,
2354 MIN($job.scheduled_date) as scheduled_date,
2355 MIN($job.start_date) as start_date,
2356 MAX($job.end_date) as end_date,
2357 createdContact.sort_name as created_by,
2358 scheduledContact.sort_name as scheduled_by,
2359 $mailing.created_id as created_id,
2360 $mailing.scheduled_id as scheduled_id,
2361 $mailing.is_archived as archived,
2362 $mailing.created_date as created_date,
2364 $mailing.sms_provider_id as sms_provider_id
2366 LEFT JOIN $job ON ( $job.mailing_id = $mailing.id AND $job.is_test = 0 AND $job.parent_id IS NULL )
2367 LEFT JOIN civicrm_contact createdContact ON ( civicrm_mailing.created_id = createdContact.id )
2368 LEFT JOIN civicrm_contact scheduledContact ON ( civicrm_mailing.scheduled_id = scheduledContact.id )
2369 WHERE $mailingACL $additionalClause
2370 GROUP BY $mailing.id ";
2373 $orderBy = trim($sort->orderBy());
2374 if (!empty($orderBy)) {
2375 $query .= " ORDER BY $orderBy";
2380 $offset = CRM_Utils_Type
::escape($offset, 'Int');
2381 $rowCount = CRM_Utils_Type
::escape($rowCount, 'Int');
2383 $query .= " LIMIT $offset, $rowCount ";
2386 if (!$additionalParams) {
2387 $additionalParams = array();
2390 $dao = CRM_Core_DAO
::executeQuery($query, $additionalParams);
2393 while ($dao->fetch()) {
2396 'name' => $dao->name
,
2397 'status' => $dao->status ?
$dao->status
: 'Not scheduled',
2398 'created_date' => CRM_Utils_Date
::customFormat($dao->created_date
),
2399 'scheduled' => CRM_Utils_Date
::customFormat($dao->scheduled_date
),
2400 'scheduled_iso' => $dao->scheduled_date
,
2401 'start' => CRM_Utils_Date
::customFormat($dao->start_date
),
2402 'end' => CRM_Utils_Date
::customFormat($dao->end_date
),
2403 'created_by' => $dao->created_by
,
2404 'scheduled_by' => $dao->scheduled_by
,
2405 'created_id' => $dao->created_id
,
2406 'scheduled_id' => $dao->scheduled_id
,
2407 'archived' => $dao->archived
,
2408 'approval_status_id' => $dao->approval_status_id
,
2409 'campaign_id' => $dao->campaign_id
,
2410 'campaign' => empty($dao->campaign_id
) ?
NULL : $allCampaigns[$dao->campaign_id
],
2411 'sms_provider_id' => $dao->sms_provider_id
,
2418 * Show detail Mailing report
2426 static function showEmailDetails($id) {
2427 return CRM_Utils_System
::url('civicrm/mailing/report', "mid=$id");
2431 * Delete Mails and all its associated records
2433 * @param int $id id of the mail to delete
2439 public static function del($id) {
2441 CRM_Core_Error
::fatal();
2444 CRM_Utils_Hook
::pre('delete', 'Mailing', $id, CRM_Core_DAO
::$_nullArray);
2446 // delete all file attachments
2447 CRM_Core_BAO_File
::deleteEntityFile('civicrm_mailing',
2451 $dao = new CRM_Mailing_DAO_Mailing();
2455 CRM_Core_Session
::setStatus(ts('Selected mailing has been deleted.'), ts('Deleted'), 'success');
2457 CRM_Utils_Hook
::post('delete', 'Mailing', $id, $dao);
2461 * Delete Jobss and all its associated records
2462 * related to test Mailings
2464 * @param int $id id of the Job to delete
2470 public static function delJob($id) {
2472 CRM_Core_Error
::fatal();
2475 $dao = new CRM_Mailing_BAO_MailingJob();
2483 function getReturnProperties() {
2484 $tokens = &$this->getTokens();
2486 $properties = array();
2487 if (isset($tokens['html']) &&
2488 isset($tokens['html']['contact'])
2490 $properties = array_merge($properties, $tokens['html']['contact']);
2493 if (isset($tokens['text']) &&
2494 isset($tokens['text']['contact'])
2496 $properties = array_merge($properties, $tokens['text']['contact']);
2499 if (isset($tokens['subject']) &&
2500 isset($tokens['subject']['contact'])
2502 $properties = array_merge($properties, $tokens['subject']['contact']);
2505 $returnProperties = array();
2506 $returnProperties['display_name'] = $returnProperties['contact_id'] = $returnProperties['preferred_mail_format'] = $returnProperties['hash'] = 1;
2508 foreach ($properties as $p) {
2509 $returnProperties[$p] = 1;
2512 return $returnProperties;
2516 * Build the compose mail form
2518 * @param CRM_Core_Form $form
2523 public static function commonCompose(&$form) {
2525 $tokens = CRM_Core_SelectValues
::contactTokens();
2527 $className = CRM_Utils_System
::getClassName($form);
2528 if ($className == 'CRM_Mailing_Form_Upload') {
2529 $tokens = array_merge(CRM_Core_SelectValues
::mailingTokens(), $tokens);
2531 elseif ($className == 'CRM_Admin_Form_ScheduleReminders') {
2532 $tokens = array_merge(CRM_Core_SelectValues
::activityTokens(), $tokens);
2533 $tokens = array_merge(CRM_Core_SelectValues
::eventTokens(), $tokens);
2534 $tokens = array_merge(CRM_Core_SelectValues
::membershipTokens(), $tokens);
2536 elseif ($className == 'CRM_Event_Form_ManageEvent_ScheduleReminders') {
2537 $tokens = array_merge(CRM_Core_SelectValues
::eventTokens(), $tokens);
2540 //sorted in ascending order tokens by ignoring word case
2541 $form->assign('tokens', CRM_Utils_Token
::formatTokensForDisplay($tokens));
2543 $templates = array();
2545 $textFields = array('text_message' => ts('HTML Format'), 'sms_text_message' => ts('SMS Message'));
2546 $modePrefixes = array('Mail' => NULL, 'SMS' => 'SMS');
2548 if ($className != 'CRM_SMS_Form_Upload' && $className != 'CRM_Contact_Form_Task_SMS' &&
2549 $className != 'CRM_Contact_Form_Task_SMS'
2551 $form->addWysiwyg('html_message',
2554 'cols' => '80', 'rows' => '8',
2555 'onkeyup' => "return verify(this)",
2559 if ($className != 'CRM_Admin_Form_ScheduleReminders') {
2560 unset($modePrefixes['SMS']);
2564 unset($textFields['text_message']);
2565 unset($modePrefixes['Mail']);
2568 //insert message Text by selecting "Select Template option"
2569 foreach ($textFields as $id => $label) {
2571 if ($id == 'sms_text_message') {
2573 $form->assign('max_sms_length', CRM_SMS_Provider
::MAX_SMS_CHAR
);
2575 $form->add('textarea', $id, $label,
2577 'cols' => '80', 'rows' => '8',
2578 'onkeyup' => "return verify(this, '{$prefix}')",
2583 foreach ($modePrefixes as $prefix) {
2584 if ($prefix == 'SMS') {
2585 $templates[$prefix] = CRM_Core_BAO_MessageTemplate
::getMessageTemplates(FALSE, TRUE);
2588 $templates[$prefix] = CRM_Core_BAO_MessageTemplate
::getMessageTemplates(FALSE);
2591 if (!empty($templates[$prefix])) {
2592 $form->assign('templates', TRUE);
2594 $form->add('select', "{$prefix}template", ts('Use Template'),
2595 array('' => ts('- select -')) +
$templates[$prefix], FALSE,
2596 array('onChange' => "selectValue( this.value, '{$prefix}');")
2599 $form->add('checkbox', "{$prefix}updateTemplate", ts('Update Template'), NULL);
2601 $form->add('checkbox', "{$prefix}saveTemplate", ts('Save As New Template'), NULL, FALSE,
2602 array('onclick' => "showSaveDetails(this, '{$prefix}');")
2604 $form->add('text', "{$prefix}saveTemplateName", ts('Template Title'));
2609 * Build the compose PDF letter form
2611 * @param CRM_Core_Form $form
2616 public static function commonLetterCompose(&$form) {
2618 $tokens = CRM_Core_SelectValues
::contactTokens();
2619 if (CRM_Utils_System
::getClassName($form) == 'CRM_Mailing_Form_Upload') {
2620 $tokens = array_merge(CRM_Core_SelectValues
::mailingTokens(), $tokens);
2622 //@todo move this fn onto the form
2623 if (CRM_Utils_System
::getClassName($form) == 'CRM_Contribute_Form_Task_PDFLetter') {
2624 $tokens = array_merge(CRM_Core_SelectValues
::contributionTokens(), $tokens);
2627 if(method_exists($form, 'listTokens')) {
2628 $tokens = array_merge($form->listTokens(), $tokens);
2631 $form->assign('tokens', CRM_Utils_Token
::formatTokensForDisplay($tokens));
2633 $form->_templates
= CRM_Core_BAO_MessageTemplate
::getMessageTemplates(FALSE);
2634 if (!empty($form->_templates
)) {
2635 $form->assign('templates', TRUE);
2636 $form->add('select', 'template', ts('Select Template'),
2638 '' => ts('- select -')) +
$form->_templates
, FALSE,
2639 array('onChange' => "selectValue( this.value,'' );")
2641 $form->add('checkbox', 'updateTemplate', ts('Update Template'), NULL);
2644 $form->add('checkbox', 'saveTemplate', ts('Save As New Template'), NULL, FALSE,
2645 array('onclick' => "showSaveDetails(this);")
2647 $form->add('text', 'saveTemplateName', ts('Template Title'));
2650 $form->addWysiwyg('html_message',
2653 'cols' => '80', 'rows' => '8',
2654 'onkeyup' => "return verify(this)",
2657 $action = CRM_Utils_Request
::retrieve('action', 'String', $form, FALSE);
2658 if ((CRM_Utils_System
::getClassName($form) == 'CRM_Contact_Form_Task_PDF') &&
2659 $action == CRM_Core_Action
::VIEW
2661 $form->freeze('html_message');
2666 * Get the search based mailing Ids
2668 * @return array $mailingIDs, searched base mailing ids.
2671 public function searchMailingIDs() {
2672 $group = CRM_Mailing_DAO_MailingGroup
::getTableName();
2673 $mailing = self
::getTableName();
2676 SELECT $mailing.id as mailing_id
2677 FROM $mailing, $group
2678 WHERE $group.mailing_id = $mailing.id
2679 AND $group.group_type = 'Base'";
2681 $searchDAO = CRM_Core_DAO
::executeQuery($query);
2682 $mailingIDs = array();
2683 while ($searchDAO->fetch()) {
2684 $mailingIDs[] = $searchDAO->mailing_id
;
2691 * Get the content/components of mailing based on mailing Id
2693 * @param $report array of mailing report
2695 * @param $form reference of this
2697 * @param bool $isSMS
2699 * @return array $report array content/component.@access public
2701 static function getMailingContent(&$report, &$form, $isSMS = FALSE) {
2702 $htmlHeader = $textHeader = NULL;
2703 $htmlFooter = $textFooter = NULL;
2706 if ($report['mailing']['header_id']) {
2707 $header = new CRM_Mailing_BAO_Component();
2708 $header->id
= $report['mailing']['header_id'];
2709 $header->find(TRUE);
2710 $htmlHeader = $header->body_html
;
2711 $textHeader = $header->body_text
;
2714 if ($report['mailing']['footer_id']) {
2715 $footer = new CRM_Mailing_BAO_Component();
2716 $footer->id
= $report['mailing']['footer_id'];
2717 $footer->find(TRUE);
2718 $htmlFooter = $footer->body_html
;
2719 $textFooter = $footer->body_text
;
2723 $mailingKey = $form->_mailing_id
;
2725 if ($hash = CRM_Mailing_BAO_Mailing
::getMailingHash($mailingKey)) {
2726 $mailingKey = $hash;
2730 if (!empty($report['mailing']['body_text'])) {
2731 $url = CRM_Utils_System
::url('civicrm/mailing/view', 'reset=1&text=1&id=' . $mailingKey);
2732 $form->assign('textViewURL', $url);
2736 if (!empty($report['mailing']['body_html'])) {
2737 $url = CRM_Utils_System
::url('civicrm/mailing/view', 'reset=1&id=' . $mailingKey);
2738 $form->assign('htmlViewURL', $url);
2743 $report['mailing']['attachment'] = CRM_Core_BAO_File
::attachmentInfo('civicrm_mailing', $form->_mailing_id
);
2753 static function overrideVerp($jobID) {
2754 static $_cache = array();
2756 if (!isset($_cache[$jobID])) {
2758 SELECT override_verp
2759 FROM civicrm_mailing
2760 INNER JOIN civicrm_mailing_job ON civicrm_mailing.id = civicrm_mailing_job.mailing_id
2761 WHERE civicrm_mailing_job.id = %1
2763 $params = array(1 => array($jobID, 'Integer'));
2764 $_cache[$jobID] = CRM_Core_DAO
::singleValueQuery($query, $params);
2766 return $_cache[$jobID];
2775 static function processQueue($mode = NULL) {
2776 $config = &CRM_Core_Config
::singleton();
2778 if ($mode == NULL && CRM_Core_BAO_MailSettings
::defaultDomain() == "EXAMPLE.ORG") {
2779 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/")));
2782 // check if we are enforcing number of parallel cron jobs
2784 $gotCronLock = FALSE;
2786 if (property_exists($config, 'mailerJobsMax') && $config->mailerJobsMax
&& $config->mailerJobsMax
> 1) {
2787 $lockArray = range(1, $config->mailerJobsMax
);
2788 shuffle($lockArray);
2790 // check if we are using global locks
2791 $serverWideLock = CRM_Core_BAO_Setting
::getItem(
2792 CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
2793 'civimail_server_wide_lock'
2795 foreach ($lockArray as $lockID) {
2796 $cronLock = new CRM_Core_Lock("civimail.cronjob.{$lockID}", NULL, $serverWideLock);
2797 if ($cronLock->isAcquired()) {
2798 $gotCronLock = TRUE;
2803 // exit here since we have enuf cronjobs running
2804 if (!$gotCronLock) {
2805 CRM_Core_Error
::debug_log_message('Returning early, since max number of cronjobs running');
2810 // load bootstrap to call hooks
2812 // Split up the parent jobs into multiple child jobs
2813 $mailerJobSize = (property_exists($config, 'mailerJobSize')) ?
$config->mailerJobSize
: NULL;
2814 CRM_Mailing_BAO_MailingJob
::runJobs_pre($mailerJobSize, $mode);
2815 CRM_Mailing_BAO_MailingJob
::runJobs(NULL, $mode);
2816 CRM_Mailing_BAO_MailingJob
::runJobs_post($mode);
2818 // lets release the global cron lock if we do have one
2820 $cronLock->release();
2827 * @param int $mailingID
2829 private static function addMultipleEmails($mailingID) {
2831 INSERT INTO civicrm_mailing_recipients
2832 (mailing_id, email_id, contact_id)
2833 SELECT %1, e.id, e.contact_id FROM civicrm_email e
2835 AND e.is_bulkmail = 1
2837 ( SELECT contact_id FROM civicrm_mailing_recipients mr WHERE mailing_id = %1 )
2838 AND e.id NOT IN ( SELECT email_id FROM civicrm_mailing_recipients mr WHERE mailing_id = %1 )
2840 $params = array(1 => array($mailingID, 'Integer'));
2842 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2846 * @param bool $isSMS
2850 static function getMailingsList($isSMS = FALSE) {
2851 static $list = array();
2854 $where .= " civicrm_mailing.sms_provider_id IS NULL ";
2857 $where .= " civicrm_mailing.sms_provider_id IS NOT NULL ";
2862 SELECT civicrm_mailing.id, civicrm_mailing.name, civicrm_mailing_job.end_date
2863 FROM civicrm_mailing
2864 INNER JOIN civicrm_mailing_job ON civicrm_mailing.id = civicrm_mailing_job.mailing_id {$where}
2865 ORDER BY civicrm_mailing.name";
2866 $mailing = CRM_Core_DAO
::executeQuery($query);
2868 while ($mailing->fetch()) {
2869 $list[$mailing->id
] = "{$mailing->name} :: {$mailing->end_date}";
2879 * @return null|string
2881 static function hiddenMailingGroup($mid) {
2884 FROM civicrm_mailing m
2885 INNER JOIN civicrm_mailing_group mg ON mg.mailing_id = m.id
2886 INNER JOIN civicrm_group g ON mg.entity_id = g.id AND mg.entity_table = 'civicrm_group'
2887 WHERE g.is_hidden = 1
2888 AND mg.group_type = 'Include'
2891 $params = array( 1 => array( $mid, 'Integer' ) );
2892 return CRM_Core_DAO
::singleValueQuery($sql, $params);
2896 * This function is a wrapper for ajax activity selector
2898 * @param array $params associated array for params record id.
2900 * @return array $contactActivities associated array of contact activities
2903 public static function getContactMailingSelector(&$params) {
2904 // format the params
2905 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2906 $params['rowCount'] = $params['rp'];
2907 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
2908 $params['caseId'] = NULL;
2910 // get contact mailings
2911 $mailings = CRM_Mailing_BAO_Mailing
::getContactMailings($params);
2914 $params['total'] = CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2917 if (!empty($mailings)) {
2918 $openCounts = CRM_Mailing_Event_BAO_Opened
::getMailingContactCount(array_keys($mailings), $params['contact_id']);
2919 $clickCounts = CRM_Mailing_Event_BAO_TrackableURLOpen
::getMailingContactCount(array_keys($mailings), $params['contact_id']);
2922 // format params and add links
2923 $contactMailings = array();
2924 foreach ($mailings as $mailingId => $values) {
2925 $contactMailings[$mailingId]['subject'] = $values['subject'];
2926 $contactMailings[$mailingId]['start_date'] = CRM_Utils_Date
::customFormat($values['start_date']);
2927 $contactMailings[$mailingId]['recipients'] = CRM_Utils_System
::href(ts('(recipients)'), 'civicrm/mailing/report/event',
2928 "mid={$values['mailing_id']}&reset=1&cid={$params['contact_id']}&event=queue&context=mailing");
2930 $contactMailings[$mailingId]['mailing_creator'] = CRM_Utils_System
::href(
2931 $values['creator_name'],
2932 'civicrm/contact/view',
2933 "reset=1&cid={$values['creator_id']}");
2936 $contactMailings[$mailingId]['openstats'] = "Opens: ".
2937 CRM_Utils_Array
::value($values['mailing_id'], $openCounts, 0).
2939 CRM_Utils_Array
::value($values['mailing_id'], $clickCounts, 0);
2941 $actionLinks = array(
2942 CRM_Core_Action
::VIEW
=> array(
2943 'name' => ts('View'),
2944 'url' => 'civicrm/mailing/view',
2945 'qs' => "reset=1&id=%%mkey%%",
2946 'title' => ts('View Mailing'),
2947 'class' => 'crm-popup',
2949 CRM_Core_Action
::BROWSE
=> array(
2950 'name' => ts('Mailing Report'),
2951 'url' => 'civicrm/mailing/report',
2952 'qs' => "mid=%%mid%%&reset=1&cid=%%cid%%&context=mailing",
2953 'title' => ts('View Mailing Report'),
2957 $mailingKey = $values['mailing_id'];
2958 if ($hash = CRM_Mailing_BAO_Mailing
::getMailingHash($mailingKey)) {
2959 $mailingKey = $hash;
2962 $contactMailings[$mailingId]['links'] = CRM_Core_Action
::formLink(
2966 'mid' => $values['mailing_id'],
2967 'cid' => $params['contact_id'],
2968 'mkey' => $mailingKey,
2972 'mailing.contact.action',
2974 $values['mailing_id']
2978 return $contactMailings;
2982 * Retrieve contact mailing
2984 * @param array $params associated array
2986 * @return array of mailings for a contact
2991 static public function getContactMailings(&$params) {
2992 $params['version'] = 3;
2993 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2994 $params['limit'] = $params['rp'];
2995 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
2997 $result = civicrm_api('MailingContact', 'get', $params);
2998 return $result['values'];
3002 * Retrieve contact mailing count
3004 * @param array $params associated array
3006 * @return int count of mailings for a contact
3011 static public function getContactMailingsCount(&$params) {
3012 $params['version'] = 3;
3013 return civicrm_api('MailingContact', 'getcount', $params);