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