Merge pull request #10677 from fuzionnz/CRM-20885-suppress_fakefile_error
[civicrm-core.git] / CRM / Utils / Mail.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
7e9e8871 4 | CiviCRM version 4.7 |
6a488035 5 +--------------------------------------------------------------------+
0f03f337 6 | Copyright CiviCRM LLC (c) 2004-2017 |
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
0f03f337 31 * @copyright CiviCRM LLC (c) 2004-2017
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) {
e633aba2 158 $defaultReturnPath = 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);
e633aba2
OT
162 if (!$defaultReturnPath) {
163 $defaultReturnPath = self::pluckEmailFromHeader($from);
6a488035 164 }
6a488035
TO
165
166 // first call the mail alter hook
38108cce 167 CRM_Utils_Hook::alterMailParams($params, 'singleEmail');
6a488035
TO
168
169 // check if any module has aborted mail sending
8cc574cf 170 if (!empty($params['abortMailSend']) || empty($params['toEmail'])) {
6a488035
TO
171 return FALSE;
172 }
173
174 $textMessage = CRM_Utils_Array::value('text', $params);
175 $htmlMessage = CRM_Utils_Array::value('html', $params);
176 $attachments = CRM_Utils_Array::value('attachments', $params);
177
178 // CRM-6224
179 if (trim(CRM_Utils_String::htmlToText($htmlMessage)) == '') {
180 $htmlMessage = FALSE;
181 }
182
353ffa53 183 $headers = array();
6a488035 184 // CRM-10699 support custom email headers
a7488080 185 if (!empty($params['headers'])) {
6a488035
TO
186 $headers = array_merge($headers, $params['headers']);
187 }
188 $headers['From'] = $params['from'];
ae5ffbb7
TO
189 $headers['To'] = self::formatRFC822Email(
190 CRM_Utils_Array::value('toName', $params),
191 CRM_Utils_Array::value('toEmail', $params),
192 FALSE
193 );
6a488035
TO
194 $headers['Cc'] = CRM_Utils_Array::value('cc', $params);
195 $headers['Bcc'] = CRM_Utils_Array::value('bcc', $params);
196 $headers['Subject'] = CRM_Utils_Array::value('subject', $params);
197 $headers['Content-Type'] = $htmlMessage ? 'multipart/mixed; charset=utf-8' : 'text/plain; charset=utf-8';
198 $headers['Content-Disposition'] = 'inline';
199 $headers['Content-Transfer-Encoding'] = '8bit';
e633aba2 200 $headers['Return-Path'] = CRM_Utils_Array::value('returnPath', $params, $defaultReturnPath);
361fb6c0 201
6a488035 202 // CRM-11295: Omit reply-to headers if empty; this avoids issues with overzealous mailservers
2e35712a 203 $replyTo = CRM_Utils_Array::value('replyTo', $params, CRM_Utils_Array::value('from', $params));
361fb6c0 204
6a488035
TO
205 if (!empty($replyTo)) {
206 $headers['Reply-To'] = $replyTo;
207 }
208 $headers['Date'] = date('r');
209 if ($includeMessageId) {
210 $headers['Message-ID'] = '<' . uniqid('civicrm_', TRUE) . "@$emailDomain>";
211 }
a7488080 212 if (!empty($params['autoSubmitted'])) {
6a488035
TO
213 $headers['Auto-Submitted'] = "Auto-Generated";
214 }
215
50bfb460 216 // make sure we has to have space, CRM-6977
6a488035
TO
217 foreach (array('From', 'To', 'Cc', 'Bcc', 'Reply-To', 'Return-Path') as $fld) {
218 if (isset($headers[$fld])) {
219 $headers[$fld] = str_replace('"<', '" <', $headers[$fld]);
220 }
221 }
222
223 // quote FROM, if comma is detected AND is not already quoted. CRM-7053
224 if (strpos($headers['From'], ',') !== FALSE) {
225 $from = explode(' <', $headers['From']);
226 $headers['From'] = self::formatRFC822Email(
227 $from[0],
228 substr(trim($from[1]), 0, -1),
229 TRUE
230 );
231 }
232
233 require_once 'Mail/mime.php';
234 $msg = new Mail_mime("\n");
235 if ($textMessage) {
236 $msg->setTxtBody($textMessage);
237 }
238
239 if ($htmlMessage) {
240 $msg->setHTMLBody($htmlMessage);
241 }
242
243 if (!empty($attachments)) {
244 foreach ($attachments as $fileID => $attach) {
245 $msg->addAttachment(
246 $attach['fullPath'],
247 $attach['mime_type'],
248 $attach['cleanName']
249 );
250 }
251 }
252
253 $message = self::setMimeParams($msg);
254 $headers = &$msg->headers($headers);
255
256 $to = array($params['toEmail']);
e7292422 257 $result = NULL;
048222df 258 $mailer = \Civi::service('pear_mail');
cbcec379 259
8125eb18
NG
260 // CRM-3795, CRM-7355, CRM-7557, CRM-9058, CRM-9887, CRM-12883, CRM-19173 and others ...
261 // The PEAR library requires different parameters based on the mailer used:
262 // * Mail_mail requires the Cc/Bcc recipients listed ONLY in the $headers variable
263 // * All other mailers require that all be recipients be listed in the $to array AND that
264 // the Bcc must not be present in $header as otherwise it will be shown to all recipients
265 // ref: https://pear.php.net/bugs/bug.php?id=8047, full thread and answer [2011-04-19 20:48 UTC]
cbcec379 266 if (get_class($mailer) != "Mail_mail") {
ea2eebc3
NG
267 // get emails from headers, since these are
268 // combination of name and email addresses.
e7292422 269 if (!empty($headers['Cc'])) {
481a74f4 270 $to[] = CRM_Utils_Array::value('Cc', $headers);
e7292422
TO
271 }
272 if (!empty($headers['Bcc'])) {
481a74f4 273 $to[] = CRM_Utils_Array::value('Bcc', $headers);
d39f2583 274 unset($headers['Bcc']);
e7292422 275 }
6a488035 276 }
8125eb18 277
ea2eebc3 278 if (is_object($mailer)) {
6a4257d4 279 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
6a488035 280 $result = $mailer->send($to, $headers, $message);
6a488035
TO
281 if (is_a($result, 'PEAR_Error')) {
282 $message = self::errorMessage($mailer, $result);
283 // append error message in case multiple calls are being made to
284 // this method in the course of sending a batch of messages.
361fb6c0 285 CRM_Core_Session::setStatus($message, ts('Mailing Error'), 'error');
6a488035
TO
286 return FALSE;
287 }
288 // CRM-10699
289 CRM_Utils_Hook::postEmailSend($params);
290 return TRUE;
291 }
292 return FALSE;
293 }
294
5bc392e6
EM
295 /**
296 * @param $mailer
297 * @param $result
298 *
299 * @return string
300 */
00be9182 301 public static function errorMessage($mailer, $result) {
6a488035 302 $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 303 1 => 'SMTP',
353ffa53 304 )) . '</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
305
306 if (is_a($mailer, 'Mail_smtp')) {
307 $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>';
308 }
309 else {
310 $message .= '<ul>' . '<li>' . ts('Your Sendmail path is incorrect.') . '</li>' . '<li>' . ts('Your Sendmail argument is incorrect.') . '</li>';
311 }
312
313 $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 314 1 => CRM_Utils_System::docURL2('user/advanced-configuration/email-system-configuration', TRUE),
353ffa53 315 )) . '</p>';
6a488035
TO
316
317 return $message;
318 }
319
5bc392e6
EM
320 /**
321 * @param $to
322 * @param $headers
323 * @param $message
324 */
00be9182 325 public static function logger(&$to, &$headers, &$message) {
6a488035
TO
326 if (is_array($to)) {
327 $toString = implode(', ', $to);
328 $fileName = $to[0];
329 }
330 else {
331 $toString = $fileName = $to;
332 }
333 $content = "To: " . $toString . "\n";
334 foreach ($headers as $key => $val) {
335 $content .= "$key: $val\n";
336 }
337 $content .= "\n" . $message . "\n";
338
339 if (is_numeric(CIVICRM_MAIL_LOG)) {
340 $config = CRM_Core_Config::singleton();
341 // create the directory if not there
342 $dirName = $config->configAndLogDir . 'mail' . DIRECTORY_SEPARATOR;
343 CRM_Utils_File::createDir($dirName);
344 $fileName = md5(uniqid(CRM_Utils_String::munge($fileName))) . '.txt';
345 file_put_contents($dirName . $fileName,
346 $content
347 );
348 }
349 else {
350 file_put_contents(CIVICRM_MAIL_LOG, $content, FILE_APPEND);
351 }
352 }
353
354 /**
355 * Get the email address itself from a formatted full name + address string
356 *
357 * Ugly but working.
358 *
77855840
TO
359 * @param string $header
360 * The full name + email address string.
6a488035 361 *
a6c01b45
CW
362 * @return string
363 * the plucked email address
6a488035 364 */
00be9182 365 public static function pluckEmailFromHeader($header) {
6a488035
TO
366 preg_match('/<([^<]*)>$/', $header, $matches);
367
368 if (isset($matches[1])) {
369 return $matches[1];
370 }
371 return NULL;
372 }
373
374 /**
fe482240 375 * Get the Active outBound email.
6a488035 376 *
ae5ffbb7
TO
377 * @return bool
378 * TRUE if valid outBound email configuration found, false otherwise.
6a488035 379 */
00be9182 380 public static function validOutBoundMail() {
aaffa79f 381 $mailingInfo = Civi::settings()->get('mailing_backend');
6a488035
TO
382 if ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_MAIL) {
383 return TRUE;
384 }
385 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_SMTP) {
386 if (!isset($mailingInfo['smtpServer']) || $mailingInfo['smtpServer'] == '' ||
387 $mailingInfo['smtpServer'] == 'YOUR SMTP SERVER' ||
388 ($mailingInfo['smtpAuth'] && ($mailingInfo['smtpUsername'] == '' || $mailingInfo['smtpPassword'] == ''))
389 ) {
390 return FALSE;
391 }
392 return TRUE;
393 }
394 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_SENDMAIL) {
395 if (!$mailingInfo['sendmail_path'] || !$mailingInfo['sendmail_args']) {
396 return FALSE;
397 }
398 return TRUE;
399 }
400 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_REDIRECT_TO_DB) {
401 return TRUE;
402 }
403 return FALSE;
404 }
405
5bc392e6
EM
406 /**
407 * @param $message
100fef9d 408 * @param array $params
5bc392e6
EM
409 *
410 * @return mixed
411 */
00be9182 412 public static function &setMimeParams(&$message, $params = NULL) {
6a488035
TO
413 static $mimeParams = NULL;
414 if (!$params) {
415 if (!$mimeParams) {
416 $mimeParams = array(
417 'text_encoding' => '8bit',
418 'html_encoding' => '8bit',
419 'head_charset' => 'utf-8',
420 'text_charset' => 'utf-8',
421 'html_charset' => 'utf-8',
422 );
423 }
424 $params = $mimeParams;
425 }
426 return $message->get($params);
427 }
428
5bc392e6 429 /**
100fef9d 430 * @param string $name
5bc392e6
EM
431 * @param $email
432 * @param bool $useQuote
433 *
434 * @return null|string
435 */
00be9182 436 public static function formatRFC822Email($name, $email, $useQuote = FALSE) {
6a488035
TO
437 $result = NULL;
438
439 $name = trim($name);
440
441 // strip out double quotes if present at the beginning AND end
442 if (substr($name, 0, 1) == '"' &&
443 substr($name, -1, 1) == '"'
444 ) {
445 $name = substr($name, 1, -1);
446 }
447
448 if (!empty($name)) {
449 // escape the special characters
450 $name = str_replace(array('<', '"', '>'),
451 array('\<', '\"', '\>'),
452 $name
453 );
454 if (strpos($name, ',') !== FALSE ||
455 $useQuote
456 ) {
457 // quote the string if it has a comma
458 $name = '"' . $name . '"';
459 }
460
461 $result = "$name ";
462 }
463
464 $result .= "<{$email}>";
465 return $result;
466 }
467
468 /**
469 * Takes a string and checks to see if it needs to be escaped / double quoted
470 * and if so does the needful and return the formatted name
471 *
472 * This code has been copied and adapted from ezc/Mail/src/tools.php
50bfb460
SB
473 *
474 * @param string $name
475 *
476 * @return string
6a488035 477 */
00be9182 478 public static function formatRFC2822Name($name) {
6a488035
TO
479 $name = trim($name);
480 if (!empty($name)) {
481 // remove the quotes around the name part if they are already there
482 if (substr($name, 0, 1) == '"' && substr($name, -1) == '"') {
483 $name = substr($name, 1, -1);
484 }
485
486 // add slashes to " and \ and surround the name part with quotes
487 if (strpbrk($name, ",@<>:;'\"") !== FALSE) {
488 $name = '"' . addcslashes($name, '\\"') . '"';
489 }
490 }
491
492 return $name;
493 }
383c047b
DG
494
495 /**
383c047b
DG
496 * @param string $fileName
497 * @param string $html
498 * @param string $format
499 *
a6c01b45 500 * @return array
383c047b 501 */
00be9182 502 public static function appendPDF($fileName, $html, $format = NULL) {
383c047b
DG
503 $pdf_filename = CRM_Core_Config::singleton()->templateCompileDir . CRM_Utils_File::makeFileName($fileName);
504
50bfb460
SB
505 // FIXME : CRM-7894
506 // xmlns attribute is required in XHTML but it is invalid in HTML,
507 // Also the namespace "xmlns=http://www.w3.org/1999/xhtml" is default,
508 // and will be added to the <html> tag even if you do not include it.
383c047b
DG
509 $html = preg_replace('/(<html)(.+?xmlns=["\'].[^\s]+["\'])(.+)?(>)/', '\1\3\4', $html);
510
511 file_put_contents($pdf_filename, CRM_Utils_PDF_Utils::html2pdf($html,
353ffa53
TO
512 $fileName,
513 TRUE,
514 $format)
383c047b
DG
515 );
516 return array(
517 'fullPath' => $pdf_filename,
518 'mime_type' => 'application/pdf',
519 'cleanName' => $fileName,
520 );
521 }
96025800 522
6a488035 523}