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