Merge pull request #3112 from freeform/CRM-14568
[civicrm-core.git] / CRM / Mailing / BAO / Mailing.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2014 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
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. |
13 | |
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. |
18 | |
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 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2014
32 * $Id$
33 *
34 */
35 require_once 'Mail/mime.php';
36 class CRM_Mailing_BAO_Mailing extends CRM_Mailing_DAO_Mailing {
37
38 /**
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
42 */
43 private $preparedTemplates = NULL;
44
45 /**
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
49 */
50 private $templates = NULL;
51
52 /**
53 * An array that holds the tokens that are specifically found in our text and html bodies
54 */
55 private $tokens = NULL;
56
57 /**
58 * An array that holds the tokens that are specifically found in our text and html bodies
59 */
60 private $flattenedTokens = NULL;
61
62 /**
63 * The header associated with this mailing
64 */
65 private $header = NULL;
66
67 /**
68 * The footer associated with this mailing
69 */
70 private $footer = NULL;
71
72 /**
73 * The HTML content of the message
74 */
75 private $html = NULL;
76
77 /**
78 * The text content of the message
79 */
80 private $text = NULL;
81
82 /**
83 * Cached BAO for the domain
84 */
85 private $_domain = NULL;
86
87 /**
88 * class constructor
89 */
90 function __construct() {
91 parent::__construct();
92 }
93
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);
98 return $eq->N;
99 }
100
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(
104 $job_id,
105 $mailing_id = NULL,
106 $offset = NULL,
107 $limit = NULL,
108 $storeRecipients = FALSE,
109 $dedupeEmail = FALSE,
110 $mode = NULL) {
111 $mailingGroup = new CRM_Mailing_DAO_MailingGroup();
112
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();
119
120 $email = CRM_Core_DAO_Email::getTableName();
121 if ($mode == 'sms') {
122 $phone = CRM_Core_DAO_Phone::getTableName();
123 }
124 $contact = CRM_Contact_DAO_Contact::getTableName();
125
126 $group = CRM_Contact_DAO_Group::getTableName();
127 $g2contact = CRM_Contact_DAO_GroupContact::getTableName();
128
129 /* Create a temp table for contact exclusion */
130 $mailingGroup->query(
131 "CREATE TEMPORARY TABLE X_$job_id
132 (contact_id int primary key)
133 ENGINE=HEAP"
134 );
135
136 /* Add all the members of groups excluded from this mailing to the temp
137 * table */
138
139 $excludeSubGroup = "INSERT INTO X_$job_id (contact_id)
140 SELECT DISTINCT $g2contact.contact_id
141 FROM $g2contact
142 INNER JOIN $mg
143 ON $g2contact.group_id = $mg.entity_id AND $mg.entity_table = '$group'
144 WHERE
145 $mg.mailing_id = {$mailing_id}
146 AND $g2contact.status = 'Added'
147 AND $mg.group_type = 'Exclude'";
148 $mailingGroup->query($excludeSubGroup);
149
150 /* Add all unsubscribe members of base group from this mailing to the temp
151 * table */
152
153 $unSubscribeBaseGroup = "INSERT INTO X_$job_id (contact_id)
154 SELECT DISTINCT $g2contact.contact_id
155 FROM $g2contact
156 INNER JOIN $mg
157 ON $g2contact.group_id = $mg.entity_id AND $mg.entity_table = '$group'
158 WHERE
159 $mg.mailing_id = {$mailing_id}
160 AND $g2contact.status = 'Removed'
161 AND $mg.group_type = 'Base'";
162 $mailingGroup->query($unSubscribeBaseGroup);
163
164 /* Add all the (intended) recipients of an excluded prior mailing to
165 * the temp table */
166
167 $excludeSubMailing = "INSERT IGNORE INTO X_$job_id (contact_id)
168 SELECT DISTINCT $eq.contact_id
169 FROM $eq
170 INNER JOIN $job
171 ON $eq.job_id = $job.id
172 INNER JOIN $mg
173 ON $job.mailing_id = $mg.entity_id AND $mg.entity_table = '$mailing'
174 WHERE
175 $mg.mailing_id = {$mailing_id}
176 AND $mg.group_type = 'Exclude'";
177 $mailingGroup->query($excludeSubMailing);
178
179 // get all the saved searches AND hierarchical groups
180 // and load them in the cache
181 $sql = "
182 SELECT $group.id, $group.cache_date, $group.saved_search_id, $group.children
183 FROM $group
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 )
191 ";
192
193 $groupDAO = CRM_Core_DAO::executeQuery($sql);
194 while ($groupDAO->fetch()) {
195 if ($groupDAO->cache_date == NULL) {
196 CRM_Contact_BAO_GroupContactCache::load($groupDAO);
197 }
198
199 $smartGroupExclude = "
200 INSERT IGNORE INTO X_$job_id (contact_id)
201 SELECT c.contact_id
202 FROM civicrm_group_contact_cache c
203 WHERE c.group_id = {$groupDAO->id}
204 ";
205 $mailingGroup->query($smartGroupExclude);
206 }
207
208 $tempColumn = 'email_id';
209 if ($mode == 'sms') {
210 $tempColumn = 'phone_id';
211 }
212
213 /* Get all the group contacts we want to include */
214
215 $mailingGroup->query(
216 "CREATE TEMPORARY TABLE I_$job_id
217 ($tempColumn int, contact_id int primary key)
218 ENGINE=HEAP"
219 );
220
221 /* Get the group contacts, but only those which are not in the
222 * exclusion temp table */
223
224 $query = "REPLACE INTO I_$job_id (email_id, contact_id)
225
226 SELECT DISTINCT $email.id as email_id,
227 $contact.id as contact_id
228 FROM $email
229 INNER JOIN $contact
230 ON $email.contact_id = $contact.id
231 INNER JOIN $g2contact
232 ON $contact.id = $g2contact.contact_id
233 INNER JOIN $mg
234 ON $g2contact.group_id = $mg.entity_id
235 AND $mg.entity_table = '$group'
236 LEFT JOIN X_$job_id
237 ON $contact.id = X_$job_id.contact_id
238 WHERE
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";
252
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)
256
257 SELECT DISTINCT $phone.id as phone_id,
258 $contact.id as contact_id
259 FROM $phone
260 INNER JOIN $contact
261 ON $phone.contact_id = $contact.id
262 INNER JOIN $g2contact
263 ON $contact.id = $g2contact.contact_id
264 INNER JOIN $mg
265 ON $g2contact.group_id = $mg.entity_id
266 AND $mg.entity_table = '$group'
267 LEFT JOIN X_$job_id
268 ON $contact.id = X_$job_id.contact_id
269 WHERE
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";
281 }
282 $mailingGroup->query($query);
283
284 /* Query prior mailings */
285
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
289 FROM $email
290 INNER JOIN $contact
291 ON $email.contact_id = $contact.id
292 INNER JOIN $eq
293 ON $eq.contact_id = $contact.id
294 INNER JOIN $job
295 ON $eq.job_id = $job.id
296 INNER JOIN $mg
297 ON $job.mailing_id = $mg.entity_id AND $mg.entity_table = '$mailing'
298 LEFT JOIN X_$job_id
299 ON $contact.id = X_$job_id.contact_id
300 WHERE
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";
310
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
315 FROM $phone
316 INNER JOIN $contact
317 ON $phone.contact_id = $contact.id
318 INNER JOIN $eq
319 ON $eq.contact_id = $contact.id
320 INNER JOIN $job
321 ON $eq.job_id = $job.id
322 INNER JOIN $mg
323 ON $job.mailing_id = $mg.entity_id AND $mg.entity_table = '$mailing'
324 LEFT JOIN X_$job_id
325 ON $contact.id = X_$job_id.contact_id
326 WHERE
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";
334 }
335 $mailingGroup->query($query);
336
337 $sql = "
338 SELECT $group.id, $group.cache_date, $group.saved_search_id, $group.children
339 FROM $group
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 )
348 ";
349
350 $groupDAO = CRM_Core_DAO::executeQuery($sql);
351 while ($groupDAO->fetch()) {
352 if ($groupDAO->cache_date == NULL) {
353 CRM_Contact_BAO_GroupContactCache::load($groupDAO);
354 }
355
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
365 AND c.is_opt_out = 0
366 AND c.is_deceased = 0
367 AND (e.is_bulkmail = 1 OR e.is_primary = 1)
368 AND e.on_hold = 0
369 AND X_$job_id.contact_id IS null
370 ORDER BY e.is_bulkmail
371 ";
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}
381 AND c.do_not_sms = 0
382 AND c.is_opt_out = 0
383 AND c.is_deceased = 0
384 AND p.phone_type_id = {$phoneTypes['Mobile']}
385 AND X_$job_id.contact_id IS null";
386 }
387 $mailingGroup->query($smartGroupInclude);
388 }
389
390 /**
391 * Construct the filtered search queries
392 */
393 $query = "
394 SELECT search_id, search_args, entity_id
395 FROM $mg
396 WHERE $mg.search_id IS NOT NULL
397 AND $mg.mailing_id = {$mailing_id}
398 ";
399 $dao = CRM_Core_DAO::executeQuery($query);
400 while ($dao->fetch()) {
401 $customSQL = CRM_Contact_BAO_SearchCustom::civiMailSQL($dao->search_id,
402 $dao->search_args,
403 $dao->entity_id
404 );
405 $query = "REPLACE INTO I_$job_id ({$tempColumn}, contact_id)
406 $customSQL";
407 $mailingGroup->query($query);
408 }
409
410 /* Get the emails with only location override */
411
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
415 FROM $email
416 INNER JOIN $contact
417 ON $email.contact_id = $contact.id
418 INNER JOIN $g2contact
419 ON $contact.id = $g2contact.contact_id
420 INNER JOIN $mg
421 ON $g2contact.group_id = $mg.entity_id
422 LEFT JOIN X_$job_id
423 ON $contact.id = X_$job_id.contact_id
424 WHERE
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
440 FROM $phone
441 INNER JOIN $contact
442 ON $phone.contact_id = $contact.id
443 INNER JOIN $g2contact
444 ON $contact.id = $g2contact.contact_id
445 INNER JOIN $mg
446 ON $g2contact.group_id = $mg.entity_id
447 LEFT JOIN X_$job_id
448 ON $contact.id = X_$job_id.contact_id
449 WHERE
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";
459 }
460 $mailingGroup->query($query);
461
462 $results = array();
463
464 $eq = new CRM_Mailing_Event_BAO_Queue();
465
466 list($aclFrom, $aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause();
467 $aclWhere = $aclWhere ? "WHERE {$aclWhere}" : '';
468 $limitString = NULL;
469 if ($limit && $offset !== NULL) {
470 $offset = CRM_Utils_Type::escape($offset, 'Int');
471 $limit = CRM_Utils_Type::escape($limit, 'Int');
472
473 $limitString = "LIMIT $offset, $limit";
474 }
475
476 if ($storeRecipients && $mailing_id) {
477 $sql = "
478 DELETE
479 FROM civicrm_mailing_recipients
480 WHERE mailing_id = %1
481 ";
482 $params = array(1 => array($mailing_id, 'Integer'));
483 CRM_Core_DAO::executeQuery($sql, $params);
484
485 // CRM-3975
486 $groupBy = $groupJoin = '';
487 if ($dedupeEmail) {
488 $groupJoin = " INNER JOIN civicrm_email e ON e.id = i.email_id";
489 $groupBy = " GROUP BY e.email ";
490 }
491
492 $sql = "
493 INSERT INTO civicrm_mailing_recipients ( mailing_id, contact_id, {$tempColumn} )
494 SELECT %1, i.contact_id, i.{$tempColumn}
495 FROM civicrm_contact contact_a
496 INNER JOIN I_$job_id i ON contact_a.id = i.contact_id
497 $groupJoin
498 {$aclFrom}
499 {$aclWhere}
500 $groupBy
501 ORDER BY i.contact_id, i.{$tempColumn}
502 ";
503
504 CRM_Core_DAO::executeQuery($sql, $params);
505
506 // if we need to add all emails marked bulk, do it as a post filter
507 // on the mailing recipients table
508 if (CRM_Core_BAO_Email::isMultipleBulkMail()) {
509 self::addMultipleEmails($mailing_id);
510 }
511 }
512
513 /* Delete the temp table */
514
515 $mailingGroup->reset();
516 $mailingGroup->query("DROP TEMPORARY TABLE X_$job_id");
517 $mailingGroup->query("DROP TEMPORARY TABLE I_$job_id");
518
519 return $eq;
520 }
521
522 private function _getMailingGroupIds($type = 'Include') {
523 $mailingGroup = new CRM_Mailing_DAO_MailingGroup();
524 $group = CRM_Contact_DAO_Group::getTableName();
525 if (!isset($this->id)) {
526 // we're just testing tokens, so return any group
527 $query = "SELECT id AS entity_id
528 FROM $group
529 ORDER BY id
530 LIMIT 1";
531 }
532 else {
533 $query = "SELECT entity_id
534 FROM $mg
535 WHERE mailing_id = {$this->id}
536 AND group_type = '$type'
537 AND entity_table = '$group'";
538 }
539 $mailingGroup->query($query);
540
541 $groupIds = array();
542 while ($mailingGroup->fetch()) {
543 $groupIds[] = $mailingGroup->entity_id;
544 }
545
546 return $groupIds;
547 }
548
549 /**
550 *
551 * Returns the regex patterns that are used for preparing the text and html templates
552 *
553 * @access private
554 *
555 **/
556 private function &getPatterns($onlyHrefs = FALSE) {
557
558 $patterns = array();
559
560 $protos = '(https?|ftp)';
561 $letters = '\w';
562 $gunk = '\{\}/#~:.?+=&;%@!\,\-';
563 $punc = '.:?\-';
564 $any = "{$letters}{$gunk}{$punc}";
565 if ($onlyHrefs) {
566 $pattern = "\\bhref[ ]*=[ ]*([\"'])?(($protos:[$any]+?(?=[$punc]*[^$any]|$)))([\"'])?";
567 }
568 else {
569 $pattern = "\\b($protos:[$any]+?(?=[$punc]*[^$any]|$))";
570 }
571
572 $patterns[] = $pattern;
573 $patterns[] = '\\\\\{\w+\.\w+\\\\\}|\{\{\w+\.\w+\}\}';
574 $patterns[] = '\{\w+\.\w+\}';
575
576 $patterns = '{' . join('|', $patterns) . '}im';
577
578 return $patterns;
579 }
580
581 /**
582 * returns an array that denotes the type of token that we are dealing with
583 * we use the type later on when we are doing a token replcement lookup
584 *
585 * @param string $token The token for which we will be doing adata lookup
586 *
587 * @return array $funcStruct An array that holds the token itself and the type.
588 * the type will tell us which function to use for the data lookup
589 * if we need to do a lookup at all
590 */
591 function &getDataFunc($token) {
592 static $_categories = NULL;
593 static $_categoryString = NULL;
594 if (!$_categories) {
595 $_categories = array(
596 'domain' => NULL,
597 'action' => NULL,
598 'mailing' => NULL,
599 'contact' => NULL,
600 );
601
602 CRM_Utils_Hook::tokens($_categories);
603 $_categoryString = implode('|', array_keys($_categories));
604 }
605
606 $funcStruct = array('type' => NULL, 'token' => $token);
607 $matches = array();
608 if ((preg_match('/^href/i', $token) || preg_match('/^http/i', $token))) {
609 // it is a url so we need to check to see if there are any tokens embedded
610 // if so then call this function again to get the token dataFunc
611 // and assign the type 'embedded' so that the data retrieving function
612 // will know what how to handle this token.
613 if (preg_match_all('/(\{\w+\.\w+\})/', $token, $matches)) {
614 $funcStruct['type'] = 'embedded_url';
615 $funcStruct['embed_parts'] = $funcStruct['token'] = array();
616 foreach ($matches[1] as $match) {
617 $preg_token = '/' . preg_quote($match, '/') . '/';
618 $list = preg_split($preg_token, $token, 2);
619 $funcStruct['embed_parts'][] = $list[0];
620 $token = $list[1];
621 $funcStruct['token'][] = $this->getDataFunc($match);
622 }
623 // fixed truncated url, CRM-7113
624 if ($token) {
625 $funcStruct['embed_parts'][] = $token;
626 }
627 }
628 else {
629 $funcStruct['type'] = 'url';
630 }
631 }
632 elseif (preg_match('/^\{(' . $_categoryString . ')\.(\w+)\}$/', $token, $matches)) {
633 $funcStruct['type'] = $matches[1];
634 $funcStruct['token'] = $matches[2];
635 }
636 elseif (preg_match('/\\\\\{(\w+\.\w+)\\\\\}|\{\{(\w+\.\w+)\}\}/', $token, $matches)) {
637 // we are an escaped token
638 // so remove the escape chars
639 $unescaped_token = preg_replace('/\{\{|\}\}|\\\\\{|\\\\\}/', '', $matches[0]);
640 $funcStruct['token'] = '{' . $unescaped_token . '}';
641 }
642 return $funcStruct;
643 }
644
645 /**
646 *
647 * Prepares the text and html templates
648 * for generating the emails and returns a copy of the
649 * prepared templates
650 *
651 * @access private
652 *
653 **/
654 private function getPreparedTemplates() {
655 if (!$this->preparedTemplates) {
656 $patterns['html'] = $this->getPatterns(TRUE);
657 $patterns['subject'] = $patterns['text'] = $this->getPatterns();
658 $templates = $this->getTemplates();
659
660 $this->preparedTemplates = array();
661
662 foreach (array(
663 'html', 'text', 'subject') as $key) {
664 if (!isset($templates[$key])) {
665 continue;
666 }
667
668 $matches = array();
669 $tokens = array();
670 $split_template = array();
671
672 $email = $templates[$key];
673 preg_match_all($patterns[$key], $email, $matches, PREG_PATTERN_ORDER);
674 foreach ($matches[0] as $idx => $token) {
675 $preg_token = '/' . preg_quote($token, '/') . '/im';
676 list($split_template[], $email) = preg_split($preg_token, $email, 2);
677 array_push($tokens, $this->getDataFunc($token));
678 }
679 if ($email) {
680 $split_template[] = $email;
681 }
682 $this->preparedTemplates[$key]['template'] = $split_template;
683 $this->preparedTemplates[$key]['tokens'] = $tokens;
684 }
685 }
686 return ($this->preparedTemplates);
687 }
688
689 /**
690 *
691 * Retrieve a ref to an array that holds the email and text templates for this email
692 * assembles the complete template including the header and footer
693 * that the user has uploaded or declared (if they have dome that)
694 *
695 *
696 * @return array reference to an assoc array
697 * @access private
698 *
699 **/
700 private function &getTemplates() {
701 if (!$this->templates) {
702 $this->getHeaderFooter();
703 $this->templates = array();
704
705 if ($this->body_text) {
706 $template = array();
707 if ($this->header) {
708 $template[] = $this->header->body_text;
709 }
710
711 $template[] = $this->body_text;
712
713 if ($this->footer) {
714 $template[] = $this->footer->body_text;
715 }
716
717 $this->templates['text'] = join("\n", $template);
718 }
719
720 if ($this->body_html) {
721
722 $template = array();
723 if ($this->header) {
724 $template[] = $this->header->body_html;
725 }
726
727 $template[] = $this->body_html;
728
729 if ($this->footer) {
730 $template[] = $this->footer->body_html;
731 }
732
733 $this->templates['html'] = join("\n", $template);
734
735 // this is where we create a text template from the html template if the text template did not exist
736 // this way we ensure that every recipient will receive an email even if the pref is set to text and the
737 // user uploads an html email only
738 if (!$this->body_text) {
739 $this->templates['text'] = CRM_Utils_String::htmlToText($this->templates['html']);
740 }
741 }
742
743 if ($this->subject) {
744 $template = array();
745 $template[] = $this->subject;
746 $this->templates['subject'] = join("\n", $template);
747 }
748 }
749 return $this->templates;
750 }
751
752 /**
753 *
754 * Retrieve a ref to an array that holds all of the tokens in the email body
755 * where the keys are the type of token and the values are ordinal arrays
756 * that hold the token names (even repeated tokens) in the order in which
757 * they appear in the body of the email.
758 *
759 * note: the real work is done in the _getTokens() function
760 *
761 * this function needs to have some sort of a body assigned
762 * either text or html for this to have any meaningful impact
763 *
764 * @return array reference to an assoc array
765 * @access public
766 *
767 **/
768 public function &getTokens() {
769 if (!$this->tokens) {
770
771 $this->tokens = array('html' => array(), 'text' => array(), 'subject' => array());
772
773 if ($this->body_html) {
774 $this->_getTokens('html');
775 if (!$this->body_text) {
776 // Since the text template was created from html, use the html tokens.
777 // @see CRM_Mailing_BAO_Mailing::getTemplates()
778 $this->tokens['text'] = $this->tokens['html'];
779 }
780 }
781
782 if ($this->body_text) {
783 $this->_getTokens('text');
784 }
785
786 if ($this->subject) {
787 $this->_getTokens('subject');
788 }
789 }
790
791 return $this->tokens;
792 }
793
794 /**
795 * Returns the token set for all 3 parts as one set. This allows it to be sent to the
796 * hook in one call and standardizes it across other token workflows
797 *
798 * @return array reference to an assoc array
799 * @access public
800 *
801 **/
802 public function &getFlattenedTokens() {
803 if (!$this->flattenedTokens) {
804 $tokens = $this->getTokens();
805
806 $this->flattenedTokens = CRM_Utils_Token::flattenTokens($tokens);
807 }
808
809 return $this->flattenedTokens;
810 }
811
812 /**
813 *
814 * _getTokens parses out all of the tokens that have been
815 * included in the html and text bodies of the email
816 * we get the tokens and then separate them into an
817 * internal structure named tokens that has the same
818 * form as the static tokens property(?) of the CRM_Utils_Token class.
819 * The difference is that there might be repeated token names as we want the
820 * structures to represent the order in which tokens were found from left to right, top to bottom.
821 *
822 *
823 * @param str $prop name of the property that holds the text that we want to scan for tokens (html, text)
824 * @access private
825 *
826 * @return void
827 */
828 private function _getTokens($prop) {
829 $templates = $this->getTemplates();
830
831 $newTokens = CRM_Utils_Token::getTokens($templates[$prop]);
832
833 foreach ($newTokens as $type => $names) {
834 if (!isset($this->tokens[$prop][$type])) {
835 $this->tokens[$prop][$type] = array();
836 }
837 foreach ($names as $key => $name) {
838 $this->tokens[$prop][$type][] = $name;
839 }
840 }
841 }
842
843 /**
844 * Generate an event queue for a test job
845 *
846 * @params array $params contains form values
847 *
848 * @param $testParams
849 *
850 * @return void
851 * @access public
852 */
853 public function getTestRecipients($testParams) {
854 if (array_key_exists($testParams['test_group'], CRM_Core_PseudoConstant::group())) {
855 $contacts = civicrm_api('contact','get', array(
856 'version' =>3,
857 'group' => $testParams['test_group'],
858 'return' => 'id',
859 'options' => array('limit' => 100000000000,
860 ))
861 );
862
863 foreach (array_keys($contacts['values']) as $groupContact) {
864 $query = "
865 SELECT civicrm_email.id AS email_id,
866 civicrm_email.is_primary as is_primary,
867 civicrm_email.is_bulkmail as is_bulkmail
868 FROM civicrm_email
869 INNER JOIN civicrm_contact ON civicrm_email.contact_id = civicrm_contact.id
870 WHERE (civicrm_email.is_bulkmail = 1 OR civicrm_email.is_primary = 1)
871 AND civicrm_contact.id = {$groupContact}
872 AND civicrm_contact.do_not_email = 0
873 AND civicrm_contact.is_deceased = 0
874 AND civicrm_email.on_hold = 0
875 AND civicrm_contact.is_opt_out = 0
876 GROUP BY civicrm_email.id
877 ORDER BY civicrm_email.is_bulkmail DESC
878 ";
879 $dao = CRM_Core_DAO::executeQuery($query);
880 if ($dao->fetch()) {
881 $params = array(
882 'job_id' => $testParams['job_id'],
883 'email_id' => $dao->email_id,
884 'contact_id' => $groupContact,
885 );
886 $queue = CRM_Mailing_Event_BAO_Queue::create($params);
887 }
888 }
889 }
890 }
891
892 /**
893 * Retrieve the header and footer for this mailing
894 *
895 * @param void
896 *
897 * @return void
898 * @access private
899 */
900 private function getHeaderFooter() {
901 if (!$this->header and $this->header_id) {
902 $this->header = new CRM_Mailing_BAO_Component();
903 $this->header->id = $this->header_id;
904 $this->header->find(TRUE);
905 $this->header->free();
906 }
907
908 if (!$this->footer and $this->footer_id) {
909 $this->footer = new CRM_Mailing_BAO_Component();
910 $this->footer->id = $this->footer_id;
911 $this->footer->find(TRUE);
912 $this->footer->free();
913 }
914 }
915
916 /**
917 * Given and array of headers and a prefix, job ID, event queue ID, and hash,
918 * add a Message-ID header if needed.
919 *
920 * i.e. if the global includeMessageId is set and there isn't already a
921 * Message-ID in the array.
922 * The message ID is structured the same way as a verp. However no interpretation
923 * is placed on the values received, so they do not need to follow the verp
924 * convention.
925 *
926 * @param array $headers Array of message headers to update, in-out
927 * @param string $prefix Prefix for the message ID, use same prefixes as verp
928 * wherever possible
929 * @param string $job_id Job ID component of the generated message ID
930 * @param string $event_queue_id Event Queue ID component of the generated message ID
931 * @param string $hash Hash component of the generated message ID.
932 *
933 * @return void
934 */
935 static function addMessageIdHeader(&$headers, $prefix, $job_id, $event_queue_id, $hash) {
936 $config = CRM_Core_Config::singleton();
937 $localpart = CRM_Core_BAO_MailSettings::defaultLocalpart();
938 $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
939 $includeMessageId = CRM_Core_BAO_MailSettings::includeMessageId();
940
941 if ($includeMessageId && (!array_key_exists('Message-ID', $headers))) {
942 $headers['Message-ID'] = '<' . implode($config->verpSeparator,
943 array(
944 $localpart . $prefix,
945 $job_id,
946 $event_queue_id,
947 $hash,
948 )
949 ) . "@{$emailDomain}>";
950 }
951 }
952
953 /**
954 * static wrapper for getting verp and urls
955 *
956 * @param int $job_id ID of the Job associated with this message
957 * @param int $event_queue_id ID of the EventQueue
958 * @param string $hash Hash of the EventQueue
959 * @param string $email Destination address
960 *
961 * @return array (reference) array array ref that hold array refs to the verp info and urls
962 */
963 static function getVerpAndUrls($job_id, $event_queue_id, $hash, $email) {
964 // create a skeleton object and set its properties that are required by getVerpAndUrlsAndHeaders()
965 $config = CRM_Core_Config::singleton();
966 $bao = new CRM_Mailing_BAO_Mailing();
967 $bao->_domain = CRM_Core_BAO_Domain::getDomain();
968 $bao->from_name = $bao->from_email = $bao->subject = '';
969
970 // use $bao's instance method to get verp and urls
971 list($verp, $urls, $_) = $bao->getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email);
972 return array($verp, $urls);
973 }
974
975 /**
976 * get verp, urls and headers
977 *
978 * @param int $job_id ID of the Job associated with this message
979 * @param int $event_queue_id ID of the EventQueue
980 * @param string $hash Hash of the EventQueue
981 * @param string $email Destination address
982 *
983 * @param bool $isForward
984 *
985 * @return array (reference) array array ref that hold array refs to the verp info, urls, and headers@access private
986 */
987 private function getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email, $isForward = FALSE) {
988 $config = CRM_Core_Config::singleton();
989
990 /**
991 * Inbound VERP keys:
992 * reply: user replied to mailing
993 * bounce: email address bounced
994 * unsubscribe: contact opts out of all target lists for the mailing
995 * resubscribe: contact opts back into all target lists for the mailing
996 * optOut: contact unsubscribes from the domain
997 */
998 $verp = array();
999 $verpTokens = array(
1000 'reply' => 'r',
1001 'bounce' => 'b',
1002 'unsubscribe' => 'u',
1003 'resubscribe' => 'e',
1004 'optOut' => 'o',
1005 );
1006
1007 $localpart = CRM_Core_BAO_MailSettings::defaultLocalpart();
1008 $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
1009
1010 foreach ($verpTokens as $key => $value) {
1011 $verp[$key] = implode($config->verpSeparator,
1012 array(
1013 $localpart . $value,
1014 $job_id,
1015 $event_queue_id,
1016 $hash,
1017 )
1018 ) . "@$emailDomain";
1019 }
1020
1021 //handle should override VERP address.
1022 $skipEncode = FALSE;
1023
1024 if ($job_id &&
1025 self::overrideVerp($job_id)
1026 ) {
1027 $verp['reply'] = "\"{$this->from_name}\" <{$this->from_email}>";
1028 }
1029
1030 $urls = array(
1031 'forward' => CRM_Utils_System::url('civicrm/mailing/forward',
1032 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1033 TRUE, NULL, TRUE, TRUE
1034 ),
1035 'unsubscribeUrl' => CRM_Utils_System::url('civicrm/mailing/unsubscribe',
1036 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1037 TRUE, NULL, TRUE, TRUE
1038 ),
1039 'resubscribeUrl' => CRM_Utils_System::url('civicrm/mailing/resubscribe',
1040 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1041 TRUE, NULL, TRUE, TRUE
1042 ),
1043 'optOutUrl' => CRM_Utils_System::url('civicrm/mailing/optout',
1044 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1045 TRUE, NULL, TRUE, TRUE
1046 ),
1047 'subscribeUrl' => CRM_Utils_System::url('civicrm/mailing/subscribe',
1048 'reset=1',
1049 TRUE, NULL, TRUE, TRUE
1050 ),
1051 );
1052
1053 $headers = array(
1054 'Reply-To' => $verp['reply'],
1055 'Return-Path' => $verp['bounce'],
1056 'From' => "\"{$this->from_name}\" <{$this->from_email}>",
1057 'Subject' => $this->subject,
1058 'List-Unsubscribe' => "<mailto:{$verp['unsubscribe']}>",
1059 );
1060 self::addMessageIdHeader($headers, 'm', $job_id, $event_queue_id, $hash);
1061 if ($isForward) {
1062 $headers['Subject'] = "[Fwd:{$this->subject}]";
1063 }
1064 return array(&$verp, &$urls, &$headers);
1065 }
1066
1067 /**
1068 * Compose a message
1069 *
1070 * @param int $job_id ID of the Job associated with this message
1071 * @param int $event_queue_id ID of the EventQueue
1072 * @param string $hash Hash of the EventQueue
1073 * @param string $contactId ID of the Contact
1074 * @param string $email Destination address
1075 * @param string $recipient To: of the recipient
1076 * @param boolean $test Is this mailing a test?
1077 * @param $contactDetails
1078 * @param $attachments
1079 * @param boolean $isForward Is this mailing compose for forward?
1080 * @param string $fromEmail email address of who is forwardinf it.
1081 *
1082 * @param null $replyToEmail
1083 *
1084 * @return object The mail object
1085 * @access public
1086 */
1087 public function &compose($job_id, $event_queue_id, $hash, $contactId,
1088 $email, &$recipient, $test,
1089 $contactDetails, &$attachments, $isForward = FALSE,
1090 $fromEmail = NULL, $replyToEmail = NULL
1091 ) {
1092 $config = CRM_Core_Config::singleton();
1093 $knownTokens = $this->getTokens();
1094
1095 if ($this->_domain == NULL) {
1096 $this->_domain = CRM_Core_BAO_Domain::getDomain();
1097 }
1098
1099 list($verp, $urls, $headers) = $this->getVerpAndUrlsAndHeaders(
1100 $job_id,
1101 $event_queue_id,
1102 $hash,
1103 $email,
1104 $isForward
1105 );
1106
1107 //set from email who is forwarding it and not original one.
1108 if ($fromEmail) {
1109 unset($headers['From']);
1110 $headers['From'] = "<{$fromEmail}>";
1111 }
1112
1113 if ($replyToEmail && ($fromEmail != $replyToEmail)) {
1114 $headers['Reply-To'] = "{$replyToEmail}";
1115 }
1116
1117 if ($contactDetails) {
1118 $contact = $contactDetails;
1119 }
1120 elseif ($contactId === 0) {
1121 //anonymous user
1122 $contact = array();
1123 CRM_Utils_Hook::tokenValues($contact, $contactId, $job_id);
1124 }
1125 else {
1126 $params = array(array('contact_id', '=', $contactId, 0, 0));
1127 list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($params);
1128
1129 //CRM-4524
1130 $contact = reset($contact);
1131
1132 if (!$contact || is_a($contact, 'CRM_Core_Error')) {
1133 CRM_Core_Error::debug_log_message(ts('CiviMail will not send email to a non-existent contact: %1',
1134 array(1 => $contactId)
1135 ));
1136 // setting this because function is called by reference
1137 //@todo test not calling function by reference
1138 $res = NULL;
1139 return $res;
1140 }
1141
1142 // also call the hook to get contact details
1143 CRM_Utils_Hook::tokenValues($contact, $contactId, $job_id);
1144 }
1145
1146 $pTemplates = $this->getPreparedTemplates();
1147 $pEmails = array();
1148
1149 foreach ($pTemplates as $type => $pTemplate) {
1150 $html = ($type == 'html') ? TRUE : FALSE;
1151 $pEmails[$type] = array();
1152 $pEmail = &$pEmails[$type];
1153 $template = &$pTemplates[$type]['template'];
1154 $tokens = &$pTemplates[$type]['tokens'];
1155 $idx = 0;
1156 if (!empty($tokens)) {
1157 foreach ($tokens as $idx => $token) {
1158 $token_data = $this->getTokenData($token, $html, $contact, $verp, $urls, $event_queue_id);
1159 array_push($pEmail, $template[$idx]);
1160 array_push($pEmail, $token_data);
1161 }
1162 }
1163 else {
1164 array_push($pEmail, $template[$idx]);
1165 }
1166
1167 if (isset($template[($idx + 1)])) {
1168 array_push($pEmail, $template[($idx + 1)]);
1169 }
1170 }
1171
1172 $html = NULL;
1173 if (isset($pEmails['html']) && is_array($pEmails['html']) && count($pEmails['html'])) {
1174 $html = &$pEmails['html'];
1175 }
1176
1177 $text = NULL;
1178 if (isset($pEmails['text']) && is_array($pEmails['text']) && count($pEmails['text'])) {
1179 $text = &$pEmails['text'];
1180 }
1181
1182 // push the tracking url on to the html email if necessary
1183 if ($this->open_tracking && $html) {
1184 array_push($html, "\n" . '<img src="' . $config->userFrameworkResourceURL .
1185 "extern/open.php?q=$event_queue_id\" width='1' height='1' alt='' border='0'>"
1186 );
1187 }
1188
1189 $message = new Mail_mime("\n");
1190
1191 $useSmarty = defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY ? TRUE : FALSE;
1192 if ($useSmarty) {
1193 $smarty = CRM_Core_Smarty::singleton();
1194 // also add the contact tokens to the template
1195 $smarty->assign_by_ref('contact', $contact);
1196 }
1197
1198 $mailParams = $headers;
1199 if ($text && ($test || $contact['preferred_mail_format'] == 'Text' ||
1200 $contact['preferred_mail_format'] == 'Both' ||
1201 ($contact['preferred_mail_format'] == 'HTML' && !array_key_exists('html', $pEmails))
1202 )) {
1203 $textBody = join('', $text);
1204 if ($useSmarty) {
1205 $textBody = $smarty->fetch("string:$textBody");
1206 }
1207 $mailParams['text'] = $textBody;
1208 }
1209
1210 if ($html && ($test || ($contact['preferred_mail_format'] == 'HTML' ||
1211 $contact['preferred_mail_format'] == 'Both'
1212 ))) {
1213 $htmlBody = join('', $html);
1214 if ($useSmarty) {
1215 $htmlBody = $smarty->fetch("string:$htmlBody");
1216 }
1217 $mailParams['html'] = $htmlBody;
1218 }
1219
1220 if (empty($mailParams['text']) && empty($mailParams['html'])) {
1221 // CRM-9833
1222 // something went wrong, lets log it and return null (by reference)
1223 CRM_Core_Error::debug_log_message(ts('CiviMail will not send an empty mail body, Skipping: %1',
1224 array(1 => $email)
1225 ));
1226 $res = NULL;
1227 return $res;
1228 }
1229
1230 $mailParams['attachments'] = $attachments;
1231
1232 $mailingSubject = CRM_Utils_Array::value('subject', $pEmails);
1233 if (is_array($mailingSubject)) {
1234 $mailingSubject = join('', $mailingSubject);
1235 }
1236 $mailParams['Subject'] = $mailingSubject;
1237
1238 $mailParams['toName'] = CRM_Utils_Array::value('display_name',
1239 $contact
1240 );
1241 $mailParams['toEmail'] = $email;
1242
1243 CRM_Utils_Hook::alterMailParams($mailParams, 'civimail');
1244
1245 // CRM-10699 support custom email headers
1246 if (!empty($mailParams['headers'])) {
1247 $headers = array_merge($headers, $mailParams['headers']);
1248 }
1249 //cycle through mailParams and set headers array
1250 foreach ($mailParams as $paramKey => $paramValue) {
1251 //exclude values not intended for the header
1252 if (!in_array($paramKey, array(
1253 'text', 'html', 'attachments', 'toName', 'toEmail'))) {
1254 $headers[$paramKey] = $paramValue;
1255 }
1256 }
1257
1258 if (!empty($mailParams['text'])) {
1259 $message->setTxtBody($mailParams['text']);
1260 }
1261
1262 if (!empty($mailParams['html'])) {
1263 $message->setHTMLBody($mailParams['html']);
1264 }
1265
1266 if (!empty($mailParams['attachments'])) {
1267 foreach ($mailParams['attachments'] as $fileID => $attach) {
1268 $message->addAttachment($attach['fullPath'],
1269 $attach['mime_type'],
1270 $attach['cleanName']
1271 );
1272 }
1273 }
1274
1275 //pickup both params from mail params.
1276 $toName = trim($mailParams['toName']);
1277 $toEmail = trim($mailParams['toEmail']);
1278 if ($toName == $toEmail ||
1279 strpos($toName, '@') !== FALSE
1280 ) {
1281 $toName = NULL;
1282 }
1283 else {
1284 $toName = CRM_Utils_Mail::formatRFC2822Name($toName);
1285 }
1286
1287 $headers['To'] = "$toName <$toEmail>";
1288
1289 $headers['Precedence'] = 'bulk';
1290 // Will test in the mail processor if the X-VERP is set in the bounced email.
1291 // (As an option to replace real VERP for those that can't set it up)
1292 $headers['X-CiviMail-Bounce'] = $verp['bounce'];
1293
1294 //CRM-5058
1295 //token replacement of subject
1296 $headers['Subject'] = $mailingSubject;
1297
1298 CRM_Utils_Mail::setMimeParams($message);
1299 $headers = $message->headers($headers);
1300
1301 //get formatted recipient
1302 $recipient = $headers['To'];
1303
1304 // make sure we unset a lot of stuff
1305 unset($verp);
1306 unset($urls);
1307 unset($params);
1308 unset($contact);
1309 unset($ids);
1310
1311 return $message;
1312 }
1313
1314 /**
1315 *
1316 * get mailing object and replaces subscribeInvite,
1317 * domain and mailing tokens
1318 *
1319 */
1320 public static function tokenReplace(&$mailing) {
1321 $domain = CRM_Core_BAO_Domain::getDomain();
1322
1323 foreach (array('text', 'html') as $type) {
1324 $tokens = $mailing->getTokens();
1325 if (isset($mailing->templates[$type])) {
1326 $mailing->templates[$type] = CRM_Utils_Token::replaceSubscribeInviteTokens($mailing->templates[$type]);
1327 $mailing->templates[$type] = CRM_Utils_Token::replaceDomainTokens(
1328 $mailing->templates[$type],
1329 $domain,
1330 $type == 'html' ? TRUE : FALSE,
1331 $tokens[$type]
1332 );
1333 $mailing->templates[$type] = CRM_Utils_Token::replaceMailingTokens($mailing->templates[$type], $mailing, NULL, $tokens[$type]);
1334 }
1335 }
1336 }
1337
1338 /**
1339 *
1340 * getTokenData receives a token from an email
1341 * and returns the appropriate data for the token
1342 *
1343 */
1344 private function getTokenData(&$token_a, $html = FALSE, &$contact, &$verp, &$urls, $event_queue_id) {
1345 $type = $token_a['type'];
1346 $token = $token_a['token'];
1347 $data = $token;
1348
1349 $useSmarty = defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY ? TRUE : FALSE;
1350
1351 if ($type == 'embedded_url') {
1352 $embed_data = array();
1353 foreach ($token as $t) {
1354 $embed_data[] = $this->getTokenData($t, $html = FALSE, $contact, $verp, $urls, $event_queue_id);
1355 }
1356 $numSlices = count($embed_data);
1357 $url = '';
1358 for ($i = 0; $i < $numSlices; $i++) {
1359 $url .= "{$token_a['embed_parts'][$i]}{$embed_data[$i]}";
1360 }
1361 if (isset($token_a['embed_parts'][$numSlices])) {
1362 $url .= $token_a['embed_parts'][$numSlices];
1363 }
1364 // add trailing quote since we've gobbled it up in a previous regex
1365 // function getPatterns, line 431
1366 if (preg_match('/^href[ ]*=[ ]*\'/', $url)) {
1367 $url .= "'";
1368 }
1369 elseif (preg_match('/^href[ ]*=[ ]*\"/', $url)) {
1370 $url .= '"';
1371 }
1372 $data = $url;
1373 }
1374 elseif ($type == 'url') {
1375 if ($this->url_tracking) {
1376 $data = CRM_Mailing_BAO_TrackableURL::getTrackerURL($token, $this->id, $event_queue_id);
1377 }
1378 else {
1379 $data = $token;
1380 }
1381 }
1382 elseif ($type == 'contact') {
1383 $data = CRM_Utils_Token::getContactTokenReplacement($token, $contact, FALSE, FALSE, $useSmarty);
1384 }
1385 elseif ($type == 'action') {
1386 $data = CRM_Utils_Token::getActionTokenReplacement($token, $verp, $urls, $html);
1387 }
1388 elseif ($type == 'domain') {
1389 $domain = CRM_Core_BAO_Domain::getDomain();
1390 $data = CRM_Utils_Token::getDomainTokenReplacement($token, $domain, $html);
1391 }
1392 elseif ($type == 'mailing') {
1393 if ($token == 'name') {
1394 $data = $this->name;
1395 }
1396 elseif ($token == 'group') {
1397 $groups = $this->getGroupNames();
1398 $data = implode(', ', $groups);
1399 }
1400 }
1401 else {
1402 $data = CRM_Utils_Array::value("{$type}.{$token}", $contact);
1403 }
1404 return $data;
1405 }
1406
1407 /**
1408 * Return a list of group names for this mailing. Does not work with
1409 * prior-mailing targets.
1410 *
1411 * @return array Names of groups receiving this mailing
1412 * @access public
1413 */
1414 public function &getGroupNames() {
1415 if (!isset($this->id)) {
1416 return array();
1417 }
1418 $mg = new CRM_Mailing_DAO_MailingGroup();
1419 $mgtable = CRM_Mailing_DAO_MailingGroup::getTableName();
1420 $group = CRM_Contact_BAO_Group::getTableName();
1421
1422 $mg->query("SELECT $group.title as name FROM $mgtable
1423 INNER JOIN $group ON $mgtable.entity_id = $group.id
1424 WHERE $mgtable.mailing_id = {$this->id}
1425 AND $mgtable.entity_table = '$group'
1426 AND $mgtable.group_type = 'Include'
1427 ORDER BY $group.name");
1428
1429 $groups = array();
1430 while ($mg->fetch()) {
1431 $groups[] = $mg->name;
1432 }
1433 $mg->free();
1434 return $groups;
1435 }
1436
1437 /**
1438 * function to add the mailings
1439 *
1440 * @param array $params reference array contains the values submitted by the form
1441 * @param array $ids reference array contains the id
1442 *
1443 * @access public
1444 * @static
1445 *
1446 * @return object
1447 */
1448 static function add(&$params, $ids = array()) {
1449 $id = CRM_Utils_Array::value('mailing_id', $ids, CRM_Utils_Array::value('id', $params));
1450
1451 if ($id) {
1452 CRM_Utils_Hook::pre('edit', 'Mailing', $id, $params);
1453 }
1454 else {
1455 CRM_Utils_Hook::pre('create', 'Mailing', NULL, $params);
1456 }
1457
1458 $mailing = new CRM_Mailing_DAO_Mailing();
1459 $mailing->id = $id;
1460 $mailing->domain_id = CRM_Utils_Array::value('domain_id', $params, CRM_Core_Config::domainID());
1461
1462 if (!isset($params['replyto_email']) &&
1463 isset($params['from_email'])
1464 ) {
1465 $params['replyto_email'] = $params['from_email'];
1466 }
1467
1468 $mailing->copyValues($params);
1469
1470 $result = $mailing->save();
1471
1472 if (!empty($ids['mailing'])) {
1473 CRM_Utils_Hook::post('edit', 'Mailing', $mailing->id, $mailing);
1474 }
1475 else {
1476 CRM_Utils_Hook::post('create', 'Mailing', $mailing->id, $mailing);
1477 }
1478
1479 return $result;
1480 }
1481
1482 /**
1483 * Construct a new mailing object, along with job and mailing_group
1484 * objects, from the form values of the create mailing wizard.
1485 *
1486 * @params array $params Form values
1487 *
1488 * @param $params
1489 * @param array $ids
1490 *
1491 * @return object $mailing The new mailing object
1492 * @access public
1493 * @static
1494 */
1495 public static function create(&$params, $ids = array()) {
1496
1497 // CRM-12430
1498 // Do the below only for an insert
1499 // for an update, we should not set the defaults
1500 if (!isset($ids['id']) && !isset($ids['mailing_id'])) {
1501 // Retrieve domain email and name for default sender
1502 $domain = civicrm_api(
1503 'Domain',
1504 'getsingle',
1505 array(
1506 'version' => 3,
1507 'current_domain' => 1,
1508 'sequential' => 1,
1509 )
1510 );
1511 if (isset($domain['from_email'])) {
1512 $domain_email = $domain['from_email'];
1513 $domain_name = $domain['from_name'];
1514 }
1515 else {
1516 $domain_email = 'info@EXAMPLE.ORG';
1517 $domain_name = 'EXAMPLE.ORG';
1518 }
1519 if (!isset($params['created_id'])) {
1520 $session =& CRM_Core_Session::singleton();
1521 $params['created_id'] = $session->get('userID');
1522 }
1523 $defaults = array(
1524 // load the default config settings for each
1525 // eg reply_id, unsubscribe_id need to use
1526 // correct template IDs here
1527 'override_verp' => TRUE,
1528 'forward_replies' => FALSE,
1529 'open_tracking' => TRUE,
1530 'url_tracking' => TRUE,
1531 'visibility' => 'User and User Admin Only',
1532 'replyto_email' => $domain_email,
1533 'header_id' => CRM_Mailing_PseudoConstant::defaultComponent('header_id', ''),
1534 'footer_id' => CRM_Mailing_PseudoConstant::defaultComponent('footer_id', ''),
1535 'from_email' => $domain_email,
1536 'from_name' => $domain_name,
1537 'msg_template_id' => NULL,
1538 'created_id' => $params['created_id'],
1539 'approver_id' => NULL,
1540 'auto_responder' => 0,
1541 'created_date' => date('YmdHis'),
1542 'scheduled_date' => NULL,
1543 'approval_date' => NULL,
1544 );
1545
1546 // Get the default from email address, if not provided.
1547 if (empty($defaults['from_email'])) {
1548 $defaultAddress = CRM_Core_OptionGroup::values('from_email_address', NULL, NULL, NULL, ' AND is_default = 1');
1549 foreach ($defaultAddress as $id => $value) {
1550 if (preg_match('/"(.*)" <(.*)>/', $value, $match)) {
1551 $defaults['from_email'] = $match[2];
1552 $defaults['from_name'] = $match[1];
1553 }
1554 }
1555 }
1556
1557 $params = array_merge($defaults, $params);
1558 }
1559
1560 /**
1561 * Could check and warn for the following cases:
1562 *
1563 * - groups OR mailings should be populated.
1564 * - body html OR body text should be populated.
1565 */
1566
1567 $transaction = new CRM_Core_Transaction();
1568
1569 $mailing = self::add($params, $ids);
1570
1571 if (is_a($mailing, 'CRM_Core_Error')) {
1572 $transaction->rollback();
1573 return $mailing;
1574 }
1575 // update mailings with hash values
1576 CRM_Contact_BAO_Contact_Utils::generateChecksum($mailing->id, NULL, NULL, NULL, 'mailing', 16);
1577
1578 $groupTableName = CRM_Contact_BAO_Group::getTableName();
1579 $mailingTableName = CRM_Mailing_BAO_Mailing::getTableName();
1580
1581 /* Create the mailing group record */
1582 $mg = new CRM_Mailing_DAO_MailingGroup();
1583 foreach (array('groups', 'mailings') as $entity) {
1584 foreach (array('include', 'exclude', 'base') as $type) {
1585 if (isset($params[$entity]) && !empty($params[$entity][$type]) &&
1586 is_array($params[$entity][$type])) {
1587 foreach ($params[$entity][$type] as $entityId) {
1588 $mg->reset();
1589 $mg->mailing_id = $mailing->id;
1590 $mg->entity_table = ($entity == 'groups') ? $groupTableName : $mailingTableName;
1591 $mg->entity_id = $entityId;
1592 $mg->group_type = $type;
1593 $mg->save();
1594 }
1595 }
1596 }
1597 }
1598
1599 if (!empty($params['search_id']) && !empty($params['group_id'])) {
1600 $mg->reset();
1601 $mg->mailing_id = $mailing->id;
1602 $mg->entity_table = $groupTableName;
1603 $mg->entity_id = $params['group_id'];
1604 $mg->search_id = $params['search_id'];
1605 $mg->search_args = $params['search_args'];
1606 $mg->group_type = 'Include';
1607 $mg->save();
1608 }
1609
1610 // check and attach and files as needed
1611 CRM_Core_BAO_File::processAttachment($params, 'civicrm_mailing', $mailing->id);
1612
1613 $transaction->commit();
1614
1615 /**
1616 * create parent job if not yet created
1617 * condition on the existence of a scheduled date
1618 */
1619 if (!empty($params['scheduled_date']) && $params['scheduled_date'] != 'null') {
1620 $job = new CRM_Mailing_BAO_MailingJob();
1621 $job->mailing_id = $mailing->id;
1622 $job->status = 'Scheduled';
1623 $job->is_test = 0;
1624
1625 if ( !$job->find(TRUE) ) {
1626 $job->scheduled_date = $params['scheduled_date'];
1627 $job->save();
1628 }
1629
1630 // Populate the recipients.
1631 $mailing->getRecipients($job->id, $mailing->id, NULL, NULL, TRUE, FALSE);
1632 }
1633
1634 return $mailing;
1635 }
1636
1637 /**
1638 * get hash value of the mailing
1639 *
1640 */
1641 public static function getMailingHash($id) {
1642 $hash = NULL;
1643 if (CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'hash_mailing_url')) {
1644 $hash = CRM_Core_DAO::getFieldValue('CRM_Mailing_BAO_Mailing', $id, 'hash', 'id');
1645 }
1646 return $hash;
1647 }
1648
1649 /**
1650 * Generate a report. Fetch event count information, mailing data, and job
1651 * status.
1652 *
1653 * @param int $id The mailing id to report
1654 * @param boolean $skipDetails whether return all detailed report
1655 *
1656 * @param bool $isSMS
1657 *
1658 * @return array Associative array of reporting data
1659 * @access public
1660 * @static
1661 */
1662 public static function &report($id, $skipDetails = FALSE, $isSMS = FALSE) {
1663 $mailing_id = CRM_Utils_Type::escape($id, 'Integer');
1664
1665 $mailing = new CRM_Mailing_BAO_Mailing();
1666
1667 $t = array(
1668 'mailing' => self::getTableName(),
1669 'mailing_group' => CRM_Mailing_DAO_MailingGroup::getTableName(),
1670 'group' => CRM_Contact_BAO_Group::getTableName(),
1671 'job' => CRM_Mailing_BAO_MailingJob::getTableName(),
1672 'queue' => CRM_Mailing_Event_BAO_Queue::getTableName(),
1673 'delivered' => CRM_Mailing_Event_BAO_Delivered::getTableName(),
1674 'opened' => CRM_Mailing_Event_BAO_Opened::getTableName(),
1675 'reply' => CRM_Mailing_Event_BAO_Reply::getTableName(),
1676 'unsubscribe' =>
1677 CRM_Mailing_Event_BAO_Unsubscribe::getTableName(),
1678 'bounce' => CRM_Mailing_Event_BAO_Bounce::getTableName(),
1679 'forward' => CRM_Mailing_Event_BAO_Forward::getTableName(),
1680 'url' => CRM_Mailing_BAO_TrackableURL::getTableName(),
1681 'urlopen' =>
1682 CRM_Mailing_Event_BAO_TrackableURLOpen::getTableName(),
1683 'component' => CRM_Mailing_BAO_Component::getTableName(),
1684 'spool' => CRM_Mailing_BAO_Spool::getTableName(),
1685 );
1686
1687
1688 $report = array();
1689 $additionalWhereClause = " AND ";
1690 if (!$isSMS) {
1691 $additionalWhereClause .= " {$t['mailing']}.sms_provider_id IS NULL ";
1692 }
1693 else {
1694 $additionalWhereClause .= " {$t['mailing']}.sms_provider_id IS NOT NULL ";
1695 }
1696
1697 /* Get the mailing info */
1698
1699 $mailing->query("
1700 SELECT {$t['mailing']}.*
1701 FROM {$t['mailing']}
1702 WHERE {$t['mailing']}.id = $mailing_id {$additionalWhereClause}");
1703
1704 $mailing->fetch();
1705
1706 $report['mailing'] = array();
1707 foreach (array_keys(self::fields()) as $field) {
1708 $report['mailing'][$field] = $mailing->$field;
1709 }
1710
1711 //get the campaign
1712 if ($campaignId = CRM_Utils_Array::value('campaign_id', $report['mailing'])) {
1713 $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId);
1714 $report['mailing']['campaign'] = $campaigns[$campaignId];
1715 }
1716
1717 //mailing report is called by activity
1718 //we dont need all detail report
1719 if ($skipDetails) {
1720 return $report;
1721 }
1722
1723 /* Get the component info */
1724
1725 $query = array();
1726
1727 $components = array(
1728 'header' => ts('Header'),
1729 'footer' => ts('Footer'),
1730 'reply' => ts('Reply'),
1731 'unsubscribe' => ts('Unsubscribe'),
1732 'optout' => ts('Opt-Out'),
1733 );
1734 foreach (array_keys($components) as $type) {
1735 $query[] = "SELECT {$t['component']}.name as name,
1736 '$type' as type,
1737 {$t['component']}.id as id
1738 FROM {$t['component']}
1739 INNER JOIN {$t['mailing']}
1740 ON {$t['mailing']}.{$type}_id =
1741 {$t['component']}.id
1742 WHERE {$t['mailing']}.id = $mailing_id";
1743 }
1744 $q = '(' . implode(') UNION (', $query) . ')';
1745 $mailing->query($q);
1746
1747 $report['component'] = array();
1748 while ($mailing->fetch()) {
1749 $report['component'][] = array(
1750 'type' => $components[$mailing->type],
1751 'name' => $mailing->name,
1752 'link' =>
1753 CRM_Utils_System::url('civicrm/mailing/component',
1754 "reset=1&action=update&id={$mailing->id}"
1755 ),
1756 );
1757 }
1758
1759 /* Get the recipient group info */
1760
1761 $mailing->query("
1762 SELECT {$t['mailing_group']}.group_type as group_type,
1763 {$t['group']}.id as group_id,
1764 {$t['group']}.title as group_title,
1765 {$t['group']}.is_hidden as group_hidden,
1766 {$t['mailing']}.id as mailing_id,
1767 {$t['mailing']}.name as mailing_name
1768 FROM {$t['mailing_group']}
1769 LEFT JOIN {$t['group']}
1770 ON {$t['mailing_group']}.entity_id = {$t['group']}.id
1771 AND {$t['mailing_group']}.entity_table =
1772 '{$t['group']}'
1773 LEFT JOIN {$t['mailing']}
1774 ON {$t['mailing_group']}.entity_id =
1775 {$t['mailing']}.id
1776 AND {$t['mailing_group']}.entity_table =
1777 '{$t['mailing']}'
1778
1779 WHERE {$t['mailing_group']}.mailing_id = $mailing_id
1780 ");
1781
1782 $report['group'] = array('include' => array(), 'exclude' => array(), 'base' => array());
1783 while ($mailing->fetch()) {
1784 $row = array();
1785 if (isset($mailing->group_id)) {
1786 $row['id'] = $mailing->group_id;
1787 $row['name'] = $mailing->group_title;
1788 $row['link'] = CRM_Utils_System::url('civicrm/group/search',
1789 "reset=1&force=1&context=smog&gid={$row['id']}"
1790 );
1791 }
1792 else {
1793 $row['id'] = $mailing->mailing_id;
1794 $row['name'] = $mailing->mailing_name;
1795 $row['mailing'] = TRUE;
1796 $row['link'] = CRM_Utils_System::url('civicrm/mailing/report',
1797 "mid={$row['id']}"
1798 );
1799 }
1800
1801 /* Rename hidden groups */
1802
1803 if ($mailing->group_hidden == 1) {
1804 $row['name'] = "Search Results";
1805 }
1806
1807 if ($mailing->group_type == 'Include') {
1808 $report['group']['include'][] = $row;
1809 }
1810 elseif ($mailing->group_type == 'Base') {
1811 $report['group']['base'][] = $row;
1812 }
1813 else {
1814 $report['group']['exclude'][] = $row;
1815 }
1816 }
1817
1818 /* Get the event totals, grouped by job (retries) */
1819
1820 $mailing->query("
1821 SELECT {$t['job']}.*,
1822 COUNT(DISTINCT {$t['queue']}.id) as queue,
1823 COUNT(DISTINCT {$t['delivered']}.id) as delivered,
1824 COUNT(DISTINCT {$t['reply']}.id) as reply,
1825 COUNT(DISTINCT {$t['forward']}.id) as forward,
1826 COUNT(DISTINCT {$t['bounce']}.id) as bounce,
1827 COUNT(DISTINCT {$t['urlopen']}.id) as url,
1828 COUNT(DISTINCT {$t['spool']}.id) as spool
1829 FROM {$t['job']}
1830 LEFT JOIN {$t['queue']}
1831 ON {$t['queue']}.job_id = {$t['job']}.id
1832 LEFT JOIN {$t['reply']}
1833 ON {$t['reply']}.event_queue_id = {$t['queue']}.id
1834 LEFT JOIN {$t['forward']}
1835 ON {$t['forward']}.event_queue_id = {$t['queue']}.id
1836 LEFT JOIN {$t['bounce']}
1837 ON {$t['bounce']}.event_queue_id = {$t['queue']}.id
1838 LEFT JOIN {$t['delivered']}
1839 ON {$t['delivered']}.event_queue_id = {$t['queue']}.id
1840 AND {$t['bounce']}.id IS null
1841 LEFT JOIN {$t['urlopen']}
1842 ON {$t['urlopen']}.event_queue_id = {$t['queue']}.id
1843 LEFT JOIN {$t['spool']}
1844 ON {$t['spool']}.job_id = {$t['job']}.id
1845 WHERE {$t['job']}.mailing_id = $mailing_id
1846 AND {$t['job']}.is_test = 0
1847 GROUP BY {$t['job']}.id");
1848
1849 $report['jobs'] = array();
1850 $report['event_totals'] = array();
1851 $elements = array(
1852 'queue', 'delivered', 'url', 'forward',
1853 'reply', 'unsubscribe', 'optout', 'opened', 'bounce', 'spool',
1854 );
1855
1856 // initialize various counters
1857 foreach ($elements as $field) {
1858 $report['event_totals'][$field] = 0;
1859 }
1860
1861 while ($mailing->fetch()) {
1862 $row = array();
1863 foreach ($elements as $field) {
1864 if (isset($mailing->$field)) {
1865 $row[$field] = $mailing->$field;
1866 $report['event_totals'][$field] += $mailing->$field;
1867 }
1868 }
1869
1870 // compute open total separately to discount duplicates
1871 // CRM-1258
1872 $row['opened'] = CRM_Mailing_Event_BAO_Opened::getTotalCount($mailing_id, $mailing->id, TRUE);
1873 $report['event_totals']['opened'] += $row['opened'];
1874
1875 // compute unsub total separately to discount duplicates
1876 // CRM-1783
1877 $row['unsubscribe'] = CRM_Mailing_Event_BAO_Unsubscribe::getTotalCount($mailing_id, $mailing->id, TRUE, TRUE);
1878 $report['event_totals']['unsubscribe'] += $row['unsubscribe'];
1879
1880 $row['optout'] = CRM_Mailing_Event_BAO_Unsubscribe::getTotalCount($mailing_id, $mailing->id, TRUE, FALSE);
1881 $report['event_totals']['optout'] += $row['optout'];
1882
1883 foreach (array_keys(CRM_Mailing_BAO_MailingJob::fields()) as $field) {
1884 $row[$field] = $mailing->$field;
1885 }
1886
1887 if ($mailing->queue) {
1888 $row['delivered_rate'] = (100.0 * $mailing->delivered) / $mailing->queue;
1889 $row['bounce_rate'] = (100.0 * $mailing->bounce) / $mailing->queue;
1890 $row['unsubscribe_rate'] = (100.0 * $row['unsubscribe']) / $mailing->queue;
1891 $row['optout_rate'] = (100.0 * $row['optout']) / $mailing->queue;
1892 }
1893 else {
1894 $row['delivered_rate'] = 0;
1895 $row['bounce_rate'] = 0;
1896 $row['unsubscribe_rate'] = 0;
1897 $row['optout_rate'] = 0;
1898 }
1899
1900 $row['links'] = array(
1901 'clicks' => CRM_Utils_System::url(
1902 'civicrm/mailing/report/event',
1903 "reset=1&event=click&mid=$mailing_id&jid={$mailing->id}"
1904 ),
1905 'queue' => CRM_Utils_System::url(
1906 'civicrm/mailing/report/event',
1907 "reset=1&event=queue&mid=$mailing_id&jid={$mailing->id}"
1908 ),
1909 'delivered' => CRM_Utils_System::url(
1910 'civicrm/mailing/report/event',
1911 "reset=1&event=delivered&mid=$mailing_id&jid={$mailing->id}"
1912 ),
1913 'bounce' => CRM_Utils_System::url(
1914 'civicrm/mailing/report/event',
1915 "reset=1&event=bounce&mid=$mailing_id&jid={$mailing->id}"
1916 ),
1917 'unsubscribe' => CRM_Utils_System::url(
1918 'civicrm/mailing/report/event',
1919 "reset=1&event=unsubscribe&mid=$mailing_id&jid={$mailing->id}"
1920 ),
1921 'forward' => CRM_Utils_System::url(
1922 'civicrm/mailing/report/event',
1923 "reset=1&event=forward&mid=$mailing_id&jid={$mailing->id}"
1924 ),
1925 'reply' => CRM_Utils_System::url(
1926 'civicrm/mailing/report/event',
1927 "reset=1&event=reply&mid=$mailing_id&jid={$mailing->id}"
1928 ),
1929 'opened' => CRM_Utils_System::url(
1930 'civicrm/mailing/report/event',
1931 "reset=1&event=opened&mid=$mailing_id&jid={$mailing->id}"
1932 ),
1933 );
1934
1935 foreach (array(
1936 'scheduled_date', 'start_date', 'end_date') as $key) {
1937 $row[$key] = CRM_Utils_Date::customFormat($row[$key]);
1938 }
1939 $report['jobs'][] = $row;
1940 }
1941
1942 $newTableSize = CRM_Mailing_BAO_Recipients::mailingSize($mailing_id);
1943
1944 // we need to do this for backward compatibility, since old mailings did not
1945 // use the mailing_recipients table
1946 if ($newTableSize > 0) {
1947 $report['event_totals']['queue'] = $newTableSize;
1948 }
1949 else {
1950 $report['event_totals']['queue'] = self::getRecipientsCount($mailing_id, $mailing_id);
1951 }
1952
1953 if (!empty($report['event_totals']['queue'])) {
1954 $report['event_totals']['delivered_rate'] = (100.0 * $report['event_totals']['delivered']) / $report['event_totals']['queue'];
1955 $report['event_totals']['bounce_rate'] = (100.0 * $report['event_totals']['bounce']) / $report['event_totals']['queue'];
1956 $report['event_totals']['unsubscribe_rate'] = (100.0 * $report['event_totals']['unsubscribe']) / $report['event_totals']['queue'];
1957 $report['event_totals']['optout_rate'] = (100.0 * $report['event_totals']['optout']) / $report['event_totals']['queue'];
1958 }
1959 else {
1960 $report['event_totals']['delivered_rate'] = 0;
1961 $report['event_totals']['bounce_rate'] = 0;
1962 $report['event_totals']['unsubscribe_rate'] = 0;
1963 $report['event_totals']['optout_rate'] = 0;
1964 }
1965
1966 /* Get the click-through totals, grouped by URL */
1967
1968 $mailing->query("
1969 SELECT {$t['url']}.url,
1970 {$t['url']}.id,
1971 COUNT({$t['urlopen']}.id) as clicks,
1972 COUNT(DISTINCT {$t['queue']}.id) as unique_clicks
1973 FROM {$t['url']}
1974 LEFT JOIN {$t['urlopen']}
1975 ON {$t['urlopen']}.trackable_url_id = {$t['url']}.id
1976 LEFT JOIN {$t['queue']}
1977 ON {$t['urlopen']}.event_queue_id = {$t['queue']}.id
1978 LEFT JOIN {$t['job']}
1979 ON {$t['queue']}.job_id = {$t['job']}.id
1980 WHERE {$t['url']}.mailing_id = $mailing_id
1981 AND {$t['job']}.is_test = 0
1982 GROUP BY {$t['url']}.id");
1983
1984 $report['click_through'] = array();
1985
1986 while ($mailing->fetch()) {
1987 $report['click_through'][] = array(
1988 'url' => $mailing->url,
1989 'link' =>
1990 CRM_Utils_System::url(
1991 'civicrm/mailing/report/event',
1992 "reset=1&event=click&mid=$mailing_id&uid={$mailing->id}"
1993 ),
1994 'link_unique' =>
1995 CRM_Utils_System::url(
1996 'civicrm/mailing/report/event',
1997 "reset=1&event=click&mid=$mailing_id&uid={$mailing->id}&distinct=1"
1998 ),
1999 'clicks' => $mailing->clicks,
2000 'unique' => $mailing->unique_clicks,
2001 'rate' => CRM_Utils_Array::value('delivered', $report['event_totals']) ? (100.0 * $mailing->unique_clicks) / $report['event_totals']['delivered'] : 0,
2002 );
2003 }
2004
2005 $report['event_totals']['links'] = array(
2006 'clicks' => CRM_Utils_System::url(
2007 'civicrm/mailing/report/event',
2008 "reset=1&event=click&mid=$mailing_id"
2009 ),
2010 'clicks_unique' => CRM_Utils_System::url(
2011 'civicrm/mailing/report/event',
2012 "reset=1&event=click&mid=$mailing_id&distinct=1"
2013 ),
2014 'queue' => CRM_Utils_System::url(
2015 'civicrm/mailing/report/event',
2016 "reset=1&event=queue&mid=$mailing_id"
2017 ),
2018 'delivered' => CRM_Utils_System::url(
2019 'civicrm/mailing/report/event',
2020 "reset=1&event=delivered&mid=$mailing_id"
2021 ),
2022 'bounce' => CRM_Utils_System::url(
2023 'civicrm/mailing/report/event',
2024 "reset=1&event=bounce&mid=$mailing_id"
2025 ),
2026 'unsubscribe' => CRM_Utils_System::url(
2027 'civicrm/mailing/report/event',
2028 "reset=1&event=unsubscribe&mid=$mailing_id"
2029 ),
2030 'optout' => CRM_Utils_System::url(
2031 'civicrm/mailing/report/event',
2032 "reset=1&event=optout&mid=$mailing_id"
2033 ),
2034 'forward' => CRM_Utils_System::url(
2035 'civicrm/mailing/report/event',
2036 "reset=1&event=forward&mid=$mailing_id"
2037 ),
2038 'reply' => CRM_Utils_System::url(
2039 'civicrm/mailing/report/event',
2040 "reset=1&event=reply&mid=$mailing_id"
2041 ),
2042 'opened' => CRM_Utils_System::url(
2043 'civicrm/mailing/report/event',
2044 "reset=1&event=opened&mid=$mailing_id"
2045 ),
2046 );
2047
2048
2049 $actionLinks = array(CRM_Core_Action::VIEW => array('name' => ts('Report')));
2050 if (CRM_Core_Permission::check('view all contacts')) {
2051 $actionLinks[CRM_Core_Action::ADVANCED] =
2052 array(
2053 'name' => ts('Advanced Search'),
2054 'url' => 'civicrm/contact/search/advanced',
2055 );
2056 }
2057 $action = array_sum(array_keys($actionLinks));
2058
2059 $report['event_totals']['actionlinks'] = array();
2060 foreach (array(
2061 'clicks', 'clicks_unique', 'queue', 'delivered', 'bounce', 'unsubscribe',
2062 'forward', 'reply', 'opened', 'optout',
2063 ) as $key) {
2064 $url = 'mailing/detail';
2065 $reportFilter = "reset=1&mailing_id_value={$mailing_id}";
2066 $searchFilter = "force=1&mailing_id=%%mid%%";
2067 switch ($key) {
2068 case 'delivered':
2069 $reportFilter .= "&delivery_status_value=successful";
2070 $searchFilter .= "&mailing_delivery_status=Y";
2071 break;
2072
2073 case 'bounce':
2074 $url = "mailing/bounce";
2075 $searchFilter .= "&mailing_delivery_status=N";
2076 break;
2077
2078 case 'forward':
2079 $reportFilter .= "&is_forwarded_value=1";
2080 $searchFilter .= "&mailing_forward=1";
2081 break;
2082
2083 case 'reply':
2084 $reportFilter .= "&is_replied_value=1";
2085 $searchFilter .= "&mailing_reply_status=Y";
2086 break;
2087
2088 case 'unsubscribe':
2089 $reportFilter .= "&is_unsubscribed_value=1";
2090 $searchFilter .= "&mailing_unsubscribe=1";
2091 break;
2092
2093 case 'optout':
2094 $reportFilter .= "&is_optout_value=1";
2095 $searchFilter .= "&mailing_optout=1";
2096 break;
2097
2098 case 'opened':
2099 $url = "mailing/opened";
2100 $searchFilter .= "&mailing_open_status=Y";
2101 break;
2102
2103 case 'clicks':
2104 case 'clicks_unique':
2105 $url = "mailing/clicks";
2106 $searchFilter .= "&mailing_click_status=Y";
2107 break;
2108 }
2109 $actionLinks[CRM_Core_Action::VIEW]['url'] = CRM_Report_Utils_Report::getNextUrl($url, $reportFilter, FALSE, TRUE);
2110 if (array_key_exists(CRM_Core_Action::ADVANCED, $actionLinks)) {
2111 $actionLinks[CRM_Core_Action::ADVANCED]['qs'] = $searchFilter;
2112 }
2113 $report['event_totals']['actionlinks'][$key] = CRM_Core_Action::formLink(
2114 $actionLinks,
2115 $action,
2116 array('mid' => $mailing_id),
2117 ts('more'),
2118 FALSE,
2119 'mailing.report.action',
2120 'Mailing',
2121 $mailing_id
2122 );
2123 }
2124
2125 return $report;
2126 }
2127
2128 /**
2129 * Get the count of mailings
2130 *
2131 * @param
2132 *
2133 * @return int Count
2134 * @access public
2135 */
2136 public function getCount() {
2137 $this->selectAdd();
2138 $this->selectAdd('COUNT(id) as count');
2139
2140 $session = CRM_Core_Session::singleton();
2141 $this->find(TRUE);
2142
2143 return $this->count;
2144 }
2145
2146 static function checkPermission($id) {
2147 if (!$id) {
2148 return;
2149 }
2150
2151 $mailingIDs = self::mailingACLIDs();
2152 if ($mailingIDs === TRUE) {
2153 return;
2154 }
2155
2156 if (!in_array($id, $mailingIDs)) {
2157 CRM_Core_Error::fatal(ts('You do not have permission to access this mailing report'));
2158 }
2159 return;
2160 }
2161
2162 static function mailingACL($alias = NULL) {
2163 $mailingACL = " ( 0 ) ";
2164
2165 $mailingIDs = self::mailingACLIDs();
2166 if ($mailingIDs === TRUE) {
2167 return " ( 1 ) ";
2168 }
2169
2170 if (!empty($mailingIDs)) {
2171 $mailingIDs = implode(',', $mailingIDs);
2172 $tableName = !$alias ? self::getTableName() : $alias;
2173 $mailingACL = " $tableName.id IN ( $mailingIDs ) ";
2174 }
2175 return $mailingACL;
2176 }
2177
2178 /**
2179 * returns all the mailings that this user can access. This is dependent on
2180 * all the groups that the user has access to.
2181 * However since most civi installs dont use ACL's we special case the condition
2182 * where the user has access to ALL groups, and hence ALL mailings and return a
2183 * value of TRUE (to avoid the downstream where clause with a list of mailing list IDs
2184 *
2185 * @return boolean | array - TRUE if the user has access to all mailings, else array of mailing IDs (possibly empty)
2186 * @static
2187 */
2188 static function mailingACLIDs() {
2189 // CRM-11633
2190 // optimize common case where admin has access
2191 // to all mailings
2192 if (
2193 CRM_Core_Permission::check('view all contacts') ||
2194 CRM_Core_Permission::check('edit all contacts')
2195 ) {
2196 return TRUE;
2197 }
2198
2199 $mailingIDs = array();
2200
2201 // get all the groups that this user can access
2202 // if they dont have universal access
2203 $groups = CRM_Core_PseudoConstant::group(NULL, FALSE);
2204 if (!empty($groups)) {
2205 $groupIDs = implode(',', array_keys($groups));
2206
2207 // get all the mailings that are in this subset of groups
2208 $query = "
2209 SELECT DISTINCT( m.id ) as id
2210 FROM civicrm_mailing m
2211 LEFT JOIN civicrm_mailing_group g ON g.mailing_id = m.id
2212 WHERE ( ( g.entity_table like 'civicrm_group%' AND g.entity_id IN ( $groupIDs ) )
2213 OR ( g.entity_table IS NULL AND g.entity_id IS NULL ) )
2214 ";
2215 $dao = CRM_Core_DAO::executeQuery($query);
2216
2217 $mailingIDs = array();
2218 while ($dao->fetch()) {
2219 $mailingIDs[] = $dao->id;
2220 }
2221 }
2222
2223 return $mailingIDs;
2224 }
2225
2226 /**
2227 * Get the rows for a browse operation
2228 *
2229 * @param int $offset The row number to start from
2230 * @param int $rowCount The nmber of rows to return
2231 * @param string $sort The sql string that describes the sort order
2232 *
2233 * @param null $additionalClause
2234 * @param null $additionalParams
2235 *
2236 * @return array The rows
2237 * @access public
2238 */
2239 public function &getRows($offset, $rowCount, $sort, $additionalClause = NULL, $additionalParams = NULL) {
2240 $mailing = self::getTableName();
2241 $job = CRM_Mailing_BAO_MailingJob::getTableName();
2242 $group = CRM_Mailing_DAO_MailingGroup::getTableName();
2243 $session = CRM_Core_Session::singleton();
2244
2245 $mailingACL = self::mailingACL();
2246
2247 //get all campaigns.
2248 $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
2249
2250 // we only care about parent jobs, since that holds all the info on
2251 // the mailing
2252 $query = "
2253 SELECT $mailing.id,
2254 $mailing.name,
2255 $job.status,
2256 $mailing.approval_status_id,
2257 MIN($job.scheduled_date) as scheduled_date,
2258 MIN($job.start_date) as start_date,
2259 MAX($job.end_date) as end_date,
2260 createdContact.sort_name as created_by,
2261 scheduledContact.sort_name as scheduled_by,
2262 $mailing.created_id as created_id,
2263 $mailing.scheduled_id as scheduled_id,
2264 $mailing.is_archived as archived,
2265 $mailing.created_date as created_date,
2266 campaign_id,
2267 $mailing.sms_provider_id as sms_provider_id
2268 FROM $mailing
2269 LEFT JOIN $job ON ( $job.mailing_id = $mailing.id AND $job.is_test = 0 AND $job.parent_id IS NULL )
2270 LEFT JOIN civicrm_contact createdContact ON ( civicrm_mailing.created_id = createdContact.id )
2271 LEFT JOIN civicrm_contact scheduledContact ON ( civicrm_mailing.scheduled_id = scheduledContact.id )
2272 WHERE $mailingACL $additionalClause
2273 GROUP BY $mailing.id ";
2274
2275 if ($sort) {
2276 $orderBy = trim($sort->orderBy());
2277 if (!empty($orderBy)) {
2278 $query .= " ORDER BY $orderBy";
2279 }
2280 }
2281
2282 if ($rowCount) {
2283 $offset = CRM_Utils_Type::escape($offset, 'Int');
2284 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
2285
2286 $query .= " LIMIT $offset, $rowCount ";
2287 }
2288
2289 if (!$additionalParams) {
2290 $additionalParams = array();
2291 }
2292
2293 $dao = CRM_Core_DAO::executeQuery($query, $additionalParams);
2294
2295 $rows = array();
2296 while ($dao->fetch()) {
2297 $rows[] = array(
2298 'id' => $dao->id,
2299 'name' => $dao->name,
2300 'status' => $dao->status ? $dao->status : 'Not scheduled',
2301 'created_date' => CRM_Utils_Date::customFormat($dao->created_date),
2302 'scheduled' => CRM_Utils_Date::customFormat($dao->scheduled_date),
2303 'scheduled_iso' => $dao->scheduled_date,
2304 'start' => CRM_Utils_Date::customFormat($dao->start_date),
2305 'end' => CRM_Utils_Date::customFormat($dao->end_date),
2306 'created_by' => $dao->created_by,
2307 'scheduled_by' => $dao->scheduled_by,
2308 'created_id' => $dao->created_id,
2309 'scheduled_id' => $dao->scheduled_id,
2310 'archived' => $dao->archived,
2311 'approval_status_id' => $dao->approval_status_id,
2312 'campaign_id' => $dao->campaign_id,
2313 'campaign' => empty($dao->campaign_id) ? NULL : $allCampaigns[$dao->campaign_id],
2314 'sms_provider_id' => $dao->sms_provider_id,
2315 );
2316 }
2317 return $rows;
2318 }
2319
2320 /**
2321 * Function to show detail Mailing report
2322 *
2323 * @param int $id
2324 *
2325 * @return string
2326 * @static
2327 * @access public
2328 */
2329 static function showEmailDetails($id) {
2330 return CRM_Utils_System::url('civicrm/mailing/report', "mid=$id");
2331 }
2332
2333 /**
2334 * Delete Mails and all its associated records
2335 *
2336 * @param int $id id of the mail to delete
2337 *
2338 * @return void
2339 * @access public
2340 * @static
2341 */
2342 public static function del($id) {
2343 if (empty($id)) {
2344 CRM_Core_Error::fatal();
2345 }
2346
2347 CRM_Utils_Hook::pre('delete', 'Mailing', $id, CRM_Core_DAO::$_nullArray);
2348
2349 // delete all file attachments
2350 CRM_Core_BAO_File::deleteEntityFile('civicrm_mailing',
2351 $id
2352 );
2353
2354 $dao = new CRM_Mailing_DAO_Mailing();
2355 $dao->id = $id;
2356 $dao->delete();
2357
2358 CRM_Core_Session::setStatus(ts('Selected mailing has been deleted.'), ts('Deleted'), 'success');
2359
2360 CRM_Utils_Hook::post('delete', 'Mailing', $id, $dao);
2361 }
2362
2363 /**
2364 * Delete Jobss and all its associated records
2365 * related to test Mailings
2366 *
2367 * @param int $id id of the Job to delete
2368 *
2369 * @return void
2370 * @access public
2371 * @static
2372 */
2373 public static function delJob($id) {
2374 if (empty($id)) {
2375 CRM_Core_Error::fatal();
2376 }
2377
2378 $dao = new CRM_Mailing_BAO_MailingJob();
2379 $dao->id = $id;
2380 $dao->delete();
2381 }
2382
2383 function getReturnProperties() {
2384 $tokens = &$this->getTokens();
2385
2386 $properties = array();
2387 if (isset($tokens['html']) &&
2388 isset($tokens['html']['contact'])
2389 ) {
2390 $properties = array_merge($properties, $tokens['html']['contact']);
2391 }
2392
2393 if (isset($tokens['text']) &&
2394 isset($tokens['text']['contact'])
2395 ) {
2396 $properties = array_merge($properties, $tokens['text']['contact']);
2397 }
2398
2399 if (isset($tokens['subject']) &&
2400 isset($tokens['subject']['contact'])
2401 ) {
2402 $properties = array_merge($properties, $tokens['subject']['contact']);
2403 }
2404
2405 $returnProperties = array();
2406 $returnProperties['display_name'] = $returnProperties['contact_id'] = $returnProperties['preferred_mail_format'] = $returnProperties['hash'] = 1;
2407
2408 foreach ($properties as $p) {
2409 $returnProperties[$p] = 1;
2410 }
2411
2412 return $returnProperties;
2413 }
2414
2415 /**
2416 * Function to build the compose mail form
2417 *
2418 * @param $form
2419 *
2420 * @return void
2421 * @access public
2422 */
2423 public static function commonCompose(&$form) {
2424 //get the tokens.
2425 $tokens = CRM_Core_SelectValues::contactTokens();
2426
2427 $className = CRM_Utils_System::getClassName($form);
2428 if ($className == 'CRM_Mailing_Form_Upload') {
2429 $tokens = array_merge(CRM_Core_SelectValues::mailingTokens(), $tokens);
2430 }
2431 elseif ($className == 'CRM_Admin_Form_ScheduleReminders') {
2432 $tokens = array_merge(CRM_Core_SelectValues::activityTokens(), $tokens);
2433 $tokens = array_merge(CRM_Core_SelectValues::eventTokens(), $tokens);
2434 $tokens = array_merge(CRM_Core_SelectValues::membershipTokens(), $tokens);
2435 }
2436 elseif ($className == 'CRM_Event_Form_ManageEvent_ScheduleReminders') {
2437 $tokens = array_merge(CRM_Core_SelectValues::eventTokens(), $tokens);
2438 }
2439
2440 //sorted in ascending order tokens by ignoring word case
2441 $form->assign('tokens', CRM_Utils_Token::formatTokensForDisplay($tokens));
2442
2443 $form->_templates = CRM_Core_BAO_MessageTemplate::getMessageTemplates(FALSE);
2444 if (!empty($form->_templates)) {
2445 $form->assign('templates', TRUE);
2446 $form->add('select', 'template', ts('Use Template'),
2447 array(
2448 '' => ts('- select -')) + $form->_templates, FALSE,
2449 array('onChange' => "selectValue( this.value );")
2450 );
2451 $form->add('checkbox', 'updateTemplate', ts('Update Template'), NULL);
2452 }
2453
2454 $form->add('checkbox', 'saveTemplate', ts('Save As New Template'), NULL, FALSE,
2455 array('onclick' => "showSaveDetails(this);")
2456 );
2457 $form->add('text', 'saveTemplateName', ts('Template Title'));
2458
2459
2460 //insert message Text by selecting "Select Template option"
2461 $form->add('textarea',
2462 'text_message',
2463 ts('Plain-text format'),
2464 array(
2465 'cols' => '80', 'rows' => '8',
2466 'onkeyup' => "return verify(this)",
2467 )
2468 );
2469
2470 if ($className != 'CRM_SMS_Form_Upload' && $className != 'CRM_Contact_Form_Task_SMS' &&
2471 $className != 'CRM_Contact_Form_Task_SMS'
2472 ) {
2473 $form->addWysiwyg('html_message',
2474 ts('HTML format'),
2475 array(
2476 'cols' => '80', 'rows' => '8',
2477 'onkeyup' => "return verify(this)",
2478 )
2479 );
2480 }
2481 }
2482
2483 /**
2484 * Function to build the compose PDF letter form
2485 *
2486 * @param $form
2487 *
2488 * @return void
2489 * @access public
2490 */
2491 public static function commonLetterCompose(&$form) {
2492 //get the tokens.
2493 $tokens = CRM_Core_SelectValues::contactTokens();
2494 if (CRM_Utils_System::getClassName($form) == 'CRM_Mailing_Form_Upload') {
2495 $tokens = array_merge(CRM_Core_SelectValues::mailingTokens(), $tokens);
2496 }
2497 //@todo move this fn onto the form
2498 if (CRM_Utils_System::getClassName($form) == 'CRM_Contribute_Form_Task_PDFLetter') {
2499 $tokens = array_merge(CRM_Core_SelectValues::contributionTokens(), $tokens);
2500 }
2501
2502 if(method_exists($form, 'listTokens')) {
2503 $tokens = array_merge($form->listTokens(), $tokens);
2504 }
2505
2506 $form->assign('tokens', CRM_Utils_Token::formatTokensForDisplay($tokens));
2507
2508 $form->_templates = CRM_Core_BAO_MessageTemplate::getMessageTemplates(FALSE);
2509 if (!empty($form->_templates)) {
2510 $form->assign('templates', TRUE);
2511 $form->add('select', 'template', ts('Select Template'),
2512 array(
2513 '' => ts('- select -')) + $form->_templates, FALSE,
2514 array('onChange' => "selectValue( this.value );")
2515 );
2516 $form->add('checkbox', 'updateTemplate', ts('Update Template'), NULL);
2517 }
2518
2519 $form->add('checkbox', 'saveTemplate', ts('Save As New Template'), NULL, FALSE,
2520 array('onclick' => "showSaveDetails(this);")
2521 );
2522 $form->add('text', 'saveTemplateName', ts('Template Title'));
2523
2524
2525 $form->addWysiwyg('html_message',
2526 ts('Your Letter'),
2527 array(
2528 'cols' => '80', 'rows' => '8',
2529 'onkeyup' => "return verify(this)",
2530 )
2531 );
2532 $action = CRM_Utils_Request::retrieve('action', 'String', $form, FALSE);
2533 if ((CRM_Utils_System::getClassName($form) == 'CRM_Contact_Form_Task_PDF') &&
2534 $action == CRM_Core_Action::VIEW
2535 ) {
2536 $form->freeze('html_message');
2537 }
2538 }
2539
2540 /**
2541 * Get the search based mailing Ids
2542 *
2543 * @return array $mailingIDs, searched base mailing ids.
2544 * @access public
2545 */
2546 public function searchMailingIDs() {
2547 $group = CRM_Mailing_DAO_MailingGroup::getTableName();
2548 $mailing = self::getTableName();
2549
2550 $query = "
2551 SELECT $mailing.id as mailing_id
2552 FROM $mailing, $group
2553 WHERE $group.mailing_id = $mailing.id
2554 AND $group.group_type = 'Base'";
2555
2556 $searchDAO = CRM_Core_DAO::executeQuery($query);
2557 $mailingIDs = array();
2558 while ($searchDAO->fetch()) {
2559 $mailingIDs[] = $searchDAO->mailing_id;
2560 }
2561
2562 return $mailingIDs;
2563 }
2564
2565 /**
2566 * Get the content/components of mailing based on mailing Id
2567 *
2568 * @param $report array of mailing report
2569 *
2570 * @param $form reference of this
2571 *
2572 * @param bool $isSMS
2573 *
2574 * @return array $report array content/component.@access public
2575 */
2576 static function getMailingContent(&$report, &$form, $isSMS = FALSE) {
2577 $htmlHeader = $textHeader = NULL;
2578 $htmlFooter = $textFooter = NULL;
2579
2580 if (!$isSMS) {
2581 if ($report['mailing']['header_id']) {
2582 $header = new CRM_Mailing_BAO_Component();
2583 $header->id = $report['mailing']['header_id'];
2584 $header->find(TRUE);
2585 $htmlHeader = $header->body_html;
2586 $textHeader = $header->body_text;
2587 }
2588
2589 if ($report['mailing']['footer_id']) {
2590 $footer = new CRM_Mailing_BAO_Component();
2591 $footer->id = $report['mailing']['footer_id'];
2592 $footer->find(TRUE);
2593 $htmlFooter = $footer->body_html;
2594 $textFooter = $footer->body_text;
2595 }
2596 }
2597
2598 $mailingKey = $form->_mailing_id;
2599 if (!$isSMS) {
2600 if ($hash = CRM_Mailing_BAO_Mailing::getMailingHash($mailingKey)) {
2601 $mailingKey = $hash;
2602 }
2603 }
2604
2605 if (!empty($report['mailing']['body_text'])) {
2606 $url = CRM_Utils_System::url('civicrm/mailing/view', 'reset=1&text=1&id=' . $mailingKey);
2607 $form->assign('textViewURL', $url);
2608 }
2609
2610 if (!$isSMS) {
2611 if (!empty($report['mailing']['body_html'])) {
2612 $url = CRM_Utils_System::url('civicrm/mailing/view', 'reset=1&id=' . $mailingKey);
2613 $form->assign('htmlViewURL', $url);
2614 }
2615 }
2616
2617 if (!$isSMS) {
2618 $report['mailing']['attachment'] = CRM_Core_BAO_File::attachmentInfo('civicrm_mailing', $form->_mailing_id);
2619 }
2620 return $report;
2621 }
2622
2623 static function overrideVerp($jobID) {
2624 static $_cache = array();
2625
2626 if (!isset($_cache[$jobID])) {
2627 $query = "
2628 SELECT override_verp
2629 FROM civicrm_mailing
2630 INNER JOIN civicrm_mailing_job ON civicrm_mailing.id = civicrm_mailing_job.mailing_id
2631 WHERE civicrm_mailing_job.id = %1
2632 ";
2633 $params = array(1 => array($jobID, 'Integer'));
2634 $_cache[$jobID] = CRM_Core_DAO::singleValueQuery($query, $params);
2635 }
2636 return $_cache[$jobID];
2637 }
2638
2639 static function processQueue($mode = NULL) {
2640 $config = &CRM_Core_Config::singleton();
2641 // CRM_Core_Error::debug_log_message("Beginning processQueue run: {$config->mailerJobsMax}, {$config->mailerJobSize}");
2642
2643 if ($mode == NULL && CRM_Core_BAO_MailSettings::defaultDomain() == "EXAMPLE.ORG") {
2644 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/advanced-configuration/email-system-configuration/")));
2645 }
2646
2647 // check if we are enforcing number of parallel cron jobs
2648 // CRM-8460
2649 $gotCronLock = FALSE;
2650
2651 if (property_exists($config, 'mailerJobsMax') && $config->mailerJobsMax && $config->mailerJobsMax > 1) {
2652 $lockArray = range(1, $config->mailerJobsMax);
2653 shuffle($lockArray);
2654
2655 // check if we are using global locks
2656 $serverWideLock = CRM_Core_BAO_Setting::getItem(
2657 CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
2658 'civimail_server_wide_lock'
2659 );
2660 foreach ($lockArray as $lockID) {
2661 $cronLock = new CRM_Core_Lock("civimail.cronjob.{$lockID}", NULL, $serverWideLock);
2662 if ($cronLock->isAcquired()) {
2663 $gotCronLock = TRUE;
2664 break;
2665 }
2666 }
2667
2668 // exit here since we have enuf cronjobs running
2669 if (!$gotCronLock) {
2670 CRM_Core_Error::debug_log_message('Returning early, since max number of cronjobs running');
2671 return TRUE;
2672 }
2673 }
2674
2675 // load bootstrap to call hooks
2676
2677 // Split up the parent jobs into multiple child jobs
2678 $mailerJobSize = (property_exists($config, 'mailerJobSize')) ? $config->mailerJobSize : NULL;
2679 CRM_Mailing_BAO_MailingJob::runJobs_pre($mailerJobSize, $mode);
2680 CRM_Mailing_BAO_MailingJob::runJobs(NULL, $mode);
2681 CRM_Mailing_BAO_MailingJob::runJobs_post($mode);
2682
2683 // lets release the global cron lock if we do have one
2684 if ($gotCronLock) {
2685 $cronLock->release();
2686 }
2687
2688 // CRM_Core_Error::debug_log_message('Ending processQueue run');
2689 return TRUE;
2690 }
2691
2692 private static function addMultipleEmails($mailingID) {
2693 $sql = "
2694 INSERT INTO civicrm_mailing_recipients
2695 (mailing_id, email_id, contact_id)
2696 SELECT %1, e.id, e.contact_id FROM civicrm_email e
2697 WHERE e.on_hold = 0
2698 AND e.is_bulkmail = 1
2699 AND e.contact_id IN
2700 ( SELECT contact_id FROM civicrm_mailing_recipients mr WHERE mailing_id = %1 )
2701 AND e.id NOT IN ( SELECT email_id FROM civicrm_mailing_recipients mr WHERE mailing_id = %1 )
2702 ";
2703 $params = array(1 => array($mailingID, 'Integer'));
2704
2705 $dao = CRM_Core_DAO::executeQuery($sql, $params);
2706 }
2707
2708 static function getMailingsList($isSMS = FALSE) {
2709 static $list = array();
2710 $where = " WHERE ";
2711 if (!$isSMS) {
2712 $where .= " civicrm_mailing.sms_provider_id IS NULL ";
2713 }
2714 else {
2715 $where .= " civicrm_mailing.sms_provider_id IS NOT NULL ";
2716 }
2717
2718 if (empty($list)) {
2719 $query = "
2720 SELECT civicrm_mailing.id, civicrm_mailing.name, civicrm_mailing_job.end_date
2721 FROM civicrm_mailing
2722 INNER JOIN civicrm_mailing_job ON civicrm_mailing.id = civicrm_mailing_job.mailing_id {$where}
2723 ORDER BY civicrm_mailing.name";
2724 $mailing = CRM_Core_DAO::executeQuery($query);
2725
2726 while ($mailing->fetch()) {
2727 $list[$mailing->id] = "{$mailing->name} :: {$mailing->end_date}";
2728 }
2729 }
2730
2731 return $list;
2732 }
2733
2734 static function hiddenMailingGroup($mid) {
2735 $sql = "
2736 SELECT g.id
2737 FROM civicrm_mailing m
2738 INNER JOIN civicrm_mailing_group mg ON mg.mailing_id = m.id
2739 INNER JOIN civicrm_group g ON mg.entity_id = g.id AND mg.entity_table = 'civicrm_group'
2740 WHERE g.is_hidden = 1
2741 AND mg.group_type = 'Include'
2742 AND m.id = %1
2743 ";
2744 $params = array( 1 => array( $mid, 'Integer' ) );
2745 return CRM_Core_DAO::singleValueQuery($sql, $params);
2746 }
2747
2748 /**
2749 * This function is a wrapper for ajax activity selector
2750 *
2751 * @param array $params associated array for params record id.
2752 *
2753 * @return array $contactActivities associated array of contact activities
2754 * @access public
2755 */
2756 public static function getContactMailingSelector(&$params) {
2757 // format the params
2758 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2759 $params['rowCount'] = $params['rp'];
2760 $params['sort'] = CRM_Utils_Array::value('sortBy', $params);
2761 $params['caseId'] = NULL;
2762
2763 // get contact mailings
2764 $mailings = CRM_Mailing_BAO_Mailing::getContactMailings($params);
2765
2766 // add total
2767 $params['total'] = CRM_Mailing_BAO_Mailing::getContactMailingsCount($params);
2768
2769 //CRM-12814
2770 if (!empty($mailings)) {
2771 $openCounts = CRM_Mailing_Event_BAO_Opened::getMailingContactCount(array_keys($mailings), $params['contact_id']);
2772 $clickCounts = CRM_Mailing_Event_BAO_TrackableURLOpen::getMailingContactCount(array_keys($mailings), $params['contact_id']);
2773 }
2774
2775 // format params and add links
2776 $contactMailings = array();
2777 foreach ($mailings as $mailingId => $values) {
2778 $contactMailings[$mailingId]['subject'] = $values['subject'];
2779 $contactMailings[$mailingId]['start_date'] = CRM_Utils_Date::customFormat($values['start_date']);
2780 $contactMailings[$mailingId]['recipients'] = CRM_Utils_System::href(ts('(recipients)'), 'civicrm/mailing/report/event',
2781 "mid={$values['mailing_id']}&reset=1&cid={$params['contact_id']}&event=queue&context=mailing");
2782
2783 $contactMailings[$mailingId]['mailing_creator'] = CRM_Utils_System::href(
2784 $values['creator_name'],
2785 'civicrm/contact/view',
2786 "reset=1&cid={$values['creator_id']}");
2787
2788 //CRM-12814
2789 $contactMailings[$mailingId]['openstats'] = "Opens: ".
2790 CRM_Utils_Array::value($values['mailing_id'], $openCounts, 0).
2791 "<br />Clicks: ".
2792 CRM_Utils_Array::value($values['mailing_id'], $clickCounts, 0);
2793
2794 $actionLinks = array(
2795 CRM_Core_Action::VIEW => array(
2796 'name' => ts('View'),
2797 'url' => 'civicrm/mailing/view',
2798 'qs' => "reset=1&id=%%mkey%%",
2799 'title' => ts('View Mailing'),
2800 'class' => 'crm-popup',
2801 ),
2802 CRM_Core_Action::BROWSE => array(
2803 'name' => ts('Mailing Report'),
2804 'url' => 'civicrm/mailing/report',
2805 'qs' => "mid=%%mid%%&reset=1&cid=%%cid%%&context=mailing",
2806 'title' => ts('View Mailing Report'),
2807 )
2808 );
2809
2810 $mailingKey = $values['mailing_id'];
2811 if ($hash = CRM_Mailing_BAO_Mailing::getMailingHash($mailingKey)) {
2812 $mailingKey = $hash;
2813 }
2814
2815 $contactMailings[$mailingId]['links'] = CRM_Core_Action::formLink(
2816 $actionLinks,
2817 null,
2818 array(
2819 'mid' => $values['mailing_id'],
2820 'cid' => $params['contact_id'],
2821 'mkey' => $mailingKey,
2822 ),
2823 ts('more'),
2824 FALSE,
2825 'mailing.contact.action',
2826 'Mailing',
2827 $values['mailing_id']
2828 );
2829 }
2830
2831 return $contactMailings;
2832 }
2833
2834 /**
2835 * Function to retrieve contact mailing
2836 *
2837 * @param array $params associated array
2838 *
2839 * @return array of mailings for a contact
2840 *
2841 * @static
2842 * @access public
2843 */
2844 static public function getContactMailings(&$params) {
2845 $params['version'] = 3;
2846 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2847 $params['limit'] = $params['rp'];
2848 $params['sort'] = CRM_Utils_Array::value('sortBy', $params);
2849
2850 $result = civicrm_api('MailingContact', 'get', $params);
2851 return $result['values'];
2852 }
2853
2854 /**
2855 * Function to retrieve contact mailing count
2856 *
2857 * @param array $params associated array
2858 *
2859 * @return int count of mailings for a contact
2860 *
2861 * @static
2862 * @access public
2863 */
2864 static public function getContactMailingsCount(&$params) {
2865 $params['version'] = 3;
2866 return civicrm_api('MailingContact', 'getcount', $params);
2867 }
2868 }