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