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