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