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