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 | ||
ef643544 | 1478 | |
6a488035 TO |
1479 | if ($id) { |
1480 | CRM_Utils_Hook::pre('edit', 'Mailing', $id, $params); | |
1481 | } | |
1482 | else { | |
1483 | CRM_Utils_Hook::pre('create', 'Mailing', NULL, $params); | |
1484 | } | |
1485 | ||
1486 | $mailing = new CRM_Mailing_DAO_Mailing(); | |
1487 | $mailing->id = $id; | |
1488 | $mailing->domain_id = CRM_Utils_Array::value('domain_id', $params, CRM_Core_Config::domainID()); | |
1489 | ||
1490 | if (!isset($params['replyto_email']) && | |
1491 | isset($params['from_email']) | |
1492 | ) { | |
1493 | $params['replyto_email'] = $params['from_email']; | |
1494 | } | |
1495 | ||
1496 | $mailing->copyValues($params); | |
1497 | ||
1498 | $result = $mailing->save(); | |
1499 | ||
a7488080 | 1500 | if (!empty($ids['mailing'])) { |
6a488035 TO |
1501 | CRM_Utils_Hook::post('edit', 'Mailing', $mailing->id, $mailing); |
1502 | } | |
1503 | else { | |
1504 | CRM_Utils_Hook::post('create', 'Mailing', $mailing->id, $mailing); | |
1505 | } | |
1506 | ||
1507 | return $result; | |
1508 | } | |
1509 | ||
1510 | /** | |
1511 | * Construct a new mailing object, along with job and mailing_group | |
1512 | * objects, from the form values of the create mailing wizard. | |
1513 | * | |
1514 | * @params array $params Form values | |
1515 | * | |
af4c09bc EM |
1516 | * @param $params |
1517 | * @param array $ids | |
1518 | * | |
6a488035 TO |
1519 | * @return object $mailing The new mailing object |
1520 | * @access public | |
1521 | * @static | |
1522 | */ | |
1523 | public static function create(&$params, $ids = array()) { | |
6a488035 | 1524 | |
9510d1b1 DL |
1525 | // CRM-12430 |
1526 | // Do the below only for an insert | |
1527 | // for an update, we should not set the defaults | |
1528 | if (!isset($ids['id']) && !isset($ids['mailing_id'])) { | |
1529 | // Retrieve domain email and name for default sender | |
1530 | $domain = civicrm_api( | |
1531 | 'Domain', | |
1532 | 'getsingle', | |
1533 | array( | |
1534 | 'version' => 3, | |
1535 | 'current_domain' => 1, | |
1536 | 'sequential' => 1, | |
1537 | ) | |
1538 | ); | |
1539 | if (isset($domain['from_email'])) { | |
1540 | $domain_email = $domain['from_email']; | |
1541 | $domain_name = $domain['from_name']; | |
1542 | } | |
1543 | else { | |
1544 | $domain_email = 'info@EXAMPLE.ORG'; | |
1545 | $domain_name = 'EXAMPLE.ORG'; | |
1546 | } | |
1547 | if (!isset($params['created_id'])) { | |
1548 | $session =& CRM_Core_Session::singleton(); | |
1549 | $params['created_id'] = $session->get('userID'); | |
1550 | } | |
1551 | $defaults = array( | |
1552 | // load the default config settings for each | |
1553 | // eg reply_id, unsubscribe_id need to use | |
1554 | // correct template IDs here | |
1555 | 'override_verp' => TRUE, | |
1556 | 'forward_replies' => FALSE, | |
1557 | 'open_tracking' => TRUE, | |
1558 | 'url_tracking' => TRUE, | |
902d0e66 | 1559 | 'visibility' => 'Public Pages', |
9510d1b1 DL |
1560 | 'replyto_email' => $domain_email, |
1561 | 'header_id' => CRM_Mailing_PseudoConstant::defaultComponent('header_id', ''), | |
1562 | 'footer_id' => CRM_Mailing_PseudoConstant::defaultComponent('footer_id', ''), | |
1563 | 'from_email' => $domain_email, | |
1564 | 'from_name' => $domain_name, | |
1565 | 'msg_template_id' => NULL, | |
9510d1b1 | 1566 | 'created_id' => $params['created_id'], |
1365ea2f | 1567 | 'approver_id' => NULL, |
9510d1b1 DL |
1568 | 'auto_responder' => 0, |
1569 | 'created_date' => date('YmdHis'), | |
1365ea2f BS |
1570 | 'scheduled_date' => NULL, |
1571 | 'approval_date' => NULL, | |
9510d1b1 DL |
1572 | ); |
1573 | ||
1574 | // Get the default from email address, if not provided. | |
1575 | if (empty($defaults['from_email'])) { | |
1576 | $defaultAddress = CRM_Core_OptionGroup::values('from_email_address', NULL, NULL, NULL, ' AND is_default = 1'); | |
1577 | foreach ($defaultAddress as $id => $value) { | |
1578 | if (preg_match('/"(.*)" <(.*)>/', $value, $match)) { | |
1579 | $defaults['from_email'] = $match[2]; | |
1580 | $defaults['from_name'] = $match[1]; | |
1581 | } | |
6a488035 TO |
1582 | } |
1583 | } | |
6a488035 | 1584 | |
9510d1b1 DL |
1585 | $params = array_merge($defaults, $params); |
1586 | } | |
6a488035 TO |
1587 | |
1588 | /** | |
1589 | * Could check and warn for the following cases: | |
1590 | * | |
1591 | * - groups OR mailings should be populated. | |
1592 | * - body html OR body text should be populated. | |
1593 | */ | |
1594 | ||
1595 | $transaction = new CRM_Core_Transaction(); | |
1596 | ||
1597 | $mailing = self::add($params, $ids); | |
1598 | ||
1599 | if (is_a($mailing, 'CRM_Core_Error')) { | |
1600 | $transaction->rollback(); | |
1601 | return $mailing; | |
1602 | } | |
c57f36a1 PJ |
1603 | // update mailings with hash values |
1604 | CRM_Contact_BAO_Contact_Utils::generateChecksum($mailing->id, NULL, NULL, NULL, 'mailing', 16); | |
6a488035 TO |
1605 | |
1606 | $groupTableName = CRM_Contact_BAO_Group::getTableName(); | |
1607 | $mailingTableName = CRM_Mailing_BAO_Mailing::getTableName(); | |
1608 | ||
1609 | /* Create the mailing group record */ | |
04124b30 | 1610 | $mg = new CRM_Mailing_DAO_MailingGroup(); |
6a488035 TO |
1611 | foreach (array('groups', 'mailings') as $entity) { |
1612 | foreach (array('include', 'exclude', 'base') as $type) { | |
8cc574cf | 1613 | if (isset($params[$entity]) && !empty($params[$entity][$type]) && |
9510d1b1 | 1614 | is_array($params[$entity][$type])) { |
6a488035 TO |
1615 | foreach ($params[$entity][$type] as $entityId) { |
1616 | $mg->reset(); | |
1617 | $mg->mailing_id = $mailing->id; | |
1618 | $mg->entity_table = ($entity == 'groups') ? $groupTableName : $mailingTableName; | |
1619 | $mg->entity_id = $entityId; | |
1620 | $mg->group_type = $type; | |
1621 | $mg->save(); | |
1622 | } | |
1623 | } | |
1624 | } | |
1625 | } | |
1626 | ||
1627 | if (!empty($params['search_id']) && !empty($params['group_id'])) { | |
1628 | $mg->reset(); | |
1629 | $mg->mailing_id = $mailing->id; | |
1630 | $mg->entity_table = $groupTableName; | |
1631 | $mg->entity_id = $params['group_id']; | |
1632 | $mg->search_id = $params['search_id']; | |
1633 | $mg->search_args = $params['search_args']; | |
1634 | $mg->group_type = 'Include'; | |
1635 | $mg->save(); | |
1636 | } | |
1637 | ||
1638 | // check and attach and files as needed | |
1639 | CRM_Core_BAO_File::processAttachment($params, 'civicrm_mailing', $mailing->id); | |
1640 | ||
1641 | $transaction->commit(); | |
1642 | ||
1643 | /** | |
1365ea2f BS |
1644 | * create parent job if not yet created |
1645 | * condition on the existence of a scheduled date | |
6a488035 | 1646 | */ |
9e346357 | 1647 | if (!empty($params['scheduled_date']) && $params['scheduled_date'] != 'null') { |
9da8dc8c | 1648 | $job = new CRM_Mailing_BAO_MailingJob(); |
6a488035 TO |
1649 | $job->mailing_id = $mailing->id; |
1650 | $job->status = 'Scheduled'; | |
1651 | $job->is_test = 0; | |
1365ea2f BS |
1652 | |
1653 | if ( !$job->find(TRUE) ) { | |
1654 | $job->scheduled_date = $params['scheduled_date']; | |
1655 | $job->save(); | |
1656 | } | |
1657 | ||
6a488035 | 1658 | // Populate the recipients. |
553f116a | 1659 | $mailing->getRecipients($job->id, $mailing->id, NULL, NULL, TRUE, FALSE); |
6a488035 TO |
1660 | } |
1661 | ||
1662 | return $mailing; | |
1663 | } | |
1664 | ||
c57f36a1 PJ |
1665 | /** |
1666 | * get hash value of the mailing | |
1667 | * | |
1668 | */ | |
1669 | public static function getMailingHash($id) { | |
1670 | $hash = NULL; | |
1671 | if (CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, 'hash_mailing_url')) { | |
1672 | $hash = CRM_Core_DAO::getFieldValue('CRM_Mailing_BAO_Mailing', $id, 'hash', 'id'); | |
1673 | } | |
1674 | return $hash; | |
1675 | } | |
1676 | ||
6a488035 TO |
1677 | /** |
1678 | * Generate a report. Fetch event count information, mailing data, and job | |
1679 | * status. | |
1680 | * | |
77b97be7 | 1681 | * @param int $id The mailing id to report |
6a488035 TO |
1682 | * @param boolean $skipDetails whether return all detailed report |
1683 | * | |
77b97be7 EM |
1684 | * @param bool $isSMS |
1685 | * | |
6a488035 TO |
1686 | * @return array Associative array of reporting data |
1687 | * @access public | |
1688 | * @static | |
1689 | */ | |
1690 | public static function &report($id, $skipDetails = FALSE, $isSMS = FALSE) { | |
1691 | $mailing_id = CRM_Utils_Type::escape($id, 'Integer'); | |
1692 | ||
1693 | $mailing = new CRM_Mailing_BAO_Mailing(); | |
1694 | ||
1695 | $t = array( | |
1696 | 'mailing' => self::getTableName(), | |
04124b30 | 1697 | 'mailing_group' => CRM_Mailing_DAO_MailingGroup::getTableName(), |
6a488035 | 1698 | 'group' => CRM_Contact_BAO_Group::getTableName(), |
9da8dc8c | 1699 | 'job' => CRM_Mailing_BAO_MailingJob::getTableName(), |
6a488035 TO |
1700 | 'queue' => CRM_Mailing_Event_BAO_Queue::getTableName(), |
1701 | 'delivered' => CRM_Mailing_Event_BAO_Delivered::getTableName(), | |
1702 | 'opened' => CRM_Mailing_Event_BAO_Opened::getTableName(), | |
1703 | 'reply' => CRM_Mailing_Event_BAO_Reply::getTableName(), | |
1704 | 'unsubscribe' => | |
1705 | CRM_Mailing_Event_BAO_Unsubscribe::getTableName(), | |
1706 | 'bounce' => CRM_Mailing_Event_BAO_Bounce::getTableName(), | |
1707 | 'forward' => CRM_Mailing_Event_BAO_Forward::getTableName(), | |
1708 | 'url' => CRM_Mailing_BAO_TrackableURL::getTableName(), | |
1709 | 'urlopen' => | |
1710 | CRM_Mailing_Event_BAO_TrackableURLOpen::getTableName(), | |
1711 | 'component' => CRM_Mailing_BAO_Component::getTableName(), | |
1712 | 'spool' => CRM_Mailing_BAO_Spool::getTableName(), | |
1713 | ); | |
1714 | ||
1715 | ||
1716 | $report = array(); | |
1717 | $additionalWhereClause = " AND "; | |
1718 | if (!$isSMS) { | |
1719 | $additionalWhereClause .= " {$t['mailing']}.sms_provider_id IS NULL "; | |
1720 | } | |
1721 | else { | |
1722 | $additionalWhereClause .= " {$t['mailing']}.sms_provider_id IS NOT NULL "; | |
1723 | } | |
1724 | ||
1725 | /* Get the mailing info */ | |
1726 | ||
1727 | $mailing->query(" | |
1728 | SELECT {$t['mailing']}.* | |
1729 | FROM {$t['mailing']} | |
1730 | WHERE {$t['mailing']}.id = $mailing_id {$additionalWhereClause}"); | |
1731 | ||
1732 | $mailing->fetch(); | |
1733 | ||
1734 | $report['mailing'] = array(); | |
1735 | foreach (array_keys(self::fields()) as $field) { | |
1736 | $report['mailing'][$field] = $mailing->$field; | |
1737 | } | |
1738 | ||
1739 | //get the campaign | |
1740 | if ($campaignId = CRM_Utils_Array::value('campaign_id', $report['mailing'])) { | |
1741 | $campaigns = CRM_Campaign_BAO_Campaign::getCampaigns($campaignId); | |
1742 | $report['mailing']['campaign'] = $campaigns[$campaignId]; | |
1743 | } | |
1744 | ||
1745 | //mailing report is called by activity | |
1746 | //we dont need all detail report | |
1747 | if ($skipDetails) { | |
1748 | return $report; | |
1749 | } | |
1750 | ||
1751 | /* Get the component info */ | |
1752 | ||
1753 | $query = array(); | |
1754 | ||
1755 | $components = array( | |
1756 | 'header' => ts('Header'), | |
1757 | 'footer' => ts('Footer'), | |
1758 | 'reply' => ts('Reply'), | |
1759 | 'unsubscribe' => ts('Unsubscribe'), | |
1760 | 'optout' => ts('Opt-Out'), | |
1761 | ); | |
1762 | foreach (array_keys($components) as $type) { | |
1763 | $query[] = "SELECT {$t['component']}.name as name, | |
1764 | '$type' as type, | |
1765 | {$t['component']}.id as id | |
1766 | FROM {$t['component']} | |
1767 | INNER JOIN {$t['mailing']} | |
1768 | ON {$t['mailing']}.{$type}_id = | |
1769 | {$t['component']}.id | |
1770 | WHERE {$t['mailing']}.id = $mailing_id"; | |
1771 | } | |
1772 | $q = '(' . implode(') UNION (', $query) . ')'; | |
1773 | $mailing->query($q); | |
1774 | ||
1775 | $report['component'] = array(); | |
1776 | while ($mailing->fetch()) { | |
1777 | $report['component'][] = array( | |
1778 | 'type' => $components[$mailing->type], | |
1779 | 'name' => $mailing->name, | |
1780 | 'link' => | |
1781 | CRM_Utils_System::url('civicrm/mailing/component', | |
1782 | "reset=1&action=update&id={$mailing->id}" | |
1783 | ), | |
1784 | ); | |
1785 | } | |
1786 | ||
1787 | /* Get the recipient group info */ | |
1788 | ||
1789 | $mailing->query(" | |
1790 | SELECT {$t['mailing_group']}.group_type as group_type, | |
1791 | {$t['group']}.id as group_id, | |
1792 | {$t['group']}.title as group_title, | |
1793 | {$t['group']}.is_hidden as group_hidden, | |
1794 | {$t['mailing']}.id as mailing_id, | |
1795 | {$t['mailing']}.name as mailing_name | |
1796 | FROM {$t['mailing_group']} | |
1797 | LEFT JOIN {$t['group']} | |
1798 | ON {$t['mailing_group']}.entity_id = {$t['group']}.id | |
1799 | AND {$t['mailing_group']}.entity_table = | |
1800 | '{$t['group']}' | |
1801 | LEFT JOIN {$t['mailing']} | |
1802 | ON {$t['mailing_group']}.entity_id = | |
1803 | {$t['mailing']}.id | |
1804 | AND {$t['mailing_group']}.entity_table = | |
1805 | '{$t['mailing']}' | |
1806 | ||
1807 | WHERE {$t['mailing_group']}.mailing_id = $mailing_id | |
1808 | "); | |
1809 | ||
1810 | $report['group'] = array('include' => array(), 'exclude' => array(), 'base' => array()); | |
1811 | while ($mailing->fetch()) { | |
1812 | $row = array(); | |
1813 | if (isset($mailing->group_id)) { | |
1814 | $row['id'] = $mailing->group_id; | |
1815 | $row['name'] = $mailing->group_title; | |
1816 | $row['link'] = CRM_Utils_System::url('civicrm/group/search', | |
9510d1b1 | 1817 | "reset=1&force=1&context=smog&gid={$row['id']}" |
6a488035 TO |
1818 | ); |
1819 | } | |
1820 | else { | |
1821 | $row['id'] = $mailing->mailing_id; | |
1822 | $row['name'] = $mailing->mailing_name; | |
1823 | $row['mailing'] = TRUE; | |
1824 | $row['link'] = CRM_Utils_System::url('civicrm/mailing/report', | |
9510d1b1 | 1825 | "mid={$row['id']}" |
6a488035 TO |
1826 | ); |
1827 | } | |
1828 | ||
1829 | /* Rename hidden groups */ | |
1830 | ||
1831 | if ($mailing->group_hidden == 1) { | |
1832 | $row['name'] = "Search Results"; | |
1833 | } | |
1834 | ||
1835 | if ($mailing->group_type == 'Include') { | |
1836 | $report['group']['include'][] = $row; | |
1837 | } | |
1838 | elseif ($mailing->group_type == 'Base') { | |
1839 | $report['group']['base'][] = $row; | |
1840 | } | |
1841 | else { | |
1842 | $report['group']['exclude'][] = $row; | |
1843 | } | |
1844 | } | |
1845 | ||
1846 | /* Get the event totals, grouped by job (retries) */ | |
1847 | ||
1848 | $mailing->query(" | |
1849 | SELECT {$t['job']}.*, | |
1850 | COUNT(DISTINCT {$t['queue']}.id) as queue, | |
1851 | COUNT(DISTINCT {$t['delivered']}.id) as delivered, | |
1852 | COUNT(DISTINCT {$t['reply']}.id) as reply, | |
1853 | COUNT(DISTINCT {$t['forward']}.id) as forward, | |
1854 | COUNT(DISTINCT {$t['bounce']}.id) as bounce, | |
1855 | COUNT(DISTINCT {$t['urlopen']}.id) as url, | |
1856 | COUNT(DISTINCT {$t['spool']}.id) as spool | |
1857 | FROM {$t['job']} | |
1858 | LEFT JOIN {$t['queue']} | |
1859 | ON {$t['queue']}.job_id = {$t['job']}.id | |
1860 | LEFT JOIN {$t['reply']} | |
1861 | ON {$t['reply']}.event_queue_id = {$t['queue']}.id | |
1862 | LEFT JOIN {$t['forward']} | |
1863 | ON {$t['forward']}.event_queue_id = {$t['queue']}.id | |
1864 | LEFT JOIN {$t['bounce']} | |
1865 | ON {$t['bounce']}.event_queue_id = {$t['queue']}.id | |
1866 | LEFT JOIN {$t['delivered']} | |
1867 | ON {$t['delivered']}.event_queue_id = {$t['queue']}.id | |
1868 | AND {$t['bounce']}.id IS null | |
1869 | LEFT JOIN {$t['urlopen']} | |
1870 | ON {$t['urlopen']}.event_queue_id = {$t['queue']}.id | |
1871 | LEFT JOIN {$t['spool']} | |
1872 | ON {$t['spool']}.job_id = {$t['job']}.id | |
1873 | WHERE {$t['job']}.mailing_id = $mailing_id | |
1874 | AND {$t['job']}.is_test = 0 | |
1875 | GROUP BY {$t['job']}.id"); | |
1876 | ||
1877 | $report['jobs'] = array(); | |
1878 | $report['event_totals'] = array(); | |
1879 | $elements = array( | |
1880 | 'queue', 'delivered', 'url', 'forward', | |
1881 | 'reply', 'unsubscribe', 'optout', 'opened', 'bounce', 'spool', | |
1882 | ); | |
1883 | ||
1884 | // initialize various counters | |
1885 | foreach ($elements as $field) { | |
1886 | $report['event_totals'][$field] = 0; | |
1887 | } | |
1888 | ||
1889 | while ($mailing->fetch()) { | |
1890 | $row = array(); | |
1891 | foreach ($elements as $field) { | |
1892 | if (isset($mailing->$field)) { | |
1893 | $row[$field] = $mailing->$field; | |
1894 | $report['event_totals'][$field] += $mailing->$field; | |
1895 | } | |
1896 | } | |
1897 | ||
1898 | // compute open total separately to discount duplicates | |
1899 | // CRM-1258 | |
1900 | $row['opened'] = CRM_Mailing_Event_BAO_Opened::getTotalCount($mailing_id, $mailing->id, TRUE); | |
1901 | $report['event_totals']['opened'] += $row['opened']; | |
1902 | ||
1903 | // compute unsub total separately to discount duplicates | |
1904 | // CRM-1783 | |
1905 | $row['unsubscribe'] = CRM_Mailing_Event_BAO_Unsubscribe::getTotalCount($mailing_id, $mailing->id, TRUE, TRUE); | |
1906 | $report['event_totals']['unsubscribe'] += $row['unsubscribe']; | |
1907 | ||
1908 | $row['optout'] = CRM_Mailing_Event_BAO_Unsubscribe::getTotalCount($mailing_id, $mailing->id, TRUE, FALSE); | |
1909 | $report['event_totals']['optout'] += $row['optout']; | |
1910 | ||
9da8dc8c | 1911 | foreach (array_keys(CRM_Mailing_BAO_MailingJob::fields()) as $field) { |
6a488035 TO |
1912 | $row[$field] = $mailing->$field; |
1913 | } | |
1914 | ||
1915 | if ($mailing->queue) { | |
1916 | $row['delivered_rate'] = (100.0 * $mailing->delivered) / $mailing->queue; | |
1917 | $row['bounce_rate'] = (100.0 * $mailing->bounce) / $mailing->queue; | |
1918 | $row['unsubscribe_rate'] = (100.0 * $row['unsubscribe']) / $mailing->queue; | |
1919 | $row['optout_rate'] = (100.0 * $row['optout']) / $mailing->queue; | |
1920 | } | |
1921 | else { | |
1922 | $row['delivered_rate'] = 0; | |
1923 | $row['bounce_rate'] = 0; | |
1924 | $row['unsubscribe_rate'] = 0; | |
1925 | $row['optout_rate'] = 0; | |
1926 | } | |
1927 | ||
1928 | $row['links'] = array( | |
1929 | 'clicks' => CRM_Utils_System::url( | |
1930 | 'civicrm/mailing/report/event', | |
1931 | "reset=1&event=click&mid=$mailing_id&jid={$mailing->id}" | |
1932 | ), | |
1933 | 'queue' => CRM_Utils_System::url( | |
1934 | 'civicrm/mailing/report/event', | |
1935 | "reset=1&event=queue&mid=$mailing_id&jid={$mailing->id}" | |
1936 | ), | |
1937 | 'delivered' => CRM_Utils_System::url( | |
1938 | 'civicrm/mailing/report/event', | |
1939 | "reset=1&event=delivered&mid=$mailing_id&jid={$mailing->id}" | |
1940 | ), | |
1941 | 'bounce' => CRM_Utils_System::url( | |
1942 | 'civicrm/mailing/report/event', | |
1943 | "reset=1&event=bounce&mid=$mailing_id&jid={$mailing->id}" | |
1944 | ), | |
1945 | 'unsubscribe' => CRM_Utils_System::url( | |
1946 | 'civicrm/mailing/report/event', | |
1947 | "reset=1&event=unsubscribe&mid=$mailing_id&jid={$mailing->id}" | |
1948 | ), | |
1949 | 'forward' => CRM_Utils_System::url( | |
1950 | 'civicrm/mailing/report/event', | |
1951 | "reset=1&event=forward&mid=$mailing_id&jid={$mailing->id}" | |
1952 | ), | |
1953 | 'reply' => CRM_Utils_System::url( | |
1954 | 'civicrm/mailing/report/event', | |
1955 | "reset=1&event=reply&mid=$mailing_id&jid={$mailing->id}" | |
1956 | ), | |
1957 | 'opened' => CRM_Utils_System::url( | |
1958 | 'civicrm/mailing/report/event', | |
1959 | "reset=1&event=opened&mid=$mailing_id&jid={$mailing->id}" | |
1960 | ), | |
1961 | ); | |
1962 | ||
1963 | foreach (array( | |
9510d1b1 | 1964 | 'scheduled_date', 'start_date', 'end_date') as $key) { |
6a488035 TO |
1965 | $row[$key] = CRM_Utils_Date::customFormat($row[$key]); |
1966 | } | |
1967 | $report['jobs'][] = $row; | |
1968 | } | |
1969 | ||
1970 | $newTableSize = CRM_Mailing_BAO_Recipients::mailingSize($mailing_id); | |
1971 | ||
1972 | // we need to do this for backward compatibility, since old mailings did not | |
1973 | // use the mailing_recipients table | |
1974 | if ($newTableSize > 0) { | |
1975 | $report['event_totals']['queue'] = $newTableSize; | |
1976 | } | |
1977 | else { | |
1978 | $report['event_totals']['queue'] = self::getRecipientsCount($mailing_id, $mailing_id); | |
1979 | } | |
1980 | ||
a7488080 | 1981 | if (!empty($report['event_totals']['queue'])) { |
6a488035 TO |
1982 | $report['event_totals']['delivered_rate'] = (100.0 * $report['event_totals']['delivered']) / $report['event_totals']['queue']; |
1983 | $report['event_totals']['bounce_rate'] = (100.0 * $report['event_totals']['bounce']) / $report['event_totals']['queue']; | |
1984 | $report['event_totals']['unsubscribe_rate'] = (100.0 * $report['event_totals']['unsubscribe']) / $report['event_totals']['queue']; | |
1985 | $report['event_totals']['optout_rate'] = (100.0 * $report['event_totals']['optout']) / $report['event_totals']['queue']; | |
1986 | } | |
1987 | else { | |
1988 | $report['event_totals']['delivered_rate'] = 0; | |
1989 | $report['event_totals']['bounce_rate'] = 0; | |
1990 | $report['event_totals']['unsubscribe_rate'] = 0; | |
1991 | $report['event_totals']['optout_rate'] = 0; | |
1992 | } | |
1993 | ||
1994 | /* Get the click-through totals, grouped by URL */ | |
1995 | ||
1996 | $mailing->query(" | |
1997 | SELECT {$t['url']}.url, | |
1998 | {$t['url']}.id, | |
1999 | COUNT({$t['urlopen']}.id) as clicks, | |
2000 | COUNT(DISTINCT {$t['queue']}.id) as unique_clicks | |
2001 | FROM {$t['url']} | |
2002 | LEFT JOIN {$t['urlopen']} | |
2003 | ON {$t['urlopen']}.trackable_url_id = {$t['url']}.id | |
2004 | LEFT JOIN {$t['queue']} | |
2005 | ON {$t['urlopen']}.event_queue_id = {$t['queue']}.id | |
2006 | LEFT JOIN {$t['job']} | |
2007 | ON {$t['queue']}.job_id = {$t['job']}.id | |
2008 | WHERE {$t['url']}.mailing_id = $mailing_id | |
2009 | AND {$t['job']}.is_test = 0 | |
2010 | GROUP BY {$t['url']}.id"); | |
2011 | ||
2012 | $report['click_through'] = array(); | |
2013 | ||
2014 | while ($mailing->fetch()) { | |
2015 | $report['click_through'][] = array( | |
2016 | 'url' => $mailing->url, | |
2017 | 'link' => | |
2018 | CRM_Utils_System::url( | |
2019 | 'civicrm/mailing/report/event', | |
2020 | "reset=1&event=click&mid=$mailing_id&uid={$mailing->id}" | |
2021 | ), | |
2022 | 'link_unique' => | |
2023 | CRM_Utils_System::url( | |
2024 | 'civicrm/mailing/report/event', | |
2025 | "reset=1&event=click&mid=$mailing_id&uid={$mailing->id}&distinct=1" | |
2026 | ), | |
2027 | 'clicks' => $mailing->clicks, | |
2028 | 'unique' => $mailing->unique_clicks, | |
2029 | 'rate' => CRM_Utils_Array::value('delivered', $report['event_totals']) ? (100.0 * $mailing->unique_clicks) / $report['event_totals']['delivered'] : 0, | |
2030 | ); | |
2031 | } | |
2032 | ||
2033 | $report['event_totals']['links'] = array( | |
2034 | 'clicks' => CRM_Utils_System::url( | |
2035 | 'civicrm/mailing/report/event', | |
2036 | "reset=1&event=click&mid=$mailing_id" | |
2037 | ), | |
2038 | 'clicks_unique' => CRM_Utils_System::url( | |
2039 | 'civicrm/mailing/report/event', | |
2040 | "reset=1&event=click&mid=$mailing_id&distinct=1" | |
2041 | ), | |
2042 | 'queue' => CRM_Utils_System::url( | |
2043 | 'civicrm/mailing/report/event', | |
2044 | "reset=1&event=queue&mid=$mailing_id" | |
2045 | ), | |
2046 | 'delivered' => CRM_Utils_System::url( | |
2047 | 'civicrm/mailing/report/event', | |
2048 | "reset=1&event=delivered&mid=$mailing_id" | |
2049 | ), | |
2050 | 'bounce' => CRM_Utils_System::url( | |
2051 | 'civicrm/mailing/report/event', | |
2052 | "reset=1&event=bounce&mid=$mailing_id" | |
2053 | ), | |
2054 | 'unsubscribe' => CRM_Utils_System::url( | |
2055 | 'civicrm/mailing/report/event', | |
2056 | "reset=1&event=unsubscribe&mid=$mailing_id" | |
2057 | ), | |
2058 | 'optout' => CRM_Utils_System::url( | |
2059 | 'civicrm/mailing/report/event', | |
2060 | "reset=1&event=optout&mid=$mailing_id" | |
2061 | ), | |
2062 | 'forward' => CRM_Utils_System::url( | |
2063 | 'civicrm/mailing/report/event', | |
2064 | "reset=1&event=forward&mid=$mailing_id" | |
2065 | ), | |
2066 | 'reply' => CRM_Utils_System::url( | |
2067 | 'civicrm/mailing/report/event', | |
2068 | "reset=1&event=reply&mid=$mailing_id" | |
2069 | ), | |
2070 | 'opened' => CRM_Utils_System::url( | |
2071 | 'civicrm/mailing/report/event', | |
2072 | "reset=1&event=opened&mid=$mailing_id" | |
2073 | ), | |
2074 | ); | |
2075 | ||
2076 | ||
2077 | $actionLinks = array(CRM_Core_Action::VIEW => array('name' => ts('Report'))); | |
2078 | if (CRM_Core_Permission::check('view all contacts')) { | |
2079 | $actionLinks[CRM_Core_Action::ADVANCED] = | |
2080 | array( | |
2081 | 'name' => ts('Advanced Search'), | |
2082 | 'url' => 'civicrm/contact/search/advanced', | |
2083 | ); | |
2084 | } | |
2085 | $action = array_sum(array_keys($actionLinks)); | |
2086 | ||
2087 | $report['event_totals']['actionlinks'] = array(); | |
2088 | foreach (array( | |
2089 | 'clicks', 'clicks_unique', 'queue', 'delivered', 'bounce', 'unsubscribe', | |
2090 | 'forward', 'reply', 'opened', 'optout', | |
2091 | ) as $key) { | |
2092 | $url = 'mailing/detail'; | |
2093 | $reportFilter = "reset=1&mailing_id_value={$mailing_id}"; | |
87dab4a4 | 2094 | $searchFilter = "force=1&mailing_id=%%mid%%"; |
6a488035 TO |
2095 | switch ($key) { |
2096 | case 'delivered': | |
2097 | $reportFilter .= "&delivery_status_value=successful"; | |
2098 | $searchFilter .= "&mailing_delivery_status=Y"; | |
2099 | break; | |
2100 | ||
2101 | case 'bounce': | |
2102 | $url = "mailing/bounce"; | |
2103 | $searchFilter .= "&mailing_delivery_status=N"; | |
2104 | break; | |
2105 | ||
2106 | case 'forward': | |
2107 | $reportFilter .= "&is_forwarded_value=1"; | |
2108 | $searchFilter .= "&mailing_forward=1"; | |
2109 | break; | |
2110 | ||
2111 | case 'reply': | |
2112 | $reportFilter .= "&is_replied_value=1"; | |
2113 | $searchFilter .= "&mailing_reply_status=Y"; | |
2114 | break; | |
2115 | ||
2116 | case 'unsubscribe': | |
2117 | $reportFilter .= "&is_unsubscribed_value=1"; | |
2118 | $searchFilter .= "&mailing_unsubscribe=1"; | |
2119 | break; | |
2120 | ||
2121 | case 'optout': | |
2122 | $reportFilter .= "&is_optout_value=1"; | |
2123 | $searchFilter .= "&mailing_optout=1"; | |
2124 | break; | |
2125 | ||
2126 | case 'opened': | |
2127 | $url = "mailing/opened"; | |
2128 | $searchFilter .= "&mailing_open_status=Y"; | |
2129 | break; | |
2130 | ||
2131 | case 'clicks': | |
2132 | case 'clicks_unique': | |
2133 | $url = "mailing/clicks"; | |
2134 | $searchFilter .= "&mailing_click_status=Y"; | |
2135 | break; | |
2136 | } | |
2137 | $actionLinks[CRM_Core_Action::VIEW]['url'] = CRM_Report_Utils_Report::getNextUrl($url, $reportFilter, FALSE, TRUE); | |
2138 | if (array_key_exists(CRM_Core_Action::ADVANCED, $actionLinks)) { | |
2139 | $actionLinks[CRM_Core_Action::ADVANCED]['qs'] = $searchFilter; | |
2140 | } | |
87dab4a4 AH |
2141 | $report['event_totals']['actionlinks'][$key] = CRM_Core_Action::formLink( |
2142 | $actionLinks, | |
2143 | $action, | |
2144 | array('mid' => $mailing_id), | |
2145 | ts('more'), | |
2146 | FALSE, | |
2147 | 'mailing.report.action', | |
2148 | 'Mailing', | |
2149 | $mailing_id | |
2150 | ); | |
6a488035 TO |
2151 | } |
2152 | ||
2153 | return $report; | |
2154 | } | |
2155 | ||
2156 | /** | |
2157 | * Get the count of mailings | |
2158 | * | |
2159 | * @param | |
2160 | * | |
2161 | * @return int Count | |
2162 | * @access public | |
2163 | */ | |
2164 | public function getCount() { | |
2165 | $this->selectAdd(); | |
2166 | $this->selectAdd('COUNT(id) as count'); | |
2167 | ||
2168 | $session = CRM_Core_Session::singleton(); | |
2169 | $this->find(TRUE); | |
2170 | ||
2171 | return $this->count; | |
2172 | } | |
2173 | ||
65910e59 EM |
2174 | /** |
2175 | * @param $id | |
2176 | * | |
2177 | * @throws Exception | |
2178 | */ | |
6a488035 TO |
2179 | static function checkPermission($id) { |
2180 | if (!$id) { | |
2181 | return; | |
2182 | } | |
2183 | ||
2184 | $mailingIDs = self::mailingACLIDs(); | |
2185 | if ($mailingIDs === TRUE) { | |
2186 | return; | |
2187 | } | |
2188 | ||
2189 | if (!in_array($id, $mailingIDs)) { | |
2190 | CRM_Core_Error::fatal(ts('You do not have permission to access this mailing report')); | |
2191 | } | |
2192 | return; | |
2193 | } | |
2194 | ||
65910e59 EM |
2195 | /** |
2196 | * @param null $alias | |
2197 | * | |
2198 | * @return string | |
2199 | */ | |
6a488035 TO |
2200 | static function mailingACL($alias = NULL) { |
2201 | $mailingACL = " ( 0 ) "; | |
2202 | ||
2203 | $mailingIDs = self::mailingACLIDs(); | |
2204 | if ($mailingIDs === TRUE) { | |
2205 | return " ( 1 ) "; | |
2206 | } | |
2207 | ||
2208 | if (!empty($mailingIDs)) { | |
2209 | $mailingIDs = implode(',', $mailingIDs); | |
2210 | $tableName = !$alias ? self::getTableName() : $alias; | |
2211 | $mailingACL = " $tableName.id IN ( $mailingIDs ) "; | |
2212 | } | |
2213 | return $mailingACL; | |
2214 | } | |
2215 | ||
2216 | /** | |
2217 | * returns all the mailings that this user can access. This is dependent on | |
2218 | * all the groups that the user has access to. | |
2219 | * However since most civi installs dont use ACL's we special case the condition | |
2220 | * where the user has access to ALL groups, and hence ALL mailings and return a | |
2221 | * value of TRUE (to avoid the downstream where clause with a list of mailing list IDs | |
2222 | * | |
2223 | * @return boolean | array - TRUE if the user has access to all mailings, else array of mailing IDs (possibly empty) | |
2224 | * @static | |
2225 | */ | |
2226 | static function mailingACLIDs() { | |
2227 | // CRM-11633 | |
2228 | // optimize common case where admin has access | |
2229 | // to all mailings | |
2230 | if ( | |
2231 | CRM_Core_Permission::check('view all contacts') || | |
2232 | CRM_Core_Permission::check('edit all contacts') | |
2233 | ) { | |
2234 | return TRUE; | |
2235 | } | |
2236 | ||
2237 | $mailingIDs = array(); | |
2238 | ||
2239 | // get all the groups that this user can access | |
2240 | // if they dont have universal access | |
553f116a | 2241 | $groups = CRM_Core_PseudoConstant::group(NULL, FALSE); |
6a488035 TO |
2242 | if (!empty($groups)) { |
2243 | $groupIDs = implode(',', array_keys($groups)); | |
6a488035 TO |
2244 | |
2245 | // get all the mailings that are in this subset of groups | |
2246 | $query = " | |
8f463994 | 2247 | SELECT DISTINCT( m.id ) as id |
6a488035 TO |
2248 | FROM civicrm_mailing m |
2249 | LEFT JOIN civicrm_mailing_group g ON g.mailing_id = m.id | |
2250 | WHERE ( ( g.entity_table like 'civicrm_group%' AND g.entity_id IN ( $groupIDs ) ) | |
2251 | OR ( g.entity_table IS NULL AND g.entity_id IS NULL ) ) | |
2252 | "; | |
2253 | $dao = CRM_Core_DAO::executeQuery($query); | |
2254 | ||
2255 | $mailingIDs = array(); | |
2256 | while ($dao->fetch()) { | |
2257 | $mailingIDs[] = $dao->id; | |
2258 | } | |
2259 | } | |
2260 | ||
2261 | return $mailingIDs; | |
2262 | } | |
2263 | ||
2264 | /** | |
2265 | * Get the rows for a browse operation | |
2266 | * | |
77b97be7 EM |
2267 | * @param int $offset The row number to start from |
2268 | * @param int $rowCount The nmber of rows to return | |
2269 | * @param string $sort The sql string that describes the sort order | |
2270 | * | |
2271 | * @param null $additionalClause | |
2272 | * @param null $additionalParams | |
6a488035 TO |
2273 | * |
2274 | * @return array The rows | |
2275 | * @access public | |
2276 | */ | |
2277 | public function &getRows($offset, $rowCount, $sort, $additionalClause = NULL, $additionalParams = NULL) { | |
2278 | $mailing = self::getTableName(); | |
9da8dc8c | 2279 | $job = CRM_Mailing_BAO_MailingJob::getTableName(); |
04124b30 | 2280 | $group = CRM_Mailing_DAO_MailingGroup::getTableName(); |
6a488035 TO |
2281 | $session = CRM_Core_Session::singleton(); |
2282 | ||
2283 | $mailingACL = self::mailingACL(); | |
2284 | ||
2285 | //get all campaigns. | |
2286 | $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE); | |
2287 | ||
2288 | // we only care about parent jobs, since that holds all the info on | |
2289 | // the mailing | |
2290 | $query = " | |
2291 | SELECT $mailing.id, | |
2292 | $mailing.name, | |
2293 | $job.status, | |
2294 | $mailing.approval_status_id, | |
2295 | MIN($job.scheduled_date) as scheduled_date, | |
2296 | MIN($job.start_date) as start_date, | |
2297 | MAX($job.end_date) as end_date, | |
2298 | createdContact.sort_name as created_by, | |
2299 | scheduledContact.sort_name as scheduled_by, | |
2300 | $mailing.created_id as created_id, | |
2301 | $mailing.scheduled_id as scheduled_id, | |
2302 | $mailing.is_archived as archived, | |
2303 | $mailing.created_date as created_date, | |
2304 | campaign_id, | |
2305 | $mailing.sms_provider_id as sms_provider_id | |
2306 | FROM $mailing | |
2307 | LEFT JOIN $job ON ( $job.mailing_id = $mailing.id AND $job.is_test = 0 AND $job.parent_id IS NULL ) | |
2308 | LEFT JOIN civicrm_contact createdContact ON ( civicrm_mailing.created_id = createdContact.id ) | |
2309 | LEFT JOIN civicrm_contact scheduledContact ON ( civicrm_mailing.scheduled_id = scheduledContact.id ) | |
2310 | WHERE $mailingACL $additionalClause | |
2311 | GROUP BY $mailing.id "; | |
2312 | ||
2313 | if ($sort) { | |
2314 | $orderBy = trim($sort->orderBy()); | |
2315 | if (!empty($orderBy)) { | |
2316 | $query .= " ORDER BY $orderBy"; | |
2317 | } | |
2318 | } | |
2319 | ||
2320 | if ($rowCount) { | |
bf00d1b6 DL |
2321 | $offset = CRM_Utils_Type::escape($offset, 'Int'); |
2322 | $rowCount = CRM_Utils_Type::escape($rowCount, 'Int'); | |
2323 | ||
6a488035 TO |
2324 | $query .= " LIMIT $offset, $rowCount "; |
2325 | } | |
2326 | ||
2327 | if (!$additionalParams) { | |
2328 | $additionalParams = array(); | |
2329 | } | |
2330 | ||
2331 | $dao = CRM_Core_DAO::executeQuery($query, $additionalParams); | |
2332 | ||
2333 | $rows = array(); | |
2334 | while ($dao->fetch()) { | |
2335 | $rows[] = array( | |
2336 | 'id' => $dao->id, | |
2337 | 'name' => $dao->name, | |
2338 | 'status' => $dao->status ? $dao->status : 'Not scheduled', | |
2339 | 'created_date' => CRM_Utils_Date::customFormat($dao->created_date), | |
2340 | 'scheduled' => CRM_Utils_Date::customFormat($dao->scheduled_date), | |
2341 | 'scheduled_iso' => $dao->scheduled_date, | |
2342 | 'start' => CRM_Utils_Date::customFormat($dao->start_date), | |
2343 | 'end' => CRM_Utils_Date::customFormat($dao->end_date), | |
2344 | 'created_by' => $dao->created_by, | |
2345 | 'scheduled_by' => $dao->scheduled_by, | |
2346 | 'created_id' => $dao->created_id, | |
2347 | 'scheduled_id' => $dao->scheduled_id, | |
2348 | 'archived' => $dao->archived, | |
2349 | 'approval_status_id' => $dao->approval_status_id, | |
2350 | 'campaign_id' => $dao->campaign_id, | |
2351 | 'campaign' => empty($dao->campaign_id) ? NULL : $allCampaigns[$dao->campaign_id], | |
2352 | 'sms_provider_id' => $dao->sms_provider_id, | |
2353 | ); | |
2354 | } | |
2355 | return $rows; | |
2356 | } | |
2357 | ||
2358 | /** | |
2359 | * Function to show detail Mailing report | |
2360 | * | |
2361 | * @param int $id | |
2362 | * | |
77b97be7 | 2363 | * @return string |
6a488035 TO |
2364 | * @static |
2365 | * @access public | |
2366 | */ | |
2367 | static function showEmailDetails($id) { | |
2368 | return CRM_Utils_System::url('civicrm/mailing/report', "mid=$id"); | |
2369 | } | |
2370 | ||
2371 | /** | |
2372 | * Delete Mails and all its associated records | |
2373 | * | |
2374 | * @param int $id id of the mail to delete | |
2375 | * | |
2376 | * @return void | |
2377 | * @access public | |
2378 | * @static | |
2379 | */ | |
2380 | public static function del($id) { | |
2381 | if (empty($id)) { | |
2382 | CRM_Core_Error::fatal(); | |
2383 | } | |
2384 | ||
4eeb36c8 DL |
2385 | CRM_Utils_Hook::pre('delete', 'Mailing', $id, CRM_Core_DAO::$_nullArray); |
2386 | ||
6a488035 TO |
2387 | // delete all file attachments |
2388 | CRM_Core_BAO_File::deleteEntityFile('civicrm_mailing', | |
2389 | $id | |
2390 | ); | |
2391 | ||
2392 | $dao = new CRM_Mailing_DAO_Mailing(); | |
2393 | $dao->id = $id; | |
2394 | $dao->delete(); | |
2395 | ||
2396 | CRM_Core_Session::setStatus(ts('Selected mailing has been deleted.'), ts('Deleted'), 'success'); | |
4eeb36c8 DL |
2397 | |
2398 | CRM_Utils_Hook::post('delete', 'Mailing', $id, $dao); | |
6a488035 TO |
2399 | } |
2400 | ||
2401 | /** | |
2402 | * Delete Jobss and all its associated records | |
2403 | * related to test Mailings | |
2404 | * | |
2405 | * @param int $id id of the Job to delete | |
2406 | * | |
2407 | * @return void | |
2408 | * @access public | |
2409 | * @static | |
2410 | */ | |
2411 | public static function delJob($id) { | |
2412 | if (empty($id)) { | |
2413 | CRM_Core_Error::fatal(); | |
2414 | } | |
2415 | ||
9da8dc8c | 2416 | $dao = new CRM_Mailing_BAO_MailingJob(); |
6a488035 TO |
2417 | $dao->id = $id; |
2418 | $dao->delete(); | |
2419 | } | |
2420 | ||
ffd93213 EM |
2421 | /** |
2422 | * @return array | |
2423 | */ | |
6a488035 TO |
2424 | function getReturnProperties() { |
2425 | $tokens = &$this->getTokens(); | |
2426 | ||
2427 | $properties = array(); | |
2428 | if (isset($tokens['html']) && | |
2429 | isset($tokens['html']['contact']) | |
2430 | ) { | |
2431 | $properties = array_merge($properties, $tokens['html']['contact']); | |
2432 | } | |
2433 | ||
2434 | if (isset($tokens['text']) && | |
2435 | isset($tokens['text']['contact']) | |
2436 | ) { | |
2437 | $properties = array_merge($properties, $tokens['text']['contact']); | |
2438 | } | |
2439 | ||
2440 | if (isset($tokens['subject']) && | |
2441 | isset($tokens['subject']['contact']) | |
2442 | ) { | |
2443 | $properties = array_merge($properties, $tokens['subject']['contact']); | |
2444 | } | |
2445 | ||
2446 | $returnProperties = array(); | |
2447 | $returnProperties['display_name'] = $returnProperties['contact_id'] = $returnProperties['preferred_mail_format'] = $returnProperties['hash'] = 1; | |
2448 | ||
2449 | foreach ($properties as $p) { | |
2450 | $returnProperties[$p] = 1; | |
2451 | } | |
2452 | ||
2453 | return $returnProperties; | |
2454 | } | |
2455 | ||
2456 | /** | |
2457 | * Function to build the compose mail form | |
2458 | * | |
2459 | * @param $form | |
2460 | * | |
355ba699 | 2461 | * @return void |
6a488035 TO |
2462 | * @access public |
2463 | */ | |
2464 | public static function commonCompose(&$form) { | |
2465 | //get the tokens. | |
2466 | $tokens = CRM_Core_SelectValues::contactTokens(); | |
2467 | ||
6a488035 TO |
2468 | $className = CRM_Utils_System::getClassName($form); |
2469 | if ($className == 'CRM_Mailing_Form_Upload') { | |
2470 | $tokens = array_merge(CRM_Core_SelectValues::mailingTokens(), $tokens); | |
2471 | } | |
2472 | elseif ($className == 'CRM_Admin_Form_ScheduleReminders') { | |
2473 | $tokens = array_merge(CRM_Core_SelectValues::activityTokens(), $tokens); | |
2474 | $tokens = array_merge(CRM_Core_SelectValues::eventTokens(), $tokens); | |
2475 | $tokens = array_merge(CRM_Core_SelectValues::membershipTokens(), $tokens); | |
2476 | } | |
2477 | elseif ($className == 'CRM_Event_Form_ManageEvent_ScheduleReminders') { | |
2478 | $tokens = array_merge(CRM_Core_SelectValues::eventTokens(), $tokens); | |
2479 | } | |
2480 | ||
2481 | //sorted in ascending order tokens by ignoring word case | |
ac0a3db5 | 2482 | $form->assign('tokens', CRM_Utils_Token::formatTokensForDisplay($tokens)); |
6a488035 | 2483 | |
1e035d58 | 2484 | $templates = array(); |
6a488035 | 2485 | |
1e035d58 | 2486 | $textFields = array('text_message' => ts('HTML format'), 'sms_text_message' => ts('SMS Message')); |
2487 | $modePrefixes = array('Mail' => NULL, 'SMS' => 'SMS'); | |
6a488035 TO |
2488 | |
2489 | if ($className != 'CRM_SMS_Form_Upload' && $className != 'CRM_Contact_Form_Task_SMS' && | |
2490 | $className != 'CRM_Contact_Form_Task_SMS' | |
2491 | ) { | |
2492 | $form->addWysiwyg('html_message', | |
2493 | ts('HTML format'), | |
2494 | array( | |
2495 | 'cols' => '80', 'rows' => '8', | |
2496 | 'onkeyup' => "return verify(this)", | |
2497 | ) | |
2498 | ); | |
1e035d58 | 2499 | |
2500 | if ($className != 'CRM_Admin_Form_ScheduleReminders') { | |
2501 | unset($modePrefixes['SMS']); | |
2502 | } | |
2503 | } | |
2504 | else { | |
2505 | unset($textFields['text_message']); | |
2506 | unset($modePrefixes['Mail']); | |
2507 | } | |
2508 | ||
2509 | //insert message Text by selecting "Select Template option" | |
2510 | foreach ($textFields as $id => $label) { | |
2511 | $prefix = NULL; | |
2512 | if ($id == 'sms_text_message') { | |
2513 | $prefix = "SMS"; | |
2514 | $form->assign('max_sms_length', CRM_SMS_Provider::MAX_SMS_CHAR); | |
2515 | } | |
2516 | $form->add('textarea', $id, $label, | |
2517 | array( | |
2518 | 'cols' => '80', 'rows' => '8', | |
2519 | 'onkeyup' => "return verify(this, '{$prefix}')", | |
2520 | ) | |
2521 | ); | |
2522 | } | |
2523 | ||
2524 | foreach ($modePrefixes as $prefix) { | |
2525 | if ($prefix == 'SMS') { | |
2526 | $templates[$prefix] = CRM_Core_BAO_MessageTemplate::getMessageTemplates(FALSE, TRUE); | |
2527 | } | |
2528 | else { | |
2529 | $templates[$prefix] = CRM_Core_BAO_MessageTemplate::getMessageTemplates(FALSE); | |
2530 | } | |
2531 | ||
2532 | if (!empty($templates[$prefix])) { | |
2533 | $form->assign('templates', TRUE); | |
2534 | ||
2535 | $form->add('select', "{$prefix}template", ts('Use Template'), | |
2536 | array('' => ts('- select -')) + $templates[$prefix], FALSE, | |
2537 | array('onChange' => "selectValue( this.value, '{$prefix}');") | |
2538 | ); | |
2539 | } | |
2540 | $form->add('checkbox', "{$prefix}updateTemplate", ts('Update Template'), NULL); | |
2541 | ||
2542 | $form->add('checkbox', "{$prefix}saveTemplate", ts('Save As New Template'), NULL, FALSE, | |
2543 | array('onclick' => "showSaveDetails(this, '{$prefix}');") | |
2544 | ); | |
2545 | $form->add('text', "{$prefix}saveTemplateName", ts('Template Title')); | |
6a488035 TO |
2546 | } |
2547 | } | |
2548 | ||
2549 | /** | |
2550 | * Function to build the compose PDF letter form | |
2551 | * | |
2552 | * @param $form | |
2553 | * | |
355ba699 | 2554 | * @return void |
6a488035 TO |
2555 | * @access public |
2556 | */ | |
66d0e5f3 | 2557 | public static function commonLetterCompose(&$form) { |
6a488035 TO |
2558 | //get the tokens. |
2559 | $tokens = CRM_Core_SelectValues::contactTokens(); | |
2560 | if (CRM_Utils_System::getClassName($form) == 'CRM_Mailing_Form_Upload') { | |
2561 | $tokens = array_merge(CRM_Core_SelectValues::mailingTokens(), $tokens); | |
2562 | } | |
2d3e3c7b | 2563 | //@todo move this fn onto the form |
6a488035 TO |
2564 | if (CRM_Utils_System::getClassName($form) == 'CRM_Contribute_Form_Task_PDFLetter') { |
2565 | $tokens = array_merge(CRM_Core_SelectValues::contributionTokens(), $tokens); | |
2566 | } | |
2567 | ||
2d3e3c7b | 2568 | if(method_exists($form, 'listTokens')) { |
2569 | $tokens = array_merge($form->listTokens(), $tokens); | |
2570 | } | |
2571 | ||
ac0a3db5 | 2572 | $form->assign('tokens', CRM_Utils_Token::formatTokensForDisplay($tokens)); |
6a488035 | 2573 | |
c6327d7d | 2574 | $form->_templates = CRM_Core_BAO_MessageTemplate::getMessageTemplates(FALSE); |
6a488035 TO |
2575 | if (!empty($form->_templates)) { |
2576 | $form->assign('templates', TRUE); | |
2577 | $form->add('select', 'template', ts('Select Template'), | |
2578 | array( | |
2579 | '' => ts('- select -')) + $form->_templates, FALSE, | |
8474fc16 | 2580 | array('onChange' => "selectValue( this.value,'' );") |
6a488035 TO |
2581 | ); |
2582 | $form->add('checkbox', 'updateTemplate', ts('Update Template'), NULL); | |
2583 | } | |
2584 | ||
2585 | $form->add('checkbox', 'saveTemplate', ts('Save As New Template'), NULL, FALSE, | |
2586 | array('onclick' => "showSaveDetails(this);") | |
2587 | ); | |
2588 | $form->add('text', 'saveTemplateName', ts('Template Title')); | |
2589 | ||
2590 | ||
2591 | $form->addWysiwyg('html_message', | |
2592 | ts('Your Letter'), | |
2593 | array( | |
2594 | 'cols' => '80', 'rows' => '8', | |
2595 | 'onkeyup' => "return verify(this)", | |
2596 | ) | |
2597 | ); | |
66d0e5f3 | 2598 | $action = CRM_Utils_Request::retrieve('action', 'String', $form, FALSE); |
6a488035 TO |
2599 | if ((CRM_Utils_System::getClassName($form) == 'CRM_Contact_Form_Task_PDF') && |
2600 | $action == CRM_Core_Action::VIEW | |
2601 | ) { | |
2602 | $form->freeze('html_message'); | |
2603 | } | |
2604 | } | |
2605 | ||
2606 | /** | |
2607 | * Get the search based mailing Ids | |
2608 | * | |
2609 | * @return array $mailingIDs, searched base mailing ids. | |
2610 | * @access public | |
2611 | */ | |
2612 | public function searchMailingIDs() { | |
04124b30 | 2613 | $group = CRM_Mailing_DAO_MailingGroup::getTableName(); |
6a488035 TO |
2614 | $mailing = self::getTableName(); |
2615 | ||
2616 | $query = " | |
2617 | SELECT $mailing.id as mailing_id | |
2618 | FROM $mailing, $group | |
2619 | WHERE $group.mailing_id = $mailing.id | |
2620 | AND $group.group_type = 'Base'"; | |
2621 | ||
2622 | $searchDAO = CRM_Core_DAO::executeQuery($query); | |
2623 | $mailingIDs = array(); | |
2624 | while ($searchDAO->fetch()) { | |
2625 | $mailingIDs[] = $searchDAO->mailing_id; | |
2626 | } | |
2627 | ||
2628 | return $mailingIDs; | |
2629 | } | |
2630 | ||
2631 | /** | |
2632 | * Get the content/components of mailing based on mailing Id | |
2633 | * | |
2634 | * @param $report array of mailing report | |
2635 | * | |
2636 | * @param $form reference of this | |
2637 | * | |
77b97be7 EM |
2638 | * @param bool $isSMS |
2639 | * | |
2640 | * @return array $report array content/component.@access public | |
6a488035 | 2641 | */ |
323696fa | 2642 | static function getMailingContent(&$report, &$form, $isSMS = FALSE) { |
6a488035 TO |
2643 | $htmlHeader = $textHeader = NULL; |
2644 | $htmlFooter = $textFooter = NULL; | |
2645 | ||
2646 | if (!$isSMS) { | |
2647 | if ($report['mailing']['header_id']) { | |
2648 | $header = new CRM_Mailing_BAO_Component(); | |
2649 | $header->id = $report['mailing']['header_id']; | |
2650 | $header->find(TRUE); | |
2651 | $htmlHeader = $header->body_html; | |
2652 | $textHeader = $header->body_text; | |
2653 | } | |
2654 | ||
2655 | if ($report['mailing']['footer_id']) { | |
2656 | $footer = new CRM_Mailing_BAO_Component(); | |
2657 | $footer->id = $report['mailing']['footer_id']; | |
2658 | $footer->find(TRUE); | |
2659 | $htmlFooter = $footer->body_html; | |
2660 | $textFooter = $footer->body_text; | |
2661 | } | |
2662 | } | |
2663 | ||
c57f36a1 PJ |
2664 | $mailingKey = $form->_mailing_id; |
2665 | if (!$isSMS) { | |
2666 | if ($hash = CRM_Mailing_BAO_Mailing::getMailingHash($mailingKey)) { | |
2667 | $mailingKey = $hash; | |
2668 | } | |
2669 | } | |
2670 | ||
6a488035 | 2671 | if (!empty($report['mailing']['body_text'])) { |
c57f36a1 | 2672 | $url = CRM_Utils_System::url('civicrm/mailing/view', 'reset=1&text=1&id=' . $mailingKey); |
d839d441 | 2673 | $form->assign('textViewURL', $url); |
6a488035 TO |
2674 | } |
2675 | ||
2676 | if (!$isSMS) { | |
2677 | if (!empty($report['mailing']['body_html'])) { | |
c57f36a1 | 2678 | $url = CRM_Utils_System::url('civicrm/mailing/view', 'reset=1&id=' . $mailingKey); |
d839d441 | 2679 | $form->assign('htmlViewURL', $url); |
6a488035 TO |
2680 | } |
2681 | } | |
2682 | ||
2683 | if (!$isSMS) { | |
2684 | $report['mailing']['attachment'] = CRM_Core_BAO_File::attachmentInfo('civicrm_mailing', $form->_mailing_id); | |
2685 | } | |
2686 | return $report; | |
2687 | } | |
2688 | ||
65910e59 EM |
2689 | /** |
2690 | * @param $jobID | |
2691 | * | |
2692 | * @return mixed | |
2693 | */ | |
6a488035 TO |
2694 | static function overrideVerp($jobID) { |
2695 | static $_cache = array(); | |
2696 | ||
2697 | if (!isset($_cache[$jobID])) { | |
2698 | $query = " | |
2699 | SELECT override_verp | |
2700 | FROM civicrm_mailing | |
2701 | INNER JOIN civicrm_mailing_job ON civicrm_mailing.id = civicrm_mailing_job.mailing_id | |
2702 | WHERE civicrm_mailing_job.id = %1 | |
2703 | "; | |
2704 | $params = array(1 => array($jobID, 'Integer')); | |
2705 | $_cache[$jobID] = CRM_Core_DAO::singleValueQuery($query, $params); | |
2706 | } | |
2707 | return $_cache[$jobID]; | |
2708 | } | |
2709 | ||
65910e59 EM |
2710 | /** |
2711 | * @param null $mode | |
2712 | * | |
2713 | * @return bool | |
2714 | * @throws Exception | |
2715 | */ | |
6a488035 TO |
2716 | static function processQueue($mode = NULL) { |
2717 | $config = &CRM_Core_Config::singleton(); | |
29cb51c2 | 2718 | // CRM_Core_Error::debug_log_message("Beginning processQueue run: {$config->mailerJobsMax}, {$config->mailerJobSize}"); |
6a488035 TO |
2719 | |
2720 | if ($mode == NULL && CRM_Core_BAO_MailSettings::defaultDomain() == "EXAMPLE.ORG") { | |
07c09ae4 | 2721 | 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 |
2722 | } |
2723 | ||
2724 | // check if we are enforcing number of parallel cron jobs | |
2725 | // CRM-8460 | |
2726 | $gotCronLock = FALSE; | |
6a488035 | 2727 | |
29cb51c2 | 2728 | if (property_exists($config, 'mailerJobsMax') && $config->mailerJobsMax && $config->mailerJobsMax > 1) { |
6a488035 TO |
2729 | $lockArray = range(1, $config->mailerJobsMax); |
2730 | shuffle($lockArray); | |
2731 | ||
2732 | // check if we are using global locks | |
2ede60ec DL |
2733 | $serverWideLock = CRM_Core_BAO_Setting::getItem( |
2734 | CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME, | |
6a488035 TO |
2735 | 'civimail_server_wide_lock' |
2736 | ); | |
2737 | foreach ($lockArray as $lockID) { | |
2738 | $cronLock = new CRM_Core_Lock("civimail.cronjob.{$lockID}", NULL, $serverWideLock); | |
2739 | if ($cronLock->isAcquired()) { | |
2740 | $gotCronLock = TRUE; | |
2741 | break; | |
2742 | } | |
2743 | } | |
2744 | ||
2745 | // exit here since we have enuf cronjobs running | |
2746 | if (!$gotCronLock) { | |
2747 | CRM_Core_Error::debug_log_message('Returning early, since max number of cronjobs running'); | |
2748 | return TRUE; | |
2749 | } | |
2750 | } | |
2751 | ||
2752 | // load bootstrap to call hooks | |
2753 | ||
2754 | // Split up the parent jobs into multiple child jobs | |
29cb51c2 PJ |
2755 | $mailerJobSize = (property_exists($config, 'mailerJobSize')) ? $config->mailerJobSize : NULL; |
2756 | CRM_Mailing_BAO_MailingJob::runJobs_pre($mailerJobSize, $mode); | |
9da8dc8c | 2757 | CRM_Mailing_BAO_MailingJob::runJobs(NULL, $mode); |
2758 | CRM_Mailing_BAO_MailingJob::runJobs_post($mode); | |
6a488035 TO |
2759 | |
2760 | // lets release the global cron lock if we do have one | |
2761 | if ($gotCronLock) { | |
2762 | $cronLock->release(); | |
2763 | } | |
2764 | ||
2765 | // CRM_Core_Error::debug_log_message('Ending processQueue run'); | |
2766 | return TRUE; | |
2767 | } | |
2768 | ||
65910e59 EM |
2769 | /** |
2770 | * @param $mailingID | |
2771 | */ | |
ac3efd6f | 2772 | private static function addMultipleEmails($mailingID) { |
6a488035 TO |
2773 | $sql = " |
2774 | INSERT INTO civicrm_mailing_recipients | |
2775 | (mailing_id, email_id, contact_id) | |
2776 | SELECT %1, e.id, e.contact_id FROM civicrm_email e | |
2777 | WHERE e.on_hold = 0 | |
2778 | AND e.is_bulkmail = 1 | |
2779 | AND e.contact_id IN | |
2780 | ( SELECT contact_id FROM civicrm_mailing_recipients mr WHERE mailing_id = %1 ) | |
2781 | AND e.id NOT IN ( SELECT email_id FROM civicrm_mailing_recipients mr WHERE mailing_id = %1 ) | |
2782 | "; | |
2783 | $params = array(1 => array($mailingID, 'Integer')); | |
2784 | ||
2785 | $dao = CRM_Core_DAO::executeQuery($sql, $params); | |
2786 | } | |
2787 | ||
65910e59 EM |
2788 | /** |
2789 | * @param bool $isSMS | |
2790 | * | |
2791 | * @return mixed | |
2792 | */ | |
39eb89f4 | 2793 | static function getMailingsList($isSMS = FALSE) { |
6a488035 TO |
2794 | static $list = array(); |
2795 | $where = " WHERE "; | |
2796 | if (!$isSMS) { | |
2797 | $where .= " civicrm_mailing.sms_provider_id IS NULL "; | |
2798 | } | |
2799 | else { | |
2800 | $where .= " civicrm_mailing.sms_provider_id IS NOT NULL "; | |
2801 | } | |
2802 | ||
2803 | if (empty($list)) { | |
2804 | $query = " | |
2805 | SELECT civicrm_mailing.id, civicrm_mailing.name, civicrm_mailing_job.end_date | |
2806 | FROM civicrm_mailing | |
2807 | INNER JOIN civicrm_mailing_job ON civicrm_mailing.id = civicrm_mailing_job.mailing_id {$where} | |
2808 | ORDER BY civicrm_mailing.name"; | |
2809 | $mailing = CRM_Core_DAO::executeQuery($query); | |
2810 | ||
2811 | while ($mailing->fetch()) { | |
2812 | $list[$mailing->id] = "{$mailing->name} :: {$mailing->end_date}"; | |
2813 | } | |
2814 | } | |
2815 | ||
2816 | return $list; | |
2817 | } | |
2818 | ||
65910e59 EM |
2819 | /** |
2820 | * @param $mid | |
2821 | * | |
2822 | * @return null|string | |
2823 | */ | |
6a488035 TO |
2824 | static function hiddenMailingGroup($mid) { |
2825 | $sql = " | |
2826 | SELECT g.id | |
2827 | FROM civicrm_mailing m | |
2828 | INNER JOIN civicrm_mailing_group mg ON mg.mailing_id = m.id | |
2829 | INNER JOIN civicrm_group g ON mg.entity_id = g.id AND mg.entity_table = 'civicrm_group' | |
2830 | WHERE g.is_hidden = 1 | |
2831 | AND mg.group_type = 'Include' | |
2832 | AND m.id = %1 | |
2833 | "; | |
2834 | $params = array( 1 => array( $mid, 'Integer' ) ); | |
2835 | return CRM_Core_DAO::singleValueQuery($sql, $params); | |
2836 | } | |
553f116a KJ |
2837 | |
2838 | /** | |
2839 | * This function is a wrapper for ajax activity selector | |
2840 | * | |
2841 | * @param array $params associated array for params record id. | |
2842 | * | |
2843 | * @return array $contactActivities associated array of contact activities | |
2844 | * @access public | |
2845 | */ | |
2846 | public static function getContactMailingSelector(&$params) { | |
2847 | // format the params | |
2848 | $params['offset'] = ($params['page'] - 1) * $params['rp']; | |
2849 | $params['rowCount'] = $params['rp']; | |
2850 | $params['sort'] = CRM_Utils_Array::value('sortBy', $params); | |
2851 | $params['caseId'] = NULL; | |
553f116a KJ |
2852 | |
2853 | // get contact mailings | |
2854 | $mailings = CRM_Mailing_BAO_Mailing::getContactMailings($params); | |
2855 | ||
2856 | // add total | |
2857 | $params['total'] = CRM_Mailing_BAO_Mailing::getContactMailingsCount($params); | |
2858 | ||
de1cbb7c | 2859 | //CRM-12814 |
7c006637 | 2860 | if (!empty($mailings)) { |
6b62f1bb DG |
2861 | $openCounts = CRM_Mailing_Event_BAO_Opened::getMailingContactCount(array_keys($mailings), $params['contact_id']); |
2862 | $clickCounts = CRM_Mailing_Event_BAO_TrackableURLOpen::getMailingContactCount(array_keys($mailings), $params['contact_id']); | |
de1cbb7c BS |
2863 | } |
2864 | ||
553f116a KJ |
2865 | // format params and add links |
2866 | $contactMailings = array(); | |
2867 | foreach ($mailings as $mailingId => $values) { | |
2868 | $contactMailings[$mailingId]['subject'] = $values['subject']; | |
2869 | $contactMailings[$mailingId]['start_date'] = CRM_Utils_Date::customFormat($values['start_date']); | |
0f0855d8 | 2870 | $contactMailings[$mailingId]['recipients'] = CRM_Utils_System::href(ts('(recipients)'), 'civicrm/mailing/report/event', |
5a99d240 | 2871 | "mid={$values['mailing_id']}&reset=1&cid={$params['contact_id']}&event=queue&context=mailing"); |
7c006637 | 2872 | |
553f116a | 2873 | $contactMailings[$mailingId]['mailing_creator'] = CRM_Utils_System::href( |
7c006637 | 2874 | $values['creator_name'], |
2875 | 'civicrm/contact/view', | |
2876 | "reset=1&cid={$values['creator_id']}"); | |
553f116a | 2877 | |
de1cbb7c | 2878 | //CRM-12814 |
6b62f1bb DG |
2879 | $contactMailings[$mailingId]['openstats'] = "Opens: ". |
2880 | CRM_Utils_Array::value($values['mailing_id'], $openCounts, 0). | |
2881 | "<br />Clicks: ". | |
2882 | CRM_Utils_Array::value($values['mailing_id'], $clickCounts, 0); | |
50f5a393 | 2883 | |
a582d9f2 KJ |
2884 | $actionLinks = array( |
2885 | CRM_Core_Action::VIEW => array( | |
7c006637 | 2886 | 'name' => ts('View'), |
2887 | 'url' => 'civicrm/mailing/view', | |
c57f36a1 | 2888 | 'qs' => "reset=1&id=%%mkey%%", |
a582d9f2 | 2889 | 'title' => ts('View Mailing'), |
fc164be7 | 2890 | 'class' => 'crm-popup', |
a582d9f2 KJ |
2891 | ), |
2892 | CRM_Core_Action::BROWSE => array( | |
2893 | 'name' => ts('Mailing Report'), | |
2894 | 'url' => 'civicrm/mailing/report', | |
87dab4a4 | 2895 | 'qs' => "mid=%%mid%%&reset=1&cid=%%cid%%&context=mailing", |
a582d9f2 KJ |
2896 | 'title' => ts('View Mailing Report'), |
2897 | ) | |
2898 | ); | |
2899 | ||
c57f36a1 PJ |
2900 | $mailingKey = $values['mailing_id']; |
2901 | if ($hash = CRM_Mailing_BAO_Mailing::getMailingHash($mailingKey)) { | |
2902 | $mailingKey = $hash; | |
2903 | } | |
2904 | ||
87dab4a4 AH |
2905 | $contactMailings[$mailingId]['links'] = CRM_Core_Action::formLink( |
2906 | $actionLinks, | |
2907 | null, | |
2908 | array( | |
2909 | 'mid' => $values['mailing_id'], | |
2910 | 'cid' => $params['contact_id'], | |
c57f36a1 | 2911 | 'mkey' => $mailingKey, |
87dab4a4 AH |
2912 | ), |
2913 | ts('more'), | |
2914 | FALSE, | |
2915 | 'mailing.contact.action', | |
2916 | 'Mailing', | |
2917 | $values['mailing_id'] | |
2918 | ); | |
553f116a KJ |
2919 | } |
2920 | ||
2921 | return $contactMailings; | |
2922 | } | |
2923 | ||
2924 | /** | |
2925 | * Function to retrieve contact mailing | |
2926 | * | |
2927 | * @param array $params associated array | |
2928 | * | |
2929 | * @return array of mailings for a contact | |
2930 | * | |
2931 | * @static | |
2932 | * @access public | |
2933 | */ | |
2934 | static public function getContactMailings(&$params) { | |
2935 | $params['version'] = 3; | |
82845090 KJ |
2936 | $params['offset'] = ($params['page'] - 1) * $params['rp']; |
2937 | $params['limit'] = $params['rp']; | |
2938 | $params['sort'] = CRM_Utils_Array::value('sortBy', $params); | |
2939 | ||
553f116a KJ |
2940 | $result = civicrm_api('MailingContact', 'get', $params); |
2941 | return $result['values']; | |
2942 | } | |
2943 | ||
2944 | /** | |
2945 | * Function to retrieve contact mailing count | |
2946 | * | |
2947 | * @param array $params associated array | |
2948 | * | |
2949 | * @return int count of mailings for a contact | |
2950 | * | |
2951 | * @static | |
2952 | * @access public | |
2953 | */ | |
2954 | static public function getContactMailingsCount(&$params) { | |
553f116a | 2955 | $params['version'] = 3; |
7c006637 | 2956 | return civicrm_api('MailingContact', 'getcount', $params); |
553f116a | 2957 | } |
af4c09bc | 2958 | } |