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