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