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