Merge remote-tracking branch 'upstream/4.5' into 4.5-master-2015-01-05-23-28-33
[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 The job ID of the reply
57 * @param int $queue_id The queue event id
58 * @param string $hash The hash
59 *
60 * @param null $replyto
61 *
62 * @return object|null The mailing object, or null on failure
63 * @static
64 */
65 public static function &reply($job_id, $queue_id, $hash, $replyto = NULL) {
66 /* First make sure there's a matching queue event */
67
68 $q = CRM_Mailing_Event_BAO_Queue::verify($job_id, $queue_id, $hash);
69
70 $success = NULL;
71
72 if (!$q) {
73 return $success;
74 }
75
76 $mailing = new CRM_Mailing_BAO_Mailing();
77 $mailings = CRM_Mailing_BAO_Mailing::getTableName();
78 $jobs = CRM_Mailing_BAO_MailingJob::getTableName();
79 $mailing->query(
80 "SELECT * FROM $mailings
81 INNER JOIN $jobs
82 ON $jobs.mailing_id = $mailings.id
83 WHERE $jobs.id = {$q->job_id}"
84 );
85 $mailing->fetch();
86 if ($mailing->auto_responder) {
87 self::autoRespond($mailing, $queue_id, $replyto);
88 }
89
90 $re = new CRM_Mailing_Event_BAO_Reply();
91 $re->event_queue_id = $queue_id;
92 $re->time_stamp = date('YmdHis');
93 $re->save();
94
95 if (!$mailing->forward_replies || empty($mailing->replyto_email)) {
96 return $success;
97 }
98
99 return $mailing;
100 }
101
102 /**
103 * Forward a mailing reply
104 *
105 * @param int $queue_id Queue event ID of the sender
106 * @param string $mailing The mailing object
107 * @param string $bodyTxt text part of the body (ignored if $fullEmail provided)
108 * @param string $replyto Reply-to of the incoming message
109 * @param string $bodyHTML HTML part of the body (ignored if $fullEmail provided)
110 * @param string $fullEmail whole email to forward in one string
111 *
112 * @return void
113 * @static
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 = $config->getMailer();
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 The mailing object
209 * @param int $queue_id The queue ID
210 * @param string $replyto Optional reply-to from the reply
211 *
212 * @return void
213 * @static
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
258 $html = $component->body_html;
259 if ($component->body_text) {
260 $text = $component->body_text;
261 }
262 else {
263 $text = CRM_Utils_String::htmlToText($component->body_html);
264 }
265
266 $bao = new CRM_Mailing_BAO_Mailing();
267 $bao->body_text = $text;
268 $bao->body_html = $html;
269 $tokens = $bao->getTokens();
270
271 if ($eq->format == 'HTML' || $eq->format == 'Both') {
272 $html = CRM_Utils_Token::replaceDomainTokens($html, $domain, TRUE, $tokens['html']);
273 $html = CRM_Utils_Token::replaceMailingTokens($html, $mailing, NULL, $tokens['html']);
274 $message->setHTMLBody($html);
275 }
276 if (!$html || $eq->format == 'Text' || $eq->format == 'Both') {
277 $text = CRM_Utils_Token::replaceDomainTokens($text, $domain, FALSE, $tokens['text']);
278 $text = CRM_Utils_Token::replaceMailingTokens($text, $mailing, NULL, $tokens['text']);
279 $message->setTxtBody($text);
280 }
281
282 $b = CRM_Utils_Mail::setMimeParams($message);
283 $h = $message->headers($headers);
284 CRM_Mailing_BAO_Mailing::addMessageIdHeader($h, 'a', $eq->job_id, queue_id, $eq->hash);
285
286 $mailer = $config->getMailer();
287 if (is_object($mailer)) {
288 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
289 $mailer->send($to, $h, $b);
290 unset($errorScope);
291 }
292 }
293
294 /**
295 * Get row count for the event selector
296 *
297 * @param int $mailing_id ID of the mailing
298 * @param int $job_id Optional ID of a job to filter on
299 * @param boolean $is_distinct Group by queue ID?
300 *
301 * @return int Number of rows in result set
302 * @static
303 */
304 public static function getTotalCount($mailing_id, $job_id = NULL,
305 $is_distinct = FALSE
306 ) {
307 $dao = new CRM_Core_DAO();
308
309 $reply = self::getTableName();
310 $queue = CRM_Mailing_Event_BAO_Queue::getTableName();
311 $mailing = CRM_Mailing_BAO_Mailing::getTableName();
312 $job = CRM_Mailing_BAO_MailingJob::getTableName();
313
314 $query = "
315 SELECT COUNT($reply.id) as reply
316 FROM $reply
317 INNER JOIN $queue
318 ON $reply.event_queue_id = $queue.id
319 INNER JOIN $job
320 ON $queue.job_id = $job.id
321 INNER JOIN $mailing
322 ON $job.mailing_id = $mailing.id
323 AND $job.is_test = 0
324 WHERE $mailing.id = " . CRM_Utils_Type::escape($mailing_id, 'Integer');
325
326 if (!empty($job_id)) {
327 $query .= " AND $job.id = " . CRM_Utils_Type::escape($job_id, 'Integer');
328 }
329
330 if ($is_distinct) {
331 $query .= " GROUP BY $queue.id ";
332 }
333
334 // query was missing
335 $dao->query($query);
336
337 if ($dao->fetch()) {
338 return $dao->reply;
339 }
340
341 return NULL;
342 }
343
344 /**
345 * Get rows for the event browser
346 *
347 * @param int $mailing_id ID of the mailing
348 * @param int $job_id optional ID of the job
349 * @param boolean $is_distinct Group by queue id?
350 * @param int $offset Offset
351 * @param int $rowCount Number of rows
352 * @param array $sort sort array
353 *
354 * @return array Result set
355 * @static
356 */
357 public static function &getRows($mailing_id, $job_id = NULL,
358 $is_distinct = FALSE, $offset = NULL, $rowCount = NULL, $sort = NULL
359 ) {
360
361 $dao = new CRM_Core_Dao();
362
363 $reply = self::getTableName();
364 $queue = CRM_Mailing_Event_BAO_Queue::getTableName();
365 $mailing = CRM_Mailing_BAO_Mailing::getTableName();
366 $job = CRM_Mailing_BAO_MailingJob::getTableName();
367 $contact = CRM_Contact_BAO_Contact::getTableName();
368 $email = CRM_Core_BAO_Email::getTableName();
369
370 $query = "
371 SELECT $contact.display_name as display_name,
372 $contact.id as contact_id,
373 $email.email as email,
374 $reply.time_stamp as date
375 FROM $contact
376 INNER JOIN $queue
377 ON $queue.contact_id = $contact.id
378 INNER JOIN $email
379 ON $queue.email_id = $email.id
380 INNER JOIN $reply
381 ON $reply.event_queue_id = $queue.id
382 INNER JOIN $job
383 ON $queue.job_id = $job.id
384 INNER JOIN $mailing
385 ON $job.mailing_id = $mailing.id
386 AND $job.is_test = 0
387 WHERE $mailing.id = " . CRM_Utils_Type::escape($mailing_id, 'Integer');
388
389 if (!empty($job_id)) {
390 $query .= " AND $job.id = " . CRM_Utils_Type::escape($job_id, 'Integer');
391 }
392
393 if ($is_distinct) {
394 $query .= " GROUP BY $queue.id ";
395 }
396
397 $orderBy = "sort_name ASC, {$reply}.time_stamp DESC";
398 if ($sort) {
399 if (is_string($sort)) {
400 $sort = CRM_Utils_Type::escape($sort, 'String');
401 $orderBy = $sort;
402 }
403 else {
404 $orderBy = trim($sort->orderBy());
405 }
406 }
407
408 $query .= " ORDER BY {$orderBy} ";
409
410 if ($offset || $rowCount) {
411 //Added "||$rowCount" to avoid displaying all records on first page
412 $query .= ' LIMIT ' . CRM_Utils_Type::escape($offset, 'Integer') . ', ' . CRM_Utils_Type::escape($rowCount, 'Integer');
413 }
414
415 $dao->query($query);
416
417 $results = array();
418
419 while ($dao->fetch()) {
420 $url = CRM_Utils_System::url('civicrm/contact/view',
421 "reset=1&cid={$dao->contact_id}"
422 );
423 $results[] = array(
424 'name' => "<a href=\"$url\">{$dao->display_name}</a>",
425 'email' => $dao->email,
426 'date' => CRM_Utils_Date::customFormat($dao->date),
427 );
428 }
429 return $results;
430 }
431 }