3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
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-2013
35 require_once 'Mail/mime.php';
36 class CRM_Mailing_BAO_Mailing
extends CRM_Mailing_DAO_Mailing
{
39 * An array that holds the complete templates
40 * including any headers or footers that need to be prepended
41 * or appended to the body
43 private $preparedTemplates = NULL;
46 * An array that holds the complete templates
47 * including any headers or footers that need to be prepended
48 * or appended to the body
50 private $templates = NULL;
53 * An array that holds the tokens that are specifically found in our text and html bodies
55 private $tokens = NULL;
58 * An array that holds the tokens that are specifically found in our text and html bodies
60 private $flattenedTokens = NULL;
63 * The header associated with this mailing
65 private $header = NULL;
68 * The footer associated with this mailing
70 private $footer = NULL;
73 * The HTML content of the message
78 * The text content of the message
83 * Cached BAO for the domain
85 private $_domain = NULL;
90 function __construct() {
91 parent
::__construct();
94 static function &getRecipientsCount($job_id, $mailing_id = NULL, $mode = NULL) {
95 // need this for backward compatibility, so we can get count for old mailings
96 // please do not use this function if possible
97 $eq = self
::getRecipients($job_id, $mailing_id);
101 // note that $job_id is used only as a variable in the temp table construction
102 // and does not play a role in the queries generated
103 static function &getRecipients(
108 $storeRecipients = FALSE,
109 $dedupeEmail = FALSE,
111 $mailingGroup = new CRM_Mailing_DAO_MailingGroup();
113 $mailing = CRM_Mailing_BAO_Mailing
::getTableName();
114 $job = CRM_Mailing_BAO_MailingJob
::getTableName();
115 $mg = CRM_Mailing_DAO_MailingGroup
::getTableName();
116 $eq = CRM_Mailing_Event_DAO_Queue
::getTableName();
117 $ed = CRM_Mailing_Event_DAO_Delivered
::getTableName();
118 $eb = CRM_Mailing_Event_DAO_Bounce
::getTableName();
120 $email = CRM_Core_DAO_Email
::getTableName();
121 if ($mode == 'sms') {
122 $phone = CRM_Core_DAO_Phone
::getTableName();
124 $contact = CRM_Contact_DAO_Contact
::getTableName();
126 $group = CRM_Contact_DAO_Group
::getTableName();
127 $g2contact = CRM_Contact_DAO_GroupContact
::getTableName();
129 /* Create a temp table for contact exclusion */
130 $mailingGroup->query(
131 "CREATE TEMPORARY TABLE X_$job_id
132 (contact_id int primary key)
136 /* Add all the members of groups excluded from this mailing to the temp
139 $excludeSubGroup = "INSERT INTO X_$job_id (contact_id)
140 SELECT DISTINCT $g2contact.contact_id
143 ON $g2contact.group_id = $mg.entity_id AND $mg.entity_table = '$group'
145 $mg.mailing_id = {$mailing_id}
146 AND $g2contact.status = 'Added'
147 AND $mg.group_type = 'Exclude'";
148 $mailingGroup->query($excludeSubGroup);
150 /* Add all unsubscribe members of base group from this mailing to the temp
153 $unSubscribeBaseGroup = "INSERT INTO X_$job_id (contact_id)
154 SELECT DISTINCT $g2contact.contact_id
157 ON $g2contact.group_id = $mg.entity_id AND $mg.entity_table = '$group'
159 $mg.mailing_id = {$mailing_id}
160 AND $g2contact.status = 'Removed'
161 AND $mg.group_type = 'Base'";
162 $mailingGroup->query($unSubscribeBaseGroup);
164 /* Add all the (intended) recipients of an excluded prior mailing to
167 $excludeSubMailing = "INSERT IGNORE INTO X_$job_id (contact_id)
168 SELECT DISTINCT $eq.contact_id
171 ON $eq.job_id = $job.id
173 ON $job.mailing_id = $mg.entity_id AND $mg.entity_table = '$mailing'
175 $mg.mailing_id = {$mailing_id}
176 AND $mg.group_type = 'Exclude'";
177 $mailingGroup->query($excludeSubMailing);
179 // get all the saved searches AND hierarchical groups
180 // and load them in the cache
182 SELECT $group.id, $group.cache_date, $group.saved_search_id, $group.children
184 INNER JOIN $mg ON $mg.entity_id = $group.id
185 WHERE $mg.entity_table = '$group'
186 AND $mg.group_type = 'Exclude'
187 AND $mg.mailing_id = {$mailing_id}
188 AND ( saved_search_id != 0
189 OR saved_search_id IS NOT NULL
190 OR children IS NOT NULL )
193 $groupDAO = CRM_Core_DAO
::executeQuery($sql);
194 while ($groupDAO->fetch()) {
195 if ($groupDAO->cache_date
== NULL) {
196 CRM_Contact_BAO_GroupContactCache
::load($groupDAO);
199 $smartGroupExclude = "
200 INSERT IGNORE INTO X_$job_id (contact_id)
202 FROM civicrm_group_contact_cache c
203 WHERE c.group_id = {$groupDAO->id}
205 $mailingGroup->query($smartGroupExclude);
208 $tempColumn = 'email_id';
209 if ($mode == 'sms') {
210 $tempColumn = 'phone_id';
213 /* Get all the group contacts we want to include */
215 $mailingGroup->query(
216 "CREATE TEMPORARY TABLE I_$job_id
217 ($tempColumn int, contact_id int primary key)
221 /* Get the group contacts, but only those which are not in the
222 * exclusion temp table */
224 $query = "REPLACE INTO I_$job_id (email_id, contact_id)
226 SELECT DISTINCT $email.id as email_id,
227 $contact.id as contact_id
230 ON $email.contact_id = $contact.id
231 INNER JOIN $g2contact
232 ON $contact.id = $g2contact.contact_id
234 ON $g2contact.group_id = $mg.entity_id
235 AND $mg.entity_table = '$group'
237 ON $contact.id = X_$job_id.contact_id
239 ($mg.group_type = 'Include')
240 AND $mg.search_id IS NULL
241 AND $g2contact.status = 'Added'
242 AND $contact.do_not_email = 0
243 AND $contact.is_opt_out = 0
244 AND $contact.is_deceased = 0
245 AND ($email.is_bulkmail = 1 OR $email.is_primary = 1)
246 AND $email.email IS NOT NULL
247 AND $email.email != ''
248 AND $email.on_hold = 0
249 AND $mg.mailing_id = {$mailing_id}
250 AND X_$job_id.contact_id IS null
251 ORDER BY $email.is_bulkmail";
253 if ($mode == 'sms') {
254 $phoneTypes = CRM_Core_OptionGroup
::values('phone_type', TRUE, FALSE, FALSE, NULL, 'name');
255 $query = "REPLACE INTO I_$job_id (phone_id, contact_id)
257 SELECT DISTINCT $phone.id as phone_id,
258 $contact.id as contact_id
261 ON $phone.contact_id = $contact.id
262 INNER JOIN $g2contact
263 ON $contact.id = $g2contact.contact_id
265 ON $g2contact.group_id = $mg.entity_id
266 AND $mg.entity_table = '$group'
268 ON $contact.id = X_$job_id.contact_id
270 ($mg.group_type = 'Include')
271 AND $mg.search_id IS NULL
272 AND $g2contact.status = 'Added'
273 AND $contact.do_not_sms = 0
274 AND $contact.is_opt_out = 0
275 AND $contact.is_deceased = 0
276 AND $phone.phone_type_id = {$phoneTypes['Mobile']}
277 AND $phone.phone IS NOT NULL
278 AND $phone.phone != ''
279 AND $mg.mailing_id = {$mailing_id}
280 AND X_$job_id.contact_id IS null";
282 $mailingGroup->query($query);
284 /* Query prior mailings */
286 $query = "REPLACE INTO I_$job_id (email_id, contact_id)
287 SELECT DISTINCT $email.id as email_id,
288 $contact.id as contact_id
291 ON $email.contact_id = $contact.id
293 ON $eq.contact_id = $contact.id
295 ON $eq.job_id = $job.id
297 ON $job.mailing_id = $mg.entity_id AND $mg.entity_table = '$mailing'
299 ON $contact.id = X_$job_id.contact_id
301 ($mg.group_type = 'Include')
302 AND $contact.do_not_email = 0
303 AND $contact.is_opt_out = 0
304 AND $contact.is_deceased = 0
305 AND ($email.is_bulkmail = 1 OR $email.is_primary = 1)
306 AND $email.on_hold = 0
307 AND $mg.mailing_id = {$mailing_id}
308 AND X_$job_id.contact_id IS null
309 ORDER BY $email.is_bulkmail";
311 if ($mode == 'sms') {
312 $query = "REPLACE INTO I_$job_id (phone_id, contact_id)
313 SELECT DISTINCT $phone.id as phone_id,
314 $contact.id as contact_id
317 ON $phone.contact_id = $contact.id
319 ON $eq.contact_id = $contact.id
321 ON $eq.job_id = $job.id
323 ON $job.mailing_id = $mg.entity_id AND $mg.entity_table = '$mailing'
325 ON $contact.id = X_$job_id.contact_id
327 ($mg.group_type = 'Include')
328 AND $contact.do_not_sms = 0
329 AND $contact.is_opt_out = 0
330 AND $contact.is_deceased = 0
331 AND $phone.phone_type_id = {$phoneTypes['Mobile']}
332 AND $mg.mailing_id = {$mailing_id}
333 AND X_$job_id.contact_id IS null";
335 $mailingGroup->query($query);
338 SELECT $group.id, $group.cache_date, $group.saved_search_id, $group.children
340 INNER JOIN $mg ON $mg.entity_id = $group.id
341 WHERE $mg.entity_table = '$group'
342 AND $mg.group_type = 'Include'
343 AND $mg.search_id IS NULL
344 AND $mg.mailing_id = {$mailing_id}
345 AND ( saved_search_id != 0
346 OR saved_search_id IS NOT NULL
347 OR children IS NOT NULL )
350 $groupDAO = CRM_Core_DAO
::executeQuery($sql);
351 while ($groupDAO->fetch()) {
352 if ($groupDAO->cache_date
== NULL) {
353 CRM_Contact_BAO_GroupContactCache
::load($groupDAO);
356 $smartGroupInclude = "
357 INSERT IGNORE INTO I_$job_id (email_id, contact_id)
358 SELECT e.id as email_id, c.id as contact_id
359 FROM civicrm_contact c
360 INNER JOIN civicrm_email e ON e.contact_id = c.id
361 INNER JOIN civicrm_group_contact_cache gc ON gc.contact_id = c.id
362 LEFT JOIN X_$job_id ON X_$job_id.contact_id = c.id
363 WHERE gc.group_id = {$groupDAO->id}
364 AND c.do_not_email = 0
366 AND c.is_deceased = 0
367 AND (e.is_bulkmail = 1 OR e.is_primary = 1)
369 AND X_$job_id.contact_id IS null
370 ORDER BY e.is_bulkmail
372 if ($mode == 'sms') {
373 $smartGroupInclude = "
374 INSERT IGNORE INTO I_$job_id (phone_id, contact_id)
375 SELECT p.id as phone_id, c.id as contact_id
376 FROM civicrm_contact c
377 INNER JOIN civicrm_phone p ON p.contact_id = c.id
378 INNER JOIN civicrm_group_contact_cache gc ON gc.contact_id = c.id
379 LEFT JOIN X_$job_id ON X_$job_id.contact_id = c.id
380 WHERE gc.group_id = {$groupDAO->id}
383 AND c.is_deceased = 0
384 AND p.phone_type_id = {$phoneTypes['Mobile']}
385 AND X_$job_id.contact_id IS null";
387 $mailingGroup->query($smartGroupInclude);
391 * Construct the filtered search queries
394 SELECT search_id, search_args, entity_id
396 WHERE $mg.search_id IS NOT NULL
397 AND $mg.mailing_id = {$mailing_id}
399 $dao = CRM_Core_DAO
::executeQuery($query);
400 while ($dao->fetch()) {
401 $customSQL = CRM_Contact_BAO_SearchCustom
::civiMailSQL($dao->search_id
,
405 $query = "REPLACE INTO I_$job_id ({$tempColumn}, contact_id)
407 $mailingGroup->query($query);
410 /* Get the emails with only location override */
412 $query = "REPLACE INTO I_$job_id (email_id, contact_id)
413 SELECT DISTINCT $email.id as local_email_id,
414 $contact.id as contact_id
417 ON $email.contact_id = $contact.id
418 INNER JOIN $g2contact
419 ON $contact.id = $g2contact.contact_id
421 ON $g2contact.group_id = $mg.entity_id
423 ON $contact.id = X_$job_id.contact_id
425 $mg.entity_table = '$group'
426 AND $mg.group_type = 'Include'
427 AND $g2contact.status = 'Added'
428 AND $contact.do_not_email = 0
429 AND $contact.is_opt_out = 0
430 AND $contact.is_deceased = 0
431 AND ($email.is_bulkmail = 1 OR $email.is_primary = 1)
432 AND $email.on_hold = 0
433 AND $mg.mailing_id = {$mailing_id}
434 AND X_$job_id.contact_id IS null
435 ORDER BY $email.is_bulkmail";
436 if ($mode == "sms") {
437 $query = "REPLACE INTO I_$job_id (phone_id, contact_id)
438 SELECT DISTINCT $phone.id as phone_id,
439 $contact.id as contact_id
442 ON $phone.contact_id = $contact.id
443 INNER JOIN $g2contact
444 ON $contact.id = $g2contact.contact_id
446 ON $g2contact.group_id = $mg.entity_id
448 ON $contact.id = X_$job_id.contact_id
450 $mg.entity_table = '$group'
451 AND $mg.group_type = 'Include'
452 AND $g2contact.status = 'Added'
453 AND $contact.do_not_sms = 0
454 AND $contact.is_opt_out = 0
455 AND $contact.is_deceased = 0
456 AND $phone.phone_type_id = {$phoneTypes['Mobile']}
457 AND $mg.mailing_id = {$mailing_id}
458 AND X_$job_id.contact_id IS null";
460 $mailingGroup->query($query);
464 $eq = new CRM_Mailing_Event_BAO_Queue();
466 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission
::cacheClause();
467 $aclWhere = $aclWhere ?
"WHERE {$aclWhere}" : '';
469 if ($limit && $offset !== NULL) {
470 $limitString = "LIMIT $offset, $limit";
473 if ($storeRecipients && $mailing_id) {
476 FROM civicrm_mailing_recipients
477 WHERE mailing_id = %1
479 $params = array(1 => array($mailing_id, 'Integer'));
480 CRM_Core_DAO
::executeQuery($sql, $params);
483 $groupBy = $groupJoin = '';
485 $groupJoin = " INNER JOIN civicrm_email e ON e.id = i.email_id";
486 $groupBy = " GROUP BY e.email ";
490 INSERT INTO civicrm_mailing_recipients ( mailing_id, contact_id, {$tempColumn} )
491 SELECT %1, i.contact_id, i.{$tempColumn}
492 FROM civicrm_contact contact_a
493 INNER JOIN I_$job_id i ON contact_a.id = i.contact_id
498 ORDER BY i.contact_id, i.{$tempColumn}
501 CRM_Core_DAO
::executeQuery($sql, $params);
503 // if we need to add all emails marked bulk, do it as a post filter
504 // on the mailing recipients table
505 if (CRM_Core_BAO_Email
::isMultipleBulkMail()) {
506 self
::addMultipleEmails($mailing_id);
510 /* Delete the temp table */
512 $mailingGroup->reset();
513 $mailingGroup->query("DROP TEMPORARY TABLE X_$job_id");
514 $mailingGroup->query("DROP TEMPORARY TABLE I_$job_id");
519 private function _getMailingGroupIds($type = 'Include') {
520 $mailingGroup = new CRM_Mailing_DAO_MailingGroup();
521 $group = CRM_Contact_DAO_Group
::getTableName();
522 if (!isset($thi->sid
)) {
523 // we're just testing tokens, so return any group
524 $query = "SELECT id AS entity_id
530 $query = "SELECT entity_id
532 WHERE mailing_id = {$this->id}
533 AND group_type = '$type'
534 AND entity_table = '$group'";
536 $mailingGroup->query($query);
539 while ($mailingGroup->fetch()) {
540 $groupIds[] = $mailingGroup->entity_id
;
548 * Returns the regex patterns that are used for preparing the text and html templates
553 private function &getPatterns($onlyHrefs = FALSE) {
557 $protos = '(https?|ftp)';
559 $gunk = '\{\}/#~:.?+=&;%@!\,\-';
561 $any = "{$letters}{$gunk}{$punc}";
563 $pattern = "\\bhref[ ]*=[ ]*([\"'])?(($protos:[$any]+?(?=[$punc]*[^$any]|$)))([\"'])?";
566 $pattern = "\\b($protos:[$any]+?(?=[$punc]*[^$any]|$))";
569 $patterns[] = $pattern;
570 $patterns[] = '\\\\\{\w+\.\w+\\\\\}|\{\{\w+\.\w+\}\}';
571 $patterns[] = '\{\w+\.\w+\}';
573 $patterns = '{' . join('|', $patterns) . '}im';
579 * returns an array that denotes the type of token that we are dealing with
580 * we use the type later on when we are doing a token replcement lookup
582 * @param string $token The token for which we will be doing adata lookup
584 * @return array $funcStruct An array that holds the token itself and the type.
585 * the type will tell us which function to use for the data lookup
586 * if we need to do a lookup at all
588 function &getDataFunc($token) {
589 static $_categories = NULL;
590 static $_categoryString = NULL;
592 $_categories = array(
599 CRM_Utils_Hook
::tokens($_categories);
600 $_categoryString = implode('|', array_keys($_categories));
603 $funcStruct = array('type' => NULL, 'token' => $token);
605 if ((preg_match('/^href/i', $token) ||
preg_match('/^http/i', $token))) {
606 // it is a url so we need to check to see if there are any tokens embedded
607 // if so then call this function again to get the token dataFunc
608 // and assign the type 'embedded' so that the data retrieving function
609 // will know what how to handle this token.
610 if (preg_match_all('/(\{\w+\.\w+\})/', $token, $matches)) {
611 $funcStruct['type'] = 'embedded_url';
612 $funcStruct['embed_parts'] = $funcStruct['token'] = array();
613 foreach ($matches[1] as $match) {
614 $preg_token = '/' . preg_quote($match, '/') . '/';
615 $list = preg_split($preg_token, $token, 2);
616 $funcStruct['embed_parts'][] = $list[0];
618 $funcStruct['token'][] = $this->getDataFunc($match);
620 // fixed truncated url, CRM-7113
622 $funcStruct['embed_parts'][] = $token;
626 $funcStruct['type'] = 'url';
629 elseif (preg_match('/^\{(' . $_categoryString . ')\.(\w+)\}$/', $token, $matches)) {
630 $funcStruct['type'] = $matches[1];
631 $funcStruct['token'] = $matches[2];
633 elseif (preg_match('/\\\\\{(\w+\.\w+)\\\\\}|\{\{(\w+\.\w+)\}\}/', $token, $matches)) {
634 // we are an escaped token
635 // so remove the escape chars
636 $unescaped_token = preg_replace('/\{\{|\}\}|\\\\\{|\\\\\}/', '', $matches[0]);
637 $funcStruct['token'] = '{' . $unescaped_token . '}';
644 * Prepares the text and html templates
645 * for generating the emails and returns a copy of the
651 private function getPreparedTemplates() {
652 if (!$this->preparedTemplates
) {
653 $patterns['html'] = $this->getPatterns(TRUE);
654 $patterns['subject'] = $patterns['text'] = $this->getPatterns();
655 $templates = $this->getTemplates();
657 $this->preparedTemplates
= array();
660 'html', 'text', 'subject') as $key) {
661 if (!isset($templates[$key])) {
667 $split_template = array();
669 $email = $templates[$key];
670 preg_match_all($patterns[$key], $email, $matches, PREG_PATTERN_ORDER
);
671 foreach ($matches[0] as $idx => $token) {
672 $preg_token = '/' . preg_quote($token, '/') . '/im';
673 list($split_template[], $email) = preg_split($preg_token, $email, 2);
674 array_push($tokens, $this->getDataFunc($token));
677 $split_template[] = $email;
679 $this->preparedTemplates
[$key]['template'] = $split_template;
680 $this->preparedTemplates
[$key]['tokens'] = $tokens;
683 return ($this->preparedTemplates
);
688 * Retrieve a ref to an array that holds the email and text templates for this email
689 * assembles the complete template including the header and footer
690 * that the user has uploaded or declared (if they have dome that)
693 * @return array reference to an assoc array
697 private function &getTemplates() {
698 if (!$this->templates
) {
699 $this->getHeaderFooter();
700 $this->templates
= array();
702 if ($this->body_text
) {
705 $template[] = $this->header
->body_text
;
708 $template[] = $this->body_text
;
711 $template[] = $this->footer
->body_text
;
714 $this->templates
['text'] = join("\n", $template);
717 if ($this->body_html
) {
721 $template[] = $this->header
->body_html
;
724 $template[] = $this->body_html
;
727 $template[] = $this->footer
->body_html
;
730 $this->templates
['html'] = join("\n", $template);
732 // this is where we create a text template from the html template if the text template did not exist
733 // this way we ensure that every recipient will receive an email even if the pref is set to text and the
734 // user uploads an html email only
735 if (!$this->body_text
) {
736 $this->templates
['text'] = CRM_Utils_String
::htmlToText($this->templates
['html']);
740 if ($this->subject
) {
742 $template[] = $this->subject
;
743 $this->templates
['subject'] = join("\n", $template);
746 return $this->templates
;
751 * Retrieve a ref to an array that holds all of the tokens in the email body
752 * where the keys are the type of token and the values are ordinal arrays
753 * that hold the token names (even repeated tokens) in the order in which
754 * they appear in the body of the email.
756 * note: the real work is done in the _getTokens() function
758 * this function needs to have some sort of a body assigned
759 * either text or html for this to have any meaningful impact
761 * @return array reference to an assoc array
765 public function &getTokens() {
766 if (!$this->tokens
) {
768 $this->tokens
= array('html' => array(), 'text' => array(), 'subject' => array());
770 if ($this->body_html
) {
771 $this->_getTokens('html');
772 if (!$this->body_text
) {
773 // Since the text template was created from html, use the html tokens.
774 // @see CRM_Mailing_BAO_Mailing::getTemplates()
775 $this->tokens
['text'] = $this->tokens
['html'];
779 if ($this->body_text
) {
780 $this->_getTokens('text');
783 if ($this->subject
) {
784 $this->_getTokens('subject');
788 return $this->tokens
;
792 * Returns the token set for all 3 parts as one set. This allows it to be sent to the
793 * hook in one call and standardizes it across other token workflows
795 * @return array reference to an assoc array
799 public function &getFlattenedTokens() {
800 if (!$this->flattenedTokens
) {
801 $tokens = $this->getTokens();
803 $this->flattenedTokens
= CRM_Utils_Token
::flattenTokens($tokens);
806 return $this->flattenedTokens
;
811 * _getTokens parses out all of the tokens that have been
812 * included in the html and text bodies of the email
813 * we get the tokens and then separate them into an
814 * internal structure named tokens that has the same
815 * form as the static tokens property(?) of the CRM_Utils_Token class.
816 * The difference is that there might be repeated token names as we want the
817 * structures to represent the order in which tokens were found from left to right, top to bottom.
820 * @param str $prop name of the property that holds the text that we want to scan for tokens (html, text)
825 private function _getTokens($prop) {
826 $templates = $this->getTemplates();
828 $newTokens = CRM_Utils_Token
::getTokens($templates[$prop]);
830 foreach ($newTokens as $type => $names) {
831 if (!isset($this->tokens
[$prop][$type])) {
832 $this->tokens
[$prop][$type] = array();
834 foreach ($names as $key => $name) {
835 $this->tokens
[$prop][$type][] = $name;
841 * Generate an event queue for a test job
843 * @params array $params contains form values
848 public function getTestRecipients($testParams) {
849 if (array_key_exists($testParams['test_group'], CRM_Core_PseudoConstant
::group())) {
850 $contacts = civicrm_api('contact','get', array(
852 'group' => $testParams['test_group'],
854 'options' => array('limit' => 100000000000,
858 foreach (array_keys($contacts['values']) as $groupContact) {
860 SELECT civicrm_email.id AS email_id,
861 civicrm_email.is_primary as is_primary,
862 civicrm_email.is_bulkmail as is_bulkmail
864 INNER JOIN civicrm_contact ON civicrm_email.contact_id = civicrm_contact.id
865 WHERE (civicrm_email.is_bulkmail = 1 OR civicrm_email.is_primary = 1)
866 AND civicrm_contact.id = {$groupContact}
867 AND civicrm_contact.do_not_email = 0
868 AND civicrm_contact.is_deceased = 0
869 AND civicrm_email.on_hold = 0
870 AND civicrm_contact.is_opt_out = 0
871 GROUP BY civicrm_email.id
872 ORDER BY civicrm_email.is_bulkmail DESC
874 $dao = CRM_Core_DAO
::executeQuery($query);
877 'job_id' => $testParams['job_id'],
878 'email_id' => $dao->email_id
,
879 'contact_id' => $groupContact,
881 $queue = CRM_Mailing_Event_BAO_Queue
::create($params);
888 * Retrieve the header and footer for this mailing
895 private function getHeaderFooter() {
896 if (!$this->header
and $this->header_id
) {
897 $this->header
= new CRM_Mailing_BAO_Component();
898 $this->header
->id
= $this->header_id
;
899 $this->header
->find(TRUE);
900 $this->header
->free();
903 if (!$this->footer
and $this->footer_id
) {
904 $this->footer
= new CRM_Mailing_BAO_Component();
905 $this->footer
->id
= $this->footer_id
;
906 $this->footer
->find(TRUE);
907 $this->footer
->free();
912 * Given and array of headers and a prefix, job ID, event queue ID, and hash,
913 * add a Message-ID header if needed.
915 * i.e. if the global includeMessageId is set and there isn't already a
916 * Message-ID in the array.
917 * The message ID is structured the same way as a verp. However no interpretation
918 * is placed on the values received, so they do not need to follow the verp
921 * @param array $headers Array of message headers to update, in-out
922 * @param string $prefix Prefix for the message ID, use same prefixes as verp
924 * @param string $job_id Job ID component of the generated message ID
925 * @param string $event_queue_id Event Queue ID component of the generated message ID
926 * @param string $hash Hash component of the generated message ID.
930 static function addMessageIdHeader(&$headers, $prefix, $job_id, $event_queue_id, $hash) {
931 $config = CRM_Core_Config
::singleton();
932 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
933 $emailDomain = CRM_Core_BAO_MailSettings
::defaultDomain();
934 $includeMessageId = CRM_Core_BAO_MailSettings
::includeMessageId();
936 if ($includeMessageId && (!array_key_exists('Message-ID', $headers))) {
937 $headers['Message-ID'] = '<' . implode($config->verpSeparator
,
939 $localpart . $prefix,
944 ) . "@{$emailDomain}>";
949 * static wrapper for getting verp and urls
951 * @param int $job_id ID of the Job associated with this message
952 * @param int $event_queue_id ID of the EventQueue
953 * @param string $hash Hash of the EventQueue
954 * @param string $email Destination address
956 * @return (reference) array array ref that hold array refs to the verp info and urls
958 static function getVerpAndUrls($job_id, $event_queue_id, $hash, $email) {
959 // create a skeleton object and set its properties that are required by getVerpAndUrlsAndHeaders()
960 $config = CRM_Core_Config
::singleton();
961 $bao = new CRM_Mailing_BAO_Mailing();
962 $bao->_domain
= CRM_Core_BAO_Domain
::getDomain();
963 $bao->from_name
= $bao->from_email
= $bao->subject
= '';
965 // use $bao's instance method to get verp and urls
966 list($verp, $urls, $_) = $bao->getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email);
967 return array($verp, $urls);
971 * get verp, urls and headers
973 * @param int $job_id ID of the Job associated with this message
974 * @param int $event_queue_id ID of the EventQueue
975 * @param string $hash Hash of the EventQueue
976 * @param string $email Destination address
978 * @return (reference) array array ref that hold array refs to the verp info, urls, and headers
981 private function getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email, $isForward = FALSE) {
982 $config = CRM_Core_Config
::singleton();
986 * reply: user replied to mailing
987 * bounce: email address bounced
988 * unsubscribe: contact opts out of all target lists for the mailing
989 * resubscribe: contact opts back into all target lists for the mailing
990 * optOut: contact unsubscribes from the domain
996 'unsubscribe' => 'u',
997 'resubscribe' => 'e',
1001 $localpart = CRM_Core_BAO_MailSettings
::defaultLocalpart();
1002 $emailDomain = CRM_Core_BAO_MailSettings
::defaultDomain();
1004 foreach ($verpTokens as $key => $value) {
1005 $verp[$key] = implode($config->verpSeparator
,
1007 $localpart . $value,
1012 ) . "@$emailDomain";
1015 //handle should override VERP address.
1016 $skipEncode = FALSE;
1019 self
::overrideVerp($job_id)
1021 $verp['reply'] = "\"{$this->from_name}\" <{$this->from_email}>";
1025 'forward' => CRM_Utils_System
::url('civicrm/mailing/forward',
1026 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1027 TRUE, NULL, TRUE, TRUE
1029 'unsubscribeUrl' => CRM_Utils_System
::url('civicrm/mailing/unsubscribe',
1030 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1031 TRUE, NULL, TRUE, TRUE
1033 'resubscribeUrl' => CRM_Utils_System
::url('civicrm/mailing/resubscribe',
1034 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1035 TRUE, NULL, TRUE, TRUE
1037 'optOutUrl' => CRM_Utils_System
::url('civicrm/mailing/optout',
1038 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1039 TRUE, NULL, TRUE, TRUE
1041 'subscribeUrl' => CRM_Utils_System
::url('civicrm/mailing/subscribe',
1043 TRUE, NULL, TRUE, TRUE
1048 'Reply-To' => $verp['reply'],
1049 'Return-Path' => $verp['bounce'],
1050 'From' => "\"{$this->from_name}\" <{$this->from_email}>",
1051 'Subject' => $this->subject
,
1052 'List-Unsubscribe' => "<mailto:{$verp['unsubscribe']}>",
1054 self
::addMessageIdHeader($headers, 'm', $job_id, $event_queue_id, $hash);
1056 $headers['Subject'] = "[Fwd:{$this->subject}]";
1058 return array(&$verp, &$urls, &$headers);
1064 * @param int $job_id ID of the Job associated with this message
1065 * @param int $event_queue_id ID of the EventQueue
1066 * @param string $hash Hash of the EventQueue
1067 * @param string $contactId ID of the Contact
1068 * @param string $email Destination address
1069 * @param string $recipient To: of the recipient
1070 * @param boolean $test Is this mailing a test?
1071 * @param boolean $isForward Is this mailing compose for forward?
1072 * @param string $fromEmail email address of who is forwardinf it.
1074 * @return object The mail object
1077 public function &compose($job_id, $event_queue_id, $hash, $contactId,
1078 $email, &$recipient, $test,
1079 $contactDetails, &$attachments, $isForward = FALSE,
1080 $fromEmail = NULL, $replyToEmail = NULL
1082 $config = CRM_Core_Config
::singleton();
1083 $knownTokens = $this->getTokens();
1085 if ($this->_domain
== NULL) {
1086 $this->_domain
= CRM_Core_BAO_Domain
::getDomain();
1089 list($verp, $urls, $headers) = $this->getVerpAndUrlsAndHeaders(
1097 //set from email who is forwarding it and not original one.
1099 unset($headers['From']);
1100 $headers['From'] = "<{$fromEmail}>";
1103 if ($replyToEmail && ($fromEmail != $replyToEmail)) {
1104 $headers['Reply-To'] = "{$replyToEmail}";
1107 if ($contactDetails) {
1108 $contact = $contactDetails;
1111 $params = array(array('contact_id', '=', $contactId, 0, 0));
1112 list($contact, $_) = CRM_Contact_BAO_Query
::apiQuery($params);
1115 $contact = reset($contact);
1117 if (!$contact ||
is_a($contact, 'CRM_Core_Error')) {
1118 CRM_Core_Error
::debug_log_message(ts('CiviMail will not send email to a non-existent contact: %1',
1119 array(1 => $contactId)
1121 // setting this because function is called by reference
1122 //@todo test not calling function by reference
1127 // also call the hook to get contact details
1128 CRM_Utils_Hook
::tokenValues($contact, $contactId, $job_id);
1131 $pTemplates = $this->getPreparedTemplates();
1134 foreach ($pTemplates as $type => $pTemplate) {
1135 $html = ($type == 'html') ?
TRUE : FALSE;
1136 $pEmails[$type] = array();
1137 $pEmail = &$pEmails[$type];
1138 $template = &$pTemplates[$type]['template'];
1139 $tokens = &$pTemplates[$type]['tokens'];
1141 if (!empty($tokens)) {
1142 foreach ($tokens as $idx => $token) {
1143 $token_data = $this->getTokenData($token, $html, $contact, $verp, $urls, $event_queue_id);
1144 array_push($pEmail, $template[$idx]);
1145 array_push($pEmail, $token_data);
1149 array_push($pEmail, $template[$idx]);
1152 if (isset($template[($idx +
1)])) {
1153 array_push($pEmail, $template[($idx +
1)]);
1158 if (isset($pEmails['html']) && is_array($pEmails['html']) && count($pEmails['html'])) {
1159 $html = &$pEmails['html'];
1163 if (isset($pEmails['text']) && is_array($pEmails['text']) && count($pEmails['text'])) {
1164 $text = &$pEmails['text'];
1167 // push the tracking url on to the html email if necessary
1168 if ($this->open_tracking
&& $html) {
1169 array_push($html, "\n" . '<img src="' . $config->userFrameworkResourceURL
.
1170 "extern/open.php?q=$event_queue_id\" width='1' height='1' alt='' border='0'>"
1174 $message = new Mail_mime("\n");
1176 $useSmarty = defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY ?
TRUE : FALSE;
1178 $smarty = CRM_Core_Smarty
::singleton();
1179 // also add the contact tokens to the template
1180 $smarty->assign_by_ref('contact', $contact);
1183 $mailParams = $headers;
1184 if ($text && ($test ||
$contact['preferred_mail_format'] == 'Text' ||
1185 $contact['preferred_mail_format'] == 'Both' ||
1186 ($contact['preferred_mail_format'] == 'HTML' && !array_key_exists('html', $pEmails))
1188 $textBody = join('', $text);
1190 $textBody = $smarty->fetch("string:$textBody");
1192 $mailParams['text'] = $textBody;
1195 if ($html && ($test ||
($contact['preferred_mail_format'] == 'HTML' ||
1196 $contact['preferred_mail_format'] == 'Both'
1198 $htmlBody = join('', $html);
1200 $htmlBody = $smarty->fetch("string:$htmlBody");
1202 $mailParams['html'] = $htmlBody;
1205 if (empty($mailParams['text']) && empty($mailParams['html'])) {
1207 // something went wrong, lets log it and return null (by reference)
1208 CRM_Core_Error
::debug_log_message(ts('CiviMail will not send an empty mail body, Skipping: %1',
1215 $mailParams['attachments'] = $attachments;
1217 $mailingSubject = CRM_Utils_Array
::value('subject', $pEmails);
1218 if (is_array($mailingSubject)) {
1219 $mailingSubject = join('', $mailingSubject);
1221 $mailParams['Subject'] = $mailingSubject;
1223 $mailParams['toName'] = CRM_Utils_Array
::value('display_name',
1226 $mailParams['toEmail'] = $email;
1228 CRM_Utils_Hook
::alterMailParams($mailParams, 'civimail');
1230 // CRM-10699 support custom email headers
1231 if (CRM_Utils_Array
::value('headers', $mailParams)) {
1232 $headers = array_merge($headers, $mailParams['headers']);
1234 //cycle through mailParams and set headers array
1235 foreach ($mailParams as $paramKey => $paramValue) {
1236 //exclude values not intended for the header
1237 if (!in_array($paramKey, array(
1238 'text', 'html', 'attachments', 'toName', 'toEmail'))) {
1239 $headers[$paramKey] = $paramValue;
1243 if (!empty($mailParams['text'])) {
1244 $message->setTxtBody($mailParams['text']);
1247 if (!empty($mailParams['html'])) {
1248 $message->setHTMLBody($mailParams['html']);
1251 if (!empty($mailParams['attachments'])) {
1252 foreach ($mailParams['attachments'] as $fileID => $attach) {
1253 $message->addAttachment($attach['fullPath'],
1254 $attach['mime_type'],
1255 $attach['cleanName']
1260 //pickup both params from mail params.
1261 $toName = trim($mailParams['toName']);
1262 $toEmail = trim($mailParams['toEmail']);
1263 if ($toName == $toEmail ||
1264 strpos($toName, '@') !== FALSE
1269 $toName = CRM_Utils_Mail
::formatRFC2822Name($toName);
1272 $headers['To'] = "$toName <$toEmail>";
1274 $headers['Precedence'] = 'bulk';
1275 // Will test in the mail processor if the X-VERP is set in the bounced email.
1276 // (As an option to replace real VERP for those that can't set it up)
1277 $headers['X-CiviMail-Bounce'] = $verp['bounce'];
1280 //token replacement of subject
1281 $headers['Subject'] = $mailingSubject;
1283 CRM_Utils_Mail
::setMimeParams($message);
1284 $headers = $message->headers($headers);
1286 //get formatted recipient
1287 $recipient = $headers['To'];
1289 // make sure we unset a lot of stuff
1301 * get mailing object and replaces subscribeInvite,
1302 * domain and mailing tokens
1305 public static function tokenReplace(&$mailing) {
1306 $domain = CRM_Core_BAO_Domain
::getDomain();
1308 foreach (array('text', 'html') as $type) {
1309 $tokens = $mailing->getTokens();
1310 if (isset($mailing->templates
[$type])) {
1311 $mailing->templates
[$type] = CRM_Utils_Token
::replaceSubscribeInviteTokens($mailing->templates
[$type]);
1312 $mailing->templates
[$type] = CRM_Utils_Token
::replaceDomainTokens(
1313 $mailing->templates
[$type],
1315 $type == 'html' ?
TRUE : FALSE,
1318 $mailing->templates
[$type] = CRM_Utils_Token
::replaceMailingTokens($mailing->templates
[$type], $mailing, NULL, $tokens[$type]);
1325 * getTokenData receives a token from an email
1326 * and returns the appropriate data for the token
1329 private function getTokenData(&$token_a, $html = FALSE, &$contact, &$verp, &$urls, $event_queue_id) {
1330 $type = $token_a['type'];
1331 $token = $token_a['token'];
1334 $useSmarty = defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY ?
TRUE : FALSE;
1336 if ($type == 'embedded_url') {
1337 $embed_data = array();
1338 foreach ($token as $t) {
1339 $embed_data[] = $this->getTokenData($t, $html = FALSE, $contact, $verp, $urls, $event_queue_id);
1341 $numSlices = count($embed_data);
1343 for ($i = 0; $i < $numSlices; $i++
) {
1344 $url .= "{$token_a['embed_parts'][$i]}{$embed_data[$i]}";
1346 if (isset($token_a['embed_parts'][$numSlices])) {
1347 $url .= $token_a['embed_parts'][$numSlices];
1349 // add trailing quote since we've gobbled it up in a previous regex
1350 // function getPatterns, line 431
1351 if (preg_match('/^href[ ]*=[ ]*\'/', $url)) {
1354 elseif (preg_match('/^href[ ]*=[ ]*\"/', $url)) {
1359 elseif ($type == 'url') {
1360 if ($this->url_tracking
) {
1361 $data = CRM_Mailing_BAO_TrackableURL
::getTrackerURL($token, $this->id
, $event_queue_id);
1367 elseif ($type == 'contact') {
1368 $data = CRM_Utils_Token
::getContactTokenReplacement($token, $contact, FALSE, FALSE, $useSmarty);
1370 elseif ($type == 'action') {
1371 $data = CRM_Utils_Token
::getActionTokenReplacement($token, $verp, $urls, $html);
1373 elseif ($type == 'domain') {
1374 $domain = CRM_Core_BAO_Domain
::getDomain();
1375 $data = CRM_Utils_Token
::getDomainTokenReplacement($token, $domain, $html);
1377 elseif ($type == 'mailing') {
1378 if ($token == 'name') {
1379 $data = $this->name
;
1381 elseif ($token == 'group') {
1382 $groups = $this->getGroupNames();
1383 $data = implode(', ', $groups);
1387 $data = CRM_Utils_Array
::value("{$type}.{$token}", $contact);
1393 * Return a list of group names for this mailing. Does not work with
1394 * prior-mailing targets.
1396 * @return array Names of groups receiving this mailing
1399 public function &getGroupNames() {
1400 if (!isset($this->id
)) {
1403 $mg = new CRM_Mailing_DAO_MailingGroup();
1404 $mgtable = CRM_Mailing_DAO_MailingGroup
::getTableName();
1405 $group = CRM_Contact_BAO_Group
::getTableName();
1407 $mg->query("SELECT $group.title as name FROM $mgtable
1408 INNER JOIN $group ON $mgtable.entity_id = $group.id
1409 WHERE $mgtable.mailing_id = {$this->id}
1410 AND $mgtable.entity_table = '$group'
1411 AND $mgtable.group_type = 'Include'
1412 ORDER BY $group.name");
1415 while ($mg->fetch()) {
1416 $groups[] = $mg->name
;
1423 * function to add the mailings
1425 * @param array $params reference array contains the values submitted by the form
1426 * @param array $ids reference array contains the id
1433 static function add(&$params, $ids = array()) {
1434 $id = CRM_Utils_Array
::value('mailing_id', $ids, CRM_Utils_Array
::value('id', $params));
1437 CRM_Utils_Hook
::pre('edit', 'Mailing', $id, $params);
1440 CRM_Utils_Hook
::pre('create', 'Mailing', NULL, $params);
1443 $mailing = new CRM_Mailing_DAO_Mailing();
1445 $mailing->domain_id
= CRM_Utils_Array
::value('domain_id', $params, CRM_Core_Config
::domainID());
1447 if (!isset($params['replyto_email']) &&
1448 isset($params['from_email'])
1450 $params['replyto_email'] = $params['from_email'];
1453 $mailing->copyValues($params);
1455 $result = $mailing->save();
1457 if (CRM_Utils_Array
::value('mailing', $ids)) {
1458 CRM_Utils_Hook
::post('edit', 'Mailing', $mailing->id
, $mailing);
1461 CRM_Utils_Hook
::post('create', 'Mailing', $mailing->id
, $mailing);
1468 * Construct a new mailing object, along with job and mailing_group
1469 * objects, from the form values of the create mailing wizard.
1471 * @params array $params Form values
1473 * @return object $mailing The new mailing object
1477 public static function create(&$params, $ids = array()) {
1480 // Do the below only for an insert
1481 // for an update, we should not set the defaults
1482 if (!isset($ids['id']) && !isset($ids['mailing_id'])) {
1483 // Retrieve domain email and name for default sender
1484 $domain = civicrm_api(
1489 'current_domain' => 1,
1493 if (isset($domain['from_email'])) {
1494 $domain_email = $domain['from_email'];
1495 $domain_name = $domain['from_name'];
1498 $domain_email = 'info@EXAMPLE.ORG';
1499 $domain_name = 'EXAMPLE.ORG';
1501 if (!isset($params['created_id'])) {
1502 $session =& CRM_Core_Session
::singleton();
1503 $params['created_id'] = $session->get('userID');
1506 // load the default config settings for each
1507 // eg reply_id, unsubscribe_id need to use
1508 // correct template IDs here
1509 'override_verp' => TRUE,
1510 'forward_replies' => FALSE,
1511 'open_tracking' => TRUE,
1512 'url_tracking' => TRUE,
1513 'visibility' => 'User and User Admin Only',
1514 'replyto_email' => $domain_email,
1515 'header_id' => CRM_Mailing_PseudoConstant
::defaultComponent('header_id', ''),
1516 'footer_id' => CRM_Mailing_PseudoConstant
::defaultComponent('footer_id', ''),
1517 'from_email' => $domain_email,
1518 'from_name' => $domain_name,
1519 'msg_template_id' => NULL,
1520 'contact_id' => $params['created_id'],
1521 'created_id' => $params['created_id'],
1522 'approver_id' => $params['created_id'],
1523 'auto_responder' => 0,
1524 'created_date' => date('YmdHis'),
1525 'scheduled_date' => date('YmdHis'),
1526 'approval_date' => date('YmdHis'),
1529 // Get the default from email address, if not provided.
1530 if (empty($defaults['from_email'])) {
1531 $defaultAddress = CRM_Core_OptionGroup
::values('from_email_address', NULL, NULL, NULL, ' AND is_default = 1');
1532 foreach ($defaultAddress as $id => $value) {
1533 if (preg_match('/"(.*)" <(.*)>/', $value, $match)) {
1534 $defaults['from_email'] = $match[2];
1535 $defaults['from_name'] = $match[1];
1540 $params = array_merge($defaults, $params);
1544 * Could check and warn for the following cases:
1546 * - groups OR mailings should be populated.
1547 * - body html OR body text should be populated.
1550 $transaction = new CRM_Core_Transaction();
1552 $mailing = self
::add($params, $ids);
1554 if (is_a($mailing, 'CRM_Core_Error')) {
1555 $transaction->rollback();
1559 $groupTableName = CRM_Contact_BAO_Group
::getTableName();
1560 $mailingTableName = CRM_Mailing_BAO_Mailing
::getTableName();
1562 /* Create the mailing group record */
1563 $mg = new CRM_Mailing_DAO_MailingGroup();
1564 foreach (array('groups', 'mailings') as $entity) {
1565 foreach (array('include', 'exclude', 'base') as $type) {
1566 if (isset($params[$entity]) &&
1567 CRM_Utils_Array
::value($type, $params[$entity]) &&
1568 is_array($params[$entity][$type])) {
1569 foreach ($params[$entity][$type] as $entityId) {
1571 $mg->mailing_id
= $mailing->id
;
1572 $mg->entity_table
= ($entity == 'groups') ?
$groupTableName : $mailingTableName;
1573 $mg->entity_id
= $entityId;
1574 $mg->group_type
= $type;
1581 if (!empty($params['search_id']) && !empty($params['group_id'])) {
1583 $mg->mailing_id
= $mailing->id
;
1584 $mg->entity_table
= $groupTableName;
1585 $mg->entity_id
= $params['group_id'];
1586 $mg->search_id
= $params['search_id'];
1587 $mg->search_args
= $params['search_args'];
1588 $mg->group_type
= 'Include';
1592 // check and attach and files as needed
1593 CRM_Core_BAO_File
::processAttachment($params, 'civicrm_mailing', $mailing->id
);
1595 $transaction->commit();
1598 * 'approval_status_id' set in
1599 * CRM_Mailing_Form_Schedule::postProcess() or via API.
1601 if (isset($params['approval_status_id']) && $params['approval_status_id']) {
1602 $job = new CRM_Mailing_BAO_MailingJob();
1603 $job->mailing_id
= $mailing->id
;
1604 $job->status
= 'Scheduled';
1606 $job->scheduled_date
= $params['scheduled_date'];
1608 // Populate the recipients.
1609 $mailing->getRecipients($job->id
, $mailing->id
, NULL, NULL, TRUE, FALSE);
1616 * Generate a report. Fetch event count information, mailing data, and job
1619 * @param int $id The mailing id to report
1620 * @param boolean $skipDetails whether return all detailed report
1622 * @return array Associative array of reporting data
1626 public static function &report($id, $skipDetails = FALSE, $isSMS = FALSE) {
1627 $mailing_id = CRM_Utils_Type
::escape($id, 'Integer');
1629 $mailing = new CRM_Mailing_BAO_Mailing();
1632 'mailing' => self
::getTableName(),
1633 'mailing_group' => CRM_Mailing_DAO_MailingGroup
::getTableName(),
1634 'group' => CRM_Contact_BAO_Group
::getTableName(),
1635 'job' => CRM_Mailing_BAO_MailingJob
::getTableName(),
1636 'queue' => CRM_Mailing_Event_BAO_Queue
::getTableName(),
1637 'delivered' => CRM_Mailing_Event_BAO_Delivered
::getTableName(),
1638 'opened' => CRM_Mailing_Event_BAO_Opened
::getTableName(),
1639 'reply' => CRM_Mailing_Event_BAO_Reply
::getTableName(),
1641 CRM_Mailing_Event_BAO_Unsubscribe
::getTableName(),
1642 'bounce' => CRM_Mailing_Event_BAO_Bounce
::getTableName(),
1643 'forward' => CRM_Mailing_Event_BAO_Forward
::getTableName(),
1644 'url' => CRM_Mailing_BAO_TrackableURL
::getTableName(),
1646 CRM_Mailing_Event_BAO_TrackableURLOpen
::getTableName(),
1647 'component' => CRM_Mailing_BAO_Component
::getTableName(),
1648 'spool' => CRM_Mailing_BAO_Spool
::getTableName(),
1653 $additionalWhereClause = " AND ";
1655 $additionalWhereClause .= " {$t['mailing']}.sms_provider_id IS NULL ";
1658 $additionalWhereClause .= " {$t['mailing']}.sms_provider_id IS NOT NULL ";
1661 /* Get the mailing info */
1664 SELECT {$t['mailing']}.*
1665 FROM {$t['mailing']}
1666 WHERE {$t['mailing']}.id = $mailing_id {$additionalWhereClause}");
1670 $report['mailing'] = array();
1671 foreach (array_keys(self
::fields()) as $field) {
1672 $report['mailing'][$field] = $mailing->$field;
1676 if ($campaignId = CRM_Utils_Array
::value('campaign_id', $report['mailing'])) {
1677 $campaigns = CRM_Campaign_BAO_Campaign
::getCampaigns($campaignId);
1678 $report['mailing']['campaign'] = $campaigns[$campaignId];
1681 //mailing report is called by activity
1682 //we dont need all detail report
1687 /* Get the component info */
1691 $components = array(
1692 'header' => ts('Header'),
1693 'footer' => ts('Footer'),
1694 'reply' => ts('Reply'),
1695 'unsubscribe' => ts('Unsubscribe'),
1696 'optout' => ts('Opt-Out'),
1698 foreach (array_keys($components) as $type) {
1699 $query[] = "SELECT {$t['component']}.name as name,
1701 {$t['component']}.id as id
1702 FROM {$t['component']}
1703 INNER JOIN {$t['mailing']}
1704 ON {$t['mailing']}.{$type}_id =
1705 {$t['component']}.id
1706 WHERE {$t['mailing']}.id = $mailing_id";
1708 $q = '(' . implode(') UNION (', $query) . ')';
1709 $mailing->query($q);
1711 $report['component'] = array();
1712 while ($mailing->fetch()) {
1713 $report['component'][] = array(
1714 'type' => $components[$mailing->type
],
1715 'name' => $mailing->name
,
1717 CRM_Utils_System
::url('civicrm/mailing/component',
1718 "reset=1&action=update&id={$mailing->id}"
1723 /* Get the recipient group info */
1726 SELECT {$t['mailing_group']}.group_type as group_type,
1727 {$t['group']}.id as group_id,
1728 {$t['group']}.title as group_title,
1729 {$t['group']}.is_hidden as group_hidden,
1730 {$t['mailing']}.id as mailing_id,
1731 {$t['mailing']}.name as mailing_name
1732 FROM {$t['mailing_group']}
1733 LEFT JOIN {$t['group']}
1734 ON {$t['mailing_group']}.entity_id = {$t['group']}.id
1735 AND {$t['mailing_group']}.entity_table =
1737 LEFT JOIN {$t['mailing']}
1738 ON {$t['mailing_group']}.entity_id =
1740 AND {$t['mailing_group']}.entity_table =
1743 WHERE {$t['mailing_group']}.mailing_id = $mailing_id
1746 $report['group'] = array('include' => array(), 'exclude' => array(), 'base' => array());
1747 while ($mailing->fetch()) {
1749 if (isset($mailing->group_id
)) {
1750 $row['id'] = $mailing->group_id
;
1751 $row['name'] = $mailing->group_title
;
1752 $row['link'] = CRM_Utils_System
::url('civicrm/group/search',
1753 "reset=1&force=1&context=smog&gid={$row['id']}"
1757 $row['id'] = $mailing->mailing_id
;
1758 $row['name'] = $mailing->mailing_name
;
1759 $row['mailing'] = TRUE;
1760 $row['link'] = CRM_Utils_System
::url('civicrm/mailing/report',
1765 /* Rename hidden groups */
1767 if ($mailing->group_hidden
== 1) {
1768 $row['name'] = "Search Results";
1771 if ($mailing->group_type
== 'Include') {
1772 $report['group']['include'][] = $row;
1774 elseif ($mailing->group_type
== 'Base') {
1775 $report['group']['base'][] = $row;
1778 $report['group']['exclude'][] = $row;
1782 /* Get the event totals, grouped by job (retries) */
1785 SELECT {$t['job']}.*,
1786 COUNT(DISTINCT {$t['queue']}.id) as queue,
1787 COUNT(DISTINCT {$t['delivered']}.id) as delivered,
1788 COUNT(DISTINCT {$t['reply']}.id) as reply,
1789 COUNT(DISTINCT {$t['forward']}.id) as forward,
1790 COUNT(DISTINCT {$t['bounce']}.id) as bounce,
1791 COUNT(DISTINCT {$t['urlopen']}.id) as url,
1792 COUNT(DISTINCT {$t['spool']}.id) as spool
1794 LEFT JOIN {$t['queue']}
1795 ON {$t['queue']}.job_id = {$t['job']}.id
1796 LEFT JOIN {$t['reply']}
1797 ON {$t['reply']}.event_queue_id = {$t['queue']}.id
1798 LEFT JOIN {$t['forward']}
1799 ON {$t['forward']}.event_queue_id = {$t['queue']}.id
1800 LEFT JOIN {$t['bounce']}
1801 ON {$t['bounce']}.event_queue_id = {$t['queue']}.id
1802 LEFT JOIN {$t['delivered']}
1803 ON {$t['delivered']}.event_queue_id = {$t['queue']}.id
1804 AND {$t['bounce']}.id IS null
1805 LEFT JOIN {$t['urlopen']}
1806 ON {$t['urlopen']}.event_queue_id = {$t['queue']}.id
1807 LEFT JOIN {$t['spool']}
1808 ON {$t['spool']}.job_id = {$t['job']}.id
1809 WHERE {$t['job']}.mailing_id = $mailing_id
1810 AND {$t['job']}.is_test = 0
1811 GROUP BY {$t['job']}.id");
1813 $report['jobs'] = array();
1814 $report['event_totals'] = array();
1816 'queue', 'delivered', 'url', 'forward',
1817 'reply', 'unsubscribe', 'optout', 'opened', 'bounce', 'spool',
1820 // initialize various counters
1821 foreach ($elements as $field) {
1822 $report['event_totals'][$field] = 0;
1825 while ($mailing->fetch()) {
1827 foreach ($elements as $field) {
1828 if (isset($mailing->$field)) {
1829 $row[$field] = $mailing->$field;
1830 $report['event_totals'][$field] +
= $mailing->$field;
1834 // compute open total separately to discount duplicates
1836 $row['opened'] = CRM_Mailing_Event_BAO_Opened
::getTotalCount($mailing_id, $mailing->id
, TRUE);
1837 $report['event_totals']['opened'] +
= $row['opened'];
1839 // compute unsub total separately to discount duplicates
1841 $row['unsubscribe'] = CRM_Mailing_Event_BAO_Unsubscribe
::getTotalCount($mailing_id, $mailing->id
, TRUE, TRUE);
1842 $report['event_totals']['unsubscribe'] +
= $row['unsubscribe'];
1844 $row['optout'] = CRM_Mailing_Event_BAO_Unsubscribe
::getTotalCount($mailing_id, $mailing->id
, TRUE, FALSE);
1845 $report['event_totals']['optout'] +
= $row['optout'];
1847 foreach (array_keys(CRM_Mailing_BAO_MailingJob
::fields()) as $field) {
1848 $row[$field] = $mailing->$field;
1851 if ($mailing->queue
) {
1852 $row['delivered_rate'] = (100.0 * $mailing->delivered
) / $mailing->queue
;
1853 $row['bounce_rate'] = (100.0 * $mailing->bounce
) / $mailing->queue
;
1854 $row['unsubscribe_rate'] = (100.0 * $row['unsubscribe']) / $mailing->queue
;
1855 $row['optout_rate'] = (100.0 * $row['optout']) / $mailing->queue
;
1858 $row['delivered_rate'] = 0;
1859 $row['bounce_rate'] = 0;
1860 $row['unsubscribe_rate'] = 0;
1861 $row['optout_rate'] = 0;
1864 $row['links'] = array(
1865 'clicks' => CRM_Utils_System
::url(
1866 'civicrm/mailing/report/event',
1867 "reset=1&event=click&mid=$mailing_id&jid={$mailing->id}"
1869 'queue' => CRM_Utils_System
::url(
1870 'civicrm/mailing/report/event',
1871 "reset=1&event=queue&mid=$mailing_id&jid={$mailing->id}"
1873 'delivered' => CRM_Utils_System
::url(
1874 'civicrm/mailing/report/event',
1875 "reset=1&event=delivered&mid=$mailing_id&jid={$mailing->id}"
1877 'bounce' => CRM_Utils_System
::url(
1878 'civicrm/mailing/report/event',
1879 "reset=1&event=bounce&mid=$mailing_id&jid={$mailing->id}"
1881 'unsubscribe' => CRM_Utils_System
::url(
1882 'civicrm/mailing/report/event',
1883 "reset=1&event=unsubscribe&mid=$mailing_id&jid={$mailing->id}"
1885 'forward' => CRM_Utils_System
::url(
1886 'civicrm/mailing/report/event',
1887 "reset=1&event=forward&mid=$mailing_id&jid={$mailing->id}"
1889 'reply' => CRM_Utils_System
::url(
1890 'civicrm/mailing/report/event',
1891 "reset=1&event=reply&mid=$mailing_id&jid={$mailing->id}"
1893 'opened' => CRM_Utils_System
::url(
1894 'civicrm/mailing/report/event',
1895 "reset=1&event=opened&mid=$mailing_id&jid={$mailing->id}"
1900 'scheduled_date', 'start_date', 'end_date') as $key) {
1901 $row[$key] = CRM_Utils_Date
::customFormat($row[$key]);
1903 $report['jobs'][] = $row;
1906 $newTableSize = CRM_Mailing_BAO_Recipients
::mailingSize($mailing_id);
1908 // we need to do this for backward compatibility, since old mailings did not
1909 // use the mailing_recipients table
1910 if ($newTableSize > 0) {
1911 $report['event_totals']['queue'] = $newTableSize;
1914 $report['event_totals']['queue'] = self
::getRecipientsCount($mailing_id, $mailing_id);
1917 if (CRM_Utils_Array
::value('queue', $report['event_totals'])) {
1918 $report['event_totals']['delivered_rate'] = (100.0 * $report['event_totals']['delivered']) / $report['event_totals']['queue'];
1919 $report['event_totals']['bounce_rate'] = (100.0 * $report['event_totals']['bounce']) / $report['event_totals']['queue'];
1920 $report['event_totals']['unsubscribe_rate'] = (100.0 * $report['event_totals']['unsubscribe']) / $report['event_totals']['queue'];
1921 $report['event_totals']['optout_rate'] = (100.0 * $report['event_totals']['optout']) / $report['event_totals']['queue'];
1924 $report['event_totals']['delivered_rate'] = 0;
1925 $report['event_totals']['bounce_rate'] = 0;
1926 $report['event_totals']['unsubscribe_rate'] = 0;
1927 $report['event_totals']['optout_rate'] = 0;
1930 /* Get the click-through totals, grouped by URL */
1933 SELECT {$t['url']}.url,
1935 COUNT({$t['urlopen']}.id) as clicks,
1936 COUNT(DISTINCT {$t['queue']}.id) as unique_clicks
1938 LEFT JOIN {$t['urlopen']}
1939 ON {$t['urlopen']}.trackable_url_id = {$t['url']}.id
1940 LEFT JOIN {$t['queue']}
1941 ON {$t['urlopen']}.event_queue_id = {$t['queue']}.id
1942 LEFT JOIN {$t['job']}
1943 ON {$t['queue']}.job_id = {$t['job']}.id
1944 WHERE {$t['url']}.mailing_id = $mailing_id
1945 AND {$t['job']}.is_test = 0
1946 GROUP BY {$t['url']}.id");
1948 $report['click_through'] = array();
1950 while ($mailing->fetch()) {
1951 $report['click_through'][] = array(
1952 'url' => $mailing->url
,
1954 CRM_Utils_System
::url(
1955 'civicrm/mailing/report/event',
1956 "reset=1&event=click&mid=$mailing_id&uid={$mailing->id}"
1959 CRM_Utils_System
::url(
1960 'civicrm/mailing/report/event',
1961 "reset=1&event=click&mid=$mailing_id&uid={$mailing->id}&distinct=1"
1963 'clicks' => $mailing->clicks
,
1964 'unique' => $mailing->unique_clicks
,
1965 'rate' => CRM_Utils_Array
::value('delivered', $report['event_totals']) ?
(100.0 * $mailing->unique_clicks
) / $report['event_totals']['delivered'] : 0,
1969 $report['event_totals']['links'] = array(
1970 'clicks' => CRM_Utils_System
::url(
1971 'civicrm/mailing/report/event',
1972 "reset=1&event=click&mid=$mailing_id"
1974 'clicks_unique' => CRM_Utils_System
::url(
1975 'civicrm/mailing/report/event',
1976 "reset=1&event=click&mid=$mailing_id&distinct=1"
1978 'queue' => CRM_Utils_System
::url(
1979 'civicrm/mailing/report/event',
1980 "reset=1&event=queue&mid=$mailing_id"
1982 'delivered' => CRM_Utils_System
::url(
1983 'civicrm/mailing/report/event',
1984 "reset=1&event=delivered&mid=$mailing_id"
1986 'bounce' => CRM_Utils_System
::url(
1987 'civicrm/mailing/report/event',
1988 "reset=1&event=bounce&mid=$mailing_id"
1990 'unsubscribe' => CRM_Utils_System
::url(
1991 'civicrm/mailing/report/event',
1992 "reset=1&event=unsubscribe&mid=$mailing_id"
1994 'optout' => CRM_Utils_System
::url(
1995 'civicrm/mailing/report/event',
1996 "reset=1&event=optout&mid=$mailing_id"
1998 'forward' => CRM_Utils_System
::url(
1999 'civicrm/mailing/report/event',
2000 "reset=1&event=forward&mid=$mailing_id"
2002 'reply' => CRM_Utils_System
::url(
2003 'civicrm/mailing/report/event',
2004 "reset=1&event=reply&mid=$mailing_id"
2006 'opened' => CRM_Utils_System
::url(
2007 'civicrm/mailing/report/event',
2008 "reset=1&event=opened&mid=$mailing_id"
2013 $actionLinks = array(CRM_Core_Action
::VIEW
=> array('name' => ts('Report')));
2014 if (CRM_Core_Permission
::check('view all contacts')) {
2015 $actionLinks[CRM_Core_Action
::ADVANCED
] =
2017 'name' => ts('Advanced Search'),
2018 'url' => 'civicrm/contact/search/advanced',
2021 $action = array_sum(array_keys($actionLinks));
2023 $report['event_totals']['actionlinks'] = array();
2025 'clicks', 'clicks_unique', 'queue', 'delivered', 'bounce', 'unsubscribe',
2026 'forward', 'reply', 'opened', 'optout',
2028 $url = 'mailing/detail';
2029 $reportFilter = "reset=1&mailing_id_value={$mailing_id}";
2030 $searchFilter = "force=1&mailing_id={$mailing_id}";
2033 $reportFilter .= "&delivery_status_value=successful";
2034 $searchFilter .= "&mailing_delivery_status=Y";
2038 $url = "mailing/bounce";
2039 $searchFilter .= "&mailing_delivery_status=N";
2043 $reportFilter .= "&is_forwarded_value=1";
2044 $searchFilter .= "&mailing_forward=1";
2048 $reportFilter .= "&is_replied_value=1";
2049 $searchFilter .= "&mailing_reply_status=Y";
2053 $reportFilter .= "&is_unsubscribed_value=1";
2054 $searchFilter .= "&mailing_unsubscribe=1";
2058 $reportFilter .= "&is_optout_value=1";
2059 $searchFilter .= "&mailing_optout=1";
2063 $url = "mailing/opened";
2064 $searchFilter .= "&mailing_open_status=Y";
2068 case 'clicks_unique':
2069 $url = "mailing/clicks";
2070 $searchFilter .= "&mailing_click_status=Y";
2073 $actionLinks[CRM_Core_Action
::VIEW
]['url'] = CRM_Report_Utils_Report
::getNextUrl($url, $reportFilter, FALSE, TRUE);
2074 if (array_key_exists(CRM_Core_Action
::ADVANCED
, $actionLinks)) {
2075 $actionLinks[CRM_Core_Action
::ADVANCED
]['qs'] = $searchFilter;
2077 $report['event_totals']['actionlinks'][$key] = CRM_Core_Action
::formLink($actionLinks, $action, array());
2084 * Get the count of mailings
2091 public function getCount() {
2093 $this->selectAdd('COUNT(id) as count');
2095 $session = CRM_Core_Session
::singleton();
2098 return $this->count
;
2101 static function checkPermission($id) {
2106 $mailingIDs = self
::mailingACLIDs();
2107 if ($mailingIDs === TRUE) {
2111 if (!in_array($id, $mailingIDs)) {
2112 CRM_Core_Error
::fatal(ts('You do not have permission to access this mailing report'));
2117 static function mailingACL($alias = NULL) {
2118 $mailingACL = " ( 0 ) ";
2120 $mailingIDs = self
::mailingACLIDs();
2121 if ($mailingIDs === TRUE) {
2125 if (!empty($mailingIDs)) {
2126 $mailingIDs = implode(',', $mailingIDs);
2127 $tableName = !$alias ? self
::getTableName() : $alias;
2128 $mailingACL = " $tableName.id IN ( $mailingIDs ) ";
2134 * returns all the mailings that this user can access. This is dependent on
2135 * all the groups that the user has access to.
2136 * However since most civi installs dont use ACL's we special case the condition
2137 * where the user has access to ALL groups, and hence ALL mailings and return a
2138 * value of TRUE (to avoid the downstream where clause with a list of mailing list IDs
2140 * @return boolean | array - TRUE if the user has access to all mailings, else array of mailing IDs (possibly empty)
2143 static function mailingACLIDs() {
2145 // optimize common case where admin has access
2148 CRM_Core_Permission
::check('view all contacts') ||
2149 CRM_Core_Permission
::check('edit all contacts')
2154 $mailingIDs = array();
2156 // get all the groups that this user can access
2157 // if they dont have universal access
2158 $groups = CRM_Core_PseudoConstant
::group(NULL, FALSE);
2159 if (!empty($groups)) {
2160 $groupIDs = implode(',', array_keys($groups));
2161 $selectClause = ($count) ?
'COUNT( DISTINCT m.id) as count' : 'DISTINCT( m.id ) as id';
2163 // get all the mailings that are in this subset of groups
2165 SELECT $selectClause
2166 FROM civicrm_mailing m
2167 LEFT JOIN civicrm_mailing_group g ON g.mailing_id = m.id
2168 WHERE ( ( g.entity_table like 'civicrm_group%' AND g.entity_id IN ( $groupIDs ) )
2169 OR ( g.entity_table IS NULL AND g.entity_id IS NULL ) )
2171 $dao = CRM_Core_DAO
::executeQuery($query);
2173 $mailingIDs = array();
2174 while ($dao->fetch()) {
2175 $mailingIDs[] = $dao->id
;
2183 * Get the rows for a browse operation
2185 * @param int $offset The row number to start from
2186 * @param int $rowCount The nmber of rows to return
2187 * @param string $sort The sql string that describes the sort order
2189 * @return array The rows
2192 public function &getRows($offset, $rowCount, $sort, $additionalClause = NULL, $additionalParams = NULL) {
2193 $mailing = self
::getTableName();
2194 $job = CRM_Mailing_BAO_MailingJob
::getTableName();
2195 $group = CRM_Mailing_DAO_MailingGroup
::getTableName();
2196 $session = CRM_Core_Session
::singleton();
2198 $mailingACL = self
::mailingACL();
2200 //get all campaigns.
2201 $allCampaigns = CRM_Campaign_BAO_Campaign
::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
2203 // we only care about parent jobs, since that holds all the info on
2209 $mailing.approval_status_id,
2210 MIN($job.scheduled_date) as scheduled_date,
2211 MIN($job.start_date) as start_date,
2212 MAX($job.end_date) as end_date,
2213 createdContact.sort_name as created_by,
2214 scheduledContact.sort_name as scheduled_by,
2215 $mailing.created_id as created_id,
2216 $mailing.scheduled_id as scheduled_id,
2217 $mailing.is_archived as archived,
2218 $mailing.created_date as created_date,
2220 $mailing.sms_provider_id as sms_provider_id
2222 LEFT JOIN $job ON ( $job.mailing_id = $mailing.id AND $job.is_test = 0 AND $job.parent_id IS NULL )
2223 LEFT JOIN civicrm_contact createdContact ON ( civicrm_mailing.created_id = createdContact.id )
2224 LEFT JOIN civicrm_contact scheduledContact ON ( civicrm_mailing.scheduled_id = scheduledContact.id )
2225 WHERE $mailingACL $additionalClause
2226 GROUP BY $mailing.id ";
2229 $orderBy = trim($sort->orderBy());
2230 if (!empty($orderBy)) {
2231 $query .= " ORDER BY $orderBy";
2236 $query .= " LIMIT $offset, $rowCount ";
2239 if (!$additionalParams) {
2240 $additionalParams = array();
2243 $dao = CRM_Core_DAO
::executeQuery($query, $additionalParams);
2246 while ($dao->fetch()) {
2249 'name' => $dao->name
,
2250 'status' => $dao->status ?
$dao->status
: 'Not scheduled',
2251 'created_date' => CRM_Utils_Date
::customFormat($dao->created_date
),
2252 'scheduled' => CRM_Utils_Date
::customFormat($dao->scheduled_date
),
2253 'scheduled_iso' => $dao->scheduled_date
,
2254 'start' => CRM_Utils_Date
::customFormat($dao->start_date
),
2255 'end' => CRM_Utils_Date
::customFormat($dao->end_date
),
2256 'created_by' => $dao->created_by
,
2257 'scheduled_by' => $dao->scheduled_by
,
2258 'created_id' => $dao->created_id
,
2259 'scheduled_id' => $dao->scheduled_id
,
2260 'archived' => $dao->archived
,
2261 'approval_status_id' => $dao->approval_status_id
,
2262 'campaign_id' => $dao->campaign_id
,
2263 'campaign' => empty($dao->campaign_id
) ?
NULL : $allCampaigns[$dao->campaign_id
],
2264 'sms_provider_id' => $dao->sms_provider_id
,
2271 * Function to show detail Mailing report
2278 static function showEmailDetails($id) {
2279 return CRM_Utils_System
::url('civicrm/mailing/report', "mid=$id");
2283 * Delete Mails and all its associated records
2285 * @param int $id id of the mail to delete
2291 public static function del($id) {
2293 CRM_Core_Error
::fatal();
2296 // delete all file attachments
2297 CRM_Core_BAO_File
::deleteEntityFile('civicrm_mailing',
2301 $dao = new CRM_Mailing_DAO_Mailing();
2305 CRM_Core_Session
::setStatus(ts('Selected mailing has been deleted.'), ts('Deleted'), 'success');
2309 * Delete Jobss and all its associated records
2310 * related to test Mailings
2312 * @param int $id id of the Job to delete
2318 public static function delJob($id) {
2320 CRM_Core_Error
::fatal();
2323 $dao = new CRM_Mailing_BAO_MailingJob();
2328 function getReturnProperties() {
2329 $tokens = &$this->getTokens();
2331 $properties = array();
2332 if (isset($tokens['html']) &&
2333 isset($tokens['html']['contact'])
2335 $properties = array_merge($properties, $tokens['html']['contact']);
2338 if (isset($tokens['text']) &&
2339 isset($tokens['text']['contact'])
2341 $properties = array_merge($properties, $tokens['text']['contact']);
2344 if (isset($tokens['subject']) &&
2345 isset($tokens['subject']['contact'])
2347 $properties = array_merge($properties, $tokens['subject']['contact']);
2350 $returnProperties = array();
2351 $returnProperties['display_name'] = $returnProperties['contact_id'] = $returnProperties['preferred_mail_format'] = $returnProperties['hash'] = 1;
2353 foreach ($properties as $p) {
2354 $returnProperties[$p] = 1;
2357 return $returnProperties;
2361 * Function to build the compose mail form
2368 public static function commonCompose(&$form) {
2370 $tokens = CRM_Core_SelectValues
::contactTokens();
2372 //token selector for subject
2374 $form->add('select', 'token3', ts('Insert Token'),
2379 'onclick' => "return tokenReplText(this);",
2382 $className = CRM_Utils_System
::getClassName($form);
2383 if ($className == 'CRM_Mailing_Form_Upload') {
2384 $tokens = array_merge(CRM_Core_SelectValues
::mailingTokens(), $tokens);
2386 elseif ($className == 'CRM_Admin_Form_ScheduleReminders') {
2387 $tokens = array_merge(CRM_Core_SelectValues
::activityTokens(), $tokens);
2388 $tokens = array_merge(CRM_Core_SelectValues
::eventTokens(), $tokens);
2389 $tokens = array_merge(CRM_Core_SelectValues
::membershipTokens(), $tokens);
2391 elseif ($className == 'CRM_Event_Form_ManageEvent_ScheduleReminders') {
2392 $tokens = array_merge(CRM_Core_SelectValues
::eventTokens(), $tokens);
2395 //sorted in ascending order tokens by ignoring word case
2396 natcasesort($tokens);
2397 $form->assign('tokens', json_encode($tokens));
2399 $form->add('select', 'token1', ts('Insert Tokens'),
2404 'onclick' => "return tokenReplText(this);",
2408 $form->add('select', 'token2', ts('Insert Tokens'),
2413 'onclick' => "return tokenReplHtml(this);",
2418 $form->_templates
= CRM_Core_BAO_MessageTemplate
::getMessageTemplates(FALSE);
2419 if (!empty($form->_templates
)) {
2420 $form->assign('templates', TRUE);
2421 $form->add('select', 'template', ts('Use Template'),
2423 '' => ts('- select -')) +
$form->_templates
, FALSE,
2424 array('onChange' => "selectValue( this.value );")
2426 $form->add('checkbox', 'updateTemplate', ts('Update Template'), NULL);
2429 $form->add('checkbox', 'saveTemplate', ts('Save As New Template'), NULL, FALSE,
2430 array('onclick' => "showSaveDetails(this);")
2432 $form->add('text', 'saveTemplateName', ts('Template Title'));
2435 //insert message Text by selecting "Select Template option"
2436 $form->add('textarea',
2438 ts('Plain-text format'),
2440 'cols' => '80', 'rows' => '8',
2441 'onkeyup' => "return verify(this)",
2445 if ($className != 'CRM_SMS_Form_Upload' && $className != 'CRM_Contact_Form_Task_SMS' &&
2446 $className != 'CRM_Contact_Form_Task_SMS'
2448 $form->addWysiwyg('html_message',
2451 'cols' => '80', 'rows' => '8',
2452 'onkeyup' => "return verify(this)",
2459 * Function to build the compose PDF letter form
2466 public static function commonLetterCompose(&$form) {
2468 $tokens = CRM_Core_SelectValues
::contactTokens();
2469 if (CRM_Utils_System
::getClassName($form) == 'CRM_Mailing_Form_Upload') {
2470 $tokens = array_merge(CRM_Core_SelectValues
::mailingTokens(), $tokens);
2472 //@todo move this fn onto the form
2473 if (CRM_Utils_System
::getClassName($form) == 'CRM_Contribute_Form_Task_PDFLetter') {
2474 $tokens = array_merge(CRM_Core_SelectValues
::contributionTokens(), $tokens);
2477 if(method_exists($form, 'listTokens')) {
2478 $tokens = array_merge($form->listTokens(), $tokens);
2481 //sorted in ascending order tokens by ignoring word case
2482 natcasesort($tokens);
2484 $form->assign('tokens', json_encode($tokens));
2486 $form->add('select', 'token1', ts('Insert Tokens'),
2491 'onchange' => "return tokenReplHtml(this);",
2495 $form->_templates
= CRM_Core_BAO_MessageTemplate
::getMessageTemplates(FALSE);
2496 if (!empty($form->_templates
)) {
2497 $form->assign('templates', TRUE);
2498 $form->add('select', 'template', ts('Select Template'),
2500 '' => ts('- select -')) +
$form->_templates
, FALSE,
2501 array('onChange' => "selectValue( this.value );")
2503 $form->add('checkbox', 'updateTemplate', ts('Update Template'), NULL);
2506 $form->add('checkbox', 'saveTemplate', ts('Save As New Template'), NULL, FALSE,
2507 array('onclick' => "showSaveDetails(this);")
2509 $form->add('text', 'saveTemplateName', ts('Template Title'));
2512 $form->addWysiwyg('html_message',
2515 'cols' => '80', 'rows' => '8',
2516 'onkeyup' => "return verify(this)",
2519 $action = CRM_Utils_Request
::retrieve('action', 'String', $form, FALSE);
2520 if ((CRM_Utils_System
::getClassName($form) == 'CRM_Contact_Form_Task_PDF') &&
2521 $action == CRM_Core_Action
::VIEW
2523 $form->freeze('html_message');
2528 * Get the search based mailing Ids
2530 * @return array $mailingIDs, searched base mailing ids.
2533 public function searchMailingIDs() {
2534 $group = CRM_Mailing_DAO_MailingGroup
::getTableName();
2535 $mailing = self
::getTableName();
2538 SELECT $mailing.id as mailing_id
2539 FROM $mailing, $group
2540 WHERE $group.mailing_id = $mailing.id
2541 AND $group.group_type = 'Base'";
2543 $searchDAO = CRM_Core_DAO
::executeQuery($query);
2544 $mailingIDs = array();
2545 while ($searchDAO->fetch()) {
2546 $mailingIDs[] = $searchDAO->mailing_id
;
2553 * Get the content/components of mailing based on mailing Id
2555 * @param $report array of mailing report
2557 * @param $form reference of this
2559 * @return $report array content/component.
2562 static function getMailingContent(&$report, &$form, $isSMS = FALSE) {
2563 $htmlHeader = $textHeader = NULL;
2564 $htmlFooter = $textFooter = NULL;
2567 if ($report['mailing']['header_id']) {
2568 $header = new CRM_Mailing_BAO_Component();
2569 $header->id
= $report['mailing']['header_id'];
2570 $header->find(TRUE);
2571 $htmlHeader = $header->body_html
;
2572 $textHeader = $header->body_text
;
2575 if ($report['mailing']['footer_id']) {
2576 $footer = new CRM_Mailing_BAO_Component();
2577 $footer->id
= $report['mailing']['footer_id'];
2578 $footer->find(TRUE);
2579 $htmlFooter = $footer->body_html
;
2580 $textFooter = $footer->body_text
;
2584 $text = CRM_Utils_Request
::retrieve('text', 'Boolean', $form);
2586 echo "<pre>{$textHeader}</br>{$report['mailing']['body_text']}</br>{$textFooter}</pre>";
2587 CRM_Utils_System
::civiExit();
2591 $html = CRM_Utils_Request
::retrieve('html', 'Boolean', $form);
2593 $output = $htmlHeader . $report['mailing']['body_html'] . $htmlFooter ;
2594 echo str_replace( "\n", '<br />', $output );
2595 CRM_Utils_System
::civiExit();
2599 if (!empty($report['mailing']['body_text'])) {
2600 $url = CRM_Utils_System
::url('civicrm/mailing/report', 'reset=1&text=1&mid=' . $form->_mailing_id
);
2601 $popup = "javascript:popUp(\"$url\");";
2602 $form->assign('textViewURL', $popup);
2606 if (!empty($report['mailing']['body_html'])) {
2607 $url = CRM_Utils_System
::url('civicrm/mailing/report', 'reset=1&html=1&mid=' . $form->_mailing_id
);
2608 $popup = "javascript:popUp(\"$url\");";
2609 $form->assign('htmlViewURL', $popup);
2614 $report['mailing']['attachment'] = CRM_Core_BAO_File
::attachmentInfo('civicrm_mailing', $form->_mailing_id
);
2619 static function overrideVerp($jobID) {
2620 static $_cache = array();
2622 if (!isset($_cache[$jobID])) {
2624 SELECT override_verp
2625 FROM civicrm_mailing
2626 INNER JOIN civicrm_mailing_job ON civicrm_mailing.id = civicrm_mailing_job.mailing_id
2627 WHERE civicrm_mailing_job.id = %1
2629 $params = array(1 => array($jobID, 'Integer'));
2630 $_cache[$jobID] = CRM_Core_DAO
::singleValueQuery($query, $params);
2632 return $_cache[$jobID];
2635 static function processQueue($mode = NULL) {
2636 $config = &CRM_Core_Config
::singleton();
2637 // CRM_Core_Error::debug_log_message("Beginning processQueue run: {$config->mailerJobsMax}, {$config->mailerJobSize}");
2639 if ($mode == NULL && CRM_Core_BAO_MailSettings
::defaultDomain() == "EXAMPLE.ORG") {
2640 CRM_Core_Error
::fatal(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/initial-set-up/email-system-configuration")));
2643 // check if we are enforcing number of parallel cron jobs
2645 $gotCronLock = FALSE;
2646 if ($config->mailerJobsMax
&& $config->mailerJobsMax
> 1) {
2648 $lockArray = range(1, $config->mailerJobsMax
);
2649 shuffle($lockArray);
2651 // check if we are using global locks
2652 $serverWideLock = CRM_Core_BAO_Setting
::getItem(
2653 CRM_Core_BAO_Setting
::MAILING_PREFERENCES_NAME
,
2654 'civimail_server_wide_lock'
2656 foreach ($lockArray as $lockID) {
2657 $cronLock = new CRM_Core_Lock("civimail.cronjob.{$lockID}", NULL, $serverWideLock);
2658 if ($cronLock->isAcquired()) {
2659 $gotCronLock = TRUE;
2664 // exit here since we have enuf cronjobs running
2665 if (!$gotCronLock) {
2666 CRM_Core_Error
::debug_log_message('Returning early, since max number of cronjobs running');
2671 // load bootstrap to call hooks
2673 // Split up the parent jobs into multiple child jobs
2674 CRM_Mailing_BAO_MailingJob
::runJobs_pre($config->mailerJobSize
, $mode);
2675 CRM_Mailing_BAO_MailingJob
::runJobs(NULL, $mode);
2676 CRM_Mailing_BAO_MailingJob
::runJobs_post($mode);
2678 // lets release the global cron lock if we do have one
2680 $cronLock->release();
2683 // CRM_Core_Error::debug_log_message('Ending processQueue run');
2687 private function addMultipleEmails($mailingID) {
2689 INSERT INTO civicrm_mailing_recipients
2690 (mailing_id, email_id, contact_id)
2691 SELECT %1, e.id, e.contact_id FROM civicrm_email e
2693 AND e.is_bulkmail = 1
2695 ( SELECT contact_id FROM civicrm_mailing_recipients mr WHERE mailing_id = %1 )
2696 AND e.id NOT IN ( SELECT email_id FROM civicrm_mailing_recipients mr WHERE mailing_id = %1 )
2698 $params = array(1 => array($mailingID, 'Integer'));
2700 $dao = CRM_Core_DAO
::executeQuery($sql, $params);
2703 static function getMailingsList($isSMS = FALSE) {
2704 static $list = array();
2707 $where .= " civicrm_mailing.sms_provider_id IS NULL ";
2710 $where .= " civicrm_mailing.sms_provider_id IS NOT NULL ";
2715 SELECT civicrm_mailing.id, civicrm_mailing.name, civicrm_mailing_job.end_date
2716 FROM civicrm_mailing
2717 INNER JOIN civicrm_mailing_job ON civicrm_mailing.id = civicrm_mailing_job.mailing_id {$where}
2718 ORDER BY civicrm_mailing.name";
2719 $mailing = CRM_Core_DAO
::executeQuery($query);
2721 while ($mailing->fetch()) {
2722 $list[$mailing->id
] = "{$mailing->name} :: {$mailing->end_date}";
2729 static function hiddenMailingGroup($mid) {
2732 FROM civicrm_mailing m
2733 INNER JOIN civicrm_mailing_group mg ON mg.mailing_id = m.id
2734 INNER JOIN civicrm_group g ON mg.entity_id = g.id AND mg.entity_table = 'civicrm_group'
2735 WHERE g.is_hidden = 1
2736 AND mg.group_type = 'Include'
2739 $params = array( 1 => array( $mid, 'Integer' ) );
2740 return CRM_Core_DAO
::singleValueQuery($sql, $params);
2744 * This function is a wrapper for ajax activity selector
2746 * @param array $params associated array for params record id.
2748 * @return array $contactActivities associated array of contact activities
2751 public static function getContactMailingSelector(&$params) {
2752 // format the params
2753 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2754 $params['rowCount'] = $params['rp'];
2755 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
2756 $params['caseId'] = NULL;
2758 // get contact mailings
2759 $mailings = CRM_Mailing_BAO_Mailing
::getContactMailings($params);
2762 $params['total'] = CRM_Mailing_BAO_Mailing
::getContactMailingsCount($params);
2765 if (!empty($mailings)) {
2766 $openCounts = CRM_Mailing_Event_BAO_Opened
::getMailingTotalCount(array_keys($mailings));
2767 $clickCounts = CRM_Mailing_Event_BAO_TrackableURLOpen
::getMailingTotalCount(array_keys($mailings));
2770 // format params and add links
2771 $contactMailings = array();
2772 foreach ($mailings as $mailingId => $values) {
2773 $contactMailings[$mailingId]['subject'] = $values['subject'];
2774 $contactMailings[$mailingId]['start_date'] = CRM_Utils_Date
::customFormat($values['start_date']);
2775 $contactMailings[$mailingId]['recipients'] = CRM_Utils_System
::href(ts('(recipients)'), 'civicrm/mailing/report/event',
2776 "mid={$values['mailing_id']}&reset=1&cid={$params['contact_id']}&event=queue&context=mailing");
2778 $contactMailings[$mailingId]['mailing_creator'] = CRM_Utils_System
::href(
2779 $values['creator_name'],
2780 'civicrm/contact/view',
2781 "reset=1&cid={$values['creator_id']}");
2784 $contactMailings[$mailingId]['openstats'] = ts('Opens') . ': ' . $openCounts[$values['mailing_id']] .
2785 '<br />' . ts('Clicks') . ': ' . $clickCounts[$values['mailing_id']];
2787 $actionLinks = array(
2788 CRM_Core_Action
::VIEW
=> array(
2789 'name' => ts('View'),
2790 'url' => 'civicrm/mailing/view',
2791 'qs' => "reset=1&id={$values['mailing_id']}",
2792 'title' => ts('View Mailing'),
2793 'class' => 'crm-mailing-view',
2795 CRM_Core_Action
::BROWSE
=> array(
2796 'name' => ts('Mailing Report'),
2797 'url' => 'civicrm/mailing/report',
2798 'qs' => "mid={$values['mailing_id']}&reset=1&cid={$params['contact_id']}&context=mailing",
2799 'title' => ts('View Mailing Report'),
2803 $contactMailings[$mailingId]['links'] = CRM_Core_Action
::formLink($actionLinks);
2806 return $contactMailings;
2810 * Function to retrieve contact mailing
2812 * @param array $params associated array
2814 * @return array of mailings for a contact
2819 static public function getContactMailings(&$params) {
2820 $params['version'] = 3;
2821 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2822 $params['limit'] = $params['rp'];
2823 $params['sort'] = CRM_Utils_Array
::value('sortBy', $params);
2825 $result = civicrm_api('MailingContact', 'get', $params);
2826 return $result['values'];
2830 * Function to retrieve contact mailing count
2832 * @param array $params associated array
2834 * @return int count of mailings for a contact
2839 static public function getContactMailingsCount(&$params) {
2840 $params['version'] = 3;
2841 return civicrm_api('MailingContact', 'getcount', $params);