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