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