Merge remote-tracking branch 'upstream/4.5' into 4.5-master-2015-03-09-21-44-34
[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 /**
113 * note that $job_id is used only as a variable in the temp table construction
114 * and does not play a role in the queries generated
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 public 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 * Returns the regex patterns that are used for preparing the text and html templates.
627 */
628 private function &getPatterns($onlyHrefs = FALSE) {
629
630 $patterns = array();
631
632 $protos = '(https?|ftp)';
633 $letters = '\w';
634 $gunk = '\{\}/#~:.?+=&;%@!\,\-';
635 $punc = '.:?\-';
636 $any = "{$letters}{$gunk}{$punc}";
637 if ($onlyHrefs) {
638 $pattern = "\\bhref[ ]*=[ ]*([\"'])?(($protos:[$any]+?(?=[$punc]*[^$any]|$)))([\"'])?";
639 }
640 else {
641 $pattern = "\\b($protos:[$any]+?(?=[$punc]*[^$any]|$))";
642 }
643
644 $patterns[] = $pattern;
645 $patterns[] = '\\\\\{\w+\.\w+\\\\\}|\{\{\w+\.\w+\}\}';
646 $patterns[] = '\{\w+\.\w+\}';
647
648 $patterns = '{' . implode('|', $patterns) . '}im';
649
650 return $patterns;
651 }
652
653 /**
654 * Returns an array that denotes the type of token that we are dealing with
655 * we use the type later on when we are doing a token replacement lookup
656 *
657 * @param string $token
658 * The token for which we will be doing adata lookup.
659 *
660 * @return array
661 * An array that holds the token itself and the type.
662 * the type will tell us which function to use for the data lookup
663 * if we need to do a lookup at all
664 */
665 public function &getDataFunc($token) {
666 static $_categories = NULL;
667 static $_categoryString = NULL;
668 if (!$_categories) {
669 $_categories = array(
670 'domain' => NULL,
671 'action' => NULL,
672 'mailing' => NULL,
673 'contact' => NULL,
674 );
675
676 CRM_Utils_Hook::tokens($_categories);
677 $_categoryString = implode('|', array_keys($_categories));
678 }
679
680 $funcStruct = array('type' => NULL, 'token' => $token);
681 $matches = array();
682 if ((preg_match('/^href/i', $token) || preg_match('/^http/i', $token))) {
683 // it is a url so we need to check to see if there are any tokens embedded
684 // if so then call this function again to get the token dataFunc
685 // and assign the type 'embedded' so that the data retrieving function
686 // will know what how to handle this token.
687 if (preg_match_all('/(\{\w+\.\w+\})/', $token, $matches)) {
688 $funcStruct['type'] = 'embedded_url';
689 $funcStruct['embed_parts'] = $funcStruct['token'] = array();
690 foreach ($matches[1] as $match) {
691 $preg_token = '/' . preg_quote($match, '/') . '/';
692 $list = preg_split($preg_token, $token, 2);
693 $funcStruct['embed_parts'][] = $list[0];
694 $token = $list[1];
695 $funcStruct['token'][] = $this->getDataFunc($match);
696 }
697 // fixed truncated url, CRM-7113
698 if ($token) {
699 $funcStruct['embed_parts'][] = $token;
700 }
701 }
702 else {
703 $funcStruct['type'] = 'url';
704 }
705 }
706 elseif (preg_match('/^\{(' . $_categoryString . ')\.(\w+)\}$/', $token, $matches)) {
707 $funcStruct['type'] = $matches[1];
708 $funcStruct['token'] = $matches[2];
709 }
710 elseif (preg_match('/\\\\\{(\w+\.\w+)\\\\\}|\{\{(\w+\.\w+)\}\}/', $token, $matches)) {
711 // we are an escaped token
712 // so remove the escape chars
713 $unescaped_token = preg_replace('/\{\{|\}\}|\\\\\{|\\\\\}/', '', $matches[0]);
714 $funcStruct['token'] = '{' . $unescaped_token . '}';
715 }
716 return $funcStruct;
717 }
718
719 /**
720 *
721 * Prepares the text and html templates
722 * for generating the emails and returns a copy of the
723 * prepared templates
724 */
725 private function getPreparedTemplates() {
726 if (!$this->preparedTemplates) {
727 $patterns['html'] = $this->getPatterns(TRUE);
728 $patterns['subject'] = $patterns['text'] = $this->getPatterns();
729 $templates = $this->getTemplates();
730
731 $this->preparedTemplates = array();
732
733 foreach (array(
734 'html',
735 'text',
736 'subject',
737 ) 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 * Retrieve a ref to an array that holds the email and text templates for this email
765 * assembles the complete template including the header and footer
766 * that the user has uploaded or declared (if they have dome that)
767 *
768 * @return array
769 * reference to an assoc array
770 */
771 private function &getTemplates() {
772 if (!$this->templates) {
773 $this->getHeaderFooter();
774 $this->templates = array();
775
776 if ($this->body_text) {
777 $template = array();
778 if ($this->header) {
779 $template[] = $this->header->body_text;
780 }
781
782 $template[] = $this->body_text;
783
784 if ($this->footer) {
785 $template[] = $this->footer->body_text;
786 }
787
788 $this->templates['text'] = implode("\n", $template);
789 }
790
791 if ($this->body_html) {
792
793 $template = array();
794 if ($this->header) {
795 $template[] = $this->header->body_html;
796 }
797
798 $template[] = $this->body_html;
799
800 if ($this->footer) {
801 $template[] = $this->footer->body_html;
802 }
803
804 $this->templates['html'] = implode("\n", $template);
805
806 // this is where we create a text template from the html template if the text template did not exist
807 // this way we ensure that every recipient will receive an email even if the pref is set to text and the
808 // user uploads an html email only
809 if (!$this->body_text) {
810 $this->templates['text'] = CRM_Utils_String::htmlToText($this->templates['html']);
811 }
812 }
813
814 if ($this->subject) {
815 $template = array();
816 $template[] = $this->subject;
817 $this->templates['subject'] = implode("\n", $template);
818 }
819 }
820 return $this->templates;
821 }
822
823 /**
824 *
825 * Retrieve a ref to an array that holds all of the tokens in the email body
826 * where the keys are the type of token and the values are ordinal arrays
827 * that hold the token names (even repeated tokens) in the order in which
828 * they appear in the body of the email.
829 *
830 * note: the real work is done in the _getTokens() function
831 *
832 * this function needs to have some sort of a body assigned
833 * either text or html for this to have any meaningful impact
834 *
835 * @return array
836 * reference to an assoc array
837 */
838 public function &getTokens() {
839 if (!$this->tokens) {
840
841 $this->tokens = array('html' => array(), 'text' => array(), 'subject' => array());
842
843 if ($this->body_html) {
844 $this->_getTokens('html');
845 if (!$this->body_text) {
846 // Since the text template was created from html, use the html tokens.
847 // @see CRM_Mailing_BAO_Mailing::getTemplates()
848 $this->tokens['text'] = $this->tokens['html'];
849 }
850 }
851
852 if ($this->body_text) {
853 $this->_getTokens('text');
854 }
855
856 if ($this->subject) {
857 $this->_getTokens('subject');
858 }
859 }
860
861 return $this->tokens;
862 }
863
864 /**
865 * Returns the token set for all 3 parts as one set. This allows it to be sent to the
866 * hook in one call and standardizes it across other token workflows
867 *
868 * @return array
869 * reference to an assoc array
870 */
871 public function &getFlattenedTokens() {
872 if (!$this->flattenedTokens) {
873 $tokens = $this->getTokens();
874
875 $this->flattenedTokens = CRM_Utils_Token::flattenTokens($tokens);
876 }
877
878 return $this->flattenedTokens;
879 }
880
881 /**
882 *
883 * _getTokens parses out all of the tokens that have been
884 * included in the html and text bodies of the email
885 * we get the tokens and then separate them into an
886 * internal structure named tokens that has the same
887 * form as the static tokens property(?) of the CRM_Utils_Token class.
888 * The difference is that there might be repeated token names as we want the
889 * structures to represent the order in which tokens were found from left to right, top to bottom.
890 *
891 *
892 * @param string $prop name of the property that holds the text that we want to scan for tokens (html, text).
893 * Name of the property that holds the text that we want to scan for tokens (html, text).
894 *
895 * @return void
896 */
897 private function _getTokens($prop) {
898 $templates = $this->getTemplates();
899
900 $newTokens = CRM_Utils_Token::getTokens($templates[$prop]);
901
902 foreach ($newTokens as $type => $names) {
903 if (!isset($this->tokens[$prop][$type])) {
904 $this->tokens[$prop][$type] = array();
905 }
906 foreach ($names as $key => $name) {
907 $this->tokens[$prop][$type][] = $name;
908 }
909 }
910 }
911
912 /**
913 * Generate an event queue for a test job.
914 *
915 * @param array $testParams
916 * Contains form values.
917 *
918 * @return void
919 */
920 public function getTestRecipients($testParams) {
921 if (array_key_exists($testParams['test_group'], CRM_Core_PseudoConstant::group())) {
922 $contacts = civicrm_api('contact', 'get', array(
923 'version' => 3,
924 'group' => $testParams['test_group'],
925 'return' => 'id',
926 'options' => array(
927 'limit' => 100000000000,
928 ),
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 * Load this->header and this->footer.
963 */
964 private function getHeaderFooter() {
965 if (!$this->header and $this->header_id) {
966 $this->header = new CRM_Mailing_BAO_Component();
967 $this->header->id = $this->header_id;
968 $this->header->find(TRUE);
969 $this->header->free();
970 }
971
972 if (!$this->footer and $this->footer_id) {
973 $this->footer = new CRM_Mailing_BAO_Component();
974 $this->footer->id = $this->footer_id;
975 $this->footer->find(TRUE);
976 $this->footer->free();
977 }
978 }
979
980 /**
981 * Given and array of headers and a prefix, job ID, event queue ID, and hash,
982 * add a Message-ID header if needed.
983 *
984 * i.e. if the global includeMessageId is set and there isn't already a
985 * Message-ID in the array.
986 * The message ID is structured the same way as a verp. However no interpretation
987 * is placed on the values received, so they do not need to follow the verp
988 * convention.
989 *
990 * @param array $headers
991 * Array of message headers to update, in-out.
992 * @param string $prefix
993 * Prefix for the message ID, use same prefixes as verp.
994 * wherever possible
995 * @param string $job_id
996 * Job ID component of the generated message ID.
997 * @param string $event_queue_id
998 * Event Queue ID component of the generated message ID.
999 * @param string $hash
1000 * Hash component of the generated message ID.
1001 *
1002 * @return void
1003 */
1004 public static function addMessageIdHeader(&$headers, $prefix, $job_id, $event_queue_id, $hash) {
1005 $config = CRM_Core_Config::singleton();
1006 $localpart = CRM_Core_BAO_MailSettings::defaultLocalpart();
1007 $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
1008 $includeMessageId = CRM_Core_BAO_MailSettings::includeMessageId();
1009
1010 if ($includeMessageId && (!array_key_exists('Message-ID', $headers))) {
1011 $headers['Message-ID'] = '<' . implode($config->verpSeparator,
1012 array(
1013 $localpart . $prefix,
1014 $job_id,
1015 $event_queue_id,
1016 $hash,
1017 )
1018 ) . "@{$emailDomain}>";
1019 }
1020 }
1021
1022 /**
1023 * Static wrapper for getting verp and urls.
1024 *
1025 * @param int $job_id
1026 * ID of the Job associated with this message.
1027 * @param int $event_queue_id
1028 * ID of the EventQueue.
1029 * @param string $hash
1030 * Hash of the EventQueue.
1031 * @param string $email
1032 * Destination address.
1033 *
1034 * @return array
1035 * (reference) array array ref that hold array refs to the verp info and urls
1036 */
1037 public static function getVerpAndUrls($job_id, $event_queue_id, $hash, $email) {
1038 // create a skeleton object and set its properties that are required by getVerpAndUrlsAndHeaders()
1039 $config = CRM_Core_Config::singleton();
1040 $bao = new CRM_Mailing_BAO_Mailing();
1041 $bao->_domain = CRM_Core_BAO_Domain::getDomain();
1042 $bao->from_name = $bao->from_email = $bao->subject = '';
1043
1044 // use $bao's instance method to get verp and urls
1045 list($verp, $urls, $_) = $bao->getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email);
1046 return array($verp, $urls);
1047 }
1048
1049 /**
1050 * Get verp, urls and headers
1051 *
1052 * @param int $job_id
1053 * ID of the Job associated with this message.
1054 * @param int $event_queue_id
1055 * ID of the EventQueue.
1056 * @param string $hash
1057 * Hash of the EventQueue.
1058 * @param string $email
1059 * Destination address.
1060 *
1061 * @param bool $isForward
1062 *
1063 * @return array
1064 * array ref that hold array refs to the verp info, urls, and headers
1065 */
1066 private function getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email, $isForward = FALSE) {
1067 $config = CRM_Core_Config::singleton();
1068
1069 /**
1070 * Inbound VERP keys:
1071 * reply: user replied to mailing
1072 * bounce: email address bounced
1073 * unsubscribe: contact opts out of all target lists for the mailing
1074 * resubscribe: contact opts back into all target lists for the mailing
1075 * optOut: contact unsubscribes from the domain
1076 */
1077 $verp = array();
1078 $verpTokens = array(
1079 'reply' => 'r',
1080 'bounce' => 'b',
1081 'unsubscribe' => 'u',
1082 'resubscribe' => 'e',
1083 'optOut' => 'o',
1084 );
1085
1086 $localpart = CRM_Core_BAO_MailSettings::defaultLocalpart();
1087 $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
1088
1089 foreach ($verpTokens as $key => $value) {
1090 $verp[$key] = implode($config->verpSeparator,
1091 array(
1092 $localpart . $value,
1093 $job_id,
1094 $event_queue_id,
1095 $hash,
1096 )
1097 ) . "@$emailDomain";
1098 }
1099
1100 //handle should override VERP address.
1101 $skipEncode = FALSE;
1102
1103 if ($job_id &&
1104 self::overrideVerp($job_id)
1105 ) {
1106 $verp['reply'] = "\"{$this->from_name}\" <{$this->from_email}>";
1107 }
1108
1109 $urls = array(
1110 'forward' => CRM_Utils_System::url('civicrm/mailing/forward',
1111 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1112 TRUE, NULL, TRUE, TRUE
1113 ),
1114 'unsubscribeUrl' => CRM_Utils_System::url('civicrm/mailing/unsubscribe',
1115 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1116 TRUE, NULL, TRUE, TRUE
1117 ),
1118 'resubscribeUrl' => CRM_Utils_System::url('civicrm/mailing/resubscribe',
1119 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1120 TRUE, NULL, TRUE, TRUE
1121 ),
1122 'optOutUrl' => CRM_Utils_System::url('civicrm/mailing/optout',
1123 "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}",
1124 TRUE, NULL, TRUE, TRUE
1125 ),
1126 'subscribeUrl' => CRM_Utils_System::url('civicrm/mailing/subscribe',
1127 'reset=1',
1128 TRUE, NULL, TRUE, TRUE
1129 ),
1130 );
1131
1132 $headers = array(
1133 'Reply-To' => $verp['reply'],
1134 'Return-Path' => $verp['bounce'],
1135 'From' => "\"{$this->from_name}\" <{$this->from_email}>",
1136 'Subject' => $this->subject,
1137 'List-Unsubscribe' => "<mailto:{$verp['unsubscribe']}>",
1138 );
1139 self::addMessageIdHeader($headers, 'm', $job_id, $event_queue_id, $hash);
1140 if ($isForward) {
1141 $headers['Subject'] = "[Fwd:{$this->subject}]";
1142 }
1143 return array(&$verp, &$urls, &$headers);
1144 }
1145
1146 /**
1147 * Compose a message.
1148 *
1149 * @param int $job_id
1150 * ID of the Job associated with this message.
1151 * @param int $event_queue_id
1152 * ID of the EventQueue.
1153 * @param string $hash
1154 * Hash of the EventQueue.
1155 * @param string $contactId
1156 * ID of the Contact.
1157 * @param string $email
1158 * Destination address.
1159 * @param string $recipient
1160 * To: of the recipient.
1161 * @param bool $test
1162 * Is this mailing a test?.
1163 * @param $contactDetails
1164 * @param $attachments
1165 * @param bool $isForward
1166 * Is this mailing compose for forward?.
1167 * @param string $fromEmail
1168 * Email address of who is forwardinf it.
1169 *
1170 * @param null $replyToEmail
1171 *
1172 * @return Mail_mime The mail object
1173 */
1174 public function &compose(
1175 $job_id, $event_queue_id, $hash, $contactId,
1176 $email, &$recipient, $test,
1177 $contactDetails, &$attachments, $isForward = FALSE,
1178 $fromEmail = NULL, $replyToEmail = NULL
1179 ) {
1180 $config = CRM_Core_Config::singleton();
1181 $knownTokens = $this->getTokens();
1182
1183 if ($this->_domain == NULL) {
1184 $this->_domain = CRM_Core_BAO_Domain::getDomain();
1185 }
1186
1187 list($verp, $urls, $headers) = $this->getVerpAndUrlsAndHeaders(
1188 $job_id,
1189 $event_queue_id,
1190 $hash,
1191 $email,
1192 $isForward
1193 );
1194
1195 //set from email who is forwarding it and not original one.
1196 if ($fromEmail) {
1197 unset($headers['From']);
1198 $headers['From'] = "<{$fromEmail}>";
1199 }
1200
1201 if ($replyToEmail && ($fromEmail != $replyToEmail)) {
1202 $headers['Reply-To'] = "{$replyToEmail}";
1203 }
1204
1205 if ($contactDetails) {
1206 $contact = $contactDetails;
1207 }
1208 elseif ($contactId === 0) {
1209 //anonymous user
1210 $contact = array();
1211 CRM_Utils_Hook::tokenValues($contact, $contactId, $job_id);
1212 }
1213 else {
1214 $params = array(array('contact_id', '=', $contactId, 0, 0));
1215 list($contact, $_) = CRM_Contact_BAO_Query::apiQuery($params);
1216
1217 //CRM-4524
1218 $contact = reset($contact);
1219
1220 if (!$contact || is_a($contact, 'CRM_Core_Error')) {
1221 CRM_Core_Error::debug_log_message(ts('CiviMail will not send email to a non-existent contact: %1',
1222 array(1 => $contactId)
1223 ));
1224 // setting this because function is called by reference
1225 //@todo test not calling function by reference
1226 $res = NULL;
1227 return $res;
1228 }
1229
1230 // also call the hook to get contact details
1231 CRM_Utils_Hook::tokenValues($contact, $contactId, $job_id);
1232 }
1233
1234 $pTemplates = $this->getPreparedTemplates();
1235 $pEmails = array();
1236
1237 foreach ($pTemplates as $type => $pTemplate) {
1238 $html = ($type == 'html') ? TRUE : FALSE;
1239 $pEmails[$type] = array();
1240 $pEmail = &$pEmails[$type];
1241 $template = &$pTemplates[$type]['template'];
1242 $tokens = &$pTemplates[$type]['tokens'];
1243 $idx = 0;
1244 if (!empty($tokens)) {
1245 foreach ($tokens as $idx => $token) {
1246 $token_data = $this->getTokenData($token, $html, $contact, $verp, $urls, $event_queue_id);
1247 array_push($pEmail, $template[$idx]);
1248 array_push($pEmail, $token_data);
1249 }
1250 }
1251 else {
1252 array_push($pEmail, $template[$idx]);
1253 }
1254
1255 if (isset($template[($idx + 1)])) {
1256 array_push($pEmail, $template[($idx + 1)]);
1257 }
1258 }
1259
1260 $html = NULL;
1261 if (isset($pEmails['html']) && is_array($pEmails['html']) && count($pEmails['html'])) {
1262 $html = &$pEmails['html'];
1263 }
1264
1265 $text = NULL;
1266 if (isset($pEmails['text']) && is_array($pEmails['text']) && count($pEmails['text'])) {
1267 $text = &$pEmails['text'];
1268 }
1269
1270 // push the tracking url on to the html email if necessary
1271 if ($this->open_tracking && $html) {
1272 array_push($html, "\n" . '<img src="' . $config->userFrameworkResourceURL .
1273 "extern/open.php?q=$event_queue_id\" width='1' height='1' alt='' border='0'>"
1274 );
1275 }
1276
1277 $message = new Mail_mime("\n");
1278
1279 $useSmarty = defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY ? TRUE : FALSE;
1280 if ($useSmarty) {
1281 $smarty = CRM_Core_Smarty::singleton();
1282 // also add the contact tokens to the template
1283 $smarty->assign_by_ref('contact', $contact);
1284 }
1285
1286 $mailParams = $headers;
1287 if ($text && ($test || $contact['preferred_mail_format'] == 'Text' ||
1288 $contact['preferred_mail_format'] == 'Both' ||
1289 ($contact['preferred_mail_format'] == 'HTML' && !array_key_exists('html', $pEmails))
1290 )
1291 ) {
1292 $textBody = implode('', $text);
1293 if ($useSmarty) {
1294 $textBody = $smarty->fetch("string:$textBody");
1295 }
1296 $mailParams['text'] = $textBody;
1297 }
1298
1299 if ($html && ($test || ($contact['preferred_mail_format'] == 'HTML' ||
1300 $contact['preferred_mail_format'] == 'Both'
1301 ))
1302 ) {
1303 $htmlBody = implode('', $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 = implode('', $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 // Add job ID to mailParams for external email delivery service to utilise
1334 $mailParams['job_id'] = $job_id;
1335
1336 CRM_Utils_Hook::alterMailParams($mailParams, 'civimail');
1337
1338 // CRM-10699 support custom email headers
1339 if (!empty($mailParams['headers'])) {
1340 $headers = array_merge($headers, $mailParams['headers']);
1341 }
1342 //cycle through mailParams and set headers array
1343 foreach ($mailParams as $paramKey => $paramValue) {
1344 //exclude values not intended for the header
1345 if (!in_array($paramKey, array(
1346 'text',
1347 'html',
1348 'attachments',
1349 'toName',
1350 'toEmail',
1351 ))
1352 ) {
1353 $headers[$paramKey] = $paramValue;
1354 }
1355 }
1356
1357 if (!empty($mailParams['text'])) {
1358 $message->setTxtBody($mailParams['text']);
1359 }
1360
1361 if (!empty($mailParams['html'])) {
1362 $message->setHTMLBody($mailParams['html']);
1363 }
1364
1365 if (!empty($mailParams['attachments'])) {
1366 foreach ($mailParams['attachments'] as $fileID => $attach) {
1367 $message->addAttachment($attach['fullPath'],
1368 $attach['mime_type'],
1369 $attach['cleanName']
1370 );
1371 }
1372 }
1373
1374 //pickup both params from mail params.
1375 $toName = trim($mailParams['toName']);
1376 $toEmail = trim($mailParams['toEmail']);
1377 if ($toName == $toEmail ||
1378 strpos($toName, '@') !== FALSE
1379 ) {
1380 $toName = NULL;
1381 }
1382 else {
1383 $toName = CRM_Utils_Mail::formatRFC2822Name($toName);
1384 }
1385
1386 $headers['To'] = "$toName <$toEmail>";
1387
1388 $headers['Precedence'] = 'bulk';
1389 // Will test in the mail processor if the X-VERP is set in the bounced email.
1390 // (As an option to replace real VERP for those that can't set it up)
1391 $headers['X-CiviMail-Bounce'] = $verp['bounce'];
1392
1393 //CRM-5058
1394 //token replacement of subject
1395 $headers['Subject'] = $mailingSubject;
1396
1397 CRM_Utils_Mail::setMimeParams($message);
1398 $headers = $message->headers($headers);
1399
1400 //get formatted recipient
1401 $recipient = $headers['To'];
1402
1403 // make sure we unset a lot of stuff
1404 unset($verp);
1405 unset($urls);
1406 unset($params);
1407 unset($contact);
1408 unset($ids);
1409
1410 return $message;
1411 }
1412
1413 /**
1414 *
1415 * get mailing object and replaces subscribeInvite,
1416 * domain and mailing tokens
1417 */
1418 public static function tokenReplace(&$mailing) {
1419 $domain = CRM_Core_BAO_Domain::getDomain();
1420
1421 foreach (array('text', 'html') as $type) {
1422 $tokens = $mailing->getTokens();
1423 if (isset($mailing->templates[$type])) {
1424 $mailing->templates[$type] = CRM_Utils_Token::replaceSubscribeInviteTokens($mailing->templates[$type]);
1425 $mailing->templates[$type] = CRM_Utils_Token::replaceDomainTokens(
1426 $mailing->templates[$type],
1427 $domain,
1428 $type == 'html' ? TRUE : FALSE,
1429 $tokens[$type]
1430 );
1431 $mailing->templates[$type] = CRM_Utils_Token::replaceMailingTokens($mailing->templates[$type], $mailing, NULL, $tokens[$type]);
1432 }
1433 }
1434 }
1435
1436 /**
1437 *
1438 * getTokenData receives a token from an email
1439 * and returns the appropriate data for the token
1440 */
1441 private function getTokenData(&$token_a, $html = FALSE, &$contact, &$verp, &$urls, $event_queue_id) {
1442 $type = $token_a['type'];
1443 $token = $token_a['token'];
1444 $data = $token;
1445
1446 $useSmarty = defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY ? TRUE : FALSE;
1447
1448 if ($type == 'embedded_url') {
1449 $embed_data = array();
1450 foreach ($token as $t) {
1451 $embed_data[] = $this->getTokenData($t, $html = FALSE, $contact, $verp, $urls, $event_queue_id);
1452 }
1453 $numSlices = count($embed_data);
1454 $url = '';
1455 for ($i = 0; $i < $numSlices; $i++) {
1456 $url .= "{$token_a['embed_parts'][$i]}{$embed_data[$i]}";
1457 }
1458 if (isset($token_a['embed_parts'][$numSlices])) {
1459 $url .= $token_a['embed_parts'][$numSlices];
1460 }
1461 // add trailing quote since we've gobbled it up in a previous regex
1462 // function getPatterns, line 431
1463 if (preg_match('/^href[ ]*=[ ]*\'/', $url)) {
1464 $url .= "'";
1465 }
1466 elseif (preg_match('/^href[ ]*=[ ]*\"/', $url)) {
1467 $url .= '"';
1468 }
1469 $data = $url;
1470 }
1471 elseif ($type == 'url') {
1472 if ($this->url_tracking) {
1473 $data = CRM_Mailing_BAO_TrackableURL::getTrackerURL($token, $this->id, $event_queue_id);
1474 if (!empty($html)) {
1475 $data = htmlentities($data);
1476 }
1477 }
1478 else {
1479 $data = $token;
1480 }
1481 }
1482 elseif ($type == 'contact') {
1483 $data = CRM_Utils_Token::getContactTokenReplacement($token, $contact, FALSE, FALSE, $useSmarty);
1484 }
1485 elseif ($type == 'action') {
1486 $data = CRM_Utils_Token::getActionTokenReplacement($token, $verp, $urls, $html);
1487 }
1488 elseif ($type == 'domain') {
1489 $domain = CRM_Core_BAO_Domain::getDomain();
1490 $data = CRM_Utils_Token::getDomainTokenReplacement($token, $domain, $html);
1491 }
1492 elseif ($type == 'mailing') {
1493 if ($token == 'name') {
1494 $data = $this->name;
1495 }
1496 elseif ($token == 'group') {
1497 $groups = $this->getGroupNames();
1498 $data = implode(', ', $groups);
1499 }
1500 }
1501 else {
1502 $data = CRM_Utils_Array::value("{$type}.{$token}", $contact);
1503 }
1504 return $data;
1505 }
1506
1507 /**
1508 * Return a list of group names for this mailing. Does not work with
1509 * prior-mailing targets.
1510 *
1511 * @return array
1512 * Names of groups receiving this mailing
1513 */
1514 public function &getGroupNames() {
1515 if (!isset($this->id)) {
1516 return array();
1517 }
1518 $mg = new CRM_Mailing_DAO_MailingGroup();
1519 $mgtable = CRM_Mailing_DAO_MailingGroup::getTableName();
1520 $group = CRM_Contact_BAO_Group::getTableName();
1521
1522 $mg->query("SELECT $group.title as name FROM $mgtable
1523 INNER JOIN $group ON $mgtable.entity_id = $group.id
1524 WHERE $mgtable.mailing_id = {$this->id}
1525 AND $mgtable.entity_table = '$group'
1526 AND $mgtable.group_type = 'Include'
1527 ORDER BY $group.name");
1528
1529 $groups = array();
1530 while ($mg->fetch()) {
1531 $groups[] = $mg->name;
1532 }
1533 $mg->free();
1534 return $groups;
1535 }
1536
1537 /**
1538 * Add the mailings.
1539 *
1540 * @param array $params
1541 * Reference array contains the values submitted by the form.
1542 * @param array $ids
1543 * Reference array contains the id.
1544 *
1545 *
1546 * @return CRM_Mailing_DAO_Mailing
1547 */
1548 public static function add(&$params, $ids = array()) {
1549 $id = CRM_Utils_Array::value('mailing_id', $ids, CRM_Utils_Array::value('id', $params));
1550
1551 if ($id) {
1552 CRM_Utils_Hook::pre('edit', 'Mailing', $id, $params);
1553 }
1554 else {
1555 CRM_Utils_Hook::pre('create', 'Mailing', NULL, $params);
1556 }
1557
1558 $mailing = new static();
1559 if ($id) {
1560 $mailing->id = $id;
1561 $mailing->find(TRUE);
1562 }
1563 $mailing->domain_id = CRM_Utils_Array::value('domain_id', $params, CRM_Core_Config::domainID());
1564
1565 if (!isset($params['replyto_email']) &&
1566 isset($params['from_email'])
1567 ) {
1568 $params['replyto_email'] = $params['from_email'];
1569 }
1570
1571 $mailing->copyValues($params);
1572
1573 $result = $mailing->save();
1574
1575 if (!empty($ids['mailing'])) {
1576 CRM_Utils_Hook::post('edit', 'Mailing', $mailing->id, $mailing);
1577 }
1578 else {
1579 CRM_Utils_Hook::post('create', 'Mailing', $mailing->id, $mailing);
1580 }
1581
1582 return $result;
1583 }
1584
1585 /**
1586 * Construct a new mailing object, along with job and mailing_group
1587 * objects, from the form values of the create mailing wizard.
1588 *
1589 * This function is a bit evil. It not only merges $params and saves
1590 * the mailing -- it also schedules the mailing and chooses the recipients.
1591 * Since it merges $params, it's also the only place to correctly trigger
1592 * multi-field validation. It should be broken up.
1593 *
1594 * In the mean time, use-cases which break under the weight of this
1595 * evil may find reprieve in these extra evil params:
1596 *
1597 * - _skip_evil_bao_auto_recipients_: bool
1598 * - _skip_evil_bao_auto_schedule_: bool
1599 * - _evil_bao_validator_: string|callable
1600 *
1601 * </twowrongsmakesaright>
1602 *
1603 * @params array $params
1604 * Form values.
1605 *
1606 * @param array $params
1607 * @param array $ids
1608 *
1609 * @return object
1610 * $mailing The new mailing object
1611 * @throws \Exception
1612 */
1613 public static function create(&$params, $ids = array()) {
1614 // WTH $ids
1615 if (empty($ids) && isset($params['id'])) {
1616 $ids['mailing_id'] = $ids['id'] = $params['id'];
1617 }
1618
1619 // CRM-12430
1620 // Do the below only for an insert
1621 // for an update, we should not set the defaults
1622 if (!isset($ids['id']) && !isset($ids['mailing_id'])) {
1623 // Retrieve domain email and name for default sender
1624 $domain = civicrm_api(
1625 'Domain',
1626 'getsingle',
1627 array(
1628 'version' => 3,
1629 'current_domain' => 1,
1630 'sequential' => 1,
1631 )
1632 );
1633 if (isset($domain['from_email'])) {
1634 $domain_email = $domain['from_email'];
1635 $domain_name = $domain['from_name'];
1636 }
1637 else {
1638 $domain_email = 'info@EXAMPLE.ORG';
1639 $domain_name = 'EXAMPLE.ORG';
1640 }
1641 if (!isset($params['created_id'])) {
1642 $session =& CRM_Core_Session::singleton();
1643 $params['created_id'] = $session->get('userID');
1644 }
1645 $defaults = array(
1646 // load the default config settings for each
1647 // eg reply_id, unsubscribe_id need to use
1648 // correct template IDs here
1649 'override_verp' => TRUE,
1650 'forward_replies' => FALSE,
1651 'open_tracking' => TRUE,
1652 'url_tracking' => TRUE,
1653 'visibility' => 'Public Pages',
1654 'replyto_email' => $domain_email,
1655 'header_id' => CRM_Mailing_PseudoConstant::defaultComponent('header_id', ''),
1656 'footer_id' => CRM_Mailing_PseudoConstant::defaultComponent('footer_id', ''),
1657 'from_email' => $domain_email,
1658 'from_name' => $domain_name,
1659 'msg_template_id' => NULL,
1660 'created_id' => $params['created_id'],
1661 'approver_id' => NULL,
1662 'auto_responder' => 0,
1663 'created_date' => date('YmdHis'),
1664 'scheduled_date' => NULL,
1665 'approval_date' => NULL,
1666 );
1667
1668 // Get the default from email address, if not provided.
1669 if (empty($defaults['from_email'])) {
1670 $defaultAddress = CRM_Core_OptionGroup::values('from_email_address', NULL, NULL, NULL, ' AND is_default = 1');
1671 foreach ($defaultAddress as $id => $value) {
1672 if (preg_match('/"(.*)" <(.*)>/', $value, $match)) {
1673 $defaults['from_email'] = $match[2];
1674 $defaults['from_name'] = $match[1];
1675 }
1676 }
1677 }
1678
1679 $params = array_merge($defaults, $params);
1680 }
1681
1682 /**
1683 * Could check and warn for the following cases:
1684 *
1685 * - groups OR mailings should be populated.
1686 * - body html OR body text should be populated.
1687 */
1688
1689 $transaction = new CRM_Core_Transaction();
1690
1691 $mailing = self::add($params, $ids);
1692
1693 if (is_a($mailing, 'CRM_Core_Error')) {
1694 $transaction->rollback();
1695 return $mailing;
1696 }
1697 // update mailings with hash values
1698 CRM_Contact_BAO_Contact_Utils::generateChecksum($mailing->id, NULL, NULL, NULL, 'mailing', 16);
1699
1700 $groupTableName = CRM_Contact_BAO_Group::getTableName();
1701 $mailingTableName = CRM_Mailing_BAO_Mailing::getTableName();
1702
1703 /* Create the mailing group record */
1704 $mg = new CRM_Mailing_DAO_MailingGroup();
1705 $groupTypes = array('include' => 'Include', 'exclude' => 'Exclude', 'base' => 'Base');
1706 foreach (array('groups', 'mailings') as $entity) {
1707 foreach (array('include', 'exclude', 'base') as $type) {
1708 if (isset($params[$entity][$type])) {
1709 self::replaceGroups($mailing->id, $groupTypes[$type], $entity, $params[$entity][$type]);
1710 }
1711 }
1712 }
1713
1714 if (!empty($params['search_id']) && !empty($params['group_id'])) {
1715 $mg->reset();
1716 $mg->mailing_id = $mailing->id;
1717 $mg->entity_table = $groupTableName;
1718 $mg->entity_id = $params['group_id'];
1719 $mg->search_id = $params['search_id'];
1720 $mg->search_args = $params['search_args'];
1721 $mg->group_type = 'Include';
1722 $mg->save();
1723 }
1724
1725 // check and attach and files as needed
1726 CRM_Core_BAO_File::processAttachment($params, 'civicrm_mailing', $mailing->id);
1727
1728 // If we're going to autosend, then check validity before saving.
1729 if (!empty($params['scheduled_date']) && $params['scheduled_date'] != 'null' && !empty($params['_evil_bao_validator_'])) {
1730 $cb = Civi\Core\Resolver::singleton()->get($params['_evil_bao_validator_']);
1731 $errors = call_user_func($cb, $mailing);
1732 if (!empty($errors)) {
1733 $fields = implode(',', array_keys($errors));
1734 throw new CRM_Core_Exception("Mailing cannot be sent. There are missing or invalid fields ($fields).", 'cannot-send', $errors);
1735 }
1736 }
1737
1738 $transaction->commit();
1739
1740 // Create parent job if not yet created.
1741 // Condition on the existence of a scheduled date.
1742 if (!empty($params['scheduled_date']) && $params['scheduled_date'] != 'null' && empty($params['_skip_evil_bao_auto_schedule_'])) {
1743 $job = new CRM_Mailing_BAO_MailingJob();
1744 $job->mailing_id = $mailing->id;
1745 $job->status = 'Scheduled';
1746 $job->is_test = 0;
1747
1748 if (!$job->find(TRUE)) {
1749 $job->scheduled_date = $params['scheduled_date'];
1750 $job->save();
1751 }
1752
1753 // Populate the recipients.
1754 if (empty($params['_skip_evil_bao_auto_recipients_'])) {
1755 self::getRecipients($job->id, $mailing->id, NULL, NULL, TRUE, FALSE);
1756 }
1757 }
1758
1759 return $mailing;
1760 }
1761
1762 /**
1763 * @param CRM_Mailing_DAO_Mailing $mailing
1764 * The mailing which may or may not be sendable.
1765 * @return array
1766 * List of error messages.
1767 */
1768 public static function checkSendable($mailing) {
1769 $errors = array();
1770 foreach (array('subject', 'name', 'from_name', 'from_email') as $field) {
1771 if (empty($mailing->{$field})) {
1772 $errors[$field] = ts('Field "%1" is required.', array(
1773 1 => $field,
1774 ));
1775 }
1776 }
1777 if (empty($mailing->body_html) && empty($mailing->body_text)) {
1778 $errors['body'] = ts('Field "body_html" or "body_text" is required.');
1779 }
1780
1781 if (!CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'disable_mandatory_tokens_check')) {
1782 $header = $mailing->header_id && $mailing->header_id != 'null' ? CRM_Mailing_BAO_Component::findById($mailing->header_id) : NULL;
1783 $footer = $mailing->footer_id && $mailing->footer_id != 'null' ? CRM_Mailing_BAO_Component::findById($mailing->footer_id) : NULL;
1784 foreach (array('body_html', 'body_text') as $field) {
1785 if (empty($mailing->{$field})) {
1786 continue;
1787 }
1788 $str = ($header ? $header->{$field} : '') . $mailing->{$field} . ($footer ? $footer->{$field} : '');
1789 $err = CRM_Utils_Token::requiredTokens($str);
1790 if ($err !== TRUE) {
1791 foreach ($err as $token => $desc) {
1792 $errors["{$field}:{$token}"] = ts('This message is missing a required token - {%1}: %2',
1793 array(1 => $token, 2 => $desc)
1794 );
1795 }
1796 }
1797 }
1798 }
1799
1800 return $errors;
1801 }
1802
1803 /**
1804 * Replace the list of recipients on a given mailing.
1805 *
1806 * @param int $mailingId
1807 * @param string $type
1808 * 'include' or 'exclude'.
1809 * @param string $entity
1810 * 'groups' or 'mailings'.
1811 * @param array <int> $entityIds
1812 * @throws CiviCRM_API3_Exception
1813 */
1814 public static function replaceGroups($mailingId, $type, $entity, $entityIds) {
1815 $values = array();
1816 foreach ($entityIds as $entityId) {
1817 $values[] = array('entity_id' => $entityId);
1818 }
1819 civicrm_api3('mailing_group', 'replace', array(
1820 'mailing_id' => $mailingId,
1821 'group_type' => $type,
1822 'entity_table' => ($entity == 'groups') ? CRM_Contact_BAO_Group::getTableName() : CRM_Mailing_BAO_Mailing::getTableName(),
1823 'values' => $values,
1824 ));
1825 }
1826
1827 /**
1828 * Get hash value of the mailing.
1829 *
1830 * @param $id
1831 *
1832 * @return null|string
1833 */
1834 public static function getMailingHash($id) {
1835 $hash = NULL;
1836 if (CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'hash_mailing_url')) {
1837 $hash = CRM_Core_DAO::getFieldValue('CRM_Mailing_BAO_Mailing', $id, 'hash', 'id');
1838 }
1839 return $hash;
1840 }
1841
1842 /**
1843 * Generate a report. Fetch event count information, mailing data, and job
1844 * status.
1845 *
1846 * @param int $id
1847 * The mailing id to report.
1848 * @param bool $skipDetails
1849 * Whether return all detailed report.
1850 *
1851 * @param bool $isSMS
1852 *
1853 * @return array
1854 * Associative array of reporting data
1855 */
1856 public static function &report($id, $skipDetails = FALSE, $isSMS = FALSE) {
1857 $mailing_id = CRM_Utils_Type::escape($id, 'Integer');
1858
1859 $mailing = new CRM_Mailing_BAO_Mailing();
1860
1861 $t = array(
1862 'mailing' => self::getTableName(),
1863 'mailing_group' => CRM_Mailing_DAO_MailingGroup::getTableName(),
1864 'group' => CRM_Contact_BAO_Group::getTableName(),
1865 'job' => CRM_Mailing_BAO_MailingJob::getTableName(),
1866 'queue' => CRM_Mailing_Event_BAO_Queue::getTableName(),
1867 'delivered' => CRM_Mailing_Event_BAO_Delivered::getTableName(),
1868 'opened' => CRM_Mailing_Event_BAO_Opened::getTableName(),
1869 'reply' => CRM_Mailing_Event_BAO_Reply::getTableName(),
1870 'unsubscribe' => CRM_Mailing_Event_BAO_Unsubscribe::getTableName(),
1871 'bounce' => CRM_Mailing_Event_BAO_Bounce::getTableName(),
1872 'forward' => CRM_Mailing_Event_BAO_Forward::getTableName(),
1873 'url' => CRM_Mailing_BAO_TrackableURL::getTableName(),
1874 'urlopen' => CRM_Mailing_Event_BAO_TrackableURLOpen::getTableName(),
1875 'component' => CRM_Mailing_BAO_Component::getTableName(),
1876 'spool' => CRM_Mailing_BAO_Spool::getTableName(),
1877 );
1878
1879 $report = array();
1880 $additionalWhereClause = " AND ";
1881 if (!$isSMS) {
1882 $additionalWhereClause .= " {$t['mailing']}.sms_provider_id IS NULL ";
1883 }
1884 else {
1885 $additionalWhereClause .= " {$t['mailing']}.sms_provider_id IS NOT NULL ";
1886 }
1887
1888 /* Get the mailing info */
1889
1890 $mailing->query("
1891 SELECT {$t['mailing']}.*
1892 FROM {$t['mailing']}
1893 WHERE {$t['mailing']}.id = $mailing_id {$additionalWhereClause}");
1894
1895 $mailing->fetch();
1896
1897 $report['mailing'] = array();
1898 foreach (array_keys(self::fields()) as $field) {
1899 $report['mailing'][$field] = $mailing->$field;
1900 }
1901
1902 //get the campaign
1903 if ($campaignId = CRM_Utils_Array::value('campaign_id', $report['mailing'])) {
1904 $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId);
1905 $report['mailing']['campaign'] = $campaigns[$campaignId];
1906 }
1907
1908 //mailing report is called by activity
1909 //we dont need all detail report
1910 if ($skipDetails) {
1911 return $report;
1912 }
1913
1914 /* Get the component info */
1915
1916 $query = array();
1917
1918 $components = array(
1919 'header' => ts('Header'),
1920 'footer' => ts('Footer'),
1921 'reply' => ts('Reply'),
1922 'unsubscribe' => ts('Unsubscribe'),
1923 'optout' => ts('Opt-Out'),
1924 );
1925 foreach (array_keys($components) as $type) {
1926 $query[] = "SELECT {$t['component']}.name as name,
1927 '$type' as type,
1928 {$t['component']}.id as id
1929 FROM {$t['component']}
1930 INNER JOIN {$t['mailing']}
1931 ON {$t['mailing']}.{$type}_id =
1932 {$t['component']}.id
1933 WHERE {$t['mailing']}.id = $mailing_id";
1934 }
1935 $q = '(' . implode(') UNION (', $query) . ')';
1936 $mailing->query($q);
1937
1938 $report['component'] = array();
1939 while ($mailing->fetch()) {
1940 $report['component'][] = array(
1941 'type' => $components[$mailing->type],
1942 'name' => $mailing->name,
1943 'link' => CRM_Utils_System::url('civicrm/mailing/component',
1944 "reset=1&action=update&id={$mailing->id}"
1945 ),
1946 );
1947 }
1948
1949 /* Get the recipient group info */
1950
1951 $mailing->query("
1952 SELECT {$t['mailing_group']}.group_type as group_type,
1953 {$t['group']}.id as group_id,
1954 {$t['group']}.title as group_title,
1955 {$t['group']}.is_hidden as group_hidden,
1956 {$t['mailing']}.id as mailing_id,
1957 {$t['mailing']}.name as mailing_name
1958 FROM {$t['mailing_group']}
1959 LEFT JOIN {$t['group']}
1960 ON {$t['mailing_group']}.entity_id = {$t['group']}.id
1961 AND {$t['mailing_group']}.entity_table =
1962 '{$t['group']}'
1963 LEFT JOIN {$t['mailing']}
1964 ON {$t['mailing_group']}.entity_id =
1965 {$t['mailing']}.id
1966 AND {$t['mailing_group']}.entity_table =
1967 '{$t['mailing']}'
1968
1969 WHERE {$t['mailing_group']}.mailing_id = $mailing_id
1970 ");
1971
1972 $report['group'] = array('include' => array(), 'exclude' => array(), 'base' => array());
1973 while ($mailing->fetch()) {
1974 $row = array();
1975 if (isset($mailing->group_id)) {
1976 $row['id'] = $mailing->group_id;
1977 $row['name'] = $mailing->group_title;
1978 $row['link'] = CRM_Utils_System::url('civicrm/group/search',
1979 "reset=1&force=1&context=smog&gid={$row['id']}"
1980 );
1981 }
1982 else {
1983 $row['id'] = $mailing->mailing_id;
1984 $row['name'] = $mailing->mailing_name;
1985 $row['mailing'] = TRUE;
1986 $row['link'] = CRM_Utils_System::url('civicrm/mailing/report',
1987 "mid={$row['id']}"
1988 );
1989 }
1990
1991 /* Rename hidden groups */
1992
1993 if ($mailing->group_hidden == 1) {
1994 $row['name'] = "Search Results";
1995 }
1996
1997 if ($mailing->group_type == 'Include') {
1998 $report['group']['include'][] = $row;
1999 }
2000 elseif ($mailing->group_type == 'Base') {
2001 $report['group']['base'][] = $row;
2002 }
2003 else {
2004 $report['group']['exclude'][] = $row;
2005 }
2006 }
2007
2008 /* Get the event totals, grouped by job (retries) */
2009
2010 $mailing->query("
2011 SELECT {$t['job']}.*,
2012 COUNT(DISTINCT {$t['queue']}.id) as queue,
2013 COUNT(DISTINCT {$t['delivered']}.id) as delivered,
2014 COUNT(DISTINCT {$t['reply']}.id) as reply,
2015 COUNT(DISTINCT {$t['forward']}.id) as forward,
2016 COUNT(DISTINCT {$t['bounce']}.id) as bounce,
2017 COUNT(DISTINCT {$t['urlopen']}.id) as url,
2018 COUNT(DISTINCT {$t['spool']}.id) as spool
2019 FROM {$t['job']}
2020 LEFT JOIN {$t['queue']}
2021 ON {$t['queue']}.job_id = {$t['job']}.id
2022 LEFT JOIN {$t['reply']}
2023 ON {$t['reply']}.event_queue_id = {$t['queue']}.id
2024 LEFT JOIN {$t['forward']}
2025 ON {$t['forward']}.event_queue_id = {$t['queue']}.id
2026 LEFT JOIN {$t['bounce']}
2027 ON {$t['bounce']}.event_queue_id = {$t['queue']}.id
2028 LEFT JOIN {$t['delivered']}
2029 ON {$t['delivered']}.event_queue_id = {$t['queue']}.id
2030 AND {$t['bounce']}.id IS null
2031 LEFT JOIN {$t['urlopen']}
2032 ON {$t['urlopen']}.event_queue_id = {$t['queue']}.id
2033 LEFT JOIN {$t['spool']}
2034 ON {$t['spool']}.job_id = {$t['job']}.id
2035 WHERE {$t['job']}.mailing_id = $mailing_id
2036 AND {$t['job']}.is_test = 0
2037 GROUP BY {$t['job']}.id");
2038
2039 $report['jobs'] = array();
2040 $report['event_totals'] = array();
2041 $elements = array(
2042 'queue',
2043 'delivered',
2044 'url',
2045 'forward',
2046 'reply',
2047 'unsubscribe',
2048 'optout',
2049 'opened',
2050 'bounce',
2051 'spool',
2052 );
2053
2054 // initialize various counters
2055 foreach ($elements as $field) {
2056 $report['event_totals'][$field] = 0;
2057 }
2058
2059 while ($mailing->fetch()) {
2060 $row = array();
2061 foreach ($elements as $field) {
2062 if (isset($mailing->$field)) {
2063 $row[$field] = $mailing->$field;
2064 $report['event_totals'][$field] += $mailing->$field;
2065 }
2066 }
2067
2068 // compute open total separately to discount duplicates
2069 // CRM-1258
2070 $row['opened'] = CRM_Mailing_Event_BAO_Opened::getTotalCount($mailing_id, $mailing->id, TRUE);
2071 $report['event_totals']['opened'] += $row['opened'];
2072
2073 // compute unsub total separately to discount duplicates
2074 // CRM-1783
2075 $row['unsubscribe'] = CRM_Mailing_Event_BAO_Unsubscribe::getTotalCount($mailing_id, $mailing->id, TRUE, TRUE);
2076 $report['event_totals']['unsubscribe'] += $row['unsubscribe'];
2077
2078 $row['optout'] = CRM_Mailing_Event_BAO_Unsubscribe::getTotalCount($mailing_id, $mailing->id, TRUE, FALSE);
2079 $report['event_totals']['optout'] += $row['optout'];
2080
2081 foreach (array_keys(CRM_Mailing_BAO_MailingJob::fields()) as $field) {
2082 $row[$field] = $mailing->$field;
2083 }
2084
2085 if ($mailing->queue) {
2086 $row['delivered_rate'] = (100.0 * $mailing->delivered) / $mailing->queue;
2087 $row['bounce_rate'] = (100.0 * $mailing->bounce) / $mailing->queue;
2088 $row['unsubscribe_rate'] = (100.0 * $row['unsubscribe']) / $mailing->queue;
2089 $row['optout_rate'] = (100.0 * $row['optout']) / $mailing->queue;
2090 }
2091 else {
2092 $row['delivered_rate'] = 0;
2093 $row['bounce_rate'] = 0;
2094 $row['unsubscribe_rate'] = 0;
2095 $row['optout_rate'] = 0;
2096 }
2097
2098 $row['links'] = array(
2099 'clicks' => CRM_Utils_System::url(
2100 'civicrm/mailing/report/event',
2101 "reset=1&event=click&mid=$mailing_id&jid={$mailing->id}"
2102 ),
2103 'queue' => CRM_Utils_System::url(
2104 'civicrm/mailing/report/event',
2105 "reset=1&event=queue&mid=$mailing_id&jid={$mailing->id}"
2106 ),
2107 'delivered' => CRM_Utils_System::url(
2108 'civicrm/mailing/report/event',
2109 "reset=1&event=delivered&mid=$mailing_id&jid={$mailing->id}"
2110 ),
2111 'bounce' => CRM_Utils_System::url(
2112 'civicrm/mailing/report/event',
2113 "reset=1&event=bounce&mid=$mailing_id&jid={$mailing->id}"
2114 ),
2115 'unsubscribe' => CRM_Utils_System::url(
2116 'civicrm/mailing/report/event',
2117 "reset=1&event=unsubscribe&mid=$mailing_id&jid={$mailing->id}"
2118 ),
2119 'forward' => CRM_Utils_System::url(
2120 'civicrm/mailing/report/event',
2121 "reset=1&event=forward&mid=$mailing_id&jid={$mailing->id}"
2122 ),
2123 'reply' => CRM_Utils_System::url(
2124 'civicrm/mailing/report/event',
2125 "reset=1&event=reply&mid=$mailing_id&jid={$mailing->id}"
2126 ),
2127 'opened' => CRM_Utils_System::url(
2128 'civicrm/mailing/report/event',
2129 "reset=1&event=opened&mid=$mailing_id&jid={$mailing->id}"
2130 ),
2131 );
2132
2133 foreach (array(
2134 'scheduled_date',
2135 'start_date',
2136 'end_date',
2137 ) as $key) {
2138 $row[$key] = CRM_Utils_Date::customFormat($row[$key]);
2139 }
2140 $report['jobs'][] = $row;
2141 }
2142
2143 $newTableSize = CRM_Mailing_BAO_Recipients::mailingSize($mailing_id);
2144
2145 // we need to do this for backward compatibility, since old mailings did not
2146 // use the mailing_recipients table
2147 if ($newTableSize > 0) {
2148 $report['event_totals']['queue'] = $newTableSize;
2149 }
2150 else {
2151 $report['event_totals']['queue'] = self::getRecipientsCount($mailing_id, $mailing_id);
2152 }
2153
2154 if (!empty($report['event_totals']['queue'])) {
2155 $report['event_totals']['delivered_rate'] = (100.0 * $report['event_totals']['delivered']) / $report['event_totals']['queue'];
2156 $report['event_totals']['bounce_rate'] = (100.0 * $report['event_totals']['bounce']) / $report['event_totals']['queue'];
2157 $report['event_totals']['unsubscribe_rate'] = (100.0 * $report['event_totals']['unsubscribe']) / $report['event_totals']['queue'];
2158 $report['event_totals']['optout_rate'] = (100.0 * $report['event_totals']['optout']) / $report['event_totals']['queue'];
2159 }
2160 else {
2161 $report['event_totals']['delivered_rate'] = 0;
2162 $report['event_totals']['bounce_rate'] = 0;
2163 $report['event_totals']['unsubscribe_rate'] = 0;
2164 $report['event_totals']['optout_rate'] = 0;
2165 }
2166
2167 /* Get the click-through totals, grouped by URL */
2168
2169 $mailing->query("
2170 SELECT {$t['url']}.url,
2171 {$t['url']}.id,
2172 COUNT({$t['urlopen']}.id) as clicks,
2173 COUNT(DISTINCT {$t['queue']}.id) as unique_clicks
2174 FROM {$t['url']}
2175 LEFT JOIN {$t['urlopen']}
2176 ON {$t['urlopen']}.trackable_url_id = {$t['url']}.id
2177 LEFT JOIN {$t['queue']}
2178 ON {$t['urlopen']}.event_queue_id = {$t['queue']}.id
2179 LEFT JOIN {$t['job']}
2180 ON {$t['queue']}.job_id = {$t['job']}.id
2181 WHERE {$t['url']}.mailing_id = $mailing_id
2182 AND {$t['job']}.is_test = 0
2183 GROUP BY {$t['url']}.id");
2184
2185 $report['click_through'] = array();
2186
2187 while ($mailing->fetch()) {
2188 $report['click_through'][] = array(
2189 'url' => $mailing->url,
2190 'link' => CRM_Utils_System::url(
2191 'civicrm/mailing/report/event',
2192 "reset=1&event=click&mid=$mailing_id&uid={$mailing->id}"
2193 ),
2194 'link_unique' => CRM_Utils_System::url(
2195 'civicrm/mailing/report/event',
2196 "reset=1&event=click&mid=$mailing_id&uid={$mailing->id}&distinct=1"
2197 ),
2198 'clicks' => $mailing->clicks,
2199 'unique' => $mailing->unique_clicks,
2200 'rate' => CRM_Utils_Array::value('delivered', $report['event_totals']) ? (100.0 * $mailing->unique_clicks) / $report['event_totals']['delivered'] : 0,
2201 );
2202 }
2203
2204 $report['event_totals']['links'] = array(
2205 'clicks' => CRM_Utils_System::url(
2206 'civicrm/mailing/report/event',
2207 "reset=1&event=click&mid=$mailing_id"
2208 ),
2209 'clicks_unique' => CRM_Utils_System::url(
2210 'civicrm/mailing/report/event',
2211 "reset=1&event=click&mid=$mailing_id&distinct=1"
2212 ),
2213 'queue' => CRM_Utils_System::url(
2214 'civicrm/mailing/report/event',
2215 "reset=1&event=queue&mid=$mailing_id"
2216 ),
2217 'delivered' => CRM_Utils_System::url(
2218 'civicrm/mailing/report/event',
2219 "reset=1&event=delivered&mid=$mailing_id"
2220 ),
2221 'bounce' => CRM_Utils_System::url(
2222 'civicrm/mailing/report/event',
2223 "reset=1&event=bounce&mid=$mailing_id"
2224 ),
2225 'unsubscribe' => CRM_Utils_System::url(
2226 'civicrm/mailing/report/event',
2227 "reset=1&event=unsubscribe&mid=$mailing_id"
2228 ),
2229 'optout' => CRM_Utils_System::url(
2230 'civicrm/mailing/report/event',
2231 "reset=1&event=optout&mid=$mailing_id"
2232 ),
2233 'forward' => CRM_Utils_System::url(
2234 'civicrm/mailing/report/event',
2235 "reset=1&event=forward&mid=$mailing_id"
2236 ),
2237 'reply' => CRM_Utils_System::url(
2238 'civicrm/mailing/report/event',
2239 "reset=1&event=reply&mid=$mailing_id"
2240 ),
2241 'opened' => CRM_Utils_System::url(
2242 'civicrm/mailing/report/event',
2243 "reset=1&event=opened&mid=$mailing_id"
2244 ),
2245 );
2246
2247 $actionLinks = array(CRM_Core_Action::VIEW => array('name' => ts('Report')));
2248 if (CRM_Core_Permission::check('view all contacts')) {
2249 $actionLinks[CRM_Core_Action::ADVANCED] = array(
2250 'name' => ts('Advanced Search'),
2251 'url' => 'civicrm/contact/search/advanced',
2252 );
2253 }
2254 $action = array_sum(array_keys($actionLinks));
2255
2256 $report['event_totals']['actionlinks'] = array();
2257 foreach (array(
2258 'clicks',
2259 'clicks_unique',
2260 'queue',
2261 'delivered',
2262 'bounce',
2263 'unsubscribe',
2264 'forward',
2265 'reply',
2266 'opened',
2267 'optout',
2268 ) as $key) {
2269 $url = 'mailing/detail';
2270 $reportFilter = "reset=1&mailing_id_value={$mailing_id}";
2271 $searchFilter = "force=1&mailing_id=%%mid%%";
2272 switch ($key) {
2273 case 'delivered':
2274 $reportFilter .= "&delivery_status_value=successful";
2275 $searchFilter .= "&mailing_delivery_status=Y";
2276 break;
2277
2278 case 'bounce':
2279 $url = "mailing/bounce";
2280 $searchFilter .= "&mailing_delivery_status=N";
2281 break;
2282
2283 case 'forward':
2284 $reportFilter .= "&is_forwarded_value=1";
2285 $searchFilter .= "&mailing_forward=1";
2286 break;
2287
2288 case 'reply':
2289 $reportFilter .= "&is_replied_value=1";
2290 $searchFilter .= "&mailing_reply_status=Y";
2291 break;
2292
2293 case 'unsubscribe':
2294 $reportFilter .= "&is_unsubscribed_value=1";
2295 $searchFilter .= "&mailing_unsubscribe=1";
2296 break;
2297
2298 case 'optout':
2299 $reportFilter .= "&is_optout_value=1";
2300 $searchFilter .= "&mailing_optout=1";
2301 break;
2302
2303 case 'opened':
2304 $url = "mailing/opened";
2305 $searchFilter .= "&mailing_open_status=Y";
2306 break;
2307
2308 case 'clicks':
2309 case 'clicks_unique':
2310 $url = "mailing/clicks";
2311 $searchFilter .= "&mailing_click_status=Y";
2312 break;
2313 }
2314 $actionLinks[CRM_Core_Action::VIEW]['url'] = CRM_Report_Utils_Report::getNextUrl($url, $reportFilter, FALSE, TRUE);
2315 if (array_key_exists(CRM_Core_Action::ADVANCED, $actionLinks)) {
2316 $actionLinks[CRM_Core_Action::ADVANCED]['qs'] = $searchFilter;
2317 }
2318 $report['event_totals']['actionlinks'][$key] = CRM_Core_Action::formLink(
2319 $actionLinks,
2320 $action,
2321 array('mid' => $mailing_id),
2322 ts('more'),
2323 FALSE,
2324 'mailing.report.action',
2325 'Mailing',
2326 $mailing_id
2327 );
2328 }
2329
2330 return $report;
2331 }
2332
2333 /**
2334 * Get the count of mailings.
2335 *
2336 * @param
2337 *
2338 * @return int
2339 * Count
2340 */
2341 public function getCount() {
2342 $this->selectAdd();
2343 $this->selectAdd('COUNT(id) as count');
2344
2345 $session = CRM_Core_Session::singleton();
2346 $this->find(TRUE);
2347
2348 return $this->count;
2349 }
2350
2351 /**
2352 * @param int $id
2353 *
2354 * @throws Exception
2355 */
2356 public static function checkPermission($id) {
2357 if (!$id) {
2358 return;
2359 }
2360
2361 $mailingIDs = self::mailingACLIDs();
2362 if ($mailingIDs === TRUE) {
2363 return;
2364 }
2365
2366 if (!in_array($id, $mailingIDs)) {
2367 CRM_Core_Error::fatal(ts('You do not have permission to access this mailing report'));
2368 }
2369 }
2370
2371 /**
2372 * @param null $alias
2373 *
2374 * @return string
2375 */
2376 public static function mailingACL($alias = NULL) {
2377 $mailingACL = " ( 0 ) ";
2378
2379 $mailingIDs = self::mailingACLIDs();
2380 if ($mailingIDs === TRUE) {
2381 return " ( 1 ) ";
2382 }
2383
2384 if (!empty($mailingIDs)) {
2385 $mailingIDs = implode(',', $mailingIDs);
2386 $tableName = !$alias ? self::getTableName() : $alias;
2387 $mailingACL = " $tableName.id IN ( $mailingIDs ) ";
2388 }
2389 return $mailingACL;
2390 }
2391
2392 /**
2393 * Returns all the mailings that this user can access. This is dependent on
2394 * all the groups that the user has access to.
2395 * However since most civi installs dont use ACL's we special case the condition
2396 * where the user has access to ALL groups, and hence ALL mailings and return a
2397 * value of TRUE (to avoid the downstream where clause with a list of mailing list IDs
2398 *
2399 * @return bool|array
2400 * TRUE if the user has access to all mailings, else array of mailing IDs (possibly empty).
2401 */
2402 public static function mailingACLIDs() {
2403 // CRM-11633
2404 // optimize common case where admin has access
2405 // to all mailings
2406 if (
2407 CRM_Core_Permission::check('view all contacts') ||
2408 CRM_Core_Permission::check('edit all contacts')
2409 ) {
2410 return TRUE;
2411 }
2412
2413 $mailingIDs = array();
2414
2415 // get all the groups that this user can access
2416 // if they dont have universal access
2417 $groups = CRM_Core_PseudoConstant::group(NULL, FALSE);
2418 if (!empty($groups)) {
2419 $groupIDs = implode(',', array_keys($groups));
2420
2421 // get all the mailings that are in this subset of groups
2422 $query = "
2423 SELECT DISTINCT( m.id ) as id
2424 FROM civicrm_mailing m
2425 LEFT JOIN civicrm_mailing_group g ON g.mailing_id = m.id
2426 WHERE ( ( g.entity_table like 'civicrm_group%' AND g.entity_id IN ( $groupIDs ) )
2427 OR ( g.entity_table IS NULL AND g.entity_id IS NULL ) )
2428 ";
2429 $dao = CRM_Core_DAO::executeQuery($query);
2430
2431 $mailingIDs = array();
2432 while ($dao->fetch()) {
2433 $mailingIDs[] = $dao->id;
2434 }
2435 }
2436
2437 return $mailingIDs;
2438 }
2439
2440 /**
2441 * Get the rows for a browse operation.
2442 *
2443 * @param int $offset
2444 * The row number to start from.
2445 * @param int $rowCount
2446 * The nmber of rows to return.
2447 * @param string $sort
2448 * The sql string that describes the sort order.
2449 *
2450 * @param null $additionalClause
2451 * @param array $additionalParams
2452 *
2453 * @return array
2454 * The rows
2455 */
2456 public function &getRows($offset, $rowCount, $sort, $additionalClause = NULL, $additionalParams = NULL) {
2457 $mailing = self::getTableName();
2458 $job = CRM_Mailing_BAO_MailingJob::getTableName();
2459 $group = CRM_Mailing_DAO_MailingGroup::getTableName();
2460 $session = CRM_Core_Session::singleton();
2461
2462 $mailingACL = self::mailingACL();
2463
2464 //get all campaigns.
2465 $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
2466
2467 // we only care about parent jobs, since that holds all the info on
2468 // the mailing
2469 $query = "
2470 SELECT $mailing.id,
2471 $mailing.name,
2472 $job.status,
2473 $mailing.approval_status_id,
2474 MIN($job.scheduled_date) as scheduled_date,
2475 MIN($job.start_date) as start_date,
2476 MAX($job.end_date) as end_date,
2477 createdContact.sort_name as created_by,
2478 scheduledContact.sort_name as scheduled_by,
2479 $mailing.created_id as created_id,
2480 $mailing.scheduled_id as scheduled_id,
2481 $mailing.is_archived as archived,
2482 $mailing.created_date as created_date,
2483 campaign_id,
2484 $mailing.sms_provider_id as sms_provider_id
2485 FROM $mailing
2486 LEFT JOIN $job ON ( $job.mailing_id = $mailing.id AND $job.is_test = 0 AND $job.parent_id IS NULL )
2487 LEFT JOIN civicrm_contact createdContact ON ( civicrm_mailing.created_id = createdContact.id )
2488 LEFT JOIN civicrm_contact scheduledContact ON ( civicrm_mailing.scheduled_id = scheduledContact.id )
2489 WHERE $mailingACL $additionalClause
2490 GROUP BY $mailing.id ";
2491
2492 if ($sort) {
2493 $orderBy = trim($sort->orderBy());
2494 if (!empty($orderBy)) {
2495 $query .= " ORDER BY $orderBy";
2496 }
2497 }
2498
2499 if ($rowCount) {
2500 $offset = CRM_Utils_Type::escape($offset, 'Int');
2501 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
2502
2503 $query .= " LIMIT $offset, $rowCount ";
2504 }
2505
2506 if (!$additionalParams) {
2507 $additionalParams = array();
2508 }
2509
2510 $dao = CRM_Core_DAO::executeQuery($query, $additionalParams);
2511
2512 $rows = array();
2513 while ($dao->fetch()) {
2514 $rows[] = array(
2515 'id' => $dao->id,
2516 'name' => $dao->name,
2517 'status' => $dao->status ? $dao->status : 'Not scheduled',
2518 'created_date' => CRM_Utils_Date::customFormat($dao->created_date),
2519 'scheduled' => CRM_Utils_Date::customFormat($dao->scheduled_date),
2520 'scheduled_iso' => $dao->scheduled_date,
2521 'start' => CRM_Utils_Date::customFormat($dao->start_date),
2522 'end' => CRM_Utils_Date::customFormat($dao->end_date),
2523 'created_by' => $dao->created_by,
2524 'scheduled_by' => $dao->scheduled_by,
2525 'created_id' => $dao->created_id,
2526 'scheduled_id' => $dao->scheduled_id,
2527 'archived' => $dao->archived,
2528 'approval_status_id' => $dao->approval_status_id,
2529 'campaign_id' => $dao->campaign_id,
2530 'campaign' => empty($dao->campaign_id) ? NULL : $allCampaigns[$dao->campaign_id],
2531 'sms_provider_id' => $dao->sms_provider_id,
2532 );
2533 }
2534 return $rows;
2535 }
2536
2537 /**
2538 * Show detail Mailing report.
2539 *
2540 * @param int $id
2541 *
2542 * @return string
2543 */
2544 public static function showEmailDetails($id) {
2545 return CRM_Utils_System::url('civicrm/mailing/report', "mid=$id");
2546 }
2547
2548 /**
2549 * Delete Mails and all its associated records.
2550 *
2551 * @param int $id
2552 * Id of the mail to delete.
2553 *
2554 * @return void
2555 */
2556 public static function del($id) {
2557 if (empty($id)) {
2558 CRM_Core_Error::fatal();
2559 }
2560
2561 CRM_Utils_Hook::pre('delete', 'Mailing', $id, CRM_Core_DAO::$_nullArray);
2562
2563 // delete all file attachments
2564 CRM_Core_BAO_File::deleteEntityFile('civicrm_mailing',
2565 $id
2566 );
2567
2568 $dao = new CRM_Mailing_DAO_Mailing();
2569 $dao->id = $id;
2570 $dao->delete();
2571
2572 CRM_Core_Session::setStatus(ts('Selected mailing has been deleted.'), ts('Deleted'), 'success');
2573
2574 CRM_Utils_Hook::post('delete', 'Mailing', $id, $dao);
2575 }
2576
2577 /**
2578 * Delete Jobss and all its associated records
2579 * related to test Mailings
2580 *
2581 * @param int $id
2582 * Id of the Job to delete.
2583 *
2584 * @return void
2585 */
2586 public static function delJob($id) {
2587 if (empty($id)) {
2588 CRM_Core_Error::fatal();
2589 }
2590
2591 $dao = new CRM_Mailing_BAO_MailingJob();
2592 $dao->id = $id;
2593 $dao->delete();
2594 }
2595
2596 /**
2597 * @return array
2598 */
2599 public function getReturnProperties() {
2600 $tokens = &$this->getTokens();
2601
2602 $properties = array();
2603 if (isset($tokens['html']) &&
2604 isset($tokens['html']['contact'])
2605 ) {
2606 $properties = array_merge($properties, $tokens['html']['contact']);
2607 }
2608
2609 if (isset($tokens['text']) &&
2610 isset($tokens['text']['contact'])
2611 ) {
2612 $properties = array_merge($properties, $tokens['text']['contact']);
2613 }
2614
2615 if (isset($tokens['subject']) &&
2616 isset($tokens['subject']['contact'])
2617 ) {
2618 $properties = array_merge($properties, $tokens['subject']['contact']);
2619 }
2620
2621 $returnProperties = array();
2622 $returnProperties['display_name'] = $returnProperties['contact_id'] = $returnProperties['preferred_mail_format'] = $returnProperties['hash'] = 1;
2623
2624 foreach ($properties as $p) {
2625 $returnProperties[$p] = 1;
2626 }
2627
2628 return $returnProperties;
2629 }
2630
2631 /**
2632 * Build the compose mail form.
2633 *
2634 * @param CRM_Core_Form $form
2635 *
2636 * @return void
2637 */
2638 public static function commonCompose(&$form) {
2639 //get the tokens.
2640 $tokens = CRM_Core_SelectValues::contactTokens();
2641
2642 $className = CRM_Utils_System::getClassName($form);
2643 if ($className == 'CRM_Mailing_Form_Upload') {
2644 $tokens = array_merge(CRM_Core_SelectValues::mailingTokens(), $tokens);
2645 }
2646 elseif ($className == 'CRM_Admin_Form_ScheduleReminders') {
2647 $tokens = array_merge(CRM_Core_SelectValues::activityTokens(), $tokens);
2648 $tokens = array_merge(CRM_Core_SelectValues::eventTokens(), $tokens);
2649 $tokens = array_merge(CRM_Core_SelectValues::membershipTokens(), $tokens);
2650 }
2651 elseif ($className == 'CRM_Event_Form_ManageEvent_ScheduleReminders') {
2652 $tokens = array_merge(CRM_Core_SelectValues::eventTokens(), $tokens);
2653 }
2654
2655 //sorted in ascending order tokens by ignoring word case
2656 $form->assign('tokens', CRM_Utils_Token::formatTokensForDisplay($tokens));
2657
2658 $templates = array();
2659
2660 $textFields = array('text_message' => ts('HTML Format'), 'sms_text_message' => ts('SMS Message'));
2661 $modePrefixes = array('Mail' => NULL, 'SMS' => 'SMS');
2662
2663 if ($className != 'CRM_SMS_Form_Upload' && $className != 'CRM_Contact_Form_Task_SMS' &&
2664 $className != 'CRM_Contact_Form_Task_SMS'
2665 ) {
2666 $form->addWysiwyg('html_message',
2667 ts('HTML Format'),
2668 array(
2669 'cols' => '80',
2670 'rows' => '8',
2671 'onkeyup' => "return verify(this)",
2672 )
2673 );
2674
2675 if ($className != 'CRM_Admin_Form_ScheduleReminders') {
2676 unset($modePrefixes['SMS']);
2677 }
2678 }
2679 else {
2680 unset($textFields['text_message']);
2681 unset($modePrefixes['Mail']);
2682 }
2683
2684 //insert message Text by selecting "Select Template option"
2685 foreach ($textFields as $id => $label) {
2686 $prefix = NULL;
2687 if ($id == 'sms_text_message') {
2688 $prefix = "SMS";
2689 $form->assign('max_sms_length', CRM_SMS_Provider::MAX_SMS_CHAR);
2690 }
2691 $form->add('textarea', $id, $label,
2692 array(
2693 'cols' => '80',
2694 'rows' => '8',
2695 'onkeyup' => "return verify(this, '{$prefix}')",
2696 )
2697 );
2698 }
2699
2700 foreach ($modePrefixes as $prefix) {
2701 if ($prefix == 'SMS') {
2702 $templates[$prefix] = CRM_Core_BAO_MessageTemplate::getMessageTemplates(FALSE, TRUE);
2703 }
2704 else {
2705 $templates[$prefix] = CRM_Core_BAO_MessageTemplate::getMessageTemplates(FALSE);
2706 }
2707
2708 if (!empty($templates[$prefix])) {
2709 $form->assign('templates', TRUE);
2710
2711 $form->add('select', "{$prefix}template", ts('Use Template'),
2712 array('' => ts('- select -')) + $templates[$prefix], FALSE,
2713 array('onChange' => "selectValue( this.value, '{$prefix}');")
2714 );
2715 }
2716 $form->add('checkbox', "{$prefix}updateTemplate", ts('Update Template'), NULL);
2717
2718 $form->add('checkbox', "{$prefix}saveTemplate", ts('Save As New Template'), NULL, FALSE,
2719 array('onclick' => "showSaveDetails(this, '{$prefix}');")
2720 );
2721 $form->add('text', "{$prefix}saveTemplateName", ts('Template Title'));
2722 }
2723 }
2724
2725 /**
2726 * Build the compose PDF letter form.
2727 *
2728 * @param CRM_Core_Form $form
2729 *
2730 * @return void
2731 */
2732 public static function commonLetterCompose(&$form) {
2733 //get the tokens.
2734 $tokens = CRM_Core_SelectValues::contactTokens();
2735 if (CRM_Utils_System::getClassName($form) == 'CRM_Mailing_Form_Upload') {
2736 $tokens = array_merge(CRM_Core_SelectValues::mailingTokens(), $tokens);
2737 }
2738 //@todo move this fn onto the form
2739 if (CRM_Utils_System::getClassName($form) == 'CRM_Contribute_Form_Task_PDFLetter') {
2740 $tokens = array_merge(CRM_Core_SelectValues::contributionTokens(), $tokens);
2741 }
2742
2743 if (method_exists($form, 'listTokens')) {
2744 $tokens = array_merge($form->listTokens(), $tokens);
2745 }
2746
2747 $form->assign('tokens', CRM_Utils_Token::formatTokensForDisplay($tokens));
2748
2749 $form->_templates = CRM_Core_BAO_MessageTemplate::getMessageTemplates(FALSE);
2750 if (!empty($form->_templates)) {
2751 $form->assign('templates', TRUE);
2752 $form->add('select', 'template', ts('Select Template'),
2753 array(
2754 '' => ts('- select -'),
2755 ) + $form->_templates, FALSE,
2756 array('onChange' => "selectValue( this.value,'' );")
2757 );
2758 $form->add('checkbox', 'updateTemplate', ts('Update Template'), NULL);
2759 }
2760
2761 $form->add('checkbox', 'saveTemplate', ts('Save As New Template'), NULL, FALSE,
2762 array('onclick' => "showSaveDetails(this);")
2763 );
2764 $form->add('text', 'saveTemplateName', ts('Template Title'));
2765
2766 $form->addWysiwyg('html_message',
2767 ts('Your Letter'),
2768 array(
2769 'cols' => '80',
2770 'rows' => '8',
2771 'onkeyup' => "return verify(this)",
2772 )
2773 );
2774 $action = CRM_Utils_Request::retrieve('action', 'String', $form, FALSE);
2775 if ((CRM_Utils_System::getClassName($form) == 'CRM_Contact_Form_Task_PDF') &&
2776 $action == CRM_Core_Action::VIEW
2777 ) {
2778 $form->freeze('html_message');
2779 }
2780 }
2781
2782 /**
2783 * Get the search based mailing Ids.
2784 *
2785 * @return array
2786 * , searched base mailing ids.
2787 */
2788 public function searchMailingIDs() {
2789 $group = CRM_Mailing_DAO_MailingGroup::getTableName();
2790 $mailing = self::getTableName();
2791
2792 $query = "
2793 SELECT $mailing.id as mailing_id
2794 FROM $mailing, $group
2795 WHERE $group.mailing_id = $mailing.id
2796 AND $group.group_type = 'Base'";
2797
2798 $searchDAO = CRM_Core_DAO::executeQuery($query);
2799 $mailingIDs = array();
2800 while ($searchDAO->fetch()) {
2801 $mailingIDs[] = $searchDAO->mailing_id;
2802 }
2803
2804 return $mailingIDs;
2805 }
2806
2807 /**
2808 * Get the content/components of mailing based on mailing Id
2809 *
2810 * @param array $report
2811 * of mailing report.
2812 *
2813 * @param $form
2814 * Reference of this.
2815 *
2816 * @param bool $isSMS
2817 *
2818 * @return array
2819 * array content/component.
2820 */
2821 public static function getMailingContent(&$report, &$form, $isSMS = FALSE) {
2822 $htmlHeader = $textHeader = NULL;
2823 $htmlFooter = $textFooter = NULL;
2824
2825 if (!$isSMS) {
2826 if ($report['mailing']['header_id']) {
2827 $header = new CRM_Mailing_BAO_Component();
2828 $header->id = $report['mailing']['header_id'];
2829 $header->find(TRUE);
2830 $htmlHeader = $header->body_html;
2831 $textHeader = $header->body_text;
2832 }
2833
2834 if ($report['mailing']['footer_id']) {
2835 $footer = new CRM_Mailing_BAO_Component();
2836 $footer->id = $report['mailing']['footer_id'];
2837 $footer->find(TRUE);
2838 $htmlFooter = $footer->body_html;
2839 $textFooter = $footer->body_text;
2840 }
2841 }
2842
2843 $mailingKey = $form->_mailing_id;
2844 if (!$isSMS) {
2845 if ($hash = CRM_Mailing_BAO_Mailing::getMailingHash($mailingKey)) {
2846 $mailingKey = $hash;
2847 }
2848 }
2849
2850 if (!empty($report['mailing']['body_text'])) {
2851 $url = CRM_Utils_System::url('civicrm/mailing/view', 'reset=1&text=1&id=' . $mailingKey);
2852 $form->assign('textViewURL', $url);
2853 }
2854
2855 if (!$isSMS) {
2856 if (!empty($report['mailing']['body_html'])) {
2857 $url = CRM_Utils_System::url('civicrm/mailing/view', 'reset=1&id=' . $mailingKey);
2858 $form->assign('htmlViewURL', $url);
2859 }
2860 }
2861
2862 if (!$isSMS) {
2863 $report['mailing']['attachment'] = CRM_Core_BAO_File::attachmentInfo('civicrm_mailing', $form->_mailing_id);
2864 }
2865 return $report;
2866 }
2867
2868 /**
2869 * @param int $jobID
2870 *
2871 * @return mixed
2872 */
2873 public static function overrideVerp($jobID) {
2874 static $_cache = array();
2875
2876 if (!isset($_cache[$jobID])) {
2877 $query = "
2878 SELECT override_verp
2879 FROM civicrm_mailing
2880 INNER JOIN civicrm_mailing_job ON civicrm_mailing.id = civicrm_mailing_job.mailing_id
2881 WHERE civicrm_mailing_job.id = %1
2882 ";
2883 $params = array(1 => array($jobID, 'Integer'));
2884 $_cache[$jobID] = CRM_Core_DAO::singleValueQuery($query, $params);
2885 }
2886 return $_cache[$jobID];
2887 }
2888
2889 /**
2890 * @param null $mode
2891 *
2892 * @return bool
2893 * @throws Exception
2894 */
2895 public static function processQueue($mode = NULL) {
2896 $config = &CRM_Core_Config::singleton();
2897
2898 if ($mode == NULL && CRM_Core_BAO_MailSettings::defaultDomain() == "EXAMPLE.ORG") {
2899 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(
2900 1 => CRM_Utils_System::url('civicrm/admin/mailSettings', 'reset=1'),
2901 2 => "http://book.civicrm.org/user/advanced-configuration/email-system-configuration/",
2902 )));
2903 }
2904
2905 // check if we are enforcing number of parallel cron jobs
2906 // CRM-8460
2907 $gotCronLock = FALSE;
2908
2909 if (property_exists($config, 'mailerJobsMax') && $config->mailerJobsMax && $config->mailerJobsMax > 1) {
2910 $lockArray = range(1, $config->mailerJobsMax);
2911 shuffle($lockArray);
2912
2913 // check if we are using global locks
2914 $serverWideLock = CRM_Core_BAO_Setting::getItem(
2915 CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
2916 'civimail_server_wide_lock'
2917 );
2918 foreach ($lockArray as $lockID) {
2919 $cronLock = new CRM_Core_Lock("civimail.cronjob.{$lockID}", NULL, $serverWideLock);
2920 if ($cronLock->isAcquired()) {
2921 $gotCronLock = TRUE;
2922 break;
2923 }
2924 }
2925
2926 // exit here since we have enuf cronjobs running
2927 if (!$gotCronLock) {
2928 CRM_Core_Error::debug_log_message('Returning early, since max number of cronjobs running');
2929 return TRUE;
2930 }
2931 }
2932
2933 // load bootstrap to call hooks
2934
2935 // Split up the parent jobs into multiple child jobs
2936 $mailerJobSize = (property_exists($config, 'mailerJobSize')) ? $config->mailerJobSize : NULL;
2937 CRM_Mailing_BAO_MailingJob::runJobs_pre($mailerJobSize, $mode);
2938 CRM_Mailing_BAO_MailingJob::runJobs(NULL, $mode);
2939 CRM_Mailing_BAO_MailingJob::runJobs_post($mode);
2940
2941 // lets release the global cron lock if we do have one
2942 if ($gotCronLock) {
2943 $cronLock->release();
2944 }
2945
2946 return TRUE;
2947 }
2948
2949 /**
2950 * @param int $mailingID
2951 */
2952 private static function addMultipleEmails($mailingID) {
2953 $sql = "
2954 INSERT INTO civicrm_mailing_recipients
2955 (mailing_id, email_id, contact_id)
2956 SELECT %1, e.id, e.contact_id FROM civicrm_email e
2957 WHERE e.on_hold = 0
2958 AND e.is_bulkmail = 1
2959 AND e.contact_id IN
2960 ( SELECT contact_id FROM civicrm_mailing_recipients mr WHERE mailing_id = %1 )
2961 AND e.id NOT IN ( SELECT email_id FROM civicrm_mailing_recipients mr WHERE mailing_id = %1 )
2962 ";
2963 $params = array(1 => array($mailingID, 'Integer'));
2964
2965 $dao = CRM_Core_DAO::executeQuery($sql, $params);
2966 }
2967
2968 /**
2969 * @param bool $isSMS
2970 *
2971 * @return mixed
2972 */
2973 public static function getMailingsList($isSMS = FALSE) {
2974 static $list = array();
2975 $where = " WHERE ";
2976 if (!$isSMS) {
2977 $where .= " civicrm_mailing.sms_provider_id IS NULL ";
2978 }
2979 else {
2980 $where .= " civicrm_mailing.sms_provider_id IS NOT NULL ";
2981 }
2982
2983 if (empty($list)) {
2984 $query = "
2985 SELECT civicrm_mailing.id, civicrm_mailing.name, civicrm_mailing_job.end_date
2986 FROM civicrm_mailing
2987 INNER JOIN civicrm_mailing_job ON civicrm_mailing.id = civicrm_mailing_job.mailing_id {$where}
2988 ORDER BY civicrm_mailing.name";
2989 $mailing = CRM_Core_DAO::executeQuery($query);
2990
2991 while ($mailing->fetch()) {
2992 $list[$mailing->id] = "{$mailing->name} :: {$mailing->end_date}";
2993 }
2994 }
2995
2996 return $list;
2997 }
2998
2999 /**
3000 * @param int $mid
3001 *
3002 * @return null|string
3003 */
3004 public static function hiddenMailingGroup($mid) {
3005 $sql = "
3006 SELECT g.id
3007 FROM civicrm_mailing m
3008 INNER JOIN civicrm_mailing_group mg ON mg.mailing_id = m.id
3009 INNER JOIN civicrm_group g ON mg.entity_id = g.id AND mg.entity_table = 'civicrm_group'
3010 WHERE g.is_hidden = 1
3011 AND mg.group_type = 'Include'
3012 AND m.id = %1
3013 ";
3014 $params = array(1 => array($mid, 'Integer'));
3015 return CRM_Core_DAO::singleValueQuery($sql, $params);
3016 }
3017
3018 /**
3019 * wrapper for ajax activity selector.
3020 *
3021 * @param array $params
3022 * Associated array for params record id.
3023 *
3024 * @return array
3025 * associated array of contact activities
3026 */
3027 public static function getContactMailingSelector(&$params) {
3028 // format the params
3029 $params['offset'] = ($params['page'] - 1) * $params['rp'];
3030 $params['rowCount'] = $params['rp'];
3031 $params['sort'] = CRM_Utils_Array::value('sortBy', $params);
3032 $params['caseId'] = NULL;
3033
3034 // get contact mailings
3035 $mailings = CRM_Mailing_BAO_Mailing::getContactMailings($params);
3036
3037 // add total
3038 $params['total'] = CRM_Mailing_BAO_Mailing::getContactMailingsCount($params);
3039
3040 //CRM-12814
3041 if (!empty($mailings)) {
3042 $openCounts = CRM_Mailing_Event_BAO_Opened::getMailingContactCount(array_keys($mailings), $params['contact_id']);
3043 $clickCounts = CRM_Mailing_Event_BAO_TrackableURLOpen::getMailingContactCount(array_keys($mailings), $params['contact_id']);
3044 }
3045
3046 // format params and add links
3047 $contactMailings = array();
3048 foreach ($mailings as $mailingId => $values) {
3049 $contactMailings[$mailingId]['subject'] = $values['subject'];
3050 $contactMailings[$mailingId]['start_date'] = CRM_Utils_Date::customFormat($values['start_date']);
3051 $contactMailings[$mailingId]['recipients'] = CRM_Utils_System::href(ts('(recipients)'), 'civicrm/mailing/report/event',
3052 "mid={$values['mailing_id']}&reset=1&cid={$params['contact_id']}&event=queue&context=mailing");
3053
3054 $contactMailings[$mailingId]['mailing_creator'] = CRM_Utils_System::href(
3055 $values['creator_name'],
3056 'civicrm/contact/view',
3057 "reset=1&cid={$values['creator_id']}");
3058
3059 //CRM-12814
3060 $contactMailings[$mailingId]['openstats'] = "Opens: " .
3061 CRM_Utils_Array::value($values['mailing_id'], $openCounts, 0) .
3062 "<br />Clicks: " .
3063 CRM_Utils_Array::value($values['mailing_id'], $clickCounts, 0);
3064
3065 $actionLinks = array(
3066 CRM_Core_Action::VIEW => array(
3067 'name' => ts('View'),
3068 'url' => 'civicrm/mailing/view',
3069 'qs' => "reset=1&id=%%mkey%%",
3070 'title' => ts('View Mailing'),
3071 'class' => 'crm-popup',
3072 ),
3073 CRM_Core_Action::BROWSE => array(
3074 'name' => ts('Mailing Report'),
3075 'url' => 'civicrm/mailing/report',
3076 'qs' => "mid=%%mid%%&reset=1&cid=%%cid%%&context=mailing",
3077 'title' => ts('View Mailing Report'),
3078 ),
3079 );
3080
3081 $mailingKey = $values['mailing_id'];
3082 if ($hash = CRM_Mailing_BAO_Mailing::getMailingHash($mailingKey)) {
3083 $mailingKey = $hash;
3084 }
3085
3086 $contactMailings[$mailingId]['links'] = CRM_Core_Action::formLink(
3087 $actionLinks,
3088 NULL,
3089 array(
3090 'mid' => $values['mailing_id'],
3091 'cid' => $params['contact_id'],
3092 'mkey' => $mailingKey,
3093 ),
3094 ts('more'),
3095 FALSE,
3096 'mailing.contact.action',
3097 'Mailing',
3098 $values['mailing_id']
3099 );
3100 }
3101
3102 return $contactMailings;
3103 }
3104
3105 /**
3106 * Retrieve contact mailing.
3107 *
3108 * @param array $params
3109 *
3110 * @return array
3111 * Array of mailings for a contact
3112 *
3113 */
3114 static public function getContactMailings(&$params) {
3115 $params['version'] = 3;
3116 $params['offset'] = ($params['page'] - 1) * $params['rp'];
3117 $params['limit'] = $params['rp'];
3118 $params['sort'] = CRM_Utils_Array::value('sortBy', $params);
3119
3120 $result = civicrm_api('MailingContact', 'get', $params);
3121 return $result['values'];
3122 }
3123
3124 /**
3125 * Retrieve contact mailing count.
3126 *
3127 * @param array $params
3128 *
3129 * @return int
3130 * count of mailings for a contact
3131 *
3132 */
3133 static public function getContactMailingsCount(&$params) {
3134 $params['version'] = 3;
3135 return civicrm_api('MailingContact', 'getcount', $params);
3136 }
3137
3138 /**
3139 * Get a list of permissions required for CRUD'ing each field
3140 * (when workflow is enabled).
3141 *
3142 * @return array
3143 * Array (string $fieldName => string $permName)
3144 */
3145 public static function getWorkflowFieldPerms() {
3146 $fieldNames = array_keys(CRM_Mailing_DAO_Mailing::fields());
3147 $fieldPerms = array();
3148 foreach ($fieldNames as $fieldName) {
3149 if ($fieldName == 'id') {
3150 $fieldPerms[$fieldName] = array(
3151 array('access CiviMail', 'schedule mailings', 'approve mailings', 'create mailings'), // OR
3152 );
3153 }
3154 elseif (in_array($fieldName, array('scheduled_date', 'scheduled_id'))) {
3155 $fieldPerms[$fieldName] = array(
3156 array('access CiviMail', 'schedule mailings'), // OR
3157 );
3158 }
3159 elseif (in_array($fieldName, array('approval_date', 'approver_id', 'approval_status_id', 'approval_note'))) {
3160 $fieldPerms[$fieldName] = array(
3161 array('access CiviMail', 'approve mailings'), // OR
3162 );
3163 }
3164 else {
3165 $fieldPerms[$fieldName] = array(
3166 array('access CiviMail', 'create mailings'), // OR
3167 );
3168 }
3169 }
3170 return $fieldPerms;
3171 }
3172
3173 }