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