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