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