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