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