Merge pull request #4875 from civicrm/minor-fix
[civicrm-core.git] / CRM / Utils / Mail.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 class CRM_Utils_Mail {
36
37 /**
38 * Wrapper function to send mail in CiviCRM. Hooks are called from this function. The input parameter
39 * is an associateive array which holds the values of field needed to send an email. These are:
40 *
41 * from : complete from envelope
42 * toName : name of person to send email
43 * toEmail : email address to send to
44 * cc : email addresses to cc
45 * bcc : email addresses to bcc
46 * subject : subject of the email
47 * text : text of the message
48 * html : html version of the message
49 * replyTo : reply-to header in the email
50 * attachments: an associative array of
51 * fullPath : complete pathname to the file
52 * mime_type: mime type of the attachment
53 * cleanName: the user friendly name of the attachmment
54 *
55 * @param array $params
56 * (by reference).
57 *
58 *
59 * @return boolean
60 * true if a mail was sent, else false
61 */
62 public static function send(&$params) {
63 $returnPath = CRM_Core_BAO_MailSettings::defaultReturnPath();
64 $includeMessageId = CRM_Core_BAO_MailSettings::includeMessageId();
65 $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
66 $from = CRM_Utils_Array::value('from', $params);
67 if (!$returnPath) {
68 $returnPath = self::pluckEmailFromHeader($from);
69 }
70 $params['returnPath'] = $returnPath;
71
72 // first call the mail alter hook
73 CRM_Utils_Hook::alterMailParams($params);
74
75 // check if any module has aborted mail sending
76 if (!empty($params['abortMailSend']) || empty($params['toEmail'])) {
77 return FALSE;
78 }
79
80 $textMessage = CRM_Utils_Array::value('text', $params);
81 $htmlMessage = CRM_Utils_Array::value('html', $params);
82 $attachments = CRM_Utils_Array::value('attachments', $params);
83
84 // CRM-6224
85 if (trim(CRM_Utils_String::htmlToText($htmlMessage)) == '') {
86 $htmlMessage = FALSE;
87 }
88
89 $headers = array();
90 // CRM-10699 support custom email headers
91 if (!empty($params['headers'])) {
92 $headers = array_merge($headers, $params['headers']);
93 }
94 $headers['From'] = $params['from'];
95 $headers['To'] =
96 self::formatRFC822Email(
97 CRM_Utils_Array::value('toName', $params),
98 CRM_Utils_Array::value('toEmail', $params),
99 FALSE
100 );
101 $headers['Cc'] = CRM_Utils_Array::value('cc', $params);
102 $headers['Bcc'] = CRM_Utils_Array::value('bcc', $params);
103 $headers['Subject'] = CRM_Utils_Array::value('subject', $params);
104 $headers['Content-Type'] = $htmlMessage ? 'multipart/mixed; charset=utf-8' : 'text/plain; charset=utf-8';
105 $headers['Content-Disposition'] = 'inline';
106 $headers['Content-Transfer-Encoding'] = '8bit';
107 $headers['Return-Path'] = CRM_Utils_Array::value('returnPath', $params);
108
109 // CRM-11295: Omit reply-to headers if empty; this avoids issues with overzealous mailservers
110 $replyTo = CRM_Utils_Array::value('replyTo', $params, $from);
111
112 if (!empty($replyTo)) {
113 $headers['Reply-To'] = $replyTo;
114 }
115 $headers['Date'] = date('r');
116 if ($includeMessageId) {
117 $headers['Message-ID'] = '<' . uniqid('civicrm_', TRUE) . "@$emailDomain>";
118 }
119 if (!empty($params['autoSubmitted'])) {
120 $headers['Auto-Submitted'] = "Auto-Generated";
121 }
122
123 //make sure we has to have space, CRM-6977
124 foreach (array('From', 'To', 'Cc', 'Bcc', 'Reply-To', 'Return-Path') as $fld) {
125 if (isset($headers[$fld])) {
126 $headers[$fld] = str_replace('"<', '" <', $headers[$fld]);
127 }
128 }
129
130 // quote FROM, if comma is detected AND is not already quoted. CRM-7053
131 if (strpos($headers['From'], ',') !== FALSE) {
132 $from = explode(' <', $headers['From']);
133 $headers['From'] = self::formatRFC822Email(
134 $from[0],
135 substr(trim($from[1]), 0, -1),
136 TRUE
137 );
138 }
139
140 require_once 'Mail/mime.php';
141 $msg = new Mail_mime("\n");
142 if ($textMessage) {
143 $msg->setTxtBody($textMessage);
144 }
145
146 if ($htmlMessage) {
147 $msg->setHTMLBody($htmlMessage);
148 }
149
150 if (!empty($attachments)) {
151 foreach ($attachments as $fileID => $attach) {
152 $msg->addAttachment(
153 $attach['fullPath'],
154 $attach['mime_type'],
155 $attach['cleanName']
156 );
157 }
158 }
159
160 $message = self::setMimeParams($msg);
161 $headers = &$msg->headers($headers);
162
163 $to = array($params['toEmail']);
164 $result = NULL;
165 $mailer =& CRM_Core_Config::getMailer();
166
167 // Mail_smtp and Mail_sendmail mailers require Bcc anc Cc emails
168 // be included in both $to and $headers['Cc', 'Bcc']
169 if (get_class($mailer) != "Mail_mail") {
170 //get emails from headers, since these are
171 //combination of name and email addresses.
172 if (!empty($headers['Cc'])) {
173 $to[] = CRM_Utils_Array::value('Cc', $headers);
174 }
175 if (!empty($headers['Bcc'])) {
176 $to[] = CRM_Utils_Array::value('Bcc', $headers);
177 }
178 }
179 if (is_object($mailer)) {
180 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
181 $result = $mailer->send($to, $headers, $message);
182 if (is_a($result, 'PEAR_Error')) {
183 $message = self::errorMessage($mailer, $result);
184 // append error message in case multiple calls are being made to
185 // this method in the course of sending a batch of messages.
186 CRM_Core_Session::setStatus($message, ts('Mailing Error'), 'error');
187 return FALSE;
188 }
189 // CRM-10699
190 CRM_Utils_Hook::postEmailSend($params);
191 return TRUE;
192 }
193 return FALSE;
194 }
195
196 /**
197 * @param $mailer
198 * @param $result
199 *
200 * @return string
201 */
202 public static function errorMessage($mailer, $result) {
203 $message = '<p>' . ts('An error occurred when CiviCRM attempted to send an email (via %1). If you received this error after submitting on online contribution or event registration - the transaction was completed, but we were unable to send the email receipt.', array(
204 1 => 'SMTP'
205 )) . '</p>' . '<p>' . ts('The mail library returned the following error message:') . '<br /><span class="font-red"><strong>' . $result->getMessage() . '</strong></span></p>' . '<p>' . ts('This is probably related to a problem in your Outbound Email Settings (Administer CiviCRM &raquo; System Settings &raquo; Outbound Email), OR the FROM email address specifically configured for your contribution page or event. Possible causes are:') . '</p>';
206
207 if (is_a($mailer, 'Mail_smtp')) {
208 $message .= '<ul>' . '<li>' . ts('Your SMTP Username or Password are incorrect.') . '</li>' . '<li>' . ts('Your SMTP Server (machine) name is incorrect.') . '</li>' . '<li>' . ts('You need to use a Port other than the default port 25 in your environment.') . '</li>' . '<li>' . ts('Your SMTP server is just not responding right now (it is down for some reason).') . '</li>';
209 }
210 else {
211 $message .= '<ul>' . '<li>' . ts('Your Sendmail path is incorrect.') . '</li>' . '<li>' . ts('Your Sendmail argument is incorrect.') . '</li>';
212 }
213
214 $message .= '<li>' . ts('The FROM Email Address configured for this feature may not be a valid sender based on your email service provider rules.') . '</li>' . '</ul>' . '<p>' . ts('Check <a href="%1">this page</a> for more information.', array(
215 1 => CRM_Utils_System::docURL2('user/advanced-configuration/email-system-configuration', TRUE)
216 )) . '</p>';
217
218 return $message;
219 }
220
221 /**
222 * @param $to
223 * @param $headers
224 * @param $message
225 */
226 public static function logger(&$to, &$headers, &$message) {
227 if (is_array($to)) {
228 $toString = implode(', ', $to);
229 $fileName = $to[0];
230 }
231 else {
232 $toString = $fileName = $to;
233 }
234 $content = "To: " . $toString . "\n";
235 foreach ($headers as $key => $val) {
236 $content .= "$key: $val\n";
237 }
238 $content .= "\n" . $message . "\n";
239
240 if (is_numeric(CIVICRM_MAIL_LOG)) {
241 $config = CRM_Core_Config::singleton();
242 // create the directory if not there
243 $dirName = $config->configAndLogDir . 'mail' . DIRECTORY_SEPARATOR;
244 CRM_Utils_File::createDir($dirName);
245 $fileName = md5(uniqid(CRM_Utils_String::munge($fileName))) . '.txt';
246 file_put_contents($dirName . $fileName,
247 $content
248 );
249 }
250 else {
251 file_put_contents(CIVICRM_MAIL_LOG, $content, FILE_APPEND);
252 }
253 }
254
255 /**
256 * Get the email address itself from a formatted full name + address string
257 *
258 * Ugly but working.
259 *
260 * @param string $header
261 * The full name + email address string.
262 *
263 * @return string
264 * the plucked email address
265 * @static
266 */
267 public static function pluckEmailFromHeader($header) {
268 preg_match('/<([^<]*)>$/', $header, $matches);
269
270 if (isset($matches[1])) {
271 return $matches[1];
272 }
273 return NULL;
274 }
275
276 /**
277 * Get the Active outBound email
278 *
279 * @return boolean
280 * true if valid outBound email configuration found, false otherwise
281 * @static
282 */
283 public static function validOutBoundMail() {
284 $mailingInfo = CRM_Core_BAO_Setting::getItem(CRM_Core_BAO_Setting::MAILING_PREFERENCES_NAME,
285 'mailing_backend'
286 );
287 if ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_MAIL) {
288 return TRUE;
289 }
290 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_SMTP) {
291 if (!isset($mailingInfo['smtpServer']) || $mailingInfo['smtpServer'] == '' ||
292 $mailingInfo['smtpServer'] == 'YOUR SMTP SERVER' ||
293 ($mailingInfo['smtpAuth'] && ($mailingInfo['smtpUsername'] == '' || $mailingInfo['smtpPassword'] == ''))
294 ) {
295 return FALSE;
296 }
297 return TRUE;
298 }
299 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_SENDMAIL) {
300 if (!$mailingInfo['sendmail_path'] || !$mailingInfo['sendmail_args']) {
301 return FALSE;
302 }
303 return TRUE;
304 }
305 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_REDIRECT_TO_DB) {
306 return TRUE;
307 }
308 return FALSE;
309 }
310
311 /**
312 * @param $message
313 * @param array $params
314 *
315 * @return mixed
316 */
317 public static function &setMimeParams(&$message, $params = NULL) {
318 static $mimeParams = NULL;
319 if (!$params) {
320 if (!$mimeParams) {
321 $mimeParams = array(
322 'text_encoding' => '8bit',
323 'html_encoding' => '8bit',
324 'head_charset' => 'utf-8',
325 'text_charset' => 'utf-8',
326 'html_charset' => 'utf-8',
327 );
328 }
329 $params = $mimeParams;
330 }
331 return $message->get($params);
332 }
333
334 /**
335 * @param string $name
336 * @param $email
337 * @param bool $useQuote
338 *
339 * @return null|string
340 */
341 public static function formatRFC822Email($name, $email, $useQuote = FALSE) {
342 $result = NULL;
343
344 $name = trim($name);
345
346 // strip out double quotes if present at the beginning AND end
347 if (substr($name, 0, 1) == '"' &&
348 substr($name, -1, 1) == '"'
349 ) {
350 $name = substr($name, 1, -1);
351 }
352
353 if (!empty($name)) {
354 // escape the special characters
355 $name = str_replace(array('<', '"', '>'),
356 array('\<', '\"', '\>'),
357 $name
358 );
359 if (strpos($name, ',') !== FALSE ||
360 $useQuote
361 ) {
362 // quote the string if it has a comma
363 $name = '"' . $name . '"';
364 }
365
366 $result = "$name ";
367 }
368
369 $result .= "<{$email}>";
370 return $result;
371 }
372
373 /**
374 * Takes a string and checks to see if it needs to be escaped / double quoted
375 * and if so does the needful and return the formatted name
376 *
377 * This code has been copied and adapted from ezc/Mail/src/tools.php
378 */
379 public static function formatRFC2822Name($name) {
380 $name = trim($name);
381 if (!empty($name)) {
382 // remove the quotes around the name part if they are already there
383 if (substr($name, 0, 1) == '"' && substr($name, -1) == '"') {
384 $name = substr($name, 1, -1);
385 }
386
387 // add slashes to " and \ and surround the name part with quotes
388 if (strpbrk($name, ",@<>:;'\"") !== FALSE) {
389 $name = '"' . addcslashes($name, '\\"') . '"';
390 }
391 }
392
393 return $name;
394 }
395
396 /**
397 * @param string $fileName
398 * @param string $html
399 * @param string $format
400 *
401 * @return array
402 */
403 public static function appendPDF($fileName, $html, $format = NULL) {
404 $pdf_filename = CRM_Core_Config::singleton()->templateCompileDir . CRM_Utils_File::makeFileName($fileName);
405
406 //FIXME : CRM-7894
407 //xmlns attribute is required in XHTML but it is invalid in HTML,
408 //Also the namespace "xmlns=http://www.w3.org/1999/xhtml" is default,
409 //and will be added to the <html> tag even if you do not include it.
410 $html = preg_replace('/(<html)(.+?xmlns=["\'].[^\s]+["\'])(.+)?(>)/', '\1\3\4', $html);
411
412 file_put_contents($pdf_filename, CRM_Utils_PDF_Utils::html2pdf($html,
413 $fileName,
414 TRUE,
415 $format)
416 );
417 return array(
418 'fullPath' => $pdf_filename,
419 'mime_type' => 'application/pdf',
420 'cleanName' => $fileName,
421 );
422 }
423 }