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