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