Merge pull request #22850 from ixiam/dev_Issue#3080
[civicrm-core.git] / CRM / Mailing / Event / BAO / Reply.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035
TO
16 */
17
18require_once 'Mail/mime.php';
19
28518c90
EM
20/**
21 * Class CRM_Mailing_Event_BAO_Reply
22 */
6a488035
TO
23class CRM_Mailing_Event_BAO_Reply extends CRM_Mailing_Event_DAO_Reply {
24
6a488035
TO
25 /**
26 * Register a reply event.
27 *
90c8230e
TO
28 * @param int $job_id
29 * The job ID of the reply.
30 * @param int $queue_id
31 * The queue event id.
32 * @param string $hash
33 * The hash.
fd31fa4c
EM
34 *
35 * @param null $replyto
6a488035 36 *
72b3a70c
CW
37 * @return object|null
38 * The mailing object, or null on failure
6a488035
TO
39 */
40 public static function &reply($job_id, $queue_id, $hash, $replyto = NULL) {
25606795 41 // First make sure there's a matching queue event.
6a488035
TO
42 $q = CRM_Mailing_Event_BAO_Queue::verify($job_id, $queue_id, $hash);
43
44 $success = NULL;
45
46 if (!$q) {
47 return $success;
48 }
49
50 $mailing = new CRM_Mailing_BAO_Mailing();
51 $mailings = CRM_Mailing_BAO_Mailing::getTableName();
9da8dc8c 52 $jobs = CRM_Mailing_BAO_MailingJob::getTableName();
6a488035 53 $mailing->query(
03e04002 54 "SELECT * FROM $mailings
55 INNER JOIN $jobs
6a488035
TO
56 ON $jobs.mailing_id = $mailings.id
57 WHERE $jobs.id = {$q->job_id}"
58 );
59 $mailing->fetch();
60 if ($mailing->auto_responder) {
61 self::autoRespond($mailing, $queue_id, $replyto);
62 }
63
64 $re = new CRM_Mailing_Event_BAO_Reply();
65 $re->event_queue_id = $queue_id;
66 $re->time_stamp = date('YmdHis');
67 $re->save();
68
69 if (!$mailing->forward_replies || empty($mailing->replyto_email)) {
70 return $success;
71 }
72
73 return $mailing;
74 }
75
76 /**
fe482240 77 * Forward a mailing reply.
6a488035 78 *
90c8230e
TO
79 * @param int $queue_id
80 * Queue event ID of the sender.
81 * @param string $mailing
82 * The mailing object.
83 * @param string $bodyTxt
84 * Text part of the body (ignored if $fullEmail provided).
85 * @param string $replyto
86 * Reply-to of the incoming message.
87 * @param string $bodyHTML
88 * HTML part of the body (ignored if $fullEmail provided).
89 * @param string $fullEmail
90 * Whole email to forward in one string.
6a488035
TO
91 */
92 public static function send($queue_id, &$mailing, &$bodyTxt, $replyto, &$bodyHTML = NULL, &$fullEmail = NULL) {
93 $domain = CRM_Core_BAO_Domain::getDomain();
94 $emails = CRM_Core_BAO_Email::getTableName();
95 $queue = CRM_Mailing_Event_BAO_Queue::getTableName();
96 $contacts = CRM_Contact_BAO_Contact::getTableName();
bf309c74 97 $domain_id = CRM_Core_Config::domainID();
be2fb01f 98 $domainValues = civicrm_api3('Domain', 'get', ['sequential' => 1, 'id' => $domain_id]);
73dd1b20 99 $fromEmail = CRM_Core_BAO_Domain::getNoReplyEmailAddress();
6a488035
TO
100
101 $eq = new CRM_Core_DAO();
102 $eq->query("SELECT $contacts.display_name as display_name,
8c8b0e30
DL
103 $emails.email as email,
104 $queue.job_id as job_id,
105 $queue.hash as hash
6a488035
TO
106 FROM $queue
107 INNER JOIN $contacts
108 ON $queue.contact_id = $contacts.id
109 INNER JOIN $emails
110 ON $queue.email_id = $emails.id
111 WHERE $queue.id = " . CRM_Utils_Type::escape($queue_id, 'Integer')
112 );
113 $eq->fetch();
114
115 if ($fullEmail) {
116 // parse the email and set a new destination
bed98343 117 $parser = new ezcMailParser();
6a488035
TO
118 $set = new ezcMailVariableSet($fullEmail);
119 $parsed = array_shift($parser->parseMail($set));
be2fb01f 120 $parsed->to = [new ezcMailAddress($mailing->replyto_email)];
6a488035
TO
121
122 // CRM-5567: we need to set Reply-To: so that any response
123 // to the forward goes to the sender of the reply
fb18363b 124 $parsed->setHeader('Reply-To', $replyto instanceof ezcMailAddress ? $replyto : $parsed->from->__toString());
6a488035 125
73dd1b20 126 // Using the original from address may not be permitted by the mailer.
127 $fromName = empty($parsed->from->name) ? $parsed->from->email : "{$parsed->from->name} ({$parsed->from->email})";
128 $parsed->from = new ezcMailAddress($fromEmail, $fromName);
129
bf309c74
SL
130 // CRM-17754 Include re-sent headers to indicate that we have forwarded on the email
131 $domainEmail = $domainValues['values'][0]['from_email'];
132 $parsed->setHeader('Resent-From', $domainEmail);
133 $parsed->setHeader('Resent-Date', date('r'));
c8f920d6 134 // Rewrite any invalid Return-Path headers.
135 $parsed->setHeader('Return-Path', $fromEmail);
bf309c74 136
6a488035
TO
137 // $h must be an array, so we can't use generateHeaders()'s result,
138 // but we have to regenerate the headers because we changed To
139 $parsed->generateHeaders();
140 $h = $parsed->headers->getCaseSensitiveArray();
141 $b = $parsed->generateBody();
142
6a488035
TO
143 // FIXME: ugly hack - find the first MIME boundary in
144 // the body and make the boundary in the header match it
145 $ct = $h['Content-Type'];
146 if (substr_count($ct, 'boundary=')) {
be2fb01f 147 $matches = [];
6a488035
TO
148 preg_match('/^--(.*)$/m', $b, $matches);
149 $boundary = rtrim($matches[1]);
150 $parts = explode('boundary=', $ct);
151 $ct = "{$parts[0]} boundary=\"$boundary\"";
152 }
153 }
154 else {
73dd1b20 155 $fromName = empty($eq->display_name) ? $eq->email : "{$eq->display_name} ({$eq->email})";
6a488035
TO
156
157 $message = new Mail_mime("\n");
158
be2fb01f 159 $headers = [
6a488035
TO
160 'Subject' => "Re: {$mailing->subject}",
161 'To' => $mailing->replyto_email,
73dd1b20 162 'From' => "\"$fromName\" <$fromEmail>",
fb18363b 163 'Reply-To' => empty($replyto) ? $eq->email : $replyto,
576fcb9c 164 'Return-Path' => CRM_Core_BAO_Domain::getNoReplyEmailAddress(),
bf309c74
SL
165 // CRM-17754 Include re-sent headers to indicate that we have forwarded on the email
166 'Resent-From' => $domainValues['values'][0]['from_email'],
167 'Resent-Date' => date('r'),
be2fb01f 168 ];
6a488035
TO
169
170 $message->setTxtBody($bodyTxt);
171 $message->setHTMLBody($bodyHTML);
172 $b = CRM_Utils_Mail::setMimeParams($message);
173 $h = $message->headers($headers);
174 }
175
176 CRM_Mailing_BAO_Mailing::addMessageIdHeader($h, 'r', $eq->job_id, $queue_id, $eq->hash);
177 $config = CRM_Core_Config::singleton();
048222df 178 $mailer = \Civi::service('pear_mail');
6a488035 179
6a488035 180 if (is_object($mailer)) {
6a4257d4 181 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
6a488035 182 $mailer->send($mailing->replyto_email, $h, $b);
6a4257d4 183 unset($errorScope);
6a488035
TO
184 }
185 }
186
187 /**
fe482240 188 * Send an automated response.
6a488035 189 *
90c8230e
TO
190 * @param object $mailing
191 * The mailing object.
192 * @param int $queue_id
193 * The queue ID.
194 * @param string $replyto
195 * Optional reply-to from the reply.
6a488035
TO
196 */
197 private static function autoRespond(&$mailing, $queue_id, $replyto) {
198 $config = CRM_Core_Config::singleton();
199
200 $contacts = CRM_Contact_DAO_Contact::getTableName();
201 $email = CRM_Core_DAO_Email::getTableName();
202 $queue = CRM_Mailing_Event_DAO_Queue::getTableName();
203
204 $eq = new CRM_Core_DAO();
205 $eq->query(
206 "SELECT $contacts.preferred_mail_format as format,
60bf6dfe
DL
207 $email.email as email,
208 $queue.job_id as job_id,
209 $queue.hash as hash
6a488035
TO
210 FROM $contacts
211 INNER JOIN $queue ON $queue.contact_id = $contacts.id
212 INNER JOIN $email ON $queue.email_id = $email.id
213 WHERE $queue.id = " . CRM_Utils_Type::escape($queue_id, 'Integer')
214 );
215 $eq->fetch();
216
217 $to = empty($replyto) ? $eq->email : $replyto;
218
4825de4a 219 $component = new CRM_Mailing_BAO_MailingComponent();
6a488035
TO
220 $component->id = $mailing->reply_id;
221 $component->find(TRUE);
222
6a488035 223 $domain = CRM_Core_BAO_Domain::getDomain();
a5c03029 224 list($domainEmailName, $domainEmailAddress) = CRM_Core_BAO_Domain::getNameAndEmail();
6a488035 225
52f4ecb2
SL
226 $params = [
227 'subject' => $component->subject,
228 'toEmail' => $to,
a5c03029 229 'from' => "\"{$domainEmailName}\" <{$domainEmailAddress}>",
52f4ecb2
SL
230 'replyTo' => CRM_Core_BAO_Domain::getNoReplyEmailAddress(),
231 'returnPath' => CRM_Core_BAO_Domain::getNoReplyEmailAddress(),
be2fb01f 232 ];
6a488035 233
25606795 234 // TODO: do we need reply tokens?
6a488035
TO
235 $html = $component->body_html;
236 if ($component->body_text) {
237 $text = $component->body_text;
238 }
239 else {
240 $text = CRM_Utils_String::htmlToText($component->body_html);
241 }
242
243 $bao = new CRM_Mailing_BAO_Mailing();
244 $bao->body_text = $text;
245 $bao->body_html = $html;
246 $tokens = $bao->getTokens();
247
248 if ($eq->format == 'HTML' || $eq->format == 'Both') {
249 $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html']);
250 $html = CRM_Utils_Token::replaceMailingTokens($html, $mailing, NULL, $tokens['html']);
6a488035
TO
251 }
252 if (!$html || $eq->format == 'Text' || $eq->format == 'Both') {
253 $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text']);
254 $text = CRM_Utils_Token::replaceMailingTokens($text, $mailing, NULL, $tokens['text']);
6a488035 255 }
52f4ecb2
SL
256 $params['html'] = $html;
257 $params['text'] = $text;
6a488035 258
0c211687 259 CRM_Mailing_BAO_Mailing::addMessageIdHeader($params, 'a', $eq->job_id, $queue_id, $eq->hash);
52f4ecb2
SL
260 if (CRM_Core_BAO_MailSettings::includeMessageId()) {
261 $params['messageId'] = $params['Message-ID'];
6a488035 262 }
52f4ecb2 263 CRM_Utils_Mail::send($params);
6a488035
TO
264 }
265
266 /**
fe482240 267 * Get row count for the event selector.
6a488035 268 *
90c8230e
TO
269 * @param int $mailing_id
270 * ID of the mailing.
271 * @param int $job_id
272 * Optional ID of a job to filter on.
273 * @param bool $is_distinct
274 * Group by queue ID?.
6a488035 275 *
a6c01b45
CW
276 * @return int
277 * Number of rows in result set
6a488035 278 */
a3d7e8ee
TO
279 public static function getTotalCount(
280 $mailing_id, $job_id = NULL,
6a488035
TO
281 $is_distinct = FALSE
282 ) {
283 $dao = new CRM_Core_DAO();
284
285 $reply = self::getTableName();
286 $queue = CRM_Mailing_Event_BAO_Queue::getTableName();
287 $mailing = CRM_Mailing_BAO_Mailing::getTableName();
9da8dc8c 288 $job = CRM_Mailing_BAO_MailingJob::getTableName();
6a488035
TO
289
290 $query = "
291 SELECT COUNT($reply.id) as reply
292 FROM $reply
293 INNER JOIN $queue
294 ON $reply.event_queue_id = $queue.id
295 INNER JOIN $job
296 ON $queue.job_id = $job.id
297 INNER JOIN $mailing
298 ON $job.mailing_id = $mailing.id
299 AND $job.is_test = 0
300 WHERE $mailing.id = " . CRM_Utils_Type::escape($mailing_id, 'Integer');
301
302 if (!empty($job_id)) {
303 $query .= " AND $job.id = " . CRM_Utils_Type::escape($job_id, 'Integer');
304 }
305
306 if ($is_distinct) {
307 $query .= " GROUP BY $queue.id ";
308 }
309
310 // query was missing
311 $dao->query($query);
312
313 if ($dao->fetch()) {
314 return $dao->reply;
315 }
316
317 return NULL;
318 }
319
320 /**
fe482240 321 * Get rows for the event browser.
6a488035 322 *
90c8230e
TO
323 * @param int $mailing_id
324 * ID of the mailing.
325 * @param int $job_id
326 * Optional ID of the job.
327 * @param bool $is_distinct
328 * Group by queue id?.
329 * @param int $offset
330 * Offset.
331 * @param int $rowCount
332 * Number of rows.
333 * @param array $sort
334 * Sort array.
6a488035 335 *
a6c01b45
CW
336 * @return array
337 * Result set
6a488035 338 */
a3d7e8ee
TO
339 public static function &getRows(
340 $mailing_id, $job_id = NULL,
6a488035
TO
341 $is_distinct = FALSE, $offset = NULL, $rowCount = NULL, $sort = NULL
342 ) {
343
0fc59d7a 344 $dao = new CRM_Core_DAO();
6a488035
TO
345
346 $reply = self::getTableName();
347 $queue = CRM_Mailing_Event_BAO_Queue::getTableName();
348 $mailing = CRM_Mailing_BAO_Mailing::getTableName();
9da8dc8c 349 $job = CRM_Mailing_BAO_MailingJob::getTableName();
6a488035
TO
350 $contact = CRM_Contact_BAO_Contact::getTableName();
351 $email = CRM_Core_BAO_Email::getTableName();
352
353 $query = "
354 SELECT $contact.display_name as display_name,
355 $contact.id as contact_id,
356 $email.email as email,
357 $reply.time_stamp as date
358 FROM $contact
359 INNER JOIN $queue
360 ON $queue.contact_id = $contact.id
361 INNER JOIN $email
362 ON $queue.email_id = $email.id
363 INNER JOIN $reply
364 ON $reply.event_queue_id = $queue.id
365 INNER JOIN $job
366 ON $queue.job_id = $job.id
367 INNER JOIN $mailing
368 ON $job.mailing_id = $mailing.id
369 AND $job.is_test = 0
370 WHERE $mailing.id = " . CRM_Utils_Type::escape($mailing_id, 'Integer');
371
372 if (!empty($job_id)) {
373 $query .= " AND $job.id = " . CRM_Utils_Type::escape($job_id, 'Integer');
374 }
375
376 if ($is_distinct) {
0ee5581e 377 $query .= " GROUP BY $queue.id, $contact.id, $reply.time_stamp ";
6a488035
TO
378 }
379
380 $orderBy = "sort_name ASC, {$reply}.time_stamp DESC";
381 if ($sort) {
382 if (is_string($sort)) {
21d32567 383 $sort = CRM_Utils_Type::escape($sort, 'String');
6a488035
TO
384 $orderBy = $sort;
385 }
386 else {
387 $orderBy = trim($sort->orderBy());
388 }
389 }
390
391 $query .= " ORDER BY {$orderBy} ";
392
393 if ($offset || $rowCount) {
394 //Added "||$rowCount" to avoid displaying all records on first page
395 $query .= ' LIMIT ' . CRM_Utils_Type::escape($offset, 'Integer') . ', ' . CRM_Utils_Type::escape($rowCount, 'Integer');
396 }
397
398 $dao->query($query);
399
be2fb01f 400 $results = [];
6a488035
TO
401
402 while ($dao->fetch()) {
403 $url = CRM_Utils_System::url('civicrm/contact/view',
404 "reset=1&cid={$dao->contact_id}"
405 );
be2fb01f 406 $results[] = [
6a488035
TO
407 'name' => "<a href=\"$url\">{$dao->display_name}</a>",
408 'email' => $dao->email,
409 'date' => CRM_Utils_Date::customFormat($dao->date),
be2fb01f 410 ];
6a488035
TO
411 }
412 return $results;
413 }
96025800 414
6a488035 415}