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