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