Merge branch 'master' of https://github.com/civicrm/civicrm-core into CRM-17745
[civicrm-core.git] / CRM / Utils / Mail.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
6a488035
TO
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 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
e7112fa7 31 * @copyright CiviCRM LLC (c) 2004-2015
6a488035
TO
32 */
33class CRM_Utils_Mail {
34
247eb841
TO
35 /**
36 * Create a new mailer to send any mail from the application.
37 *
38 * Note: The mailer is opened in persistent mode.
39 *
40 * Note: You probably don't want to call this directly. Get a reference
41 * to the mailer through the container.
42 *
43 * @return Mail
44 */
45 public static function createMailer() {
aaffa79f 46 $mailingInfo = Civi::settings()->get('mailing_backend');
247eb841
TO
47
48 if ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_REDIRECT_TO_DB ||
49 (defined('CIVICRM_MAILER_SPOOL') && CIVICRM_MAILER_SPOOL)
50 ) {
51 $mailer = self::_createMailer('CRM_Mailing_BAO_Spool', array());
52 }
53 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_SMTP) {
54 if ($mailingInfo['smtpServer'] == '' || !$mailingInfo['smtpServer']) {
55 CRM_Core_Error::debug_log_message(ts('There is no valid smtp server setting. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the SMTP Server.', array(1 => CRM_Utils_System::url('civicrm/admin/setting/smtp', 'reset=1'))));
56 CRM_Core_Error::fatal(ts('There is no valid smtp server setting. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the SMTP Server.', array(1 => CRM_Utils_System::url('civicrm/admin/setting/smtp', 'reset=1'))));
57 }
58
59 $params['host'] = $mailingInfo['smtpServer'] ? $mailingInfo['smtpServer'] : 'localhost';
60 $params['port'] = $mailingInfo['smtpPort'] ? $mailingInfo['smtpPort'] : 25;
61
62 if ($mailingInfo['smtpAuth']) {
63 $params['username'] = $mailingInfo['smtpUsername'];
64 $params['password'] = CRM_Utils_Crypt::decrypt($mailingInfo['smtpPassword']);
65 $params['auth'] = TRUE;
66 }
67 else {
68 $params['auth'] = FALSE;
69 }
70
71 // set the localhost value, CRM-3153
72 $params['localhost'] = CRM_Utils_Array::value('SERVER_NAME', $_SERVER, 'localhost');
73
74 // also set the timeout value, lets set it to 30 seconds
75 // CRM-7510
76 $params['timeout'] = 30;
77
78 // CRM-9349
79 $params['persist'] = TRUE;
80
81 $mailer = self::_createMailer('smtp', $params);
82 }
83 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_SENDMAIL) {
84 if ($mailingInfo['sendmail_path'] == '' ||
85 !$mailingInfo['sendmail_path']
86 ) {
87 CRM_Core_Error::debug_log_message(ts('There is no valid sendmail path setting. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the sendmail server.', array(1 => CRM_Utils_System::url('civicrm/admin/setting/smtp', 'reset=1'))));
88 CRM_Core_Error::fatal(ts('There is no valid sendmail path setting. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the sendmail server.', array(1 => CRM_Utils_System::url('civicrm/admin/setting/smtp', 'reset=1'))));
89 }
90 $params['sendmail_path'] = $mailingInfo['sendmail_path'];
91 $params['sendmail_args'] = $mailingInfo['sendmail_args'];
92
93 $mailer = self::_createMailer('sendmail', $params);
94 }
95 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_MAIL) {
96 $mailer = self::_createMailer('mail', array());
97 }
98 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_MOCK) {
99 $mailer = self::_createMailer('mock', array());
100 }
101 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_DISABLED) {
102 CRM_Core_Error::debug_log_message(ts('Outbound mail has been disabled. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the OutBound Email.', array(1 => CRM_Utils_System::url('civicrm/admin/setting/smtp', 'reset=1'))));
103 CRM_Core_Session::setStatus(ts('Outbound mail has been disabled. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the OutBound Email.', array(1 => CRM_Utils_System::url('civicrm/admin/setting/smtp', 'reset=1'))));
104 }
105 else {
106 CRM_Core_Error::debug_log_message(ts('There is no valid SMTP server Setting Or SendMail path setting. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the OutBound Email.', array(1 => CRM_Utils_System::url('civicrm/admin/setting/smtp', 'reset=1'))));
107 CRM_Core_Session::setStatus(ts('There is no valid SMTP server Setting Or sendMail path setting. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the OutBound Email.', array(1 => CRM_Utils_System::url('civicrm/admin/setting/smtp', 'reset=1'))));
108 CRM_Core_Error::debug_var('mailing_info', $mailingInfo);
109 }
110 return $mailer;
111 }
112
113 /**
114 * Create a new instance of a PEAR Mail driver.
115 *
116 * @param string $driver
117 * 'CRM_Mailing_BAO_Spool' or a name suitable for Mail::factory().
118 * @param array $params
119 * @return object
120 * More specifically, a class which implements the "send()" function
121 */
122 public static function _createMailer($driver, $params) {
123 if ($driver == 'CRM_Mailing_BAO_Spool') {
124 $mailer = new CRM_Mailing_BAO_Spool($params);
125 }
126 else {
127 $mailer = Mail::factory($driver, $params);
128 }
f2b63bd3 129 CRM_Utils_Hook::alterMailer($mailer, $driver, $params);
247eb841
TO
130 return $mailer;
131 }
132
6a488035
TO
133 /**
134 * Wrapper function to send mail in CiviCRM. Hooks are called from this function. The input parameter
135 * is an associateive array which holds the values of field needed to send an email. These are:
136 *
137 * from : complete from envelope
138 * toName : name of person to send email
139 * toEmail : email address to send to
140 * cc : email addresses to cc
141 * bcc : email addresses to bcc
142 * subject : subject of the email
143 * text : text of the message
144 * html : html version of the message
145 * replyTo : reply-to header in the email
146 * attachments: an associative array of
147 * fullPath : complete pathname to the file
148 * mime_type: mime type of the attachment
149 * cleanName: the user friendly name of the attachmment
150 *
77855840
TO
151 * @param array $params
152 * (by reference).
6a488035 153 *
ae5ffbb7
TO
154 * @return bool
155 * TRUE if a mail was sent, else FALSE.
6a488035 156 */
00be9182 157 public static function send(&$params) {
353ffa53 158 $returnPath = CRM_Core_BAO_MailSettings::defaultReturnPath();
6a488035 159 $includeMessageId = CRM_Core_BAO_MailSettings::includeMessageId();
353ffa53
TO
160 $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
161 $from = CRM_Utils_Array::value('from', $params);
6a488035
TO
162 if (!$returnPath) {
163 $returnPath = self::pluckEmailFromHeader($from);
164 }
165 $params['returnPath'] = $returnPath;
166
167 // first call the mail alter hook
168 CRM_Utils_Hook::alterMailParams($params);
169
170 // check if any module has aborted mail sending
8cc574cf 171 if (!empty($params['abortMailSend']) || empty($params['toEmail'])) {
6a488035
TO
172 return FALSE;
173 }
174
175 $textMessage = CRM_Utils_Array::value('text', $params);
176 $htmlMessage = CRM_Utils_Array::value('html', $params);
177 $attachments = CRM_Utils_Array::value('attachments', $params);
178
179 // CRM-6224
180 if (trim(CRM_Utils_String::htmlToText($htmlMessage)) == '') {
181 $htmlMessage = FALSE;
182 }
183
353ffa53 184 $headers = array();
6a488035 185 // CRM-10699 support custom email headers
a7488080 186 if (!empty($params['headers'])) {
6a488035
TO
187 $headers = array_merge($headers, $params['headers']);
188 }
189 $headers['From'] = $params['from'];
ae5ffbb7
TO
190 $headers['To'] = self::formatRFC822Email(
191 CRM_Utils_Array::value('toName', $params),
192 CRM_Utils_Array::value('toEmail', $params),
193 FALSE
194 );
6a488035
TO
195 $headers['Cc'] = CRM_Utils_Array::value('cc', $params);
196 $headers['Bcc'] = CRM_Utils_Array::value('bcc', $params);
197 $headers['Subject'] = CRM_Utils_Array::value('subject', $params);
198 $headers['Content-Type'] = $htmlMessage ? 'multipart/mixed; charset=utf-8' : 'text/plain; charset=utf-8';
199 $headers['Content-Disposition'] = 'inline';
200 $headers['Content-Transfer-Encoding'] = '8bit';
201 $headers['Return-Path'] = CRM_Utils_Array::value('returnPath', $params);
361fb6c0 202
6a488035 203 // CRM-11295: Omit reply-to headers if empty; this avoids issues with overzealous mailservers
2e35712a 204 $replyTo = CRM_Utils_Array::value('replyTo', $params, CRM_Utils_Array::value('from', $params));
361fb6c0 205
6a488035
TO
206 if (!empty($replyTo)) {
207 $headers['Reply-To'] = $replyTo;
208 }
209 $headers['Date'] = date('r');
210 if ($includeMessageId) {
211 $headers['Message-ID'] = '<' . uniqid('civicrm_', TRUE) . "@$emailDomain>";
212 }
a7488080 213 if (!empty($params['autoSubmitted'])) {
6a488035
TO
214 $headers['Auto-Submitted'] = "Auto-Generated";
215 }
216
50bfb460 217 // make sure we has to have space, CRM-6977
6a488035
TO
218 foreach (array('From', 'To', 'Cc', 'Bcc', 'Reply-To', 'Return-Path') as $fld) {
219 if (isset($headers[$fld])) {
220 $headers[$fld] = str_replace('"<', '" <', $headers[$fld]);
221 }
222 }
223
224 // quote FROM, if comma is detected AND is not already quoted. CRM-7053
225 if (strpos($headers['From'], ',') !== FALSE) {
226 $from = explode(' <', $headers['From']);
227 $headers['From'] = self::formatRFC822Email(
228 $from[0],
229 substr(trim($from[1]), 0, -1),
230 TRUE
231 );
232 }
233
234 require_once 'Mail/mime.php';
235 $msg = new Mail_mime("\n");
236 if ($textMessage) {
237 $msg->setTxtBody($textMessage);
238 }
239
240 if ($htmlMessage) {
241 $msg->setHTMLBody($htmlMessage);
242 }
243
244 if (!empty($attachments)) {
245 foreach ($attachments as $fileID => $attach) {
246 $msg->addAttachment(
247 $attach['fullPath'],
248 $attach['mime_type'],
249 $attach['cleanName']
250 );
251 }
252 }
253
254 $message = self::setMimeParams($msg);
255 $headers = &$msg->headers($headers);
256
257 $to = array($params['toEmail']);
e7292422 258 $result = NULL;
048222df 259 $mailer = \Civi::service('pear_mail');
cbcec379
DL
260
261 // Mail_smtp and Mail_sendmail mailers require Bcc anc Cc emails
262 // be included in both $to and $headers['Cc', 'Bcc']
263 if (get_class($mailer) != "Mail_mail") {
50bfb460
SB
264 // get emails from headers, since these are
265 // combination of name and email addresses.
e7292422 266 if (!empty($headers['Cc'])) {
481a74f4 267 $to[] = CRM_Utils_Array::value('Cc', $headers);
e7292422
TO
268 }
269 if (!empty($headers['Bcc'])) {
481a74f4 270 $to[] = CRM_Utils_Array::value('Bcc', $headers);
e7292422 271 }
6a488035 272 }
6a488035 273 if (is_object($mailer)) {
6a4257d4 274 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
6a488035 275 $result = $mailer->send($to, $headers, $message);
6a488035
TO
276 if (is_a($result, 'PEAR_Error')) {
277 $message = self::errorMessage($mailer, $result);
278 // append error message in case multiple calls are being made to
279 // this method in the course of sending a batch of messages.
361fb6c0 280 CRM_Core_Session::setStatus($message, ts('Mailing Error'), 'error');
6a488035
TO
281 return FALSE;
282 }
283 // CRM-10699
284 CRM_Utils_Hook::postEmailSend($params);
285 return TRUE;
286 }
287 return FALSE;
288 }
289
5bc392e6
EM
290 /**
291 * @param $mailer
292 * @param $result
293 *
294 * @return string
295 */
00be9182 296 public static function errorMessage($mailer, $result) {
6a488035 297 $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(
ae5ffbb7 298 1 => 'SMTP',
353ffa53 299 )) . '</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>';
6a488035
TO
300
301 if (is_a($mailer, 'Mail_smtp')) {
302 $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>';
303 }
304 else {
305 $message .= '<ul>' . '<li>' . ts('Your Sendmail path is incorrect.') . '</li>' . '<li>' . ts('Your Sendmail argument is incorrect.') . '</li>';
306 }
307
308 $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(
ae5ffbb7 309 1 => CRM_Utils_System::docURL2('user/advanced-configuration/email-system-configuration', TRUE),
353ffa53 310 )) . '</p>';
6a488035
TO
311
312 return $message;
313 }
314
5bc392e6
EM
315 /**
316 * @param $to
317 * @param $headers
318 * @param $message
319 */
00be9182 320 public static function logger(&$to, &$headers, &$message) {
6a488035
TO
321 if (is_array($to)) {
322 $toString = implode(', ', $to);
323 $fileName = $to[0];
324 }
325 else {
326 $toString = $fileName = $to;
327 }
328 $content = "To: " . $toString . "\n";
329 foreach ($headers as $key => $val) {
330 $content .= "$key: $val\n";
331 }
332 $content .= "\n" . $message . "\n";
333
334 if (is_numeric(CIVICRM_MAIL_LOG)) {
335 $config = CRM_Core_Config::singleton();
336 // create the directory if not there
337 $dirName = $config->configAndLogDir . 'mail' . DIRECTORY_SEPARATOR;
338 CRM_Utils_File::createDir($dirName);
339 $fileName = md5(uniqid(CRM_Utils_String::munge($fileName))) . '.txt';
340 file_put_contents($dirName . $fileName,
341 $content
342 );
343 }
344 else {
345 file_put_contents(CIVICRM_MAIL_LOG, $content, FILE_APPEND);
346 }
347 }
348
349 /**
350 * Get the email address itself from a formatted full name + address string
351 *
352 * Ugly but working.
353 *
77855840
TO
354 * @param string $header
355 * The full name + email address string.
6a488035 356 *
a6c01b45
CW
357 * @return string
358 * the plucked email address
6a488035 359 */
00be9182 360 public static function pluckEmailFromHeader($header) {
6a488035
TO
361 preg_match('/<([^<]*)>$/', $header, $matches);
362
363 if (isset($matches[1])) {
364 return $matches[1];
365 }
366 return NULL;
367 }
368
369 /**
fe482240 370 * Get the Active outBound email.
6a488035 371 *
ae5ffbb7
TO
372 * @return bool
373 * TRUE if valid outBound email configuration found, false otherwise.
6a488035 374 */
00be9182 375 public static function validOutBoundMail() {
aaffa79f 376 $mailingInfo = Civi::settings()->get('mailing_backend');
6a488035
TO
377 if ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_MAIL) {
378 return TRUE;
379 }
380 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_SMTP) {
381 if (!isset($mailingInfo['smtpServer']) || $mailingInfo['smtpServer'] == '' ||
382 $mailingInfo['smtpServer'] == 'YOUR SMTP SERVER' ||
383 ($mailingInfo['smtpAuth'] && ($mailingInfo['smtpUsername'] == '' || $mailingInfo['smtpPassword'] == ''))
384 ) {
385 return FALSE;
386 }
387 return TRUE;
388 }
389 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_SENDMAIL) {
390 if (!$mailingInfo['sendmail_path'] || !$mailingInfo['sendmail_args']) {
391 return FALSE;
392 }
393 return TRUE;
394 }
395 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_REDIRECT_TO_DB) {
396 return TRUE;
397 }
398 return FALSE;
399 }
400
5bc392e6
EM
401 /**
402 * @param $message
100fef9d 403 * @param array $params
5bc392e6
EM
404 *
405 * @return mixed
406 */
00be9182 407 public static function &setMimeParams(&$message, $params = NULL) {
6a488035
TO
408 static $mimeParams = NULL;
409 if (!$params) {
410 if (!$mimeParams) {
411 $mimeParams = array(
412 'text_encoding' => '8bit',
413 'html_encoding' => '8bit',
414 'head_charset' => 'utf-8',
415 'text_charset' => 'utf-8',
416 'html_charset' => 'utf-8',
417 );
418 }
419 $params = $mimeParams;
420 }
421 return $message->get($params);
422 }
423
5bc392e6 424 /**
100fef9d 425 * @param string $name
5bc392e6
EM
426 * @param $email
427 * @param bool $useQuote
428 *
429 * @return null|string
430 */
00be9182 431 public static function formatRFC822Email($name, $email, $useQuote = FALSE) {
6a488035
TO
432 $result = NULL;
433
434 $name = trim($name);
435
436 // strip out double quotes if present at the beginning AND end
437 if (substr($name, 0, 1) == '"' &&
438 substr($name, -1, 1) == '"'
439 ) {
440 $name = substr($name, 1, -1);
441 }
442
443 if (!empty($name)) {
444 // escape the special characters
445 $name = str_replace(array('<', '"', '>'),
446 array('\<', '\"', '\>'),
447 $name
448 );
449 if (strpos($name, ',') !== FALSE ||
450 $useQuote
451 ) {
452 // quote the string if it has a comma
453 $name = '"' . $name . '"';
454 }
455
456 $result = "$name ";
457 }
458
459 $result .= "<{$email}>";
460 return $result;
461 }
462
463 /**
464 * Takes a string and checks to see if it needs to be escaped / double quoted
465 * and if so does the needful and return the formatted name
466 *
467 * This code has been copied and adapted from ezc/Mail/src/tools.php
50bfb460
SB
468 *
469 * @param string $name
470 *
471 * @return string
6a488035 472 */
00be9182 473 public static function formatRFC2822Name($name) {
6a488035
TO
474 $name = trim($name);
475 if (!empty($name)) {
476 // remove the quotes around the name part if they are already there
477 if (substr($name, 0, 1) == '"' && substr($name, -1) == '"') {
478 $name = substr($name, 1, -1);
479 }
480
481 // add slashes to " and \ and surround the name part with quotes
482 if (strpbrk($name, ",@<>:;'\"") !== FALSE) {
483 $name = '"' . addcslashes($name, '\\"') . '"';
484 }
485 }
486
487 return $name;
488 }
383c047b
DG
489
490 /**
383c047b
DG
491 * @param string $fileName
492 * @param string $html
493 * @param string $format
494 *
a6c01b45 495 * @return array
383c047b 496 */
00be9182 497 public static function appendPDF($fileName, $html, $format = NULL) {
383c047b
DG
498 $pdf_filename = CRM_Core_Config::singleton()->templateCompileDir . CRM_Utils_File::makeFileName($fileName);
499
50bfb460
SB
500 // FIXME : CRM-7894
501 // xmlns attribute is required in XHTML but it is invalid in HTML,
502 // Also the namespace "xmlns=http://www.w3.org/1999/xhtml" is default,
503 // and will be added to the <html> tag even if you do not include it.
383c047b
DG
504 $html = preg_replace('/(<html)(.+?xmlns=["\'].[^\s]+["\'])(.+)?(>)/', '\1\3\4', $html);
505
506 file_put_contents($pdf_filename, CRM_Utils_PDF_Utils::html2pdf($html,
353ffa53
TO
507 $fileName,
508 TRUE,
509 $format)
383c047b
DG
510 );
511 return array(
512 'fullPath' => $pdf_filename,
513 'mime_type' => 'application/pdf',
514 'cleanName' => $fileName,
515 );
516 }
96025800 517
6a488035 518}