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