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