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