Merge pull request #15824 from mfb/email-search-speed-boost
[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 $this->templates['mailingID'] = $this->id;
693 CRM_Utils_Hook::alterMailContent($this->templates);
694 }
695 return $this->templates;
696 }
697
698 /**
699 *
700 * Retrieve a ref to an array that holds all of the tokens in the email body
701 * where the keys are the type of token and the values are ordinal arrays
702 * that hold the token names (even repeated tokens) in the order in which
703 * they appear in the body of the email.
704 *
705 * note: the real work is done in the _getTokens() function
706 *
707 * this function needs to have some sort of a body assigned
708 * either text or html for this to have any meaningful impact
709 *
710 * @return array
711 * reference to an assoc array
712 */
713 public function &getTokens() {
714 if (!$this->tokens) {
715
716 $this->tokens = ['html' => [], 'text' => [], 'subject' => []];
717
718 if ($this->body_html) {
719 $this->_getTokens('html');
720 if (!$this->body_text) {
721 // Since the text template was created from html, use the html tokens.
722 // @see CRM_Mailing_BAO_Mailing::getTemplates()
723 $this->tokens['text'] = $this->tokens['html'];
724 }
725 }
726
727 if ($this->body_text) {
728 $this->_getTokens('text');
729 }
730
731 if ($this->subject) {
732 $this->_getTokens('subject');
733 }
734 }
735
736 return $this->tokens;
737 }
738
739 /**
740 * Returns the token set for all 3 parts as one set. This allows it to be sent to the
741 * hook in one call and standardizes it across other token workflows
742 *
743 * @return array
744 * reference to an assoc array
745 */
746 public function &getFlattenedTokens() {
747 if (!$this->flattenedTokens) {
748 $tokens = $this->getTokens();
749
750 $this->flattenedTokens = CRM_Utils_Token::flattenTokens($tokens);
751 }
752
753 return $this->flattenedTokens;
754 }
755
756 /**
757 *
758 * _getTokens parses out all of the tokens that have been
759 * included in the html and text bodies of the email
760 * we get the tokens and then separate them into an
761 * internal structure named tokens that has the same
762 * form as the static tokens property(?) of the CRM_Utils_Token class.
763 * The difference is that there might be repeated token names as we want the
764 * structures to represent the order in which tokens were found from left to right, top to bottom.
765 *
766 *
767 * @param string $prop name of the property that holds the text that we want to scan for tokens (html, text).
768 * Name of the property that holds the text that we want to scan for tokens (html, text).
769 *
770 * @return void
771 */
772 private function _getTokens($prop) {
773 $templates = $this->getTemplates();
774
775 $newTokens = CRM_Utils_Token::getTokens($templates[$prop]);
776
777 foreach ($newTokens as $type => $names) {
778 if (!isset($this->tokens[$prop][$type])) {
779 $this->tokens[$prop][$type] = [];
780 }
781 foreach ($names as $key => $name) {
782 $this->tokens[$prop][$type][] = $name;
783 }
784 }
785 }
786
787 /**
788 * Generate an event queue for a test job.
789 *
790 * @param array $testParams
791 * Contains form values.
792 *
793 * @return void
794 */
795 public function getTestRecipients($testParams) {
796 if (!empty($testParams['test_group']) && array_key_exists($testParams['test_group'], CRM_Core_PseudoConstant::group())) {
797 $contacts = civicrm_api('contact', 'get', [
798 'version' => 3,
799 'group' => $testParams['test_group'],
800 'return' => 'id',
801 'options' => [
802 'limit' => 100000000000,
803 ],
804 ]);
805
806 foreach (array_keys($contacts['values']) as $groupContact) {
807 $query = "
808 SELECT civicrm_email.id AS email_id,
809 civicrm_email.is_primary as is_primary,
810 civicrm_email.is_bulkmail as is_bulkmail
811 FROM civicrm_email
812 INNER JOIN civicrm_contact ON civicrm_email.contact_id = civicrm_contact.id
813 WHERE (civicrm_email.is_bulkmail = 1 OR civicrm_email.is_primary = 1)
814 AND civicrm_contact.id = {$groupContact}
815 AND civicrm_contact.do_not_email = 0
816 AND civicrm_contact.is_deceased <> 1
817 AND civicrm_email.on_hold = 0
818 AND civicrm_contact.is_opt_out = 0
819 GROUP BY civicrm_email.id
820 ORDER BY civicrm_email.is_bulkmail DESC
821 ";
822 $dao = CRM_Core_DAO::executeQuery($query);
823 if ($dao->fetch()) {
824 $params = [
825 'job_id' => $testParams['job_id'],
826 'email_id' => $dao->email_id,
827 'contact_id' => $groupContact,
828 ];
829 CRM_Mailing_Event_BAO_Queue::create($params);
830 }
831 }
832 }
833 }
834
835 /**
836 * Load this->header and this->footer.
837 */
838 private function getHeaderFooter() {
839 if (!$this->header and $this->header_id) {
840 $this->header = new CRM_Mailing_BAO_MailingComponent();
841 $this->header->id = $this->header_id;
842 $this->header->find(TRUE);
843 }
844
845 if (!$this->footer and $this->footer_id) {
846 $this->footer = new CRM_Mailing_BAO_MailingComponent();
847 $this->footer->id = $this->footer_id;
848 $this->footer->find(TRUE);
849 }
850 }
851
852 /**
853 * Given and array of headers and a prefix, job ID, event queue ID, and hash,
854 * add a Message-ID header if needed.
855 *
856 * i.e. if the global includeMessageId is set and there isn't already a
857 * Message-ID in the array.
858 * The message ID is structured the same way as a verp. However no interpretation
859 * is placed on the values received, so they do not need to follow the verp
860 * convention.
861 *
862 * @param array $headers
863 * Array of message headers to update, in-out.
864 * @param string $prefix
865 * Prefix for the message ID, use same prefixes as verp.
866 * wherever possible
867 * @param string $job_id
868 * Job ID component of the generated message ID.
869 * @param string $event_queue_id
870 * Event Queue ID component of the generated message ID.
871 * @param string $hash
872 * Hash component of the generated message ID.
873 *
874 * @return void
875 */
876 public static function addMessageIdHeader(&$headers, $prefix, $job_id, $event_queue_id, $hash) {
877 $config = CRM_Core_Config::singleton();
878 $localpart = CRM_Core_BAO_MailSettings::defaultLocalpart();
879 $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
880 $includeMessageId = CRM_Core_BAO_MailSettings::includeMessageId();
881 $fields = [];
882 $fields[] = 'Message-ID';
883 // CRM-17754 check if Resent-Message-id is set also if not add it in when re-laying reply email
884 if ($prefix == 'r') {
885 $fields[] = 'Resent-Message-ID';
886 }
887 foreach ($fields as $field) {
888 if ($includeMessageId && (!array_key_exists($field, $headers))) {
889 $headers[$field] = '<' . implode($config->verpSeparator,
890 [
891 $localpart . $prefix,
892 $job_id,
893 $event_queue_id,
894 $hash,
895 ]
896 ) . "@{$emailDomain}>";
897 }
898 }
899
900 }
901
902 /**
903 * Static wrapper for getting verp and urls.
904 *
905 * @param int $job_id
906 * ID of the Job associated with this message.
907 * @param int $event_queue_id
908 * ID of the EventQueue.
909 * @param string $hash
910 * Hash of the EventQueue.
911 * @param string $email
912 * Destination address.
913 *
914 * @return array
915 * (reference) array array ref that hold array refs to the verp info and urls
916 */
917 public static function getVerpAndUrls($job_id, $event_queue_id, $hash, $email) {
918 // create a skeleton object and set its properties that are required by getVerpAndUrlsAndHeaders()
919 $config = CRM_Core_Config::singleton();
920 $bao = new CRM_Mailing_BAO_Mailing();
921 $bao->_domain = CRM_Core_BAO_Domain::getDomain();
922 $bao->from_name = $bao->from_email = $bao->subject = '';
923
924 // use $bao's instance method to get verp and urls
925 list($verp, $urls, $_) = $bao->getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email);
926 return [$verp, $urls];
927 }
928
929 /**
930 * Get verp, urls and headers
931 *
932 * @param int $job_id
933 * ID of the Job associated with this message.
934 * @param int $event_queue_id
935 * ID of the EventQueue.
936 * @param string $hash
937 * Hash of the EventQueue.
938 * @param string $email
939 * Destination address.
940 *
941 * @param bool $isForward
942 *
943 * @return array
944 * array ref that hold array refs to the verp info, urls, and headers
945 */
946 public function getVerpAndUrlsAndHeaders($job_id, $event_queue_id, $hash, $email, $isForward = FALSE) {
947 $config = CRM_Core_Config::singleton();
948
949 /**
950 * Inbound VERP keys:
951 * reply: user replied to mailing
952 * bounce: email address bounced
953 * unsubscribe: contact opts out of all target lists for the mailing
954 * resubscribe: contact opts back into all target lists for the mailing
955 * optOut: contact unsubscribes from the domain
956 */
957 $verp = [];
958 $verpTokens = [
959 'reply' => 'r',
960 'bounce' => 'b',
961 'unsubscribe' => 'u',
962 'resubscribe' => 'e',
963 'optOut' => 'o',
964 ];
965
966 $localpart = CRM_Core_BAO_MailSettings::defaultLocalpart();
967 $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
968 // 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
969 if (empty($emailDomain)) {
970 CRM_Core_Error::debug_log_message('Error setting verp parameters, defaultDomain is NULL. Did you configure the bounce processing account for this domain?');
971 }
972
973 foreach ($verpTokens as $key => $value) {
974 $verp[$key] = implode($config->verpSeparator,
975 [
976 $localpart . $value,
977 $job_id,
978 $event_queue_id,
979 $hash,
980 ]
981 ) . "@$emailDomain";
982 }
983
984 //handle should override VERP address.
985 $skipEncode = FALSE;
986
987 if ($job_id &&
988 self::overrideVerp($job_id)
989 ) {
990 $verp['reply'] = "\"{$this->from_name}\" <{$this->from_email}>";
991 }
992
993 $urls = [
994 'forward' => CRM_Utils_System::url('civicrm/mailing/forward', "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}", TRUE, NULL, TRUE, TRUE),
995 'unsubscribeUrl' => CRM_Utils_System::url('civicrm/mailing/unsubscribe', "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}", TRUE, NULL, TRUE, TRUE),
996 'resubscribeUrl' => CRM_Utils_System::url('civicrm/mailing/resubscribe', "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}", TRUE, NULL, TRUE, TRUE),
997 'optOutUrl' => CRM_Utils_System::url('civicrm/mailing/optout', "reset=1&jid={$job_id}&qid={$event_queue_id}&h={$hash}", TRUE, NULL, TRUE, TRUE),
998 'subscribeUrl' => CRM_Utils_System::url('civicrm/mailing/subscribe', 'reset=1', TRUE, NULL, TRUE, TRUE),
999 ];
1000
1001 $headers = [
1002 'Reply-To' => $verp['reply'],
1003 'Return-Path' => $verp['bounce'],
1004 'From' => "\"{$this->from_name}\" <{$this->from_email}>",
1005 'Subject' => $this->subject,
1006 'List-Unsubscribe' => "<mailto:{$verp['unsubscribe']}>",
1007 ];
1008 self::addMessageIdHeader($headers, 'm', $job_id, $event_queue_id, $hash);
1009 if ($isForward) {
1010 $headers['Subject'] = "[Fwd:{$this->subject}]";
1011 }
1012 return [&$verp, &$urls, &$headers];
1013 }
1014
1015 /**
1016 * Compose a message.
1017 *
1018 * @deprecated
1019 * This is used by CiviMail but will be made redundant by FlexMailer/TokenProcessor.
1020 * @param int $job_id
1021 * ID of the Job associated with this message.
1022 * @param int $event_queue_id
1023 * ID of the EventQueue.
1024 * @param string $hash
1025 * Hash of the EventQueue.
1026 * @param string $contactId
1027 * ID of the Contact.
1028 * @param string $email
1029 * Destination address.
1030 * @param string $recipient
1031 * To: of the recipient.
1032 * @param bool $test
1033 * Is this mailing a test?.
1034 * @param $contactDetails
1035 * @param $attachments
1036 * @param bool $isForward
1037 * Is this mailing compose for forward?.
1038 * @param string $fromEmail
1039 * Email address of who is forwardinf it.
1040 *
1041 * @param null $replyToEmail
1042 *
1043 * @return Mail_mime The mail object
1044 */
1045 public function compose(
1046 $job_id, $event_queue_id, $hash, $contactId,
1047 $email, &$recipient, $test,
1048 $contactDetails, &$attachments, $isForward = FALSE,
1049 $fromEmail = NULL, $replyToEmail = NULL
1050 ) {
1051 $config = CRM_Core_Config::singleton();
1052 $this->getTokens();
1053
1054 if ($this->_domain == NULL) {
1055 $this->_domain = CRM_Core_BAO_Domain::getDomain();
1056 }
1057
1058 list($verp, $urls, $headers) = $this->getVerpAndUrlsAndHeaders(
1059 $job_id,
1060 $event_queue_id,
1061 $hash,
1062 $email,
1063 $isForward
1064 );
1065
1066 //set from email who is forwarding it and not original one.
1067 if ($fromEmail) {
1068 unset($headers['From']);
1069 $headers['From'] = "<{$fromEmail}>";
1070 }
1071
1072 if ($replyToEmail && ($fromEmail != $replyToEmail)) {
1073 $headers['Reply-To'] = "{$replyToEmail}";
1074 }
1075
1076 if ($contactDetails) {
1077 $contact = $contactDetails;
1078 }
1079 elseif ($contactId === 0) {
1080 //anonymous user
1081 $contact = [];
1082 CRM_Utils_Hook::tokenValues($contact, $contactId, $job_id);
1083 }
1084 else {
1085 $params = [['contact_id', '=', $contactId, 0, 0]];
1086 list($contact) = CRM_Contact_BAO_Query::apiQuery($params);
1087
1088 //CRM-4524
1089 $contact = reset($contact);
1090
1091 if (!$contact || is_a($contact, 'CRM_Core_Error')) {
1092 CRM_Core_Error::debug_log_message(ts('CiviMail will not send email to a non-existent contact: %1',
1093 [1 => $contactId]
1094 ));
1095 // setting this because function is called by reference
1096 //@todo test not calling function by reference
1097 $res = NULL;
1098 return $res;
1099 }
1100
1101 // also call the hook to get contact details
1102 CRM_Utils_Hook::tokenValues($contact, $contactId, $job_id);
1103 }
1104
1105 $pTemplates = $this->getPreparedTemplates();
1106 $pEmails = [];
1107
1108 foreach ($pTemplates as $type => $pTemplate) {
1109 $html = ($type == 'html') ? TRUE : FALSE;
1110 $pEmails[$type] = [];
1111 $pEmail = &$pEmails[$type];
1112 $template = &$pTemplates[$type]['template'];
1113 $tokens = &$pTemplates[$type]['tokens'];
1114 $idx = 0;
1115 if (!empty($tokens)) {
1116 foreach ($tokens as $idx => $token) {
1117 $token_data = $this->getTokenData($token, $html, $contact, $verp, $urls, $event_queue_id);
1118 array_push($pEmail, $template[$idx]);
1119 array_push($pEmail, $token_data);
1120 }
1121 }
1122 else {
1123 array_push($pEmail, $template[$idx]);
1124 }
1125
1126 if (isset($template[($idx + 1)])) {
1127 array_push($pEmail, $template[($idx + 1)]);
1128 }
1129 }
1130
1131 $html = NULL;
1132 if (isset($pEmails['html']) && is_array($pEmails['html']) && count($pEmails['html'])) {
1133 $html = &$pEmails['html'];
1134 }
1135
1136 $text = NULL;
1137 if (isset($pEmails['text']) && is_array($pEmails['text']) && count($pEmails['text'])) {
1138 $text = &$pEmails['text'];
1139 }
1140
1141 // push the tracking url on to the html email if necessary
1142 if ($this->open_tracking && $html) {
1143 array_push($html, "\n" . '<img src="' . CRM_Utils_System::externUrl('extern/open', "q=$event_queue_id")
1144 . '" width="1" height="1" alt="" border="0">'
1145 );
1146 }
1147
1148 $message = new Mail_mime("\n");
1149
1150 $useSmarty = defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY ? TRUE : FALSE;
1151 if ($useSmarty) {
1152 $smarty = CRM_Core_Smarty::singleton();
1153 // also add the contact tokens to the template
1154 $smarty->assign_by_ref('contact', $contact);
1155 }
1156
1157 $mailParams = $headers;
1158 if ($text && ($test || $contact['preferred_mail_format'] == 'Text' ||
1159 $contact['preferred_mail_format'] == 'Both' ||
1160 ($contact['preferred_mail_format'] == 'HTML' && !array_key_exists('html', $pEmails))
1161 )
1162 ) {
1163 $textBody = implode('', $text);
1164 if ($useSmarty) {
1165 $textBody = $smarty->fetch("string:$textBody");
1166 }
1167 $mailParams['text'] = $textBody;
1168 }
1169
1170 if ($html && ($test || ($contact['preferred_mail_format'] == 'HTML' ||
1171 $contact['preferred_mail_format'] == 'Both'
1172 ))
1173 ) {
1174 $htmlBody = implode('', $html);
1175 if ($useSmarty) {
1176 $htmlBody = $smarty->fetch("string:$htmlBody");
1177 }
1178 $mailParams['html'] = $htmlBody;
1179 }
1180
1181 if (empty($mailParams['text']) && empty($mailParams['html'])) {
1182 // CRM-9833
1183 // something went wrong, lets log it and return null (by reference)
1184 CRM_Core_Error::debug_log_message(ts('CiviMail will not send an empty mail body, Skipping: %1',
1185 [1 => $email]
1186 ));
1187 $res = NULL;
1188 return $res;
1189 }
1190
1191 $mailParams['attachments'] = $attachments;
1192
1193 $mailParams['Subject'] = CRM_Utils_Array::value('subject', $pEmails);
1194 if (is_array($mailParams['Subject'])) {
1195 $mailParams['Subject'] = implode('', $mailParams['Subject']);
1196 }
1197
1198 $mailParams['toName'] = CRM_Utils_Array::value('display_name',
1199 $contact
1200 );
1201 $mailParams['toEmail'] = $email;
1202
1203 // Add job ID to mailParams for external email delivery service to utilise
1204 $mailParams['job_id'] = $job_id;
1205
1206 CRM_Utils_Hook::alterMailParams($mailParams, 'civimail');
1207
1208 // CRM-10699 support custom email headers
1209 if (!empty($mailParams['headers'])) {
1210 $headers = array_merge($headers, $mailParams['headers']);
1211 }
1212 //cycle through mailParams and set headers array
1213 foreach ($mailParams as $paramKey => $paramValue) {
1214 //exclude values not intended for the header
1215 if (!in_array($paramKey, [
1216 'text',
1217 'html',
1218 'attachments',
1219 'toName',
1220 'toEmail',
1221 ])
1222 ) {
1223 $headers[$paramKey] = $paramValue;
1224 }
1225 }
1226
1227 if (!empty($mailParams['text'])) {
1228 $message->setTxtBody($mailParams['text']);
1229 }
1230
1231 if (!empty($mailParams['html'])) {
1232 $message->setHTMLBody($mailParams['html']);
1233 }
1234
1235 if (!empty($mailParams['attachments'])) {
1236 foreach ($mailParams['attachments'] as $fileID => $attach) {
1237 $message->addAttachment($attach['fullPath'],
1238 $attach['mime_type'],
1239 $attach['cleanName']
1240 );
1241 }
1242 }
1243
1244 //pickup both params from mail params.
1245 $toName = trim($mailParams['toName']);
1246 $toEmail = trim($mailParams['toEmail']);
1247 if ($toName == $toEmail ||
1248 strpos($toName, '@') !== FALSE
1249 ) {
1250 $toName = NULL;
1251 }
1252 else {
1253 $toName = CRM_Utils_Mail::formatRFC2822Name($toName);
1254 }
1255
1256 $headers['To'] = "$toName <$toEmail>";
1257
1258 $headers['Precedence'] = 'bulk';
1259 // Will test in the mail processor if the X-VERP is set in the bounced email.
1260 // (As an option to replace real VERP for those that can't set it up)
1261 $headers['X-CiviMail-Bounce'] = $verp['bounce'];
1262
1263 //CRM-5058
1264 //token replacement of subject
1265 $headers['Subject'] = $mailParams['Subject'];
1266
1267 CRM_Utils_Mail::setMimeParams($message);
1268 $headers = $message->headers($headers);
1269
1270 //get formatted recipient
1271 $recipient = $headers['To'];
1272
1273 // make sure we unset a lot of stuff
1274 unset($verp);
1275 unset($urls);
1276 unset($params);
1277 unset($contact);
1278 unset($ids);
1279
1280 return $message;
1281 }
1282
1283 /**
1284 * Replace tokens.
1285 *
1286 * Get mailing object and replaces subscribeInvite, domain and mailing tokens.
1287 *
1288 * @deprecated
1289 * This is used by CiviMail but will be made redundant by FlexMailer/TokenProcessor.
1290 * @param CRM_Mailing_BAO_Mailing $mailing
1291 */
1292 public static function tokenReplace(&$mailing) {
1293 $domain = CRM_Core_BAO_Domain::getDomain();
1294
1295 foreach (['text', 'html'] as $type) {
1296 $tokens = $mailing->getTokens();
1297 if (isset($mailing->templates[$type])) {
1298 $mailing->templates[$type] = CRM_Utils_Token::replaceSubscribeInviteTokens($mailing->templates[$type]);
1299 $mailing->templates[$type] = CRM_Utils_Token::replaceDomainTokens(
1300 $mailing->templates[$type],
1301 $domain,
1302 $type == 'html' ? TRUE : FALSE,
1303 $tokens[$type]
1304 );
1305 $mailing->templates[$type] = CRM_Utils_Token::replaceMailingTokens($mailing->templates[$type], $mailing, NULL, $tokens[$type]);
1306 }
1307 }
1308 }
1309
1310 /**
1311 * Get data to resolve tokens.
1312 *
1313 * @deprecated
1314 * This is used by CiviMail but will be made redundant by FlexMailer/TokenProcessor.
1315 *
1316 * @param array $token_a
1317 * @param bool $html
1318 * Whether to encode the token result for use in HTML email
1319 * @param array $contact
1320 * @param string $verp
1321 * @param array $urls
1322 * @param int $event_queue_id
1323 *
1324 * @return bool|mixed|null|string
1325 */
1326 private function getTokenData(&$token_a, $html = FALSE, &$contact, &$verp, &$urls, $event_queue_id) {
1327 $type = $token_a['type'];
1328 $token = $token_a['token'];
1329 $data = $token;
1330
1331 $useSmarty = defined('CIVICRM_MAIL_SMARTY') && CIVICRM_MAIL_SMARTY ? TRUE : FALSE;
1332
1333 if ($type == 'embedded_url') {
1334 $embed_data = [];
1335 foreach ($token as $t) {
1336 $embed_data[] = $this->getTokenData($t, $html, $contact, $verp, $urls, $event_queue_id);
1337 }
1338 $numSlices = count($embed_data);
1339 $url = '';
1340 for ($i = 0; $i < $numSlices; $i++) {
1341 $embed_url_data = parse_url($embed_data[$i]);
1342 if (!empty($embed_url_data['scheme'])) {
1343 $token_a['embed_parts'][$i] = preg_replace("/href=\"(https*:\/\/)/", "href=\"", $token_a['embed_parts'][$i]);
1344 }
1345 $url .= "{$token_a['embed_parts'][$i]}{$embed_data[$i]}";
1346 }
1347 if (isset($token_a['embed_parts'][$numSlices])) {
1348 $url .= $token_a['embed_parts'][$numSlices];
1349 }
1350 // add trailing quote since we've gobbled it up in a previous regex
1351 // function getPatterns, line 431
1352 if (preg_match("/^href[ ]*=[ ]*'.*[^']$/", $url)) {
1353 $url .= "'";
1354 }
1355 elseif (preg_match('/^href[ ]*=[ ]*".*[^"]$/', $url)) {
1356 $url .= '"';
1357 }
1358 $data = $url;
1359 // CRM-20206 Fix ampersand encoding in plain text emails
1360 if (empty($html)) {
1361 $data = CRM_Utils_String::unstupifyUrl($data);
1362 }
1363 }
1364 elseif ($type == 'url') {
1365 if ($this->url_tracking && !empty($this->id)) {
1366 // ensure that Google CSS and any .css files are not tracked.
1367 if (!(strpos($token, 'css?family') || strpos($token, '.css'))) {
1368 $data = CRM_Mailing_BAO_TrackableURL::getTrackerURL($token, $this->id, $event_queue_id);
1369 if (!empty($html)) {
1370 $data = htmlentities($data, ENT_NOQUOTES);
1371 }
1372 }
1373 }
1374 else {
1375 $data = $token;
1376 }
1377 }
1378 elseif ($type == 'contact') {
1379 $data = CRM_Utils_Token::getContactTokenReplacement($token, $contact, FALSE, FALSE, $useSmarty);
1380 }
1381 elseif ($type == 'action') {
1382 $data = CRM_Utils_Token::getActionTokenReplacement($token, $verp, $urls, $html);
1383 }
1384 elseif ($type == 'domain') {
1385 $domain = CRM_Core_BAO_Domain::getDomain();
1386 $data = CRM_Utils_Token::getDomainTokenReplacement($token, $domain, $html);
1387 }
1388 elseif ($type == 'mailing') {
1389 if ($token == 'name') {
1390 $data = $this->name;
1391 }
1392 elseif ($token == 'group') {
1393 $groups = $this->getGroupNames();
1394 $data = implode(', ', $groups);
1395 }
1396 }
1397 else {
1398 $data = CRM_Utils_Array::value("{$type}.{$token}", $contact);
1399 }
1400 return $data;
1401 }
1402
1403 /**
1404 * Return a list of group names for this mailing. Does not work with
1405 * prior-mailing targets.
1406 *
1407 * @return array
1408 * Names of groups receiving this mailing
1409 */
1410 public function &getGroupNames() {
1411 if (!isset($this->id)) {
1412 return [];
1413 }
1414 $mg = new CRM_Mailing_DAO_MailingGroup();
1415 $mgtable = CRM_Mailing_DAO_MailingGroup::getTableName();
1416 $group = CRM_Contact_BAO_Group::getTableName();
1417
1418 $mg->query("SELECT $group.title as name FROM $mgtable
1419 INNER JOIN $group ON $mgtable.entity_id = $group.id
1420 WHERE $mgtable.mailing_id = {$this->id}
1421 AND $mgtable.entity_table = '$group'
1422 AND $mgtable.group_type = 'Include'
1423 ORDER BY $group.name");
1424
1425 $groups = [];
1426 while ($mg->fetch()) {
1427 $groups[] = $mg->name;
1428 }
1429 return $groups;
1430 }
1431
1432 /**
1433 * Add the mailings.
1434 *
1435 * @param array $params
1436 * Reference array contains the values submitted by the form.
1437 * @param array $ids
1438 * Reference array contains the id.
1439 *
1440 *
1441 * @return CRM_Mailing_DAO_Mailing
1442 */
1443 public static function add(&$params, $ids = []) {
1444 $id = CRM_Utils_Array::value('id', $params, CRM_Utils_Array::value('mailing_id', $ids));
1445
1446 if (empty($params['id']) && !empty($ids)) {
1447 \Civi::log('Parameter $ids is no longer used by Mailing::add. Use the api or just pass $params', ['civi.tag' => 'deprecated']);
1448 }
1449
1450 if ($id) {
1451 CRM_Utils_Hook::pre('edit', 'Mailing', $id, $params);
1452 }
1453 else {
1454 CRM_Utils_Hook::pre('create', 'Mailing', NULL, $params);
1455 }
1456
1457 $mailing = new static();
1458 if ($id) {
1459 $mailing->id = $id;
1460 $mailing->find(TRUE);
1461 }
1462 $mailing->domain_id = CRM_Utils_Array::value('domain_id', $params, CRM_Core_Config::domainID());
1463
1464 if (((!$id && empty($params['replyto_email'])) || !isset($params['replyto_email'])) &&
1465 isset($params['from_email'])
1466 ) {
1467 $params['replyto_email'] = $params['from_email'];
1468 }
1469 $mailing->copyValues($params);
1470
1471 // CRM-20892 Unset Modifed Date here so that MySQL can correctly set an updated modfied date.
1472 unset($mailing->modified_date);
1473 $result = $mailing->save();
1474
1475 // CRM-20892 Re find record after saing so we can set the updated modified date in the result.
1476 $mailing->find(TRUE);
1477
1478 if (isset($mailing->modified_date)) {
1479 $result->modified_date = $mailing->modified_date;
1480 }
1481
1482 if ($id) {
1483 CRM_Utils_Hook::post('edit', 'Mailing', $mailing->id, $mailing);
1484 }
1485 else {
1486 CRM_Utils_Hook::post('create', 'Mailing', $mailing->id, $mailing);
1487 }
1488
1489 return $result;
1490 }
1491
1492 /**
1493 * Construct a new mailing object, along with job and mailing_group
1494 * objects, from the form values of the create mailing wizard.
1495 *
1496 * This function is a bit evil. It not only merges $params and saves
1497 * the mailing -- it also schedules the mailing and chooses the recipients.
1498 * Since it merges $params, it's also the only place to correctly trigger
1499 * multi-field validation. It should be broken up.
1500 *
1501 * In the mean time, use-cases which break under the weight of this
1502 * evil may find reprieve in these extra evil params:
1503 *
1504 * - _skip_evil_bao_auto_recipients_: bool
1505 * - _skip_evil_bao_auto_schedule_: bool
1506 * - _evil_bao_validator_: string|callable
1507 *
1508 * </twowrongsmakesaright>
1509 *
1510 * @params array $params
1511 * Form values.
1512 *
1513 * @param array $params
1514 * @param array $ids
1515 *
1516 * @return object
1517 * $mailing The new mailing object
1518 *
1519 * @throws \CRM_Core_Exception
1520 * @throws \CiviCRM_API3_Exception
1521 */
1522 public static function create(&$params, $ids = []) {
1523
1524 if (empty($params['id']) && (array_filter($ids) !== [])) {
1525 $params['id'] = isset($ids['mailing_id']) ? $ids['mailing_id'] : $ids['id'];
1526 \Civi::log('Parameter $ids is no longer used by Mailing::create. Use the api or just pass $params', ['civi.tag' => 'deprecated']);
1527 }
1528
1529 // CRM-12430
1530 // Do the below only for an insert
1531 // for an update, we should not set the defaults
1532 if (!isset($params['id'])) {
1533 // Retrieve domain email and name for default sender
1534 $domain = civicrm_api(
1535 'Domain',
1536 'getsingle',
1537 [
1538 'version' => 3,
1539 'current_domain' => 1,
1540 'sequential' => 1,
1541 ]
1542 );
1543 if (isset($domain['from_email'])) {
1544 $domain_email = $domain['from_email'];
1545 $domain_name = $domain['from_name'];
1546 }
1547 else {
1548 $domain_email = 'info@EXAMPLE.ORG';
1549 $domain_name = 'EXAMPLE.ORG';
1550 }
1551 if (!isset($params['created_id'])) {
1552 $params['created_id'] = CRM_Core_Session::getLoggedInContactID();
1553 }
1554 $defaults = [
1555 // load the default config settings for each
1556 // eg reply_id, unsubscribe_id need to use
1557 // correct template IDs here
1558 'override_verp' => TRUE,
1559 'forward_replies' => FALSE,
1560 'open_tracking' => TRUE,
1561 'url_tracking' => TRUE,
1562 'visibility' => 'Public Pages',
1563 'replyto_email' => $domain_email,
1564 'header_id' => CRM_Mailing_PseudoConstant::defaultComponent('header_id', ''),
1565 'footer_id' => CRM_Mailing_PseudoConstant::defaultComponent('footer_id', ''),
1566 'from_email' => $domain_email,
1567 'from_name' => $domain_name,
1568 'msg_template_id' => NULL,
1569 'created_id' => $params['created_id'],
1570 'approver_id' => NULL,
1571 'auto_responder' => 0,
1572 'created_date' => date('YmdHis'),
1573 'scheduled_date' => NULL,
1574 'approval_date' => NULL,
1575 ];
1576
1577 // Get the default from email address, if not provided.
1578 if (empty($defaults['from_email'])) {
1579 $defaultAddress = CRM_Core_BAO_Domain::getNameAndEmail(TRUE, TRUE);
1580 foreach ($defaultAddress as $id => $value) {
1581 if (preg_match('/"(.*)" <(.*)>/', $value, $match)) {
1582 $defaults['from_email'] = $match[2];
1583 $defaults['from_name'] = $match[1];
1584 }
1585 }
1586 }
1587
1588 $params = array_merge($defaults, $params);
1589 }
1590
1591 /**
1592 * Could check and warn for the following cases:
1593 *
1594 * - groups OR mailings should be populated.
1595 * - body html OR body text should be populated.
1596 */
1597
1598 $transaction = new CRM_Core_Transaction();
1599
1600 $mailing = self::add($params);
1601
1602 if (is_a($mailing, 'CRM_Core_Error')) {
1603 $transaction->rollback();
1604 return $mailing;
1605 }
1606 // update mailings with hash values
1607 CRM_Contact_BAO_Contact_Utils::generateChecksum($mailing->id, NULL, NULL, NULL, 'mailing', 16);
1608
1609 $groupTableName = CRM_Contact_BAO_Group::getTableName();
1610
1611 /* Create the mailing group record */
1612 $mg = new CRM_Mailing_DAO_MailingGroup();
1613 $groupTypes = [
1614 'include' => 'Include',
1615 'exclude' => 'Exclude',
1616 'base' => 'Base',
1617 ];
1618 foreach (['groups', 'mailings'] as $entity) {
1619 foreach (['include', 'exclude', 'base'] as $type) {
1620 if (isset($params[$entity][$type])) {
1621 self::replaceGroups($mailing->id, $groupTypes[$type], $entity, $params[$entity][$type]);
1622 }
1623 }
1624 }
1625
1626 if (!empty($params['search_id']) && !empty($params['group_id'])) {
1627 $mg->reset();
1628 $mg->mailing_id = $mailing->id;
1629 $mg->entity_table = $groupTableName;
1630 $mg->entity_id = $params['group_id'];
1631 $mg->search_id = $params['search_id'];
1632 $mg->search_args = $params['search_args'];
1633 $mg->group_type = 'Include';
1634 $mg->save();
1635 }
1636
1637 // check and attach and files as needed
1638 CRM_Core_BAO_File::processAttachment($params, 'civicrm_mailing', $mailing->id);
1639
1640 // If we're going to autosend, then check validity before saving.
1641 if (empty($params['is_completed']) && !empty($params['scheduled_date']) && $params['scheduled_date'] != 'null' && !empty($params['_evil_bao_validator_'])) {
1642 $cb = Civi\Core\Resolver::singleton()
1643 ->get($params['_evil_bao_validator_']);
1644 $errors = call_user_func($cb, $mailing);
1645 if (!empty($errors)) {
1646 $fields = implode(',', array_keys($errors));
1647 throw new CRM_Core_Exception("Mailing cannot be sent. There are missing or invalid fields ($fields).", 'cannot-send', $errors);
1648 }
1649 }
1650
1651 $transaction->commit();
1652
1653 // Create parent job if not yet created.
1654 // Condition on the existence of a scheduled date.
1655 if (!empty($params['scheduled_date']) && $params['scheduled_date'] != 'null' && empty($params['_skip_evil_bao_auto_schedule_'])) {
1656 $job = new CRM_Mailing_BAO_MailingJob();
1657 $job->mailing_id = $mailing->id;
1658 // If we are creating a new Completed mailing (e.g. import from another system) set the job to completed.
1659 // Keeping former behaviour when an id is present is precautionary and may warrant reconsideration later.
1660 $job->status = ((empty($params['is_completed']) || !empty($params['id'])) ? 'Scheduled' : 'Complete');
1661 $job->is_test = 0;
1662
1663 if (!$job->find(TRUE)) {
1664 // Don't schedule job until we populate the recipients.
1665 $job->scheduled_date = NULL;
1666 $job->save();
1667 }
1668 // Schedule the job now that it has recipients.
1669 $job->scheduled_date = $params['scheduled_date'];
1670 $job->save();
1671 }
1672
1673 // Populate the recipients.
1674 if (empty($params['_skip_evil_bao_auto_recipients_'])) {
1675 self::getRecipients($mailing->id);
1676 }
1677
1678 return $mailing;
1679 }
1680
1681 /**
1682 * @deprecated
1683 * This is used by CiviMail but will be made redundant by FlexMailer.
1684 * @param CRM_Mailing_DAO_Mailing $mailing
1685 * The mailing which may or may not be sendable.
1686 * @return array
1687 * List of error messages.
1688 */
1689 public static function checkSendable($mailing) {
1690 $errors = [];
1691 foreach (['subject', 'name', 'from_name', 'from_email'] as $field) {
1692 if (empty($mailing->{$field})) {
1693 $errors[$field] = ts('Field "%1" is required.', [
1694 1 => $field,
1695 ]);
1696 }
1697 }
1698 if (empty($mailing->body_html) && empty($mailing->body_text)) {
1699 $errors['body'] = ts('Field "body_html" or "body_text" is required.');
1700 }
1701
1702 if (!Civi::settings()->get('disable_mandatory_tokens_check')) {
1703 $header = $mailing->header_id && $mailing->header_id != 'null' ? CRM_Mailing_BAO_MailingComponent::findById($mailing->header_id) : NULL;
1704 $footer = $mailing->footer_id && $mailing->footer_id != 'null' ? CRM_Mailing_BAO_MailingComponent::findById($mailing->footer_id) : NULL;
1705 foreach (['body_html', 'body_text'] as $field) {
1706 if (empty($mailing->{$field})) {
1707 continue;
1708 }
1709 $str = ($header ? $header->{$field} : '') . $mailing->{$field} . ($footer ? $footer->{$field} : '');
1710 $err = CRM_Utils_Token::requiredTokens($str);
1711 if ($err !== TRUE) {
1712 foreach ($err as $token => $desc) {
1713 $errors["{$field}:{$token}"] = ts('This message is missing a required token - {%1}: %2',
1714 [1 => $token, 2 => $desc]
1715 );
1716 }
1717 }
1718 }
1719 }
1720
1721 return $errors;
1722 }
1723
1724 /**
1725 * Replace the list of recipients on a given mailing.
1726 *
1727 * @param int $mailingId
1728 * @param string $type
1729 * 'include' or 'exclude'.
1730 * @param string $entity
1731 * 'groups' or 'mailings'.
1732 * @param array $entityIds
1733 * @throws CiviCRM_API3_Exception
1734 */
1735 public static function replaceGroups($mailingId, $type, $entity, $entityIds) {
1736 $values = [];
1737 foreach ($entityIds as $entityId) {
1738 $values[] = ['entity_id' => $entityId];
1739 }
1740 civicrm_api3('mailing_group', 'replace', [
1741 'mailing_id' => $mailingId,
1742 'group_type' => $type,
1743 'entity_table' => ($entity == 'groups') ? CRM_Contact_BAO_Group::getTableName() : CRM_Mailing_BAO_Mailing::getTableName(),
1744 'values' => $values,
1745 ]);
1746 }
1747
1748 /**
1749 * Get hash value of the mailing.
1750 *
1751 * @param $id
1752 *
1753 * @return null|string
1754 */
1755 public static function getMailingHash($id) {
1756 $hash = NULL;
1757 if (Civi::settings()->get('hash_mailing_url') && !empty($id)) {
1758 $hash = CRM_Core_DAO::getFieldValue('CRM_Mailing_BAO_Mailing', $id, 'hash', 'id');
1759 }
1760 return $hash;
1761 }
1762
1763 /**
1764 * Generate a report. Fetch event count information, mailing data, and job
1765 * status.
1766 *
1767 * @param int $id
1768 * The mailing id to report.
1769 * @param bool $skipDetails
1770 * Whether return all detailed report.
1771 *
1772 * @param bool $isSMS
1773 *
1774 * @return array
1775 * Associative array of reporting data
1776 */
1777 public static function &report($id, $skipDetails = FALSE, $isSMS = FALSE) {
1778 $mailing_id = CRM_Utils_Type::escape($id, 'Integer');
1779
1780 $mailing = new CRM_Mailing_BAO_Mailing();
1781
1782 $t = [
1783 'mailing' => self::getTableName(),
1784 'mailing_group' => CRM_Mailing_DAO_MailingGroup::getTableName(),
1785 'group' => CRM_Contact_BAO_Group::getTableName(),
1786 'job' => CRM_Mailing_BAO_MailingJob::getTableName(),
1787 'queue' => CRM_Mailing_Event_BAO_Queue::getTableName(),
1788 'delivered' => CRM_Mailing_Event_BAO_Delivered::getTableName(),
1789 'opened' => CRM_Mailing_Event_BAO_Opened::getTableName(),
1790 'reply' => CRM_Mailing_Event_BAO_Reply::getTableName(),
1791 'unsubscribe' => CRM_Mailing_Event_BAO_Unsubscribe::getTableName(),
1792 'bounce' => CRM_Mailing_Event_BAO_Bounce::getTableName(),
1793 'forward' => CRM_Mailing_Event_BAO_Forward::getTableName(),
1794 'url' => CRM_Mailing_BAO_TrackableURL::getTableName(),
1795 'urlopen' => CRM_Mailing_Event_BAO_TrackableURLOpen::getTableName(),
1796 'component' => CRM_Mailing_BAO_MailingComponent::getTableName(),
1797 'spool' => CRM_Mailing_BAO_Spool::getTableName(),
1798 ];
1799
1800 $report = [];
1801 $additionalWhereClause = " AND ";
1802 if (!$isSMS) {
1803 $additionalWhereClause .= " {$t['mailing']}.sms_provider_id IS NULL ";
1804 }
1805 else {
1806 $additionalWhereClause .= " {$t['mailing']}.sms_provider_id IS NOT NULL ";
1807 }
1808
1809 /* Get the mailing info */
1810
1811 $mailing->query("
1812 SELECT {$t['mailing']}.*
1813 FROM {$t['mailing']}
1814 WHERE {$t['mailing']}.id = $mailing_id {$additionalWhereClause}");
1815
1816 $mailing->fetch();
1817
1818 $report['mailing'] = [];
1819 foreach (array_keys(self::fields()) as $field) {
1820 $field = self::fields()[$field]['name'];
1821 $report['mailing'][$field] = $mailing->$field;
1822 }
1823
1824 //get the campaign
1825 if ($campaignId = CRM_Utils_Array::value('campaign_id', $report['mailing'])) {
1826 $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId);
1827 $report['mailing']['campaign'] = $campaigns[$campaignId];
1828 }
1829
1830 //mailing report is called by activity
1831 //we dont need all detail report
1832 if ($skipDetails) {
1833 return $report;
1834 }
1835
1836 /* Get the component info */
1837
1838 $query = [];
1839
1840 $components = [
1841 'header' => ts('Header'),
1842 'footer' => ts('Footer'),
1843 'reply' => ts('Reply'),
1844 'optout' => ts('Opt-Out'),
1845 'resubscribe' => ts('Resubscribe'),
1846 'unsubscribe' => ts('Unsubscribe'),
1847 ];
1848 foreach (array_keys($components) as $type) {
1849 $query[] = "SELECT {$t['component']}.name as name,
1850 '$type' as type,
1851 {$t['component']}.id as id
1852 FROM {$t['component']}
1853 INNER JOIN {$t['mailing']}
1854 ON {$t['mailing']}.{$type}_id =
1855 {$t['component']}.id
1856 WHERE {$t['mailing']}.id = $mailing_id";
1857 }
1858 $q = '(' . implode(') UNION (', $query) . ')';
1859 $mailing->query($q);
1860
1861 $report['component'] = [];
1862 while ($mailing->fetch()) {
1863 $report['component'][] = [
1864 'type' => $components[$mailing->type],
1865 'name' => $mailing->name,
1866 'link' => CRM_Utils_System::url('civicrm/mailing/component', "reset=1&action=update&id={$mailing->id}"),
1867 ];
1868 }
1869
1870 /* Get the recipient group info */
1871
1872 $mailing->query("
1873 SELECT {$t['mailing_group']}.group_type as group_type,
1874 {$t['group']}.id as group_id,
1875 {$t['group']}.title as group_title,
1876 {$t['group']}.is_hidden as group_hidden,
1877 {$t['mailing']}.id as mailing_id,
1878 {$t['mailing']}.name as mailing_name
1879 FROM {$t['mailing_group']}
1880 LEFT JOIN {$t['group']}
1881 ON {$t['mailing_group']}.entity_id = {$t['group']}.id
1882 AND {$t['mailing_group']}.entity_table =
1883 '{$t['group']}'
1884 LEFT JOIN {$t['mailing']}
1885 ON {$t['mailing_group']}.entity_id =
1886 {$t['mailing']}.id
1887 AND {$t['mailing_group']}.entity_table =
1888 '{$t['mailing']}'
1889
1890 WHERE {$t['mailing_group']}.mailing_id = $mailing_id
1891 ");
1892
1893 $report['group'] = ['include' => [], 'exclude' => [], 'base' => []];
1894 while ($mailing->fetch()) {
1895 $row = [];
1896 if (isset($mailing->group_id)) {
1897 $row['id'] = $mailing->group_id;
1898 $row['name'] = $mailing->group_title;
1899 $row['link'] = CRM_Utils_System::url('civicrm/group/search',
1900 "reset=1&force=1&context=smog&gid={$row['id']}"
1901 );
1902 }
1903 else {
1904 $row['id'] = $mailing->mailing_id;
1905 $row['name'] = $mailing->mailing_name;
1906 $row['mailing'] = TRUE;
1907 $row['link'] = CRM_Utils_System::url('civicrm/mailing/report',
1908 "mid={$row['id']}"
1909 );
1910 }
1911
1912 /* Rename hidden groups */
1913
1914 if ($mailing->group_hidden == 1) {
1915 $row['name'] = "Search Results";
1916 }
1917
1918 if ($mailing->group_type == 'Include') {
1919 $report['group']['include'][] = $row;
1920 }
1921 elseif ($mailing->group_type == 'Base') {
1922 $report['group']['base'][] = $row;
1923 }
1924 else {
1925 $report['group']['exclude'][] = $row;
1926 }
1927 }
1928
1929 /* Get the event totals, grouped by job (retries) */
1930
1931 $mailing->query("
1932 SELECT {$t['job']}.*,
1933 COUNT(DISTINCT {$t['queue']}.id) as queue,
1934 COUNT(DISTINCT {$t['delivered']}.id) as delivered,
1935 COUNT(DISTINCT {$t['reply']}.id) as reply,
1936 COUNT(DISTINCT {$t['forward']}.id) as forward,
1937 COUNT(DISTINCT {$t['bounce']}.id) as bounce,
1938 COUNT(DISTINCT {$t['urlopen']}.id) as url,
1939 COUNT(DISTINCT {$t['spool']}.id) as spool
1940 FROM {$t['job']}
1941 LEFT JOIN {$t['queue']}
1942 ON {$t['queue']}.job_id = {$t['job']}.id
1943 LEFT JOIN {$t['reply']}
1944 ON {$t['reply']}.event_queue_id = {$t['queue']}.id
1945 LEFT JOIN {$t['forward']}
1946 ON {$t['forward']}.event_queue_id = {$t['queue']}.id
1947 LEFT JOIN {$t['bounce']}
1948 ON {$t['bounce']}.event_queue_id = {$t['queue']}.id
1949 LEFT JOIN {$t['delivered']}
1950 ON {$t['delivered']}.event_queue_id = {$t['queue']}.id
1951 AND {$t['bounce']}.id IS null
1952 LEFT JOIN {$t['urlopen']}
1953 ON {$t['urlopen']}.event_queue_id = {$t['queue']}.id
1954 LEFT JOIN {$t['spool']}
1955 ON {$t['spool']}.job_id = {$t['job']}.id
1956 WHERE {$t['job']}.mailing_id = $mailing_id
1957 AND {$t['job']}.is_test = 0
1958 GROUP BY {$t['job']}.id");
1959
1960 $report['jobs'] = [];
1961 $report['event_totals'] = [];
1962 $path = 'civicrm/mailing/report/event';
1963 $elements = [
1964 'queue',
1965 'delivered',
1966 'url',
1967 'forward',
1968 'reply',
1969 'unsubscribe',
1970 'optout',
1971 'opened',
1972 'total_opened',
1973 'bounce',
1974 'spool',
1975 ];
1976
1977 // initialize various counters
1978 foreach ($elements as $field) {
1979 $report['event_totals'][$field] = 0;
1980 }
1981
1982 while ($mailing->fetch()) {
1983 $row = [];
1984 foreach ($elements as $field) {
1985 if (isset($mailing->$field)) {
1986 $row[$field] = $mailing->$field;
1987 $report['event_totals'][$field] += $mailing->$field;
1988 }
1989 }
1990
1991 // compute open total separately to discount duplicates
1992 // CRM-1258
1993 $row['opened'] = CRM_Mailing_Event_BAO_Opened::getTotalCount($mailing_id, $mailing->id, TRUE);
1994 $report['event_totals']['opened'] += $row['opened'];
1995 $row['total_opened'] = CRM_Mailing_Event_BAO_Opened::getTotalCount($mailing_id, $mailing->id);
1996 $report['event_totals']['total_opened'] += $row['total_opened'];
1997
1998 // compute unsub total separately to discount duplicates
1999 // CRM-1783
2000 $row['unsubscribe'] = CRM_Mailing_Event_BAO_Unsubscribe::getTotalCount($mailing_id, $mailing->id, TRUE, TRUE);
2001 $report['event_totals']['unsubscribe'] += $row['unsubscribe'];
2002
2003 $row['optout'] = CRM_Mailing_Event_BAO_Unsubscribe::getTotalCount($mailing_id, $mailing->id, TRUE, FALSE);
2004 $report['event_totals']['optout'] += $row['optout'];
2005
2006 foreach (array_keys(CRM_Mailing_BAO_MailingJob::fields()) as $field) {
2007 // Get the field name from the MailingJob fields as that will not have any prefixing.
2008 // dev/mailing#56
2009 $field = CRM_Mailing_BAO_MailingJob::fields()[$field]['name'];
2010 $row[$field] = $mailing->$field;
2011 }
2012
2013 if ($mailing->queue) {
2014 $row['delivered_rate'] = (100.0 * $mailing->delivered) / $mailing->queue;
2015 $row['bounce_rate'] = (100.0 * $mailing->bounce) / $mailing->queue;
2016 $row['unsubscribe_rate'] = (100.0 * $row['unsubscribe']) / $mailing->queue;
2017 $row['optout_rate'] = (100.0 * $row['optout']) / $mailing->queue;
2018 $row['opened_rate'] = $mailing->delivered ? (($row['opened'] / $mailing->delivered) * 100.0) : 0;
2019 $row['clickthrough_rate'] = $mailing->delivered ? (($mailing->url / $mailing->delivered) * 100.0) : 0;
2020 }
2021 else {
2022 $row['delivered_rate'] = 0;
2023 $row['bounce_rate'] = 0;
2024 $row['unsubscribe_rate'] = 0;
2025 $row['optout_rate'] = 0;
2026 $row['opened_rate'] = 0;
2027 $row['clickthrough_rate'] = 0;
2028 }
2029
2030 $arg = "reset=1&mid=$mailing_id&jid={$mailing->id}";
2031 $row['links'] = [
2032 'clicks' => CRM_Utils_System::url($path, "$arg&event=click"),
2033 'queue' => CRM_Utils_System::url($path, "$arg&event=queue"),
2034 'delivered' => CRM_Utils_System::url($path, "$arg&event=delivered"),
2035 'bounce' => CRM_Utils_System::url($path, "$arg&event=bounce"),
2036 'unsubscribe' => CRM_Utils_System::url($path, "$arg&event=unsubscribe"),
2037 'forward' => CRM_Utils_System::url($path, "$arg&event=forward"),
2038 'reply' => CRM_Utils_System::url($path, "$arg&event=reply"),
2039 'opened' => CRM_Utils_System::url($path, "$arg&event=opened"),
2040 ];
2041
2042 foreach (['scheduled_date', 'start_date', 'end_date'] as $key) {
2043 $row[$key] = CRM_Utils_Date::customFormat($row[$key]);
2044 }
2045 $report['jobs'][] = $row;
2046 }
2047
2048 $newTableSize = CRM_Mailing_BAO_Recipients::mailingSize($mailing_id);
2049
2050 // we need to do this for backward compatibility, since old mailings did not
2051 // use the mailing_recipients table
2052 if ($newTableSize > 0) {
2053 $report['event_totals']['queue'] = $newTableSize;
2054 }
2055 else {
2056 $report['event_totals']['queue'] = self::getRecipientsCount($mailing_id);
2057 }
2058
2059 if (!empty($report['event_totals']['queue'])) {
2060 $report['event_totals']['delivered_rate'] = (100.0 * $report['event_totals']['delivered']) / $report['event_totals']['queue'];
2061 $report['event_totals']['bounce_rate'] = (100.0 * $report['event_totals']['bounce']) / $report['event_totals']['queue'];
2062 $report['event_totals']['unsubscribe_rate'] = (100.0 * $report['event_totals']['unsubscribe']) / $report['event_totals']['queue'];
2063 $report['event_totals']['optout_rate'] = (100.0 * $report['event_totals']['optout']) / $report['event_totals']['queue'];
2064 $report['event_totals']['opened_rate'] = !empty($report['event_totals']['delivered']) ? (($report['event_totals']['opened'] / $report['event_totals']['delivered']) * 100.0) : 0;
2065 $report['event_totals']['clickthrough_rate'] = !empty($report['event_totals']['delivered']) ? (($report['event_totals']['url'] / $report['event_totals']['delivered']) * 100.0) : 0;
2066 }
2067 else {
2068 $report['event_totals']['delivered_rate'] = 0;
2069 $report['event_totals']['bounce_rate'] = 0;
2070 $report['event_totals']['unsubscribe_rate'] = 0;
2071 $report['event_totals']['optout_rate'] = 0;
2072 $report['event_totals']['opened_rate'] = 0;
2073 $report['event_totals']['clickthrough_rate'] = 0;
2074 }
2075
2076 /* Get the click-through totals, grouped by URL */
2077
2078 $mailing->query("
2079 SELECT {$t['url']}.url,
2080 {$t['url']}.id,
2081 COUNT({$t['urlopen']}.id) as clicks,
2082 COUNT(DISTINCT {$t['queue']}.id) as unique_clicks
2083 FROM {$t['url']}
2084 LEFT JOIN {$t['urlopen']}
2085 ON {$t['urlopen']}.trackable_url_id = {$t['url']}.id
2086 LEFT JOIN {$t['queue']}
2087 ON {$t['urlopen']}.event_queue_id = {$t['queue']}.id
2088 LEFT JOIN {$t['job']}
2089 ON {$t['queue']}.job_id = {$t['job']}.id
2090 WHERE {$t['url']}.mailing_id = $mailing_id
2091 AND {$t['job']}.is_test = 0
2092 GROUP BY {$t['url']}.id
2093 ORDER BY unique_clicks DESC");
2094
2095 $report['click_through'] = [];
2096
2097 while ($mailing->fetch()) {
2098 $report['click_through'][] = [
2099 'url' => $mailing->url,
2100 'link' => CRM_Utils_System::url($path, "reset=1&event=click&mid=$mailing_id&uid={$mailing->id}"),
2101 'link_unique' => CRM_Utils_System::url($path, "reset=1&event=click&mid=$mailing_id&uid={$mailing->id}&distinct=1"),
2102 'clicks' => $mailing->clicks,
2103 'unique' => $mailing->unique_clicks,
2104 'rate' => CRM_Utils_Array::value('delivered', $report['event_totals']) ? (100.0 * $mailing->unique_clicks) / $report['event_totals']['delivered'] : 0,
2105 'report' => CRM_Report_Utils_Report::getNextUrl('mailing/clicks', "reset=1&mailing_id_value={$mailing_id}&url_value={$mailing->url}", FALSE, TRUE),
2106 ];
2107 }
2108
2109 $arg = "reset=1&mid=$mailing_id";
2110 $report['event_totals']['links'] = [
2111 'clicks' => CRM_Utils_System::url($path, "$arg&event=click"),
2112 'clicks_unique' => CRM_Utils_System::url($path, "$arg&event=click&distinct=1"),
2113 'queue' => CRM_Utils_System::url($path, "$arg&event=queue"),
2114 'delivered' => CRM_Utils_System::url($path, "$arg&event=delivered"),
2115 'bounce' => CRM_Utils_System::url($path, "$arg&event=bounce"),
2116 'unsubscribe' => CRM_Utils_System::url($path, "$arg&event=unsubscribe"),
2117 'optout' => CRM_Utils_System::url($path, "$arg&event=optout"),
2118 'forward' => CRM_Utils_System::url($path, "$arg&event=forward"),
2119 'reply' => CRM_Utils_System::url($path, "$arg&event=reply"),
2120 'opened' => CRM_Utils_System::url($path, "$arg&event=opened"),
2121 ];
2122
2123 $actionLinks = [CRM_Core_Action::VIEW => ['name' => ts('Report')]];
2124 $actionLinks[CRM_Core_Action::ADVANCED] = [
2125 'name' => ts('Advanced Search'),
2126 'url' => 'civicrm/contact/search/advanced',
2127 ];
2128 $action = array_sum(array_keys($actionLinks));
2129
2130 $report['event_totals']['actionlinks'] = [];
2131 foreach (['clicks', 'clicks_unique', 'queue', 'delivered', 'bounce', 'unsubscribe', 'forward', 'reply', 'opened', 'opened_unique', 'optout'] as $key) {
2132 $url = 'mailing/detail';
2133 $reportFilter = "reset=1&mailing_id_value={$mailing_id}";
2134 $searchFilter = "force=1&mailing_id=%%mid%%";
2135 switch ($key) {
2136 case 'delivered':
2137 $reportFilter .= "&delivery_status_value=successful";
2138 $searchFilter .= "&mailing_delivery_status=Y";
2139 break;
2140
2141 case 'bounce':
2142 $url = "mailing/bounce";
2143 $searchFilter .= "&mailing_delivery_status=N";
2144 break;
2145
2146 case 'forward':
2147 $reportFilter .= "&is_forwarded_value=1";
2148 $searchFilter .= "&mailing_forward=1";
2149 break;
2150
2151 case 'reply':
2152 $reportFilter .= "&is_replied_value=1";
2153 $searchFilter .= "&mailing_reply_status=Y";
2154 break;
2155
2156 case 'unsubscribe':
2157 $reportFilter .= "&is_unsubscribed_value=1";
2158 $searchFilter .= "&mailing_unsubscribe=1";
2159 break;
2160
2161 case 'optout':
2162 $reportFilter .= "&is_optout_value=1";
2163 $searchFilter .= "&mailing_optout=1";
2164 break;
2165
2166 case 'opened':
2167 // do not use group by clause in report, because same report used for total and unique open
2168 $reportFilter .= "&distinct=0";
2169 case 'opened_unique':
2170 $url = "mailing/opened";
2171 $searchFilter .= "&mailing_open_status=Y";
2172 break;
2173
2174 case 'clicks':
2175 case 'clicks_unique':
2176 $url = "mailing/clicks";
2177 $searchFilter .= "&mailing_click_status=Y";
2178 break;
2179 }
2180 $actionLinks[CRM_Core_Action::VIEW]['url'] = CRM_Report_Utils_Report::getNextUrl($url, $reportFilter, FALSE, TRUE);
2181 if (array_key_exists(CRM_Core_Action::ADVANCED, $actionLinks)) {
2182 $actionLinks[CRM_Core_Action::ADVANCED]['qs'] = $searchFilter;
2183 }
2184 $report['event_totals']['actionlinks'][$key] = CRM_Core_Action::formLink(
2185 $actionLinks,
2186 $action,
2187 ['mid' => $mailing_id],
2188 ts('more'),
2189 FALSE,
2190 'mailing.report.action',
2191 'Mailing',
2192 $mailing_id
2193 );
2194 }
2195
2196 return $report;
2197 }
2198
2199 /**
2200 * Get the count of mailings.
2201 *
2202 * @param
2203 *
2204 * @return int
2205 * Count
2206 */
2207 public function getCount() {
2208 $this->selectAdd();
2209 $this->selectAdd('COUNT(id) as count');
2210
2211 $session = CRM_Core_Session::singleton();
2212 $this->find(TRUE);
2213
2214 return $this->count;
2215 }
2216
2217 /**
2218 * @param int $id
2219 *
2220 * @throws Exception
2221 */
2222 public static function checkPermission($id) {
2223 if (!$id) {
2224 return;
2225 }
2226
2227 $mailingIDs = self::mailingACLIDs();
2228 if ($mailingIDs === TRUE) {
2229 return;
2230 }
2231
2232 if (!in_array($id, $mailingIDs)) {
2233 throw new CRM_Core_Exception(ts('You do not have permission to access this mailing report'));
2234 }
2235 }
2236
2237 /**
2238 * @param null $alias
2239 *
2240 * @return string
2241 */
2242 public static function mailingACL($alias = NULL) {
2243 $mailingACL = " ( 0 ) ";
2244
2245 $mailingIDs = self::mailingACLIDs();
2246 if ($mailingIDs === TRUE) {
2247 return " ( 1 ) ";
2248 }
2249
2250 if (!empty($mailingIDs)) {
2251 $mailingIDs = implode(',', $mailingIDs);
2252 $tableName = !$alias ? self::getTableName() : $alias;
2253 $mailingACL = " $tableName.id IN ( $mailingIDs ) ";
2254 }
2255 return $mailingACL;
2256 }
2257
2258 /**
2259 * Returns all the mailings that this user can access. This is dependent on
2260 * all the groups that the user has access to.
2261 * However since most civi installs dont use ACL's we special case the condition
2262 * where the user has access to ALL groups, and hence ALL mailings and return a
2263 * value of TRUE (to avoid the downstream where clause with a list of mailing list IDs
2264 *
2265 * @return bool|array
2266 * TRUE if the user has access to all mailings, else array of mailing IDs (possibly empty).
2267 */
2268 public static function mailingACLIDs() {
2269 // CRM-11633
2270 // optimize common case where admin has access
2271 // to all mailings
2272 if (
2273 CRM_Core_Permission::check('view all contacts') ||
2274 CRM_Core_Permission::check('edit all contacts')
2275 ) {
2276 return TRUE;
2277 }
2278
2279 $mailingIDs = [];
2280
2281 // get all the groups that this user can access
2282 // if they dont have universal access
2283 $groupNames = civicrm_api3('Group', 'get', [
2284 'check_permissions' => TRUE,
2285 'return' => ['title', 'id'],
2286 'options' => ['limit' => 0],
2287 ]);
2288 foreach ($groupNames['values'] as $group) {
2289 $groups[$group['id']] = $group['title'];
2290 }
2291 if (!empty($groups)) {
2292 $groupIDs = implode(',', array_keys($groups));
2293 $domain_id = CRM_Core_Config::domainID();
2294
2295 // get all the mailings that are in this subset of groups
2296 $query = "
2297 SELECT DISTINCT( m.id ) as id
2298 FROM civicrm_mailing m
2299 LEFT JOIN civicrm_mailing_group g ON g.mailing_id = m.id
2300 WHERE ( ( g.entity_table like 'civicrm_group%' AND g.entity_id IN ( $groupIDs ) )
2301 OR ( g.entity_table IS NULL AND g.entity_id IS NULL AND m.domain_id = $domain_id ) )
2302 ";
2303 $dao = CRM_Core_DAO::executeQuery($query);
2304
2305 $mailingIDs = [];
2306 while ($dao->fetch()) {
2307 $mailingIDs[] = $dao->id;
2308 }
2309 //CRM-18181 Get all mailings that use the mailings found earlier as receipients
2310 if (!empty($mailingIDs)) {
2311 $mailings = implode(',', $mailingIDs);
2312 $mailingQuery = "
2313 SELECT DISTINCT ( m.id ) as id
2314 FROM civicrm_mailing m
2315 LEFT JOIN civicrm_mailing_group g ON g.mailing_id = m.id
2316 WHERE g.entity_table like 'civicrm_mailing%' AND g.entity_id IN ($mailings)";
2317 $mailingDao = CRM_Core_DAO::executeQuery($mailingQuery);
2318 while ($mailingDao->fetch()) {
2319 $mailingIDs[] = $mailingDao->id;
2320 }
2321 }
2322 }
2323
2324 return $mailingIDs;
2325 }
2326
2327 /**
2328 * Get the rows for a browse operation.
2329 *
2330 * @param int $offset
2331 * The row number to start from.
2332 * @param int $rowCount
2333 * The nmber of rows to return.
2334 * @param string $sort
2335 * The sql string that describes the sort order.
2336 *
2337 * @param null $additionalClause
2338 * @param array $additionalParams
2339 *
2340 * @return array
2341 * The rows
2342 */
2343 public function &getRows($offset, $rowCount, $sort, $additionalClause = NULL, $additionalParams = NULL) {
2344 $mailing = self::getTableName();
2345 $job = CRM_Mailing_BAO_MailingJob::getTableName();
2346 $group = CRM_Mailing_DAO_MailingGroup::getTableName();
2347 $session = CRM_Core_Session::singleton();
2348
2349 $mailingACL = self::mailingACL();
2350
2351 //get all campaigns.
2352 $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);
2353 $select = [
2354 "$mailing.id",
2355 "$mailing.name",
2356 "$job.status",
2357 "$mailing.approval_status_id",
2358 "createdContact.sort_name as created_by",
2359 "scheduledContact.sort_name as scheduled_by",
2360 "$mailing.created_id as created_id",
2361 "$mailing.scheduled_id as scheduled_id",
2362 "$mailing.is_archived as archived",
2363 "$mailing.created_date as created_date",
2364 "campaign_id",
2365 "$mailing.sms_provider_id as sms_provider_id",
2366 "$mailing.language",
2367 ];
2368
2369 // we only care about parent jobs, since that holds all the info on
2370 // the mailing
2371 $selectClause = implode(', ', $select);
2372 $groupFromSelect = CRM_Contact_BAO_Query::getGroupByFromSelectColumns($select, "$mailing.id");
2373 $query = "
2374 SELECT {$selectClause},
2375 MIN($job.scheduled_date) as scheduled_date,
2376 MIN($job.start_date) as start_date,
2377 MAX($job.end_date) as end_date
2378 FROM $mailing
2379 LEFT JOIN $job ON ( $job.mailing_id = $mailing.id AND $job.is_test = 0 AND $job.parent_id IS NULL )
2380 LEFT JOIN civicrm_contact createdContact ON ( civicrm_mailing.created_id = createdContact.id )
2381 LEFT JOIN civicrm_contact scheduledContact ON ( civicrm_mailing.scheduled_id = scheduledContact.id )
2382 WHERE $mailingACL $additionalClause";
2383
2384 if (!empty($groupFromSelect)) {
2385 $query .= $groupFromSelect;
2386 }
2387
2388 if ($sort) {
2389 $orderBy = trim($sort->orderBy());
2390 if (!empty($orderBy)) {
2391 $query .= " ORDER BY $orderBy";
2392 }
2393 }
2394
2395 if ($rowCount) {
2396 $offset = CRM_Utils_Type::escape($offset, 'Int');
2397 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
2398
2399 $query .= " LIMIT $offset, $rowCount ";
2400 }
2401
2402 if (!$additionalParams) {
2403 $additionalParams = [];
2404 }
2405
2406 $dao = CRM_Core_DAO::executeQuery($query, $additionalParams);
2407
2408 $rows = [];
2409 while ($dao->fetch()) {
2410 $rows[] = [
2411 'id' => $dao->id,
2412 'name' => $dao->name,
2413 'status' => $dao->status ? $dao->status : 'Not scheduled',
2414 'created_date' => CRM_Utils_Date::customFormat($dao->created_date),
2415 'scheduled' => CRM_Utils_Date::customFormat($dao->scheduled_date),
2416 'scheduled_iso' => $dao->scheduled_date,
2417 'start' => CRM_Utils_Date::customFormat($dao->start_date),
2418 'end' => CRM_Utils_Date::customFormat($dao->end_date),
2419 'created_by' => $dao->created_by,
2420 'scheduled_by' => $dao->scheduled_by,
2421 'created_id' => $dao->created_id,
2422 'scheduled_id' => $dao->scheduled_id,
2423 'archived' => $dao->archived,
2424 'approval_status_id' => $dao->approval_status_id,
2425 'campaign_id' => $dao->campaign_id,
2426 'campaign' => empty($dao->campaign_id) ? NULL : $allCampaigns[$dao->campaign_id],
2427 'sms_provider_id' => $dao->sms_provider_id,
2428 'language' => $dao->language,
2429 ];
2430 }
2431 return $rows;
2432 }
2433
2434 /**
2435 * Show detail Mailing report.
2436 *
2437 * @param int $id
2438 *
2439 * @return string
2440 */
2441 public static function showEmailDetails($id) {
2442 return CRM_Utils_System::url('civicrm/mailing/report', "mid=$id");
2443 }
2444
2445 /**
2446 * Delete Mails and all its associated records.
2447 *
2448 * @param int $id
2449 * Id of the mail to delete.
2450 *
2451 * @return void
2452 */
2453 public static function del($id) {
2454 if (empty($id)) {
2455 throw new CRM_Core_Exception(ts('No id passed to mailing del function'));
2456 }
2457
2458 CRM_Utils_Hook::pre('delete', 'Mailing', $id, CRM_Core_DAO::$_nullArray);
2459
2460 // delete all file attachments
2461 CRM_Core_BAO_File::deleteEntityFile('civicrm_mailing',
2462 $id
2463 );
2464
2465 $dao = new CRM_Mailing_DAO_Mailing();
2466 $dao->id = $id;
2467 $dao->delete();
2468
2469 CRM_Core_Session::setStatus(ts('Selected mailing has been deleted.'), ts('Deleted'), 'success');
2470
2471 CRM_Utils_Hook::post('delete', 'Mailing', $id, $dao);
2472 }
2473
2474 /**
2475 * @deprecated
2476 * Use CRM_Mailing_BAO_MailingJob::del($id)
2477 *
2478 * @param int $id
2479 * Id of the Job to delete.
2480 *
2481 * @return void
2482 */
2483 public static function delJob($id) {
2484 if (empty($id)) {
2485 throw new CRM_Core_Exception(ts('No id passed to mailing delJob function'));
2486 }
2487
2488 \Civi::log('This function is deprecated, use CRM_Mailing_BAO_MailingJob::del instead', ['civi.tag' => 'deprecated']);
2489
2490 CRM_Mailing_BAO_MailingJob::del($id);
2491 }
2492
2493 /**
2494 * @deprecated
2495 * This is used by CiviMail but will be made redundant by FlexMailer/TokenProcessor.
2496 * @return array
2497 */
2498 public function getReturnProperties() {
2499 $tokens = &$this->getTokens();
2500
2501 $properties = [];
2502 if (isset($tokens['html']) &&
2503 isset($tokens['html']['contact'])
2504 ) {
2505 $properties = array_merge($properties, $tokens['html']['contact']);
2506 }
2507
2508 if (isset($tokens['text']) &&
2509 isset($tokens['text']['contact'])
2510 ) {
2511 $properties = array_merge($properties, $tokens['text']['contact']);
2512 }
2513
2514 if (isset($tokens['subject']) &&
2515 isset($tokens['subject']['contact'])
2516 ) {
2517 $properties = array_merge($properties, $tokens['subject']['contact']);
2518 }
2519
2520 $returnProperties = [];
2521 $returnProperties['display_name'] = $returnProperties['contact_id'] = $returnProperties['preferred_mail_format'] = $returnProperties['hash'] = 1;
2522
2523 foreach ($properties as $p) {
2524 $returnProperties[$p] = 1;
2525 }
2526
2527 return $returnProperties;
2528 }
2529
2530 /**
2531 * Build the compose mail form.
2532 *
2533 * @param CRM_Core_Form $form
2534 *
2535 * @return void
2536 */
2537 public static function commonCompose(&$form) {
2538 //get the tokens.
2539 $tokens = [];
2540
2541 if (method_exists($form, 'listTokens')) {
2542 $tokens = array_merge($form->listTokens(), $tokens);
2543 }
2544
2545 //sorted in ascending order tokens by ignoring word case
2546 $form->assign('tokens', CRM_Utils_Token::formatTokensForDisplay($tokens));
2547
2548 $templates = [];
2549
2550 $textFields = [
2551 'text_message' => ts('HTML Format'),
2552 'sms_text_message' => ts('SMS Message'),
2553 ];
2554 $modePrefixes = ['Mail' => NULL, 'SMS' => 'SMS'];
2555
2556 $className = CRM_Utils_System::getClassName($form);
2557
2558 if ($className != 'CRM_SMS_Form_Upload' && $className != 'CRM_Contact_Form_Task_SMS' &&
2559 $className != 'CRM_Contact_Form_Task_SMS'
2560 ) {
2561 $form->add('wysiwyg', 'html_message',
2562 strstr($className, 'PDF') ? ts('Document Body') : ts('HTML Format'),
2563 [
2564 'cols' => '80',
2565 'rows' => '8',
2566 'onkeyup' => "return verify(this)",
2567 ]
2568 );
2569
2570 if ($className != 'CRM_Admin_Form_ScheduleReminders') {
2571 unset($modePrefixes['SMS']);
2572 }
2573 }
2574 else {
2575 unset($textFields['text_message']);
2576 unset($modePrefixes['Mail']);
2577 }
2578
2579 //insert message Text by selecting "Select Template option"
2580 foreach ($textFields as $id => $label) {
2581 $prefix = NULL;
2582 if ($id == 'sms_text_message') {
2583 $prefix = "SMS";
2584 $form->assign('max_sms_length', CRM_SMS_Provider::MAX_SMS_CHAR);
2585 }
2586 $form->add('textarea', $id, $label,
2587 [
2588 'cols' => '80',
2589 'rows' => '8',
2590 'onkeyup' => "return verify(this, '{$prefix}')",
2591 ]
2592 );
2593 }
2594
2595 foreach ($modePrefixes as $prefix) {
2596 if ($prefix == 'SMS') {
2597 $templates[$prefix] = CRM_Core_BAO_MessageTemplate::getMessageTemplates(FALSE, TRUE);
2598 }
2599 else {
2600 $templates[$prefix] = CRM_Core_BAO_MessageTemplate::getMessageTemplates(FALSE);
2601 }
2602 if (!empty($templates[$prefix])) {
2603 $form->assign('templates', TRUE);
2604
2605 $form->add('select', "{$prefix}template", ts('Use Template'),
2606 ['' => ts('- select -')] + $templates[$prefix], FALSE,
2607 ['onChange' => "selectValue( this.value, '{$prefix}');"]
2608 );
2609 }
2610 $form->add('checkbox', "{$prefix}updateTemplate", ts('Update Template'), NULL);
2611
2612 $form->add('checkbox', "{$prefix}saveTemplate", ts('Save As New Template'), NULL, FALSE,
2613 ['onclick' => "showSaveDetails(this, '{$prefix}');"]
2614 );
2615 $form->add('text', "{$prefix}saveTemplateName", ts('Template Title'));
2616 }
2617
2618 // I'm not sure this is ever called.
2619 $action = CRM_Utils_Request::retrieve('action', 'String', $form, FALSE);
2620 if ((CRM_Utils_System::getClassName($form) == 'CRM_Contact_Form_Task_PDF') &&
2621 $action == CRM_Core_Action::VIEW
2622 ) {
2623 $form->freeze('html_message');
2624 }
2625 }
2626
2627 /**
2628 * Get the search based mailing Ids.
2629 *
2630 * @return array
2631 * , searched base mailing ids.
2632 */
2633 public function searchMailingIDs() {
2634 $group = CRM_Mailing_DAO_MailingGroup::getTableName();
2635 $mailing = self::getTableName();
2636
2637 $query = "
2638 SELECT $mailing.id as mailing_id
2639 FROM $mailing, $group
2640 WHERE $group.mailing_id = $mailing.id
2641 AND $group.group_type = 'Base'";
2642
2643 $searchDAO = CRM_Core_DAO::executeQuery($query);
2644 $mailingIDs = [];
2645 while ($searchDAO->fetch()) {
2646 $mailingIDs[] = $searchDAO->mailing_id;
2647 }
2648
2649 return $mailingIDs;
2650 }
2651
2652 /**
2653 * Get the content/components of mailing based on mailing Id
2654 *
2655 * @param array $report
2656 * of mailing report.
2657 *
2658 * @param $form
2659 * Reference of this.
2660 *
2661 * @param bool $isSMS
2662 *
2663 * @return array
2664 * array content/component.
2665 */
2666 public static function getMailingContent(&$report, &$form, $isSMS = FALSE) {
2667 $htmlHeader = $textHeader = NULL;
2668 $htmlFooter = $textFooter = NULL;
2669
2670 if (!$isSMS) {
2671 if ($report['mailing']['header_id']) {
2672 $header = new CRM_Mailing_BAO_MailingComponent();
2673 $header->id = $report['mailing']['header_id'];
2674 $header->find(TRUE);
2675 $htmlHeader = $header->body_html;
2676 $textHeader = $header->body_text;
2677 }
2678
2679 if ($report['mailing']['footer_id']) {
2680 $footer = new CRM_Mailing_BAO_MailingComponent();
2681 $footer->id = $report['mailing']['footer_id'];
2682 $footer->find(TRUE);
2683 $htmlFooter = $footer->body_html;
2684 $textFooter = $footer->body_text;
2685 }
2686 }
2687
2688 $mailingKey = $form->_mailing_id;
2689 if (!$isSMS) {
2690 if ($hash = CRM_Mailing_BAO_Mailing::getMailingHash($mailingKey)) {
2691 $mailingKey = $hash;
2692 }
2693 }
2694
2695 if (!empty($report['mailing']['body_text'])) {
2696 $url = CRM_Utils_System::url('civicrm/mailing/view', 'reset=1&text=1&id=' . $mailingKey);
2697 $form->assign('textViewURL', $url);
2698 }
2699
2700 if (!$isSMS) {
2701 if (!empty($report['mailing']['body_html'])) {
2702 $url = CRM_Utils_System::url('civicrm/mailing/view', 'reset=1&id=' . $mailingKey);
2703 $form->assign('htmlViewURL', $url);
2704 }
2705 }
2706
2707 if (!$isSMS) {
2708 $report['mailing']['attachment'] = CRM_Core_BAO_File::attachmentInfo('civicrm_mailing', $form->_mailing_id);
2709 }
2710 return $report;
2711 }
2712
2713 /**
2714 * @param int $jobID
2715 *
2716 * @return mixed
2717 */
2718 public static function overrideVerp($jobID) {
2719 static $_cache = [];
2720
2721 if (!isset($_cache[$jobID])) {
2722 $query = "
2723 SELECT override_verp
2724 FROM civicrm_mailing
2725 INNER JOIN civicrm_mailing_job ON civicrm_mailing.id = civicrm_mailing_job.mailing_id
2726 WHERE civicrm_mailing_job.id = %1
2727 ";
2728 $params = [1 => [$jobID, 'Integer']];
2729 $_cache[$jobID] = CRM_Core_DAO::singleValueQuery($query, $params);
2730 }
2731 return $_cache[$jobID];
2732 }
2733
2734 /**
2735 * @param null $mode
2736 *
2737 * @return bool
2738 * @throws Exception
2739 */
2740 public static function processQueue($mode = NULL) {
2741 $config = CRM_Core_Config::singleton();
2742
2743 if ($mode == NULL && CRM_Core_BAO_MailSettings::defaultDomain() == "EXAMPLE.ORG") {
2744 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>', [
2745 1 => CRM_Utils_System::url('civicrm/admin/mailSettings', 'reset=1'),
2746 2 => "https://docs.civicrm.org/sysadmin/en/latest/setup/civimail/",
2747 ]));
2748 }
2749
2750 // check if we are enforcing number of parallel cron jobs
2751 // CRM-8460
2752 $gotCronLock = FALSE;
2753
2754 $mailerJobsMax = Civi::settings()->get('mailerJobsMax');
2755 if (is_numeric($mailerJobsMax) && $mailerJobsMax > 0) {
2756 $lockArray = range(1, $mailerJobsMax);
2757
2758 // Shuffle the array to improve chances of quickly finding an open thread
2759 shuffle($lockArray);
2760
2761 // Check if we are using global locks
2762 foreach ($lockArray as $lockID) {
2763 $cronLock = Civi::lockManager()
2764 ->acquire("worker.mailing.send.{$lockID}");
2765 if ($cronLock->isAcquired()) {
2766 $gotCronLock = TRUE;
2767 break;
2768 }
2769 }
2770
2771 // Exit here since we have enough mailing processes running
2772 if (!$gotCronLock) {
2773 CRM_Core_Error::debug_log_message('Returning early, since the maximum number of mailing processes are running');
2774 return TRUE;
2775 }
2776
2777 if (getenv('CIVICRM_CRON_HOLD')) {
2778 // In testing, we may need to simulate some slow activities.
2779 sleep(getenv('CIVICRM_CRON_HOLD'));
2780 }
2781 }
2782
2783 // Split up the parent jobs into multiple child jobs
2784 $mailerJobSize = Civi::settings()->get('mailerJobSize');
2785 CRM_Mailing_BAO_MailingJob::runJobs_pre($mailerJobSize, $mode);
2786 CRM_Mailing_BAO_MailingJob::runJobs(NULL, $mode);
2787 CRM_Mailing_BAO_MailingJob::runJobs_post($mode);
2788
2789 // Release the global lock if we do have one
2790 if ($gotCronLock) {
2791 $cronLock->release();
2792 }
2793
2794 return TRUE;
2795 }
2796
2797 /**
2798 * @param int $mailingID
2799 */
2800 private static function addMultipleEmails($mailingID) {
2801 $sql = "
2802 INSERT INTO civicrm_mailing_recipients
2803 (mailing_id, email_id, contact_id)
2804 SELECT %1, e.id, e.contact_id FROM civicrm_email e
2805 WHERE e.on_hold = 0
2806 AND e.is_bulkmail = 1
2807 AND e.contact_id IN
2808 ( SELECT contact_id FROM civicrm_mailing_recipients mr WHERE mailing_id = %1 )
2809 AND e.id NOT IN ( SELECT email_id FROM civicrm_mailing_recipients mr WHERE mailing_id = %1 )
2810 ";
2811 $params = [1 => [$mailingID, 'Integer']];
2812
2813 $dao = CRM_Core_DAO::executeQuery($sql, $params);
2814 }
2815
2816 /**
2817 * @param bool $isSMS
2818 *
2819 * @return mixed
2820 */
2821 public static function getMailingsList($isSMS = FALSE) {
2822 static $list = [];
2823 $where = " WHERE ";
2824 if (!$isSMS) {
2825 $where .= " civicrm_mailing.sms_provider_id IS NULL ";
2826 }
2827 else {
2828 $where .= " civicrm_mailing.sms_provider_id IS NOT NULL ";
2829 }
2830
2831 if (empty($list)) {
2832 $query = "
2833 SELECT civicrm_mailing.id, civicrm_mailing.name, civicrm_mailing_job.end_date
2834 FROM civicrm_mailing
2835 INNER JOIN civicrm_mailing_job ON civicrm_mailing.id = civicrm_mailing_job.mailing_id {$where}
2836 ORDER BY civicrm_mailing.name";
2837 $mailing = CRM_Core_DAO::executeQuery($query);
2838
2839 while ($mailing->fetch()) {
2840 $list[$mailing->id] = "{$mailing->name} :: {$mailing->end_date}";
2841 }
2842 }
2843
2844 return $list;
2845 }
2846
2847 /**
2848 * wrapper for ajax activity selector.
2849 *
2850 * @param array $params
2851 * Associated array for params record id.
2852 *
2853 * @return array
2854 * associated array of contact activities
2855 */
2856 public static function getContactMailingSelector(&$params) {
2857 // format the params
2858 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2859 $params['rowCount'] = $params['rp'];
2860 $params['sort'] = CRM_Utils_Array::value('sortBy', $params);
2861 $params['caseId'] = NULL;
2862
2863 // get contact mailings
2864 $mailings = CRM_Mailing_BAO_Mailing::getContactMailings($params);
2865
2866 // add total
2867 $params['total'] = CRM_Mailing_BAO_Mailing::getContactMailingsCount($params);
2868
2869 //CRM-12814
2870 if (!empty($mailings)) {
2871 $openCounts = CRM_Mailing_Event_BAO_Opened::getMailingContactCount(array_keys($mailings), $params['contact_id']);
2872 $clickCounts = CRM_Mailing_Event_BAO_TrackableURLOpen::getMailingContactCount(array_keys($mailings), $params['contact_id']);
2873 }
2874
2875 // format params and add links
2876 $contactMailings = [];
2877 foreach ($mailings as $mailingId => $values) {
2878 $mailing = [];
2879 $mailing['subject'] = $values['subject'];
2880 $mailing['creator_name'] = CRM_Utils_System::href(
2881 $values['creator_name'],
2882 'civicrm/contact/view',
2883 "reset=1&cid={$values['creator_id']}");
2884 $mailing['recipients'] = CRM_Utils_System::href(ts('(recipients)'), 'civicrm/mailing/report/event',
2885 "mid={$values['mailing_id']}&reset=1&cid={$params['contact_id']}&event=queue&context=mailing");
2886 $mailing['start_date'] = CRM_Utils_Date::customFormat($values['start_date']);
2887 //CRM-12814
2888 $mailing['openstats'] = "Opens: " .
2889 CRM_Utils_Array::value($values['mailing_id'], $openCounts, 0) .
2890 "<br />Clicks: " .
2891 CRM_Utils_Array::value($values['mailing_id'], $clickCounts, 0);
2892
2893 $actionLinks = [
2894 CRM_Core_Action::VIEW => [
2895 'name' => ts('View'),
2896 'url' => 'civicrm/mailing/view',
2897 'qs' => "reset=1&id=%%mkey%%",
2898 'title' => ts('View Mailing'),
2899 'class' => 'crm-popup',
2900 ],
2901 CRM_Core_Action::BROWSE => [
2902 'name' => ts('Mailing Report'),
2903 'url' => 'civicrm/mailing/report',
2904 'qs' => "mid=%%mid%%&reset=1&cid=%%cid%%&context=mailing",
2905 'title' => ts('View Mailing Report'),
2906 ],
2907 ];
2908
2909 $mailingKey = $values['mailing_id'];
2910 if ($hash = CRM_Mailing_BAO_Mailing::getMailingHash($mailingKey)) {
2911 $mailingKey = $hash;
2912 }
2913
2914 $mailing['links'] = CRM_Core_Action::formLink(
2915 $actionLinks,
2916 NULL,
2917 [
2918 'mid' => $values['mailing_id'],
2919 'cid' => $params['contact_id'],
2920 'mkey' => $mailingKey,
2921 ],
2922 ts('more'),
2923 FALSE,
2924 'mailing.contact.action',
2925 'Mailing',
2926 $values['mailing_id']
2927 );
2928
2929 array_push($contactMailings, $mailing);
2930 }
2931
2932 $contactMailingsDT = [];
2933 $contactMailingsDT['data'] = $contactMailings;
2934 $contactMailingsDT['recordsTotal'] = $params['total'];
2935 $contactMailingsDT['recordsFiltered'] = $params['total'];
2936
2937 return $contactMailingsDT;
2938 }
2939
2940 /**
2941 * Retrieve contact mailing.
2942 *
2943 * @param array $params
2944 *
2945 * @return array
2946 * Array of mailings for a contact
2947 *
2948 */
2949 public static function getContactMailings(&$params) {
2950 $params['version'] = 3;
2951 $params['offset'] = ($params['page'] - 1) * $params['rp'];
2952 $params['limit'] = $params['rp'];
2953 $params['sort'] = CRM_Utils_Array::value('sortBy', $params);
2954
2955 $result = civicrm_api('MailingContact', 'get', $params);
2956 return $result['values'];
2957 }
2958
2959 /**
2960 * Retrieve contact mailing count.
2961 *
2962 * @param array $params
2963 *
2964 * @return int
2965 * count of mailings for a contact
2966 *
2967 */
2968 public static function getContactMailingsCount(&$params) {
2969 $params['version'] = 3;
2970 return civicrm_api('MailingContact', 'getcount', $params);
2971 }
2972
2973 /**
2974 * Get a list of permissions required for CRUD'ing each field
2975 * (when workflow is enabled).
2976 *
2977 * @return array
2978 * Array (string $fieldName => string $permName)
2979 */
2980 public static function getWorkflowFieldPerms() {
2981 $fieldNames = array_keys(CRM_Mailing_DAO_Mailing::fields());
2982 $fieldPerms = [];
2983 foreach ($fieldNames as $fieldName) {
2984 if ($fieldName == 'id') {
2985 $fieldPerms[$fieldName] = [
2986 // OR
2987 [
2988 'access CiviMail',
2989 'schedule mailings',
2990 'approve mailings',
2991 ],
2992 ];
2993 }
2994 elseif (in_array($fieldName, ['scheduled_date', 'scheduled_id'])) {
2995 $fieldPerms[$fieldName] = [
2996 // OR
2997 ['access CiviMail', 'schedule mailings'],
2998 ];
2999 }
3000 elseif (in_array($fieldName, [
3001 'approval_date',
3002 'approver_id',
3003 'approval_status_id',
3004 'approval_note',
3005 ])) {
3006 $fieldPerms[$fieldName] = [
3007 // OR
3008 ['access CiviMail', 'approve mailings'],
3009 ];
3010 }
3011 else {
3012 $fieldPerms[$fieldName] = [
3013 // OR
3014 ['access CiviMail', 'create mailings'],
3015 ];
3016 }
3017 }
3018 return $fieldPerms;
3019 }
3020
3021 /**
3022 * White-list of possible values for the entity_table field.
3023 *
3024 * @return array
3025 */
3026 public static function mailingGroupEntityTables() {
3027 return [
3028 CRM_Contact_BAO_Group::getTableName() => 'Group',
3029 CRM_Mailing_BAO_Mailing::getTableName() => 'Mailing',
3030 ];
3031 }
3032
3033 /**
3034 * Get the public view url.
3035 *
3036 * @param int $id
3037 * @param bool $absolute
3038 *
3039 * @return string
3040 */
3041 public static function getPublicViewUrl($id, $absolute = TRUE) {
3042 if ((civicrm_api3('Mailing', 'getvalue', [
3043 'id' => $id,
3044 'return' => 'visibility',
3045 ])) === 'Public Pages') {
3046
3047 // if hash setting is on then we change the public url into a hash
3048 $hash = CRM_Mailing_BAO_Mailing::getMailingHash($id);
3049 if (!empty($hash)) {
3050 $id = $hash;
3051 }
3052
3053 return CRM_Utils_System::url('civicrm/mailing/view', ['id' => $id], $absolute, NULL, TRUE, TRUE);
3054 }
3055 }
3056
3057 /**
3058 * Get a list of template types which can be used as `civicrm_mailing.template_type`.
3059 *
3060 * @return array
3061 * A list of template-types, keyed numerically. Each defines:
3062 * - name: string, a short symbolic name
3063 * - editorUrl: string, Angular template name
3064 *
3065 * Ex: $templateTypes[0] === array('name' => 'mosaico', 'editorUrl' => '~/crmMosaico/editor.html').
3066 */
3067 public static function getTemplateTypes() {
3068 if (!isset(Civi::$statics[__CLASS__]['templateTypes'])) {
3069 $types = [];
3070 $types[] = [
3071 'name' => 'traditional',
3072 'editorUrl' => CRM_Mailing_Info::workflowEnabled() ? '~/crmMailing/EditMailingCtrl/workflow.html' : '~/crmMailing/EditMailingCtrl/2step.html',
3073 'weight' => 0,
3074 ];
3075
3076 CRM_Utils_Hook::mailingTemplateTypes($types);
3077
3078 $defaults = ['weight' => 0];
3079 foreach (array_keys($types) as $typeName) {
3080 $types[$typeName] = array_merge($defaults, $types[$typeName]);
3081 }
3082 usort($types, function ($a, $b) {
3083 if ($a['weight'] === $b['weight']) {
3084 return 0;
3085 }
3086 return $a['weight'] < $b['weight'] ? -1 : 1;
3087 });
3088
3089 Civi::$statics[__CLASS__]['templateTypes'] = $types;
3090 }
3091
3092 return Civi::$statics[__CLASS__]['templateTypes'];
3093 }
3094
3095 /**
3096 * Get a list of template types.
3097 *
3098 * @return array
3099 * Array(string $name => string $label).
3100 */
3101 public static function getTemplateTypeNames() {
3102 $r = [];
3103 foreach (self::getTemplateTypes() as $type) {
3104 $r[$type['name']] = $type['name'];
3105 }
3106 return $r;
3107 }
3108
3109 }