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