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