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