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