Merge pull request #2937 from seamuslee001/master
[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 * @return void
849 * @access public
850 */
851 public function getTestRecipients($testParams) {
852 if (array_key_exists($testParams['test_group'], CRM_Core_PseudoConstant::group())) {
853 $contacts = civicrm_api('contact','get', array(
854 'version' =>3,
855 'group' => $testParams['test_group'],
856 'return' => 'id',
857 'options' => array('limit' => 100000000000,
858 ))
859 );
860
861 foreach (array_keys($contacts['values']) as $groupContact) {
862 $query = "
863 SELECT civicrm_email.id AS email_id,
864 civicrm_email.is_primary as is_primary,
865 civicrm_email.is_bulkmail as is_bulkmail
866 FROM civicrm_email
867 INNER JOIN civicrm_contact ON civicrm_email.contact_id = civicrm_contact.id
868 WHERE (civicrm_email.is_bulkmail = 1 OR civicrm_email.is_primary = 1)
869 AND civicrm_contact.id = {$groupContact}
870 AND civicrm_contact.do_not_email = 0
871 AND civicrm_contact.is_deceased = 0
872 AND civicrm_email.on_hold = 0
873 AND civicrm_contact.is_opt_out = 0
874 GROUP BY civicrm_email.id
875 ORDER BY civicrm_email.is_bulkmail DESC
876 ";
877 $dao = CRM_Core_DAO::executeQuery($query);
878 if ($dao->fetch()) {
879 $params = array(
880 'job_id' => $testParams['job_id'],
881 'email_id' => $dao->email_id,
882 'contact_id' => $groupContact,
883 );
884 $queue = CRM_Mailing_Event_BAO_Queue::create($params);
885 }
886 }
887 }
888 }
889
890 /**
891 * Retrieve the header and footer for this mailing
892 *
893 * @param void
894 *
895 * @return void
896 * @access private
897 */
898 private function getHeaderFooter() {
899 if (!$this->header and $this->header_id) {
900 $this->header = new CRM_Mailing_BAO_Component();
901 $this->header->id = $this->header_id;
902 $this->header->find(TRUE);
903 $this->header->free();
904 }
905
906 if (!$this->footer and $this->footer_id) {
907 $this->footer = new CRM_Mailing_BAO_Component();
908 $this->footer->id = $this->footer_id;
909 $this->footer->find(TRUE);
910 $this->footer->free();
911 }
912 }
913
914 /**
915 * Given and array of headers and a prefix, job ID, event queue ID, and hash,
916 * add a Message-ID header if needed.
917 *
918 * i.e. if the global includeMessageId is set and there isn't already a
919 * Message-ID in the array.
920 * The message ID is structured the same way as a verp. However no interpretation
921 * is placed on the values received, so they do not need to follow the verp
922 * convention.
923 *
924 * @param array $headers Array of message headers to update, in-out
925 * @param string $prefix Prefix for the message ID, use same prefixes as verp
926 * wherever possible
927 * @param string $job_id Job ID component of the generated message ID
928 * @param string $event_queue_id Event Queue ID component of the generated message ID
929 * @param string $hash Hash component of the generated message ID.
930 *
931 * @return void
932 */
933 static function addMessageIdHeader(&$headers, $prefix, $job_id, $event_queue_id, $hash) {
934 $config = CRM_Core_Config::singleton();
935 $localpart = CRM_Core_BAO_MailSettings::defaultLocalpart();
936 $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
937 $includeMessageId = CRM_Core_BAO_MailSettings::includeMessageId();
938
939 if ($includeMessageId && (!array_key_exists('Message-ID', $headers))) {
940 $headers['Message-ID'] = '<' . implode($config->verpSeparator,
941 array(
942 $localpart . $prefix,
943 $job_id,
944 $event_queue_id,
945 $hash,
946 )
947 ) . "@{$emailDomain}>";
948 }
949 }
950
951 /**
952 * static wrapper for getting verp and urls
953 *
954 * @param int $job_id ID of the Job associated with this message
955 * @param int $event_queue_id ID of the EventQueue
956 * @param string $hash Hash of the EventQueue
957 * @param string $email Destination address
958 *
959 * @return (reference) array array ref that hold array refs to the verp info and urls
960 */
961 static function getVerpAndUrls($job_id, $event_queue_id, $hash, $email) {
962 // create a skeleton object and set its properties that are required by getVerpAndUrlsAndHeaders()
963 $config = CRM_Core_Config::singleton();
964 $bao = new CRM_Mailing_BAO_Mailing();
965 $bao->_domain = CRM_Core_BAO_Domain::getDomain();
966 $bao->from_name = $bao->from_email = $bao->subject = '';
967
968 // use $bao's instance method to get verp and urls
969 list($verp, $urls, $_) = $bao->getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email);
970 return array($verp, $urls);
971 }
972
973 /**
974 * get verp, urls and headers
975 *
976 * @param int $job_id ID of the Job associated with this message
977 * @param int $event_queue_id ID of the EventQueue
978 * @param string $hash Hash of the EventQueue
979 * @param string $email Destination address
980 *
981 * @return (reference) array array ref that hold array refs to the verp info, urls, and headers
982 * @access private
983 */
984 private function getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email, $isForward = FALSE) {
985 $config = CRM_Core_Config::singleton();
986
987 /**
988 * Inbound VERP keys:
989 * reply: user replied to mailing
990 * bounce: email address bounced
991 * unsubscribe: contact opts out of all target lists for the mailing
992 * resubscribe: contact opts back into all target lists for the mailing
993 * optOut: contact unsubscribes from the domain
994 */
995 $verp = array();
996 $verpTokens = array(
997 'reply' => 'r',
998 'bounce' => 'b',
999 'unsubscribe' => 'u',
1000 'resubscribe' => 'e',
1001 'optOut' => 'o',
1002 );
1003
1004 $localpart = CRM_Core_BAO_MailSettings::defaultLocalpart();
1005 $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
1006
1007 foreach ($verpTokens as $key => $value) {
1008 $verp[$key] = implode($config->verpSeparator,
1009 array(
1010 $localpart . $value,
1011 $job_id,
1012 $event_queue_id,
1013 $hash,
1014 )
1015 ) . "@$emailDomain";
1016 }
1017
1018 //handle should override VERP address.
1019 $skipEncode = FALSE;
1020
1021 if ($job_id &&
1022 self::overrideVerp($job_id)
1023 ) {
1024 $verp['reply'] = "\"{$this->from_name}\" <{$this->from_email}>";
1025 }
1026
1027 $urls = array(
1028 'forward' => CRM_Utils_System::url('civicrm/mailing/forward',
1029 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1030 TRUE, NULL, TRUE, TRUE
1031 ),
1032 'unsubscribeUrl' => CRM_Utils_System::url('civicrm/mailing/unsubscribe',
1033 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1034 TRUE, NULL, TRUE, TRUE
1035 ),
1036 'resubscribeUrl' => CRM_Utils_System::url('civicrm/mailing/resubscribe',
1037 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1038 TRUE, NULL, TRUE, TRUE
1039 ),
1040 'optOutUrl' => CRM_Utils_System::url('civicrm/mailing/optout',
1041 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1042 TRUE, NULL, TRUE, TRUE
1043 ),
1044 'subscribeUrl' => CRM_Utils_System::url('civicrm/mailing/subscribe',
1045 'reset=1',
1046 TRUE, NULL, TRUE, TRUE
1047 ),
1048 );
1049
1050 $headers = array(
1051 'Reply-To' => $verp['reply'],
1052 'Return-Path' => $verp['bounce'],
1053 'From' => "\"{$this->from_name}\" <{$this->from_email}>",
1054 'Subject' => $this->subject,
1055 'List-Unsubscribe' => "<mailto:{$verp['unsubscribe']}>",
1056 );
1057 self::addMessageIdHeader($headers, 'm', $job_id, $event_queue_id, $hash);
1058 if ($isForward) {
1059 $headers['Subject'] = "[Fwd:{$this->subject}]";
1060 }
1061 return array(&$verp, &$urls, &$headers);
1062 }
1063
1064 /**
1065 * Compose a message
1066 *
1067 * @param int $job_id ID of the Job associated with this message
1068 * @param int $event_queue_id ID of the EventQueue
1069 * @param string $hash Hash of the EventQueue
1070 * @param string $contactId ID of the Contact
1071 * @param string $email Destination address
1072 * @param string $recipient To: of the recipient
1073 * @param boolean $test Is this mailing a test?
1074 * @param boolean $isForward Is this mailing compose for forward?
1075 * @param string $fromEmail email address of who is forwardinf it.
1076 *
1077 * @return object The mail object
1078 * @access public
1079 */
1080 public function &compose($job_id, $event_queue_id, $hash, $contactId,
1081 $email, &$recipient, $test,
1082 $contactDetails, &$attachments, $isForward = FALSE,
1083 $fromEmail = NULL, $replyToEmail = NULL
1084 ) {
1085 $config = CRM_Core_Config::singleton();
1086 $knownTokens = $this->getTokens();
1087
1088 if ($this->_domain == NULL) {
1089 $this->_domain = CRM_Core_BAO_Domain::getDomain();
1090 }
1091
1092 list($verp, $urls, $headers) = $this->getVerpAndUrlsAndHeaders(
1093 $job_id,
1094 $event_queue_id,
1095 $hash,
1096 $email,
1097 $isForward
1098 );
1099
1100 //set from email who is forwarding it and not original one.
1101 if ($fromEmail) {
1102 unset($headers['From']);
1103 $headers['From'] = "<{$fromEmail}>";
1104 }
1105
1106 if ($replyToEmail && ($fromEmail != $replyToEmail)) {
1107 $headers['Reply-To'] = "{$replyToEmail}";
1108 }
1109
1110 if ($contactDetails) {
1111 $contact = $contactDetails;
1112 }
1113 elseif ($contactId === 0) {
1114 //anonymous user
1115 $contact = array();
1116 CRM_Utils_Hook::tokenValues($contact, $contactId, $job_id);
1117 }
1118 else {
1119 $params = array(array('contact_id', '=', $contactId, 0, 0));
1120 list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($params);
1121
1122 //CRM-4524
1123 $contact = reset($contact);
1124
1125 if (!$contact || is_a($contact, 'CRM_Core_Error')) {
1126 CRM_Core_Error::debug_log_message(ts('CiviMail will not send email to a non-existent contact: %1',
1127 array(1 => $contactId)
1128 ));
1129 // setting this because function is called by reference
1130 //@todo test not calling function by reference
1131 $res = NULL;
1132 return $res;
1133 }
1134
1135 // also call the hook to get contact details
1136 CRM_Utils_Hook::tokenValues($contact, $contactId, $job_id);
1137 }
1138
1139 $pTemplates = $this->getPreparedTemplates();
1140 $pEmails = array();
1141
1142 foreach ($pTemplates as $type => $pTemplate) {
1143 $html = ($type == 'html') ? TRUE : FALSE;
1144 $pEmails[$type] = array();
1145 $pEmail = &$pEmails[$type];
1146 $template = &$pTemplates[$type]['template'];
1147 $tokens = &$pTemplates[$type]['tokens'];
1148 $idx = 0;
1149 if (!empty($tokens)) {
1150 foreach ($tokens as $idx => $token) {
1151 $token_data = $this->getTokenData($token, $html, $contact, $verp, $urls, $event_queue_id);
1152 array_push($pEmail, $template[$idx]);
1153 array_push($pEmail, $token_data);
1154 }
1155 }
1156 else {
1157 array_push($pEmail, $template[$idx]);
1158 }
1159
1160 if (isset($template[($idx + 1)])) {
1161 array_push($pEmail, $template[($idx + 1)]);
1162 }
1163 }
1164
1165 $html = NULL;
1166 if (isset($pEmails['html']) && is_array($pEmails['html']) && count($pEmails['html'])) {
1167 $html = &$pEmails['html'];
1168 }
1169
1170 $text = NULL;
1171 if (isset($pEmails['text']) && is_array($pEmails['text']) && count($pEmails['text'])) {
1172 $text = &$pEmails['text'];
1173 }
1174
1175 // push the tracking url on to the html email if necessary
1176 if ($this->open_tracking && $html) {
1177 array_push($html, "\n" . '<img src="' . $config->userFrameworkResourceURL .
1178 "extern/open.php?q=$event_queue_id\" width='1' height='1' alt='' border='0'>"
1179 );
1180 }
1181
1182 $message = new Mail_mime("\n");
1183
1184 $useSmarty = defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY ? TRUE : FALSE;
1185 if ($useSmarty) {
1186 $smarty = CRM_Core_Smarty::singleton();
1187 // also add the contact tokens to the template
1188 $smarty->assign_by_ref('contact', $contact);
1189 }
1190
1191 $mailParams = $headers;
1192 if ($text && ($test || $contact['preferred_mail_format'] == 'Text' ||
1193 $contact['preferred_mail_format'] == 'Both' ||
1194 ($contact['preferred_mail_format'] == 'HTML' && !array_key_exists('html', $pEmails))
1195 )) {
1196 $textBody = join('', $text);
1197 if ($useSmarty) {
1198 $textBody = $smarty->fetch("string:$textBody");
1199 }
1200 $mailParams['text'] = $textBody;
1201 }
1202
1203 if ($html && ($test || ($contact['preferred_mail_format'] == 'HTML' ||
1204 $contact['preferred_mail_format'] == 'Both'
1205 ))) {
1206 $htmlBody = join('', $html);
1207 if ($useSmarty) {
1208 $htmlBody = $smarty->fetch("string:$htmlBody");
1209 }
1210 $mailParams['html'] = $htmlBody;
1211 }
1212
1213 if (empty($mailParams['text']) && empty($mailParams['html'])) {
1214 // CRM-9833
1215 // something went wrong, lets log it and return null (by reference)
1216 CRM_Core_Error::debug_log_message(ts('CiviMail will not send an empty mail body, Skipping: %1',
1217 array(1 => $email)
1218 ));
1219 $res = NULL;
1220 return $res;
1221 }
1222
1223 $mailParams['attachments'] = $attachments;
1224
1225 $mailingSubject = CRM_Utils_Array::value('subject', $pEmails);
1226 if (is_array($mailingSubject)) {
1227 $mailingSubject = join('', $mailingSubject);
1228 }
1229 $mailParams['Subject'] = $mailingSubject;
1230
1231 $mailParams['toName'] = CRM_Utils_Array::value('display_name',
1232 $contact
1233 );
1234 $mailParams['toEmail'] = $email;
1235
1236 CRM_Utils_Hook::alterMailParams($mailParams, 'civimail');
1237
1238 // CRM-10699 support custom email headers
1239 if (!empty($mailParams['headers'])) {
1240 $headers = array_merge($headers, $mailParams['headers']);
1241 }
1242 //cycle through mailParams and set headers array
1243 foreach ($mailParams as $paramKey => $paramValue) {
1244 //exclude values not intended for the header
1245 if (!in_array($paramKey, array(
1246 'text', 'html', 'attachments', 'toName', 'toEmail'))) {
1247 $headers[$paramKey] = $paramValue;
1248 }
1249 }
1250
1251 if (!empty($mailParams['text'])) {
1252 $message->setTxtBody($mailParams['text']);
1253 }
1254
1255 if (!empty($mailParams['html'])) {
1256 $message->setHTMLBody($mailParams['html']);
1257 }
1258
1259 if (!empty($mailParams['attachments'])) {
1260 foreach ($mailParams['attachments'] as $fileID => $attach) {
1261 $message->addAttachment($attach['fullPath'],
1262 $attach['mime_type'],
1263 $attach['cleanName']
1264 );
1265 }
1266 }
1267
1268 //pickup both params from mail params.
1269 $toName = trim($mailParams['toName']);
1270 $toEmail = trim($mailParams['toEmail']);
1271 if ($toName == $toEmail ||
1272 strpos($toName, '@') !== FALSE
1273 ) {
1274 $toName = NULL;
1275 }
1276 else {
1277 $toName = CRM_Utils_Mail::formatRFC2822Name($toName);
1278 }
1279
1280 $headers['To'] = "$toName <$toEmail>";
1281
1282 $headers['Precedence'] = 'bulk';
1283 // Will test in the mail processor if the X-VERP is set in the bounced email.
1284 // (As an option to replace real VERP for those that can't set it up)
1285 $headers['X-CiviMail-Bounce'] = $verp['bounce'];
1286
1287 //CRM-5058
1288 //token replacement of subject
1289 $headers['Subject'] = $mailingSubject;
1290
1291 CRM_Utils_Mail::setMimeParams($message);
1292 $headers = $message->headers($headers);
1293
1294 //get formatted recipient
1295 $recipient = $headers['To'];
1296
1297 // make sure we unset a lot of stuff
1298 unset($verp);
1299 unset($urls);
1300 unset($params);
1301 unset($contact);
1302 unset($ids);
1303
1304 return $message;
1305 }
1306
1307 /**
1308 *
1309 * get mailing object and replaces subscribeInvite,
1310 * domain and mailing tokens
1311 *
1312 */
1313 public static function tokenReplace(&$mailing) {
1314 $domain = CRM_Core_BAO_Domain::getDomain();
1315
1316 foreach (array('text', 'html') as $type) {
1317 $tokens = $mailing->getTokens();
1318 if (isset($mailing->templates[$type])) {
1319 $mailing->templates[$type] = CRM_Utils_Token::replaceSubscribeInviteTokens($mailing->templates[$type]);
1320 $mailing->templates[$type] = CRM_Utils_Token::replaceDomainTokens(
1321 $mailing->templates[$type],
1322 $domain,
1323 $type == 'html' ? TRUE : FALSE,
1324 $tokens[$type]
1325 );
1326 $mailing->templates[$type] = CRM_Utils_Token::replaceMailingTokens($mailing->templates[$type], $mailing, NULL, $tokens[$type]);
1327 }
1328 }
1329 }
1330
1331 /**
1332 *
1333 * getTokenData receives a token from an email
1334 * and returns the appropriate data for the token
1335 *
1336 */
1337 private function getTokenData(&$token_a, $html = FALSE, &$contact, &$verp, &$urls, $event_queue_id) {
1338 $type = $token_a['type'];
1339 $token = $token_a['token'];
1340 $data = $token;
1341
1342 $useSmarty = defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY ? TRUE : FALSE;
1343
1344 if ($type == 'embedded_url') {
1345 $embed_data = array();
1346 foreach ($token as $t) {
1347 $embed_data[] = $this->getTokenData($t, $html = FALSE, $contact, $verp, $urls, $event_queue_id);
1348 }
1349 $numSlices = count($embed_data);
1350 $url = '';
1351 for ($i = 0; $i < $numSlices; $i++) {
1352 $url .= "{$token_a['embed_parts'][$i]}{$embed_data[$i]}";
1353 }
1354 if (isset($token_a['embed_parts'][$numSlices])) {
1355 $url .= $token_a['embed_parts'][$numSlices];
1356 }
1357 // add trailing quote since we've gobbled it up in a previous regex
1358 // function getPatterns, line 431
1359 if (preg_match('/^href[ ]*=[ ]*\'/', $url)) {
1360 $url .= "'";
1361 }
1362 elseif (preg_match('/^href[ ]*=[ ]*\"/', $url)) {
1363 $url .= '"';
1364 }
1365 $data = $url;
1366 }
1367 elseif ($type == 'url') {
1368 if ($this->url_tracking) {
1369 $data = CRM_Mailing_BAO_TrackableURL::getTrackerURL($token, $this->id, $event_queue_id);
1370 }
1371 else {
1372 $data = $token;
1373 }
1374 }
1375 elseif ($type == 'contact') {
1376 $data = CRM_Utils_Token::getContactTokenReplacement($token, $contact, FALSE, FALSE, $useSmarty);
1377 }
1378 elseif ($type == 'action') {
1379 $data = CRM_Utils_Token::getActionTokenReplacement($token, $verp, $urls, $html);
1380 }
1381 elseif ($type == 'domain') {
1382 $domain = CRM_Core_BAO_Domain::getDomain();
1383 $data = CRM_Utils_Token::getDomainTokenReplacement($token, $domain, $html);
1384 }
1385 elseif ($type == 'mailing') {
1386 if ($token == 'name') {
1387 $data = $this->name;
1388 }
1389 elseif ($token == 'group') {
1390 $groups = $this->getGroupNames();
1391 $data = implode(', ', $groups);
1392 }
1393 }
1394 else {
1395 $data = CRM_Utils_Array::value("{$type}.{$token}", $contact);
1396 }
1397 return $data;
1398 }
1399
1400 /**
1401 * Return a list of group names for this mailing. Does not work with
1402 * prior-mailing targets.
1403 *
1404 * @return array Names of groups receiving this mailing
1405 * @access public
1406 */
1407 public function &getGroupNames() {
1408 if (!isset($this->id)) {
1409 return array();
1410 }
1411 $mg = new CRM_Mailing_DAO_MailingGroup();
1412 $mgtable = CRM_Mailing_DAO_MailingGroup::getTableName();
1413 $group = CRM_Contact_BAO_Group::getTableName();
1414
1415 $mg->query("SELECT $group.title as name FROM $mgtable
1416 INNER JOIN $group ON $mgtable.entity_id = $group.id
1417 WHERE $mgtable.mailing_id = {$this->id}
1418 AND $mgtable.entity_table = '$group'
1419 AND $mgtable.group_type = 'Include'
1420 ORDER BY $group.name");
1421
1422 $groups = array();
1423 while ($mg->fetch()) {
1424 $groups[] = $mg->name;
1425 }
1426 $mg->free();
1427 return $groups;
1428 }
1429
1430 /**
1431 * function to add the mailings
1432 *
1433 * @param array $params reference array contains the values submitted by the form
1434 * @param array $ids reference array contains the id
1435 *
1436 * @access public
1437 * @static
1438 *
1439 * @return object
1440 */
1441 static function add(&$params, $ids = array()) {
1442 $id = CRM_Utils_Array::value('mailing_id', $ids, CRM_Utils_Array::value('id', $params));
1443
1444 if ($id) {
1445 CRM_Utils_Hook::pre('edit', 'Mailing', $id, $params);
1446 }
1447 else {
1448 CRM_Utils_Hook::pre('create', 'Mailing', NULL, $params);
1449 }
1450
1451 $mailing = new CRM_Mailing_DAO_Mailing();
1452 $mailing->id = $id;
1453 $mailing->domain_id = CRM_Utils_Array::value('domain_id', $params, CRM_Core_Config::domainID());
1454
1455 if (!isset($params['replyto_email']) &&
1456 isset($params['from_email'])
1457 ) {
1458 $params['replyto_email'] = $params['from_email'];
1459 }
1460
1461 $mailing->copyValues($params);
1462
1463 $result = $mailing->save();
1464
1465 if (!empty($ids['mailing'])) {
1466 CRM_Utils_Hook::post('edit', 'Mailing', $mailing->id, $mailing);
1467 }
1468 else {
1469 CRM_Utils_Hook::post('create', 'Mailing', $mailing->id, $mailing);
1470 }
1471
1472 return $result;
1473 }
1474
1475 /**
1476 * Construct a new mailing object, along with job and mailing_group
1477 * objects, from the form values of the create mailing wizard.
1478 *
1479 * @params array $params Form values
1480 *
1481 * @return object $mailing The new mailing object
1482 * @access public
1483 * @static
1484 */
1485 public static function create(&$params, $ids = array()) {
1486
1487 // CRM-12430
1488 // Do the below only for an insert
1489 // for an update, we should not set the defaults
1490 if (!isset($ids['id']) && !isset($ids['mailing_id'])) {
1491 // Retrieve domain email and name for default sender
1492 $domain = civicrm_api(
1493 'Domain',
1494 'getsingle',
1495 array(
1496 'version' => 3,
1497 'current_domain' => 1,
1498 'sequential' => 1,
1499 )
1500 );
1501 if (isset($domain['from_email'])) {
1502 $domain_email = $domain['from_email'];
1503 $domain_name = $domain['from_name'];
1504 }
1505 else {
1506 $domain_email = 'info@EXAMPLE.ORG';
1507 $domain_name = 'EXAMPLE.ORG';
1508 }
1509 if (!isset($params['created_id'])) {
1510 $session =& CRM_Core_Session::singleton();
1511 $params['created_id'] = $session->get('userID');
1512 }
1513 $defaults = array(
1514 // load the default config settings for each
1515 // eg reply_id, unsubscribe_id need to use
1516 // correct template IDs here
1517 'override_verp' => TRUE,
1518 'forward_replies' => FALSE,
1519 'open_tracking' => TRUE,
1520 'url_tracking' => TRUE,
1521 'visibility' => 'User and User Admin Only',
1522 'replyto_email' => $domain_email,
1523 'header_id' => CRM_Mailing_PseudoConstant::defaultComponent('header_id', ''),
1524 'footer_id' => CRM_Mailing_PseudoConstant::defaultComponent('footer_id', ''),
1525 'from_email' => $domain_email,
1526 'from_name' => $domain_name,
1527 'msg_template_id' => NULL,
1528 'created_id' => $params['created_id'],
1529 'approver_id' => NULL,
1530 'auto_responder' => 0,
1531 'created_date' => date('YmdHis'),
1532 'scheduled_date' => NULL,
1533 'approval_date' => NULL,
1534 );
1535
1536 // Get the default from email address, if not provided.
1537 if (empty($defaults['from_email'])) {
1538 $defaultAddress = CRM_Core_OptionGroup::values('from_email_address', NULL, NULL, NULL, ' AND is_default = 1');
1539 foreach ($defaultAddress as $id => $value) {
1540 if (preg_match('/"(.*)" <(.*)>/', $value, $match)) {
1541 $defaults['from_email'] = $match[2];
1542 $defaults['from_name'] = $match[1];
1543 }
1544 }
1545 }
1546
1547 $params = array_merge($defaults, $params);
1548 }
1549
1550 /**
1551 * Could check and warn for the following cases:
1552 *
1553 * - groups OR mailings should be populated.
1554 * - body html OR body text should be populated.
1555 */
1556
1557 $transaction = new CRM_Core_Transaction();
1558
1559 $mailing = self::add($params, $ids);
1560
1561 if (is_a($mailing, 'CRM_Core_Error')) {
1562 $transaction->rollback();
1563 return $mailing;
1564 }
1565 // update mailings with hash values
1566 CRM_Contact_BAO_Contact_Utils::generateChecksum($mailing->id, NULL, NULL, NULL, 'mailing', 16);
1567
1568 $groupTableName = CRM_Contact_BAO_Group::getTableName();
1569 $mailingTableName = CRM_Mailing_BAO_Mailing::getTableName();
1570
1571 /* Create the mailing group record */
1572 $mg = new CRM_Mailing_DAO_MailingGroup();
1573 foreach (array('groups', 'mailings') as $entity) {
1574 foreach (array('include', 'exclude', 'base') as $type) {
1575 if (isset($params[$entity]) && !empty($params[$entity][$type]) &&
1576 is_array($params[$entity][$type])) {
1577 foreach ($params[$entity][$type] as $entityId) {
1578 $mg->reset();
1579 $mg->mailing_id = $mailing->id;
1580 $mg->entity_table = ($entity == 'groups') ? $groupTableName : $mailingTableName;
1581 $mg->entity_id = $entityId;
1582 $mg->group_type = $type;
1583 $mg->save();
1584 }
1585 }
1586 }
1587 }
1588
1589 if (!empty($params['search_id']) && !empty($params['group_id'])) {
1590 $mg->reset();
1591 $mg->mailing_id = $mailing->id;
1592 $mg->entity_table = $groupTableName;
1593 $mg->entity_id = $params['group_id'];
1594 $mg->search_id = $params['search_id'];
1595 $mg->search_args = $params['search_args'];
1596 $mg->group_type = 'Include';
1597 $mg->save();
1598 }
1599
1600 // check and attach and files as needed
1601 CRM_Core_BAO_File::processAttachment($params, 'civicrm_mailing', $mailing->id);
1602
1603 $transaction->commit();
1604
1605 /**
1606 * create parent job if not yet created
1607 * condition on the existence of a scheduled date
1608 */
1609 if (!empty($params['scheduled_date']) && $params['scheduled_date'] != 'null') {
1610 $job = new CRM_Mailing_BAO_MailingJob();
1611 $job->mailing_id = $mailing->id;
1612 $job->status = 'Scheduled';
1613 $job->is_test = 0;
1614
1615 if ( !$job->find(TRUE) ) {
1616 $job->scheduled_date = $params['scheduled_date'];
1617 $job->save();
1618 }
1619
1620 // Populate the recipients.
1621 $mailing->getRecipients($job->id, $mailing->id, NULL, NULL, TRUE, FALSE);
1622 }
1623
1624 return $mailing;
1625 }
1626
1627 /**
1628 * get hash value of the mailing
1629 *
1630 */
1631 public static function getMailingHash($id) {
1632 $hash = NULL;
1633 if (CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'hash_mailing_url')) {
1634 $hash = CRM_Core_DAO::getFieldValue('CRM_Mailing_BAO_Mailing', $id, 'hash', 'id');
1635 }
1636 return $hash;
1637 }
1638
1639 /**
1640 * Generate a report. Fetch event count information, mailing data, and job
1641 * status.
1642 *
1643 * @param int $id The mailing id to report
1644 * @param boolean $skipDetails whether return all detailed report
1645 *
1646 * @return array Associative array of reporting data
1647 * @access public
1648 * @static
1649 */
1650 public static function &report($id, $skipDetails = FALSE, $isSMS = FALSE) {
1651 $mailing_id = CRM_Utils_Type::escape($id, 'Integer');
1652
1653 $mailing = new CRM_Mailing_BAO_Mailing();
1654
1655 $t = array(
1656 'mailing' => self::getTableName(),
1657 'mailing_group' => CRM_Mailing_DAO_MailingGroup::getTableName(),
1658 'group' => CRM_Contact_BAO_Group::getTableName(),
1659 'job' => CRM_Mailing_BAO_MailingJob::getTableName(),
1660 'queue' => CRM_Mailing_Event_BAO_Queue::getTableName(),
1661 'delivered' => CRM_Mailing_Event_BAO_Delivered::getTableName(),
1662 'opened' => CRM_Mailing_Event_BAO_Opened::getTableName(),
1663 'reply' => CRM_Mailing_Event_BAO_Reply::getTableName(),
1664 'unsubscribe' =>
1665 CRM_Mailing_Event_BAO_Unsubscribe::getTableName(),
1666 'bounce' => CRM_Mailing_Event_BAO_Bounce::getTableName(),
1667 'forward' => CRM_Mailing_Event_BAO_Forward::getTableName(),
1668 'url' => CRM_Mailing_BAO_TrackableURL::getTableName(),
1669 'urlopen' =>
1670 CRM_Mailing_Event_BAO_TrackableURLOpen::getTableName(),
1671 'component' => CRM_Mailing_BAO_Component::getTableName(),
1672 'spool' => CRM_Mailing_BAO_Spool::getTableName(),
1673 );
1674
1675
1676 $report = array();
1677 $additionalWhereClause = " AND ";
1678 if (!$isSMS) {
1679 $additionalWhereClause .= " {$t['mailing']}.sms_provider_id IS NULL ";
1680 }
1681 else {
1682 $additionalWhereClause .= " {$t['mailing']}.sms_provider_id IS NOT NULL ";
1683 }
1684
1685 /* Get the mailing info */
1686
1687 $mailing->query("
1688 SELECT {$t['mailing']}.*
1689 FROM {$t['mailing']}
1690 WHERE {$t['mailing']}.id = $mailing_id {$additionalWhereClause}");
1691
1692 $mailing->fetch();
1693
1694 $report['mailing'] = array();
1695 foreach (array_keys(self::fields()) as $field) {
1696 $report['mailing'][$field] = $mailing->$field;
1697 }
1698
1699 //get the campaign
1700 if ($campaignId = CRM_Utils_Array::value('campaign_id', $report['mailing'])) {
1701 $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId);
1702 $report['mailing']['campaign'] = $campaigns[$campaignId];
1703 }
1704
1705 //mailing report is called by activity
1706 //we dont need all detail report
1707 if ($skipDetails) {
1708 return $report;
1709 }
1710
1711 /* Get the component info */
1712
1713 $query = array();
1714
1715 $components = array(
1716 'header' => ts('Header'),
1717 'footer' => ts('Footer'),
1718 'reply' => ts('Reply'),
1719 'unsubscribe' => ts('Unsubscribe'),
1720 'optout' => ts('Opt-Out'),
1721 );
1722 foreach (array_keys($components) as $type) {
1723 $query[] = "SELECT {$t['component']}.name as name,
1724 '$type' as type,
1725 {$t['component']}.id as id
1726 FROM {$t['component']}
1727 INNER JOIN {$t['mailing']}
1728 ON {$t['mailing']}.{$type}_id =
1729 {$t['component']}.id
1730 WHERE {$t['mailing']}.id = $mailing_id";
1731 }
1732 $q = '(' . implode(') UNION (', $query) . ')';
1733 $mailing->query($q);
1734
1735 $report['component'] = array();
1736 while ($mailing->fetch()) {
1737 $report['component'][] = array(
1738 'type' => $components[$mailing->type],
1739 'name' => $mailing->name,
1740 'link' =>
1741 CRM_Utils_System::url('civicrm/mailing/component',
1742 "reset=1&action=update&id={$mailing->id}"
1743 ),
1744 );
1745 }
1746
1747 /* Get the recipient group info */
1748
1749 $mailing->query("
1750 SELECT {$t['mailing_group']}.group_type as group_type,
1751 {$t['group']}.id as group_id,
1752 {$t['group']}.title as group_title,
1753 {$t['group']}.is_hidden as group_hidden,
1754 {$t['mailing']}.id as mailing_id,
1755 {$t['mailing']}.name as mailing_name
1756 FROM {$t['mailing_group']}
1757 LEFT JOIN {$t['group']}
1758 ON {$t['mailing_group']}.entity_id = {$t['group']}.id
1759 AND {$t['mailing_group']}.entity_table =
1760 '{$t['group']}'
1761 LEFT JOIN {$t['mailing']}
1762 ON {$t['mailing_group']}.entity_id =
1763 {$t['mailing']}.id
1764 AND {$t['mailing_group']}.entity_table =
1765 '{$t['mailing']}'
1766
1767 WHERE {$t['mailing_group']}.mailing_id = $mailing_id
1768 ");
1769
1770 $report['group'] = array('include' => array(), 'exclude' => array(), 'base' => array());
1771 while ($mailing->fetch()) {
1772 $row = array();
1773 if (isset($mailing->group_id)) {
1774 $row['id'] = $mailing->group_id;
1775 $row['name'] = $mailing->group_title;
1776 $row['link'] = CRM_Utils_System::url('civicrm/group/search',
1777 "reset=1&force=1&context=smog&gid={$row['id']}"
1778 );
1779 }
1780 else {
1781 $row['id'] = $mailing->mailing_id;
1782 $row['name'] = $mailing->mailing_name;
1783 $row['mailing'] = TRUE;
1784 $row['link'] = CRM_Utils_System::url('civicrm/mailing/report',
1785 "mid={$row['id']}"
1786 );
1787 }
1788
1789 /* Rename hidden groups */
1790
1791 if ($mailing->group_hidden == 1) {
1792 $row['name'] = "Search Results";
1793 }
1794
1795 if ($mailing->group_type == 'Include') {
1796 $report['group']['include'][] = $row;
1797 }
1798 elseif ($mailing->group_type == 'Base') {
1799 $report['group']['base'][] = $row;
1800 }
1801 else {
1802 $report['group']['exclude'][] = $row;
1803 }
1804 }
1805
1806 /* Get the event totals, grouped by job (retries) */
1807
1808 $mailing->query("
1809 SELECT {$t['job']}.*,
1810 COUNT(DISTINCT {$t['queue']}.id) as queue,
1811 COUNT(DISTINCT {$t['delivered']}.id) as delivered,
1812 COUNT(DISTINCT {$t['reply']}.id) as reply,
1813 COUNT(DISTINCT {$t['forward']}.id) as forward,
1814 COUNT(DISTINCT {$t['bounce']}.id) as bounce,
1815 COUNT(DISTINCT {$t['urlopen']}.id) as url,
1816 COUNT(DISTINCT {$t['spool']}.id) as spool
1817 FROM {$t['job']}
1818 LEFT JOIN {$t['queue']}
1819 ON {$t['queue']}.job_id = {$t['job']}.id
1820 LEFT JOIN {$t['reply']}
1821 ON {$t['reply']}.event_queue_id = {$t['queue']}.id
1822 LEFT JOIN {$t['forward']}
1823 ON {$t['forward']}.event_queue_id = {$t['queue']}.id
1824 LEFT JOIN {$t['bounce']}
1825 ON {$t['bounce']}.event_queue_id = {$t['queue']}.id
1826 LEFT JOIN {$t['delivered']}
1827 ON {$t['delivered']}.event_queue_id = {$t['queue']}.id
1828 AND {$t['bounce']}.id IS null
1829 LEFT JOIN {$t['urlopen']}
1830 ON {$t['urlopen']}.event_queue_id = {$t['queue']}.id
1831 LEFT JOIN {$t['spool']}
1832 ON {$t['spool']}.job_id = {$t['job']}.id
1833 WHERE {$t['job']}.mailing_id = $mailing_id
1834 AND {$t['job']}.is_test = 0
1835 GROUP BY {$t['job']}.id");
1836
1837 $report['jobs'] = array();
1838 $report['event_totals'] = array();
1839 $elements = array(
1840 'queue', 'delivered', 'url', 'forward',
1841 'reply', 'unsubscribe', 'optout', 'opened', 'bounce', 'spool',
1842 );
1843
1844 // initialize various counters
1845 foreach ($elements as $field) {
1846 $report['event_totals'][$field] = 0;
1847 }
1848
1849 while ($mailing->fetch()) {
1850 $row = array();
1851 foreach ($elements as $field) {
1852 if (isset($mailing->$field)) {
1853 $row[$field] = $mailing->$field;
1854 $report['event_totals'][$field] += $mailing->$field;
1855 }
1856 }
1857
1858 // compute open total separately to discount duplicates
1859 // CRM-1258
1860 $row['opened'] = CRM_Mailing_Event_BAO_Opened::getTotalCount($mailing_id, $mailing->id, TRUE);
1861 $report['event_totals']['opened'] += $row['opened'];
1862
1863 // compute unsub total separately to discount duplicates
1864 // CRM-1783
1865 $row['unsubscribe'] = CRM_Mailing_Event_BAO_Unsubscribe::getTotalCount($mailing_id, $mailing->id, TRUE, TRUE);
1866 $report['event_totals']['unsubscribe'] += $row['unsubscribe'];
1867
1868 $row['optout'] = CRM_Mailing_Event_BAO_Unsubscribe::getTotalCount($mailing_id, $mailing->id, TRUE, FALSE);
1869 $report['event_totals']['optout'] += $row['optout'];
1870
1871 foreach (array_keys(CRM_Mailing_BAO_MailingJob::fields()) as $field) {
1872 $row[$field] = $mailing->$field;
1873 }
1874
1875 if ($mailing->queue) {
1876 $row['delivered_rate'] = (100.0 * $mailing->delivered) / $mailing->queue;
1877 $row['bounce_rate'] = (100.0 * $mailing->bounce) / $mailing->queue;
1878 $row['unsubscribe_rate'] = (100.0 * $row['unsubscribe']) / $mailing->queue;
1879 $row['optout_rate'] = (100.0 * $row['optout']) / $mailing->queue;
1880 }
1881 else {
1882 $row['delivered_rate'] = 0;
1883 $row['bounce_rate'] = 0;
1884 $row['unsubscribe_rate'] = 0;
1885 $row['optout_rate'] = 0;
1886 }
1887
1888 $row['links'] = array(
1889 'clicks' => CRM_Utils_System::url(
1890 'civicrm/mailing/report/event',
1891 "reset=1&event=click&mid=$mailing_id&jid={$mailing->id}"
1892 ),
1893 'queue' => CRM_Utils_System::url(
1894 'civicrm/mailing/report/event',
1895 "reset=1&event=queue&mid=$mailing_id&jid={$mailing->id}"
1896 ),
1897 'delivered' => CRM_Utils_System::url(
1898 'civicrm/mailing/report/event',
1899 "reset=1&event=delivered&mid=$mailing_id&jid={$mailing->id}"
1900 ),
1901 'bounce' => CRM_Utils_System::url(
1902 'civicrm/mailing/report/event',
1903 "reset=1&event=bounce&mid=$mailing_id&jid={$mailing->id}"
1904 ),
1905 'unsubscribe' => CRM_Utils_System::url(
1906 'civicrm/mailing/report/event',
1907 "reset=1&event=unsubscribe&mid=$mailing_id&jid={$mailing->id}"
1908 ),
1909 'forward' => CRM_Utils_System::url(
1910 'civicrm/mailing/report/event',
1911 "reset=1&event=forward&mid=$mailing_id&jid={$mailing->id}"
1912 ),
1913 'reply' => CRM_Utils_System::url(
1914 'civicrm/mailing/report/event',
1915 "reset=1&event=reply&mid=$mailing_id&jid={$mailing->id}"
1916 ),
1917 'opened' => CRM_Utils_System::url(
1918 'civicrm/mailing/report/event',
1919 "reset=1&event=opened&mid=$mailing_id&jid={$mailing->id}"
1920 ),
1921 );
1922
1923 foreach (array(
1924 'scheduled_date', 'start_date', 'end_date') as $key) {
1925 $row[$key] = CRM_Utils_Date::customFormat($row[$key]);
1926 }
1927 $report['jobs'][] = $row;
1928 }
1929
1930 $newTableSize = CRM_Mailing_BAO_Recipients::mailingSize($mailing_id);
1931
1932 // we need to do this for backward compatibility, since old mailings did not
1933 // use the mailing_recipients table
1934 if ($newTableSize > 0) {
1935 $report['event_totals']['queue'] = $newTableSize;
1936 }
1937 else {
1938 $report['event_totals']['queue'] = self::getRecipientsCount($mailing_id, $mailing_id);
1939 }
1940
1941 if (!empty($report['event_totals']['queue'])) {
1942 $report['event_totals']['delivered_rate'] = (100.0 * $report['event_totals']['delivered']) / $report['event_totals']['queue'];
1943 $report['event_totals']['bounce_rate'] = (100.0 * $report['event_totals']['bounce']) / $report['event_totals']['queue'];
1944 $report['event_totals']['unsubscribe_rate'] = (100.0 * $report['event_totals']['unsubscribe']) / $report['event_totals']['queue'];
1945 $report['event_totals']['optout_rate'] = (100.0 * $report['event_totals']['optout']) / $report['event_totals']['queue'];
1946 }
1947 else {
1948 $report['event_totals']['delivered_rate'] = 0;
1949 $report['event_totals']['bounce_rate'] = 0;
1950 $report['event_totals']['unsubscribe_rate'] = 0;
1951 $report['event_totals']['optout_rate'] = 0;
1952 }
1953
1954 /* Get the click-through totals, grouped by URL */
1955
1956 $mailing->query("
1957 SELECT {$t['url']}.url,
1958 {$t['url']}.id,
1959 COUNT({$t['urlopen']}.id) as clicks,
1960 COUNT(DISTINCT {$t['queue']}.id) as unique_clicks
1961 FROM {$t['url']}
1962 LEFT JOIN {$t['urlopen']}
1963 ON {$t['urlopen']}.trackable_url_id = {$t['url']}.id
1964 LEFT JOIN {$t['queue']}
1965 ON {$t['urlopen']}.event_queue_id = {$t['queue']}.id
1966 LEFT JOIN {$t['job']}
1967 ON {$t['queue']}.job_id = {$t['job']}.id
1968 WHERE {$t['url']}.mailing_id = $mailing_id
1969 AND {$t['job']}.is_test = 0
1970 GROUP BY {$t['url']}.id");
1971
1972 $report['click_through'] = array();
1973
1974 while ($mailing->fetch()) {
1975 $report['click_through'][] = array(
1976 'url' => $mailing->url,
1977 'link' =>
1978 CRM_Utils_System::url(
1979 'civicrm/mailing/report/event',
1980 "reset=1&event=click&mid=$mailing_id&uid={$mailing->id}"
1981 ),
1982 'link_unique' =>
1983 CRM_Utils_System::url(
1984 'civicrm/mailing/report/event',
1985 "reset=1&event=click&mid=$mailing_id&uid={$mailing->id}&distinct=1"
1986 ),
1987 'clicks' => $mailing->clicks,
1988 'unique' => $mailing->unique_clicks,
1989 'rate' => CRM_Utils_Array::value('delivered', $report['event_totals']) ? (100.0 * $mailing->unique_clicks) / $report['event_totals']['delivered'] : 0,
1990 );
1991 }
1992
1993 $report['event_totals']['links'] = array(
1994 'clicks' => CRM_Utils_System::url(
1995 'civicrm/mailing/report/event',
1996 "reset=1&event=click&mid=$mailing_id"
1997 ),
1998 'clicks_unique' => CRM_Utils_System::url(
1999 'civicrm/mailing/report/event',
2000 "reset=1&event=click&mid=$mailing_id&distinct=1"
2001 ),
2002 'queue' => CRM_Utils_System::url(
2003 'civicrm/mailing/report/event',
2004 "reset=1&event=queue&mid=$mailing_id"
2005 ),
2006 'delivered' => CRM_Utils_System::url(
2007 'civicrm/mailing/report/event',
2008 "reset=1&event=delivered&mid=$mailing_id"
2009 ),
2010 'bounce' => CRM_Utils_System::url(
2011 'civicrm/mailing/report/event',
2012 "reset=1&event=bounce&mid=$mailing_id"
2013 ),
2014 'unsubscribe' => CRM_Utils_System::url(
2015 'civicrm/mailing/report/event',
2016 "reset=1&event=unsubscribe&mid=$mailing_id"
2017 ),
2018 'optout' => CRM_Utils_System::url(
2019 'civicrm/mailing/report/event',
2020 "reset=1&event=optout&mid=$mailing_id"
2021 ),
2022 'forward' => CRM_Utils_System::url(
2023 'civicrm/mailing/report/event',
2024 "reset=1&event=forward&mid=$mailing_id"
2025 ),
2026 'reply' => CRM_Utils_System::url(
2027 'civicrm/mailing/report/event',
2028 "reset=1&event=reply&mid=$mailing_id"
2029 ),
2030 'opened' => CRM_Utils_System::url(
2031 'civicrm/mailing/report/event',
2032 "reset=1&event=opened&mid=$mailing_id"
2033 ),
2034 );
2035
2036
2037 $actionLinks = array(CRM_Core_Action::VIEW => array('name' => ts('Report')));
2038 if (CRM_Core_Permission::check('view all contacts')) {
2039 $actionLinks[CRM_Core_Action::ADVANCED] =
2040 array(
2041 'name' => ts('Advanced Search'),
2042 'url' => 'civicrm/contact/search/advanced',
2043 );
2044 }
2045 $action = array_sum(array_keys($actionLinks));
2046
2047 $report['event_totals']['actionlinks'] = array();
2048 foreach (array(
2049 'clicks', 'clicks_unique', 'queue', 'delivered', 'bounce', 'unsubscribe',
2050 'forward', 'reply', 'opened', 'optout',
2051 ) as $key) {
2052 $url = 'mailing/detail';
2053 $reportFilter = "reset=1&mailing_id_value={$mailing_id}";
2054 $searchFilter = "force=1&mailing_id=%%mid%%";
2055 switch ($key) {
2056 case 'delivered':
2057 $reportFilter .= "&delivery_status_value=successful";
2058 $searchFilter .= "&mailing_delivery_status=Y";
2059 break;
2060
2061 case 'bounce':
2062 $url = "mailing/bounce";
2063 $searchFilter .= "&mailing_delivery_status=N";
2064 break;
2065
2066 case 'forward':
2067 $reportFilter .= "&is_forwarded_value=1";
2068 $searchFilter .= "&mailing_forward=1";
2069 break;
2070
2071 case 'reply':
2072 $reportFilter .= "&is_replied_value=1";
2073 $searchFilter .= "&mailing_reply_status=Y";
2074 break;
2075
2076 case 'unsubscribe':
2077 $reportFilter .= "&is_unsubscribed_value=1";
2078 $searchFilter .= "&mailing_unsubscribe=1";
2079 break;
2080
2081 case 'optout':
2082 $reportFilter .= "&is_optout_value=1";
2083 $searchFilter .= "&mailing_optout=1";
2084 break;
2085
2086 case 'opened':
2087 $url = "mailing/opened";
2088 $searchFilter .= "&mailing_open_status=Y";
2089 break;
2090
2091 case 'clicks':
2092 case 'clicks_unique':
2093 $url = "mailing/clicks";
2094 $searchFilter .= "&mailing_click_status=Y";
2095 break;
2096 }
2097 $actionLinks[CRM_Core_Action::VIEW]['url'] = CRM_Report_Utils_Report::getNextUrl($url, $reportFilter, FALSE, TRUE);
2098 if (array_key_exists(CRM_Core_Action::ADVANCED, $actionLinks)) {
2099 $actionLinks[CRM_Core_Action::ADVANCED]['qs'] = $searchFilter;
2100 }
2101 $report['event_totals']['actionlinks'][$key] = CRM_Core_Action::formLink(
2102 $actionLinks,
2103 $action,
2104 array('mid' => $mailing_id),
2105 ts('more'),
2106 FALSE,
2107 'mailing.report.action',
2108 'Mailing',
2109 $mailing_id
2110 );
2111 }
2112
2113 return $report;
2114 }
2115
2116 /**
2117 * Get the count of mailings
2118 *
2119 * @param
2120 *
2121 * @return int Count
2122 * @access public
2123 */
2124 public function getCount() {
2125 $this->selectAdd();
2126 $this->selectAdd('COUNT(id) as count');
2127
2128 $session = CRM_Core_Session::singleton();
2129 $this->find(TRUE);
2130
2131 return $this->count;
2132 }
2133
2134 static function checkPermission($id) {
2135 if (!$id) {
2136 return;
2137 }
2138
2139 $mailingIDs = self::mailingACLIDs();
2140 if ($mailingIDs === TRUE) {
2141 return;
2142 }
2143
2144 if (!in_array($id, $mailingIDs)) {
2145 CRM_Core_Error::fatal(ts('You do not have permission to access this mailing report'));
2146 }
2147 return;
2148 }
2149
2150 static function mailingACL($alias = NULL) {
2151 $mailingACL = " ( 0 ) ";
2152
2153 $mailingIDs = self::mailingACLIDs();
2154 if ($mailingIDs === TRUE) {
2155 return " ( 1 ) ";
2156 }
2157
2158 if (!empty($mailingIDs)) {
2159 $mailingIDs = implode(',', $mailingIDs);
2160 $tableName = !$alias ? self::getTableName() : $alias;
2161 $mailingACL = " $tableName.id IN ( $mailingIDs ) ";
2162 }
2163 return $mailingACL;
2164 }
2165
2166 /**
2167 * returns all the mailings that this user can access. This is dependent on
2168 * all the groups that the user has access to.
2169 * However since most civi installs dont use ACL's we special case the condition
2170 * where the user has access to ALL groups, and hence ALL mailings and return a
2171 * value of TRUE (to avoid the downstream where clause with a list of mailing list IDs
2172 *
2173 * @return boolean | array - TRUE if the user has access to all mailings, else array of mailing IDs (possibly empty)
2174 * @static
2175 */
2176 static function mailingACLIDs() {
2177 // CRM-11633
2178 // optimize common case where admin has access
2179 // to all mailings
2180 if (
2181 CRM_Core_Permission::check('view all contacts') ||
2182 CRM_Core_Permission::check('edit all contacts')
2183 ) {
2184 return TRUE;
2185 }
2186
2187 $mailingIDs = array();
2188
2189 // get all the groups that this user can access
2190 // if they dont have universal access
2191 $groups = CRM_Core_PseudoConstant::group(NULL, FALSE);
2192 if (!empty($groups)) {
2193 $groupIDs = implode(',', array_keys($groups));
2194
2195 // get all the mailings that are in this subset of groups
2196 $query = "
2197 SELECT DISTINCT( m.id ) as id
2198 FROM civicrm_mailing m
2199 LEFT JOIN civicrm_mailing_group g ON g.mailing_id = m.id
2200 WHERE ( ( g.entity_table like 'civicrm_group%' AND g.entity_id IN ( $groupIDs ) )
2201 OR ( g.entity_table IS NULL AND g.entity_id IS NULL ) )
2202 ";
2203 $dao = CRM_Core_DAO::executeQuery($query);
2204
2205 $mailingIDs = array();
2206 while ($dao->fetch()) {
2207 $mailingIDs[] = $dao->id;
2208 }
2209 }
2210
2211 return $mailingIDs;
2212 }
2213
2214 /**
2215 * Get the rows for a browse operation
2216 *
2217 * @param int $offset The row number to start from
2218 * @param int $rowCount The nmber of rows to return
2219 * @param string $sort The sql string that describes the sort order
2220 *
2221 * @return array The rows
2222 * @access public
2223 */
2224 public function &getRows($offset, $rowCount, $sort, $additionalClause = NULL, $additionalParams = NULL) {
2225 $mailing = self::getTableName();
2226 $job = CRM_Mailing_BAO_MailingJob::getTableName();
2227 $group = CRM_Mailing_DAO_MailingGroup::getTableName();
2228 $session = CRM_Core_Session::singleton();
2229
2230 $mailingACL = self::mailingACL();
2231
2232 //get all campaigns.
2233 $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
2234
2235 // we only care about parent jobs, since that holds all the info on
2236 // the mailing
2237 $query = "
2238 SELECT $mailing.id,
2239 $mailing.name,
2240 $job.status,
2241 $mailing.approval_status_id,
2242 MIN($job.scheduled_date) as scheduled_date,
2243 MIN($job.start_date) as start_date,
2244 MAX($job.end_date) as end_date,
2245 createdContact.sort_name as created_by,
2246 scheduledContact.sort_name as scheduled_by,
2247 $mailing.created_id as created_id,
2248 $mailing.scheduled_id as scheduled_id,
2249 $mailing.is_archived as archived,
2250 $mailing.created_date as created_date,
2251 campaign_id,
2252 $mailing.sms_provider_id as sms_provider_id
2253 FROM $mailing
2254 LEFT JOIN $job ON ( $job.mailing_id = $mailing.id AND $job.is_test = 0 AND $job.parent_id IS NULL )
2255 LEFT JOIN civicrm_contact createdContact ON ( civicrm_mailing.created_id = createdContact.id )
2256 LEFT JOIN civicrm_contact scheduledContact ON ( civicrm_mailing.scheduled_id = scheduledContact.id )
2257 WHERE $mailingACL $additionalClause
2258 GROUP BY $mailing.id ";
2259
2260 if ($sort) {
2261 $orderBy = trim($sort->orderBy());
2262 if (!empty($orderBy)) {
2263 $query .= " ORDER BY $orderBy";
2264 }
2265 }
2266
2267 if ($rowCount) {
2268 $offset = CRM_Utils_Type::escape($offset, 'Int');
2269 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
2270
2271 $query .= " LIMIT $offset, $rowCount ";
2272 }
2273
2274 if (!$additionalParams) {
2275 $additionalParams = array();
2276 }
2277
2278 $dao = CRM_Core_DAO::executeQuery($query, $additionalParams);
2279
2280 $rows = array();
2281 while ($dao->fetch()) {
2282 $rows[] = array(
2283 'id' => $dao->id,
2284 'name' => $dao->name,
2285 'status' => $dao->status ? $dao->status : 'Not scheduled',
2286 'created_date' => CRM_Utils_Date::customFormat($dao->created_date),
2287 'scheduled' => CRM_Utils_Date::customFormat($dao->scheduled_date),
2288 'scheduled_iso' => $dao->scheduled_date,
2289 'start' => CRM_Utils_Date::customFormat($dao->start_date),
2290 'end' => CRM_Utils_Date::customFormat($dao->end_date),
2291 'created_by' => $dao->created_by,
2292 'scheduled_by' => $dao->scheduled_by,
2293 'created_id' => $dao->created_id,
2294 'scheduled_id' => $dao->scheduled_id,
2295 'archived' => $dao->archived,
2296 'approval_status_id' => $dao->approval_status_id,
2297 'campaign_id' => $dao->campaign_id,
2298 'campaign' => empty($dao->campaign_id) ? NULL : $allCampaigns[$dao->campaign_id],
2299 'sms_provider_id' => $dao->sms_provider_id,
2300 );
2301 }
2302 return $rows;
2303 }
2304
2305 /**
2306 * Function to show detail Mailing report
2307 *
2308 * @param int $id
2309 *
2310 * @static
2311 * @access public
2312 */
2313 static function showEmailDetails($id) {
2314 return CRM_Utils_System::url('civicrm/mailing/report', "mid=$id");
2315 }
2316
2317 /**
2318 * Delete Mails and all its associated records
2319 *
2320 * @param int $id id of the mail to delete
2321 *
2322 * @return void
2323 * @access public
2324 * @static
2325 */
2326 public static function del($id) {
2327 if (empty($id)) {
2328 CRM_Core_Error::fatal();
2329 }
2330
2331 CRM_Utils_Hook::pre('delete', 'Mailing', $id, CRM_Core_DAO::$_nullArray);
2332
2333 // delete all file attachments
2334 CRM_Core_BAO_File::deleteEntityFile('civicrm_mailing',
2335 $id
2336 );
2337
2338 $dao = new CRM_Mailing_DAO_Mailing();
2339 $dao->id = $id;
2340 $dao->delete();
2341
2342 CRM_Core_Session::setStatus(ts('Selected mailing has been deleted.'), ts('Deleted'), 'success');
2343
2344 CRM_Utils_Hook::post('delete', 'Mailing', $id, $dao);
2345 }
2346
2347 /**
2348 * Delete Jobss and all its associated records
2349 * related to test Mailings
2350 *
2351 * @param int $id id of the Job to delete
2352 *
2353 * @return void
2354 * @access public
2355 * @static
2356 */
2357 public static function delJob($id) {
2358 if (empty($id)) {
2359 CRM_Core_Error::fatal();
2360 }
2361
2362 $dao = new CRM_Mailing_BAO_MailingJob();
2363 $dao->id = $id;
2364 $dao->delete();
2365 }
2366
2367 function getReturnProperties() {
2368 $tokens = &$this->getTokens();
2369
2370 $properties = array();
2371 if (isset($tokens['html']) &&
2372 isset($tokens['html']['contact'])
2373 ) {
2374 $properties = array_merge($properties, $tokens['html']['contact']);
2375 }
2376
2377 if (isset($tokens['text']) &&
2378 isset($tokens['text']['contact'])
2379 ) {
2380 $properties = array_merge($properties, $tokens['text']['contact']);
2381 }
2382
2383 if (isset($tokens['subject']) &&
2384 isset($tokens['subject']['contact'])
2385 ) {
2386 $properties = array_merge($properties, $tokens['subject']['contact']);
2387 }
2388
2389 $returnProperties = array();
2390 $returnProperties['display_name'] = $returnProperties['contact_id'] = $returnProperties['preferred_mail_format'] = $returnProperties['hash'] = 1;
2391
2392 foreach ($properties as $p) {
2393 $returnProperties[$p] = 1;
2394 }
2395
2396 return $returnProperties;
2397 }
2398
2399 /**
2400 * Function to build the compose mail form
2401 *
2402 * @param $form
2403 *
2404 * @return void
2405 * @access public
2406 */
2407 public static function commonCompose(&$form) {
2408 //get the tokens.
2409 $tokens = CRM_Core_SelectValues::contactTokens();
2410
2411 $className = CRM_Utils_System::getClassName($form);
2412 if ($className == 'CRM_Mailing_Form_Upload') {
2413 $tokens = array_merge(CRM_Core_SelectValues::mailingTokens(), $tokens);
2414 }
2415 elseif ($className == 'CRM_Admin_Form_ScheduleReminders') {
2416 $tokens = array_merge(CRM_Core_SelectValues::activityTokens(), $tokens);
2417 $tokens = array_merge(CRM_Core_SelectValues::eventTokens(), $tokens);
2418 $tokens = array_merge(CRM_Core_SelectValues::membershipTokens(), $tokens);
2419 }
2420 elseif ($className == 'CRM_Event_Form_ManageEvent_ScheduleReminders') {
2421 $tokens = array_merge(CRM_Core_SelectValues::eventTokens(), $tokens);
2422 }
2423
2424 //sorted in ascending order tokens by ignoring word case
2425 $form->assign('tokens', CRM_Utils_Token::formatTokensForDisplay($tokens));
2426
2427 $form->_templates = CRM_Core_BAO_MessageTemplate::getMessageTemplates(FALSE);
2428 if (!empty($form->_templates)) {
2429 $form->assign('templates', TRUE);
2430 $form->add('select', 'template', ts('Use Template'),
2431 array(
2432 '' => ts('- select -')) + $form->_templates, FALSE,
2433 array('onChange' => "selectValue( this.value );")
2434 );
2435 $form->add('checkbox', 'updateTemplate', ts('Update Template'), NULL);
2436 }
2437
2438 $form->add('checkbox', 'saveTemplate', ts('Save As New Template'), NULL, FALSE,
2439 array('onclick' => "showSaveDetails(this);")
2440 );
2441 $form->add('text', 'saveTemplateName', ts('Template Title'));
2442
2443
2444 //insert message Text by selecting "Select Template option"
2445 $form->add('textarea',
2446 'text_message',
2447 ts('Plain-text format'),
2448 array(
2449 'cols' => '80', 'rows' => '8',
2450 'onkeyup' => "return verify(this)",
2451 )
2452 );
2453
2454 if ($className != 'CRM_SMS_Form_Upload' && $className != 'CRM_Contact_Form_Task_SMS' &&
2455 $className != 'CRM_Contact_Form_Task_SMS'
2456 ) {
2457 $form->addWysiwyg('html_message',
2458 ts('HTML format'),
2459 array(
2460 'cols' => '80', 'rows' => '8',
2461 'onkeyup' => "return verify(this)",
2462 )
2463 );
2464 }
2465 }
2466
2467 /**
2468 * Function to build the compose PDF letter form
2469 *
2470 * @param $form
2471 *
2472 * @return void
2473 * @access public
2474 */
2475 public static function commonLetterCompose(&$form) {
2476 //get the tokens.
2477 $tokens = CRM_Core_SelectValues::contactTokens();
2478 if (CRM_Utils_System::getClassName($form) == 'CRM_Mailing_Form_Upload') {
2479 $tokens = array_merge(CRM_Core_SelectValues::mailingTokens(), $tokens);
2480 }
2481 //@todo move this fn onto the form
2482 if (CRM_Utils_System::getClassName($form) == 'CRM_Contribute_Form_Task_PDFLetter') {
2483 $tokens = array_merge(CRM_Core_SelectValues::contributionTokens(), $tokens);
2484 }
2485
2486 if(method_exists($form, 'listTokens')) {
2487 $tokens = array_merge($form->listTokens(), $tokens);
2488 }
2489
2490 $form->assign('tokens', CRM_Utils_Token::formatTokensForDisplay($tokens));
2491
2492 $form->_templates = CRM_Core_BAO_MessageTemplate::getMessageTemplates(FALSE);
2493 if (!empty($form->_templates)) {
2494 $form->assign('templates', TRUE);
2495 $form->add('select', 'template', ts('Select Template'),
2496 array(
2497 '' => ts('- select -')) + $form->_templates, FALSE,
2498 array('onChange' => "selectValue( this.value );")
2499 );
2500 $form->add('checkbox', 'updateTemplate', ts('Update Template'), NULL);
2501 }
2502
2503 $form->add('checkbox', 'saveTemplate', ts('Save As New Template'), NULL, FALSE,
2504 array('onclick' => "showSaveDetails(this);")
2505 );
2506 $form->add('text', 'saveTemplateName', ts('Template Title'));
2507
2508
2509 $form->addWysiwyg('html_message',
2510 ts('Your Letter'),
2511 array(
2512 'cols' => '80', 'rows' => '8',
2513 'onkeyup' => "return verify(this)",
2514 )
2515 );
2516 $action = CRM_Utils_Request::retrieve('action', 'String', $form, FALSE);
2517 if ((CRM_Utils_System::getClassName($form) == 'CRM_Contact_Form_Task_PDF') &&
2518 $action == CRM_Core_Action::VIEW
2519 ) {
2520 $form->freeze('html_message');
2521 }
2522 }
2523
2524 /**
2525 * Get the search based mailing Ids
2526 *
2527 * @return array $mailingIDs, searched base mailing ids.
2528 * @access public
2529 */
2530 public function searchMailingIDs() {
2531 $group = CRM_Mailing_DAO_MailingGroup::getTableName();
2532 $mailing = self::getTableName();
2533
2534 $query = "
2535 SELECT $mailing.id as mailing_id
2536 FROM $mailing, $group
2537 WHERE $group.mailing_id = $mailing.id
2538 AND $group.group_type = 'Base'";
2539
2540 $searchDAO = CRM_Core_DAO::executeQuery($query);
2541 $mailingIDs = array();
2542 while ($searchDAO->fetch()) {
2543 $mailingIDs[] = $searchDAO->mailing_id;
2544 }
2545
2546 return $mailingIDs;
2547 }
2548
2549 /**
2550 * Get the content/components of mailing based on mailing Id
2551 *
2552 * @param $report array of mailing report
2553 *
2554 * @param $form reference of this
2555 *
2556 * @return $report array content/component.
2557 * @access public
2558 */
2559 static function getMailingContent(&$report, &$form, $isSMS = FALSE) {
2560 $htmlHeader = $textHeader = NULL;
2561 $htmlFooter = $textFooter = NULL;
2562
2563 if (!$isSMS) {
2564 if ($report['mailing']['header_id']) {
2565 $header = new CRM_Mailing_BAO_Component();
2566 $header->id = $report['mailing']['header_id'];
2567 $header->find(TRUE);
2568 $htmlHeader = $header->body_html;
2569 $textHeader = $header->body_text;
2570 }
2571
2572 if ($report['mailing']['footer_id']) {
2573 $footer = new CRM_Mailing_BAO_Component();
2574 $footer->id = $report['mailing']['footer_id'];
2575 $footer->find(TRUE);
2576 $htmlFooter = $footer->body_html;
2577 $textFooter = $footer->body_text;
2578 }
2579 }
2580
2581 $mailingKey = $form->_mailing_id;
2582 if (!$isSMS) {
2583 if ($hash = CRM_Mailing_BAO_Mailing::getMailingHash($mailingKey)) {
2584 $mailingKey = $hash;
2585 }
2586 }
2587
2588 if (!empty($report['mailing']['body_text'])) {
2589 $url = CRM_Utils_System::url('civicrm/mailing/view', 'reset=1&text=1&id=' . $mailingKey);
2590 $form->assign('textViewURL', $url);
2591 }
2592
2593 if (!$isSMS) {
2594 if (!empty($report['mailing']['body_html'])) {
2595 $url = CRM_Utils_System::url('civicrm/mailing/view', 'reset=1&id=' . $mailingKey);
2596 $form->assign('htmlViewURL', $url);
2597 }
2598 }
2599
2600 if (!$isSMS) {
2601 $report['mailing']['attachment'] = CRM_Core_BAO_File::attachmentInfo('civicrm_mailing', $form->_mailing_id);
2602 }
2603 return $report;
2604 }
2605
2606 static function overrideVerp($jobID) {
2607 static $_cache = array();
2608
2609 if (!isset($_cache[$jobID])) {
2610 $query = "
2611 SELECT override_verp
2612 FROM civicrm_mailing
2613 INNER JOIN civicrm_mailing_job ON civicrm_mailing.id = civicrm_mailing_job.mailing_id
2614 WHERE civicrm_mailing_job.id = %1
2615 ";
2616 $params = array(1 => array($jobID, 'Integer'));
2617 $_cache[$jobID] = CRM_Core_DAO::singleValueQuery($query, $params);
2618 }
2619 return $_cache[$jobID];
2620 }
2621
2622 static function processQueue($mode = NULL) {
2623 $config = &CRM_Core_Config::singleton();
2624 // CRM_Core_Error::debug_log_message("Beginning processQueue run: {$config->mailerJobsMax}, {$config->mailerJobSize}");
2625
2626 if ($mode == NULL && CRM_Core_BAO_MailSettings::defaultDomain() == "EXAMPLE.ORG") {
2627 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/")));
2628 }
2629
2630 // check if we are enforcing number of parallel cron jobs
2631 // CRM-8460
2632 $gotCronLock = FALSE;
2633
2634 if (property_exists($config, 'mailerJobsMax') && $config->mailerJobsMax && $config->mailerJobsMax > 1) {
2635 $lockArray = range(1, $config->mailerJobsMax);
2636 shuffle($lockArray);
2637
2638 // check if we are using global locks
2639 $serverWideLock = CRM_Core_BAO_Setting::getItem(
2640 CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
2641 'civimail_server_wide_lock'
2642 );
2643 foreach ($lockArray as $lockID) {
2644 $cronLock = new CRM_Core_Lock("civimail.cronjob.{$lockID}", NULL, $serverWideLock);
2645 if ($cronLock->isAcquired()) {
2646 $gotCronLock = TRUE;
2647 break;
2648 }
2649 }
2650
2651 // exit here since we have enuf cronjobs running
2652 if (!$gotCronLock) {
2653 CRM_Core_Error::debug_log_message('Returning early, since max number of cronjobs running');
2654 return TRUE;
2655 }
2656 }
2657
2658 // load bootstrap to call hooks
2659
2660 // Split up the parent jobs into multiple child jobs
2661 $mailerJobSize = (property_exists($config, 'mailerJobSize')) ? $config->mailerJobSize : NULL;
2662 CRM_Mailing_BAO_MailingJob::runJobs_pre($mailerJobSize, $mode);
2663 CRM_Mailing_BAO_MailingJob::runJobs(NULL, $mode);
2664 CRM_Mailing_BAO_MailingJob::runJobs_post($mode);
2665
2666 // lets release the global cron lock if we do have one
2667 if ($gotCronLock) {
2668 $cronLock->release();
2669 }
2670
2671 // CRM_Core_Error::debug_log_message('Ending processQueue run');
2672 return TRUE;
2673 }
2674
2675 private static function addMultipleEmails($mailingID) {
2676 $sql = "
2677 INSERT INTO civicrm_mailing_recipients
2678 (mailing_id, email_id, contact_id)
2679 SELECT %1, e.id, e.contact_id FROM civicrm_email e
2680 WHERE e.on_hold = 0
2681 AND e.is_bulkmail = 1
2682 AND e.contact_id IN
2683 ( SELECT contact_id FROM civicrm_mailing_recipients mr WHERE mailing_id = %1 )
2684 AND e.id NOT IN ( SELECT email_id FROM civicrm_mailing_recipients mr WHERE mailing_id = %1 )
2685 ";
2686 $params = array(1 => array($mailingID, 'Integer'));
2687
2688 $dao = CRM_Core_DAO::executeQuery($sql, $params);
2689 }
2690
2691 static function getMailingsList($isSMS = FALSE) {
2692 static $list = array();
2693 $where = " WHERE ";
2694 if (!$isSMS) {
2695 $where .= " civicrm_mailing.sms_provider_id IS NULL ";
2696 }
2697 else {
2698 $where .= " civicrm_mailing.sms_provider_id IS NOT NULL ";
2699 }
2700
2701 if (empty($list)) {
2702 $query = "
2703 SELECT civicrm_mailing.id, civicrm_mailing.name, civicrm_mailing_job.end_date
2704 FROM civicrm_mailing
2705 INNER JOIN civicrm_mailing_job ON civicrm_mailing.id = civicrm_mailing_job.mailing_id {$where}
2706 ORDER BY civicrm_mailing.name";
2707 $mailing = CRM_Core_DAO::executeQuery($query);
2708
2709 while ($mailing->fetch()) {
2710 $list[$mailing->id] = "{$mailing->name} :: {$mailing->end_date}";
2711 }
2712 }
2713
2714 return $list;
2715 }
2716
2717 static function hiddenMailingGroup($mid) {
2718 $sql = "
2719 SELECT g.id
2720 FROM civicrm_mailing m
2721 INNER JOIN civicrm_mailing_group mg ON mg.mailing_id = m.id
2722 INNER JOIN civicrm_group g ON mg.entity_id = g.id AND mg.entity_table = 'civicrm_group'
2723 WHERE g.is_hidden = 1
2724 AND mg.group_type = 'Include'
2725 AND m.id = %1
2726 ";
2727 $params = array( 1 => array( $mid, 'Integer' ) );
2728 return CRM_Core_DAO::singleValueQuery($sql, $params);
2729 }
2730
2731 /**
2732 * This function is a wrapper for ajax activity selector
2733 *
2734 * @param array $params associated array for params record id.
2735 *
2736 * @return array $contactActivities associated array of contact activities
2737 * @access public
2738 */
2739 public static function getContactMailingSelector(&$params) {
2740 // format the params
2741 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2742 $params['rowCount'] = $params['rp'];
2743 $params['sort'] = CRM_Utils_Array::value('sortBy', $params);
2744 $params['caseId'] = NULL;
2745
2746 // get contact mailings
2747 $mailings = CRM_Mailing_BAO_Mailing::getContactMailings($params);
2748
2749 // add total
2750 $params['total'] = CRM_Mailing_BAO_Mailing::getContactMailingsCount($params);
2751
2752 //CRM-12814
2753 if (!empty($mailings)) {
2754 $openCounts = CRM_Mailing_Event_BAO_Opened::getMailingContactCount(array_keys($mailings), $params['contact_id']);
2755 $clickCounts = CRM_Mailing_Event_BAO_TrackableURLOpen::getMailingContactCount(array_keys($mailings), $params['contact_id']);
2756 }
2757
2758 // format params and add links
2759 $contactMailings = array();
2760 foreach ($mailings as $mailingId => $values) {
2761 $contactMailings[$mailingId]['subject'] = $values['subject'];
2762 $contactMailings[$mailingId]['start_date'] = CRM_Utils_Date::customFormat($values['start_date']);
2763 $contactMailings[$mailingId]['recipients'] = CRM_Utils_System::href(ts('(recipients)'), 'civicrm/mailing/report/event',
2764 "mid={$values['mailing_id']}&reset=1&cid={$params['contact_id']}&event=queue&context=mailing");
2765
2766 $contactMailings[$mailingId]['mailing_creator'] = CRM_Utils_System::href(
2767 $values['creator_name'],
2768 'civicrm/contact/view',
2769 "reset=1&cid={$values['creator_id']}");
2770
2771 //CRM-12814
2772 $contactMailings[$mailingId]['openstats'] = "Opens: ".
2773 CRM_Utils_Array::value($values['mailing_id'], $openCounts, 0).
2774 "<br />Clicks: ".
2775 CRM_Utils_Array::value($values['mailing_id'], $clickCounts, 0);
2776
2777 $actionLinks = array(
2778 CRM_Core_Action::VIEW => array(
2779 'name' => ts('View'),
2780 'url' => 'civicrm/mailing/view',
2781 'qs' => "reset=1&id=%%mkey%%",
2782 'title' => ts('View Mailing'),
2783 'class' => 'crm-popup',
2784 ),
2785 CRM_Core_Action::BROWSE => array(
2786 'name' => ts('Mailing Report'),
2787 'url' => 'civicrm/mailing/report',
2788 'qs' => "mid=%%mid%%&reset=1&cid=%%cid%%&context=mailing",
2789 'title' => ts('View Mailing Report'),
2790 )
2791 );
2792
2793 $mailingKey = $values['mailing_id'];
2794 if ($hash = CRM_Mailing_BAO_Mailing::getMailingHash($mailingKey)) {
2795 $mailingKey = $hash;
2796 }
2797
2798 $contactMailings[$mailingId]['links'] = CRM_Core_Action::formLink(
2799 $actionLinks,
2800 null,
2801 array(
2802 'mid' => $values['mailing_id'],
2803 'cid' => $params['contact_id'],
2804 'mkey' => $mailingKey,
2805 ),
2806 ts('more'),
2807 FALSE,
2808 'mailing.contact.action',
2809 'Mailing',
2810 $values['mailing_id']
2811 );
2812 }
2813
2814 return $contactMailings;
2815 }
2816
2817 /**
2818 * Function to retrieve contact mailing
2819 *
2820 * @param array $params associated array
2821 *
2822 * @return array of mailings for a contact
2823 *
2824 * @static
2825 * @access public
2826 */
2827 static public function getContactMailings(&$params) {
2828 $params['version'] = 3;
2829 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2830 $params['limit'] = $params['rp'];
2831 $params['sort'] = CRM_Utils_Array::value('sortBy', $params);
2832
2833 $result = civicrm_api('MailingContact', 'get', $params);
2834 return $result['values'];
2835 }
2836
2837 /**
2838 * Function to retrieve contact mailing count
2839 *
2840 * @param array $params associated array
2841 *
2842 * @return int count of mailings for a contact
2843 *
2844 * @static
2845 * @access public
2846 */
2847 static public function getContactMailingsCount(&$params) {
2848 $params['version'] = 3;
2849 return civicrm_api('MailingContact', 'getcount', $params);
2850 }
2851 }