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