Rename MailingComponent BAO
[civicrm-core.git] / CRM / Mailing / Event / BAO / Reply.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
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', array('sequential' => 1, 'id' => $domain_id));
122
123 $eq = new CRM_Core_DAO();
124 $eq->query("SELECT $contacts.display_name as display_name,
125 $emails.email as email,
126 $queue.job_id as job_id,
127 $queue.hash as hash
128 FROM $queue
129 INNER JOIN $contacts
130 ON $queue.contact_id = $contacts.id
131 INNER JOIN $emails
132 ON $queue.email_id = $emails.id
133 WHERE $queue.id = " . CRM_Utils_Type::escape($queue_id, 'Integer')
134 );
135 $eq->fetch();
136
137 if ($fullEmail) {
138 // parse the email and set a new destination
139 $parser = new ezcMailParser();
140 $set = new ezcMailVariableSet($fullEmail);
141 $parsed = array_shift($parser->parseMail($set));
142 $parsed->to = array(new ezcMailAddress($mailing->replyto_email));
143
144 // CRM-5567: we need to set Reply-To: so that any response
145 // to the forward goes to the sender of the reply
146 $parsed->setHeader('Reply-To', $replyto instanceof ezcMailAddress ? $replyto : $parsed->from->__toString());
147
148 // CRM-17754 Include re-sent headers to indicate that we have forwarded on the email
149 $domainEmail = $domainValues['values'][0]['from_email'];
150 $parsed->setHeader('Resent-From', $domainEmail);
151 $parsed->setHeader('Resent-Date', date('r'));
152
153 // $h must be an array, so we can't use generateHeaders()'s result,
154 // but we have to regenerate the headers because we changed To
155 $parsed->generateHeaders();
156 $h = $parsed->headers->getCaseSensitiveArray();
157 $b = $parsed->generateBody();
158
159 // strip Return-Path of possible bounding brackets, CRM-4502
160 if (!empty($h['Return-Path'])) {
161 $h['Return-Path'] = trim($h['Return-Path'], '<>');
162 }
163
164 // FIXME: ugly hack - find the first MIME boundary in
165 // the body and make the boundary in the header match it
166 $ct = $h['Content-Type'];
167 if (substr_count($ct, 'boundary=')) {
168 $matches = array();
169 preg_match('/^--(.*)$/m', $b, $matches);
170 $boundary = rtrim($matches[1]);
171 $parts = explode('boundary=', $ct);
172 $ct = "{$parts[0]} boundary=\"$boundary\"";
173 }
174 }
175 else {
176 if (empty($eq->display_name)) {
177 $from = $eq->email;
178 }
179 else {
180 $from = "\"{$eq->display_name}\" <{$eq->email}>";
181 }
182
183 $message = new Mail_mime("\n");
184
185 $headers = array(
186 'Subject' => "Re: {$mailing->subject}",
187 'To' => $mailing->replyto_email,
188 'From' => $from,
189 'Reply-To' => empty($replyto) ? $eq->email : $replyto,
190 'Return-Path' => CRM_Core_BAO_Domain::getNoReplyEmailAddress(),
191 // CRM-17754 Include re-sent headers to indicate that we have forwarded on the email
192 'Resent-From' => $domainValues['values'][0]['from_email'],
193 'Resent-Date' => date('r'),
194 );
195
196 $message->setTxtBody($bodyTxt);
197 $message->setHTMLBody($bodyHTML);
198 $b = CRM_Utils_Mail::setMimeParams($message);
199 $h = $message->headers($headers);
200 }
201
202 CRM_Mailing_BAO_Mailing::addMessageIdHeader($h, 'r', $eq->job_id, $queue_id, $eq->hash);
203 $config = CRM_Core_Config::singleton();
204 $mailer = \Civi::service('pear_mail');
205
206 if (is_object($mailer)) {
207 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
208 $mailer->send($mailing->replyto_email, $h, $b);
209 unset($errorScope);
210 }
211 }
212
213 /**
214 * Send an automated response.
215 *
216 * @param object $mailing
217 * The mailing object.
218 * @param int $queue_id
219 * The queue ID.
220 * @param string $replyto
221 * Optional reply-to from the reply.
222 */
223 private static function autoRespond(&$mailing, $queue_id, $replyto) {
224 $config = CRM_Core_Config::singleton();
225
226 $contacts = CRM_Contact_DAO_Contact::getTableName();
227 $email = CRM_Core_DAO_Email::getTableName();
228 $queue = CRM_Mailing_Event_DAO_Queue::getTableName();
229
230 $eq = new CRM_Core_DAO();
231 $eq->query(
232 "SELECT $contacts.preferred_mail_format as format,
233 $email.email as email,
234 $queue.job_id as job_id,
235 $queue.hash as hash
236 FROM $contacts
237 INNER JOIN $queue ON $queue.contact_id = $contacts.id
238 INNER JOIN $email ON $queue.email_id = $email.id
239 WHERE $queue.id = " . CRM_Utils_Type::escape($queue_id, 'Integer')
240 );
241 $eq->fetch();
242
243 $to = empty($replyto) ? $eq->email : $replyto;
244
245 $component = new CRM_Mailing_BAO_MailingComponent();
246 $component->id = $mailing->reply_id;
247 $component->find(TRUE);
248
249 $message = new Mail_Mime("\n");
250
251 $domain = CRM_Core_BAO_Domain::getDomain();
252 list($domainEmailName, $_) = CRM_Core_BAO_Domain::getNameAndEmail();
253
254 $headers = array(
255 'Subject' => $component->subject,
256 'To' => $to,
257 'From' => "\"$domainEmailName\" <" . CRM_Core_BAO_Domain::getNoReplyEmailAddress() . '>',
258 'Reply-To' => CRM_Core_BAO_Domain::getNoReplyEmailAddress(),
259 'Return-Path' => CRM_Core_BAO_Domain::getNoReplyEmailAddress(),
260 );
261
262 // TODO: do we need reply tokens?
263 $html = $component->body_html;
264 if ($component->body_text) {
265 $text = $component->body_text;
266 }
267 else {
268 $text = CRM_Utils_String::htmlToText($component->body_html);
269 }
270
271 $bao = new CRM_Mailing_BAO_Mailing();
272 $bao->body_text = $text;
273 $bao->body_html = $html;
274 $tokens = $bao->getTokens();
275
276 if ($eq->format == 'HTML' || $eq->format == 'Both') {
277 $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html']);
278 $html = CRM_Utils_Token::replaceMailingTokens($html, $mailing, NULL, $tokens['html']);
279 $message->setHTMLBody($html);
280 }
281 if (!$html || $eq->format == 'Text' || $eq->format == 'Both') {
282 $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text']);
283 $text = CRM_Utils_Token::replaceMailingTokens($text, $mailing, NULL, $tokens['text']);
284 $message->setTxtBody($text);
285 }
286
287 $b = CRM_Utils_Mail::setMimeParams($message);
288 $h = $message->headers($headers);
289 CRM_Mailing_BAO_Mailing::addMessageIdHeader($h, 'a', $eq->job_id, queue_id, $eq->hash);
290
291 $mailer = \Civi::service('pear_mail');
292 if (is_object($mailer)) {
293 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
294 $mailer->send($to, $h, $b);
295 unset($errorScope);
296 }
297 }
298
299 /**
300 * Get row count for the event selector.
301 *
302 * @param int $mailing_id
303 * ID of the mailing.
304 * @param int $job_id
305 * Optional ID of a job to filter on.
306 * @param bool $is_distinct
307 * Group by queue ID?.
308 *
309 * @return int
310 * Number of rows in result set
311 */
312 public static function getTotalCount(
313 $mailing_id, $job_id = NULL,
314 $is_distinct = FALSE
315 ) {
316 $dao = new CRM_Core_DAO();
317
318 $reply = self::getTableName();
319 $queue = CRM_Mailing_Event_BAO_Queue::getTableName();
320 $mailing = CRM_Mailing_BAO_Mailing::getTableName();
321 $job = CRM_Mailing_BAO_MailingJob::getTableName();
322
323 $query = "
324 SELECT COUNT($reply.id) as reply
325 FROM $reply
326 INNER JOIN $queue
327 ON $reply.event_queue_id = $queue.id
328 INNER JOIN $job
329 ON $queue.job_id = $job.id
330 INNER JOIN $mailing
331 ON $job.mailing_id = $mailing.id
332 AND $job.is_test = 0
333 WHERE $mailing.id = " . CRM_Utils_Type::escape($mailing_id, 'Integer');
334
335 if (!empty($job_id)) {
336 $query .= " AND $job.id = " . CRM_Utils_Type::escape($job_id, 'Integer');
337 }
338
339 if ($is_distinct) {
340 $query .= " GROUP BY $queue.id ";
341 }
342
343 // query was missing
344 $dao->query($query);
345
346 if ($dao->fetch()) {
347 return $dao->reply;
348 }
349
350 return NULL;
351 }
352
353 /**
354 * Get rows for the event browser.
355 *
356 * @param int $mailing_id
357 * ID of the mailing.
358 * @param int $job_id
359 * Optional ID of the job.
360 * @param bool $is_distinct
361 * Group by queue id?.
362 * @param int $offset
363 * Offset.
364 * @param int $rowCount
365 * Number of rows.
366 * @param array $sort
367 * Sort array.
368 *
369 * @return array
370 * Result set
371 */
372 public static function &getRows(
373 $mailing_id, $job_id = NULL,
374 $is_distinct = FALSE, $offset = NULL, $rowCount = NULL, $sort = NULL
375 ) {
376
377 $dao = new CRM_Core_Dao();
378
379 $reply = self::getTableName();
380 $queue = CRM_Mailing_Event_BAO_Queue::getTableName();
381 $mailing = CRM_Mailing_BAO_Mailing::getTableName();
382 $job = CRM_Mailing_BAO_MailingJob::getTableName();
383 $contact = CRM_Contact_BAO_Contact::getTableName();
384 $email = CRM_Core_BAO_Email::getTableName();
385
386 $query = "
387 SELECT $contact.display_name as display_name,
388 $contact.id as contact_id,
389 $email.email as email,
390 $reply.time_stamp as date
391 FROM $contact
392 INNER JOIN $queue
393 ON $queue.contact_id = $contact.id
394 INNER JOIN $email
395 ON $queue.email_id = $email.id
396 INNER JOIN $reply
397 ON $reply.event_queue_id = $queue.id
398 INNER JOIN $job
399 ON $queue.job_id = $job.id
400 INNER JOIN $mailing
401 ON $job.mailing_id = $mailing.id
402 AND $job.is_test = 0
403 WHERE $mailing.id = " . CRM_Utils_Type::escape($mailing_id, 'Integer');
404
405 if (!empty($job_id)) {
406 $query .= " AND $job.id = " . CRM_Utils_Type::escape($job_id, 'Integer');
407 }
408
409 if ($is_distinct) {
410 $query .= " GROUP BY $queue.id, $contact.id, $reply.time_stamp ";
411 }
412
413 $orderBy = "sort_name ASC, {$reply}.time_stamp DESC";
414 if ($sort) {
415 if (is_string($sort)) {
416 $sort = CRM_Utils_Type::escape($sort, 'String');
417 $orderBy = $sort;
418 }
419 else {
420 $orderBy = trim($sort->orderBy());
421 }
422 }
423
424 $query .= " ORDER BY {$orderBy} ";
425
426 if ($offset || $rowCount) {
427 //Added "||$rowCount" to avoid displaying all records on first page
428 $query .= ' LIMIT ' . CRM_Utils_Type::escape($offset, 'Integer') . ', ' . CRM_Utils_Type::escape($rowCount, 'Integer');
429 }
430
431 $dao->query($query);
432
433 $results = array();
434
435 while ($dao->fetch()) {
436 $url = CRM_Utils_System::url('civicrm/contact/view',
437 "reset=1&cid={$dao->contact_id}"
438 );
439 $results[] = array(
440 'name' => "<a href=\"$url\">{$dao->display_name}</a>",
441 'email' => $dao->email,
442 'date' => CRM_Utils_Date::customFormat($dao->date),
443 );
444 }
445 return $results;
446 }
447
448 }