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