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