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