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