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