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