Merge pull request #8088 from JKingsnorth/CRM-18345
[civicrm-core.git] / CRM / Utils / Mail.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
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-2016
32 */
33 class CRM_Utils_Mail {
34
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 = Civi::settings()->get('mailing_backend');
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 }
129 CRM_Utils_Hook::alterMailer($mailer, $driver, $params);
130 return $mailer;
131 }
132
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 *
151 * @param array $params
152 * (by reference).
153 *
154 * @return bool
155 * TRUE if a mail was sent, else FALSE.
156 */
157 public static function send(&$params) {
158 $defaultReturnPath = CRM_Core_BAO_MailSettings::defaultReturnPath();
159 $includeMessageId = CRM_Core_BAO_MailSettings::includeMessageId();
160 $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
161 $from = CRM_Utils_Array::value('from', $params);
162 if (!$defaultReturnPath) {
163 $defaultReturnPath = self::pluckEmailFromHeader($from);
164 }
165
166 // first call the mail alter hook
167 CRM_Utils_Hook::alterMailParams($params);
168
169 // check if any module has aborted mail sending
170 if (!empty($params['abortMailSend']) || empty($params['toEmail'])) {
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
183 $headers = array();
184 // CRM-10699 support custom email headers
185 if (!empty($params['headers'])) {
186 $headers = array_merge($headers, $params['headers']);
187 }
188 $headers['From'] = $params['from'];
189 $headers['To'] = self::formatRFC822Email(
190 CRM_Utils_Array::value('toName', $params),
191 CRM_Utils_Array::value('toEmail', $params),
192 FALSE
193 );
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';
200 $headers['Return-Path'] = CRM_Utils_Array::value('returnPath', $params, $defaultReturnPath);
201
202 // CRM-11295: Omit reply-to headers if empty; this avoids issues with overzealous mailservers
203 $replyTo = CRM_Utils_Array::value('replyTo', $params, CRM_Utils_Array::value('from', $params));
204
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 }
212 if (!empty($params['autoSubmitted'])) {
213 $headers['Auto-Submitted'] = "Auto-Generated";
214 }
215
216 // make sure we has to have space, CRM-6977
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']);
257 $result = NULL;
258 $mailer = \Civi::service('pear_mail');
259
260 // Mail_smtp and Mail_sendmail mailers require Bcc anc Cc emails
261 // be included in both $to and $headers['Cc', 'Bcc']
262 if (get_class($mailer) != "Mail_mail") {
263 // get emails from headers, since these are
264 // combination of name and email addresses.
265 if (!empty($headers['Cc'])) {
266 $to[] = CRM_Utils_Array::value('Cc', $headers);
267 }
268 if (!empty($headers['Bcc'])) {
269 $to[] = CRM_Utils_Array::value('Bcc', $headers);
270 }
271 }
272 if (is_object($mailer)) {
273 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
274 $result = $mailer->send($to, $headers, $message);
275 if (is_a($result, 'PEAR_Error')) {
276 $message = self::errorMessage($mailer, $result);
277 // append error message in case multiple calls are being made to
278 // this method in the course of sending a batch of messages.
279 CRM_Core_Session::setStatus($message, ts('Mailing Error'), 'error');
280 return FALSE;
281 }
282 // CRM-10699
283 CRM_Utils_Hook::postEmailSend($params);
284 return TRUE;
285 }
286 return FALSE;
287 }
288
289 /**
290 * @param $mailer
291 * @param $result
292 *
293 * @return string
294 */
295 public static function errorMessage($mailer, $result) {
296 $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(
297 1 => 'SMTP',
298 )) . '</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>';
299
300 if (is_a($mailer, 'Mail_smtp')) {
301 $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>';
302 }
303 else {
304 $message .= '<ul>' . '<li>' . ts('Your Sendmail path is incorrect.') . '</li>' . '<li>' . ts('Your Sendmail argument is incorrect.') . '</li>';
305 }
306
307 $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(
308 1 => CRM_Utils_System::docURL2('user/advanced-configuration/email-system-configuration', TRUE),
309 )) . '</p>';
310
311 return $message;
312 }
313
314 /**
315 * @param $to
316 * @param $headers
317 * @param $message
318 */
319 public static function logger(&$to, &$headers, &$message) {
320 if (is_array($to)) {
321 $toString = implode(', ', $to);
322 $fileName = $to[0];
323 }
324 else {
325 $toString = $fileName = $to;
326 }
327 $content = "To: " . $toString . "\n";
328 foreach ($headers as $key => $val) {
329 $content .= "$key: $val\n";
330 }
331 $content .= "\n" . $message . "\n";
332
333 if (is_numeric(CIVICRM_MAIL_LOG)) {
334 $config = CRM_Core_Config::singleton();
335 // create the directory if not there
336 $dirName = $config->configAndLogDir . 'mail' . DIRECTORY_SEPARATOR;
337 CRM_Utils_File::createDir($dirName);
338 $fileName = md5(uniqid(CRM_Utils_String::munge($fileName))) . '.txt';
339 file_put_contents($dirName . $fileName,
340 $content
341 );
342 }
343 else {
344 file_put_contents(CIVICRM_MAIL_LOG, $content, FILE_APPEND);
345 }
346 }
347
348 /**
349 * Get the email address itself from a formatted full name + address string
350 *
351 * Ugly but working.
352 *
353 * @param string $header
354 * The full name + email address string.
355 *
356 * @return string
357 * the plucked email address
358 */
359 public static function pluckEmailFromHeader($header) {
360 preg_match('/<([^<]*)>$/', $header, $matches);
361
362 if (isset($matches[1])) {
363 return $matches[1];
364 }
365 return NULL;
366 }
367
368 /**
369 * Get the Active outBound email.
370 *
371 * @return bool
372 * TRUE if valid outBound email configuration found, false otherwise.
373 */
374 public static function validOutBoundMail() {
375 $mailingInfo = Civi::settings()->get('mailing_backend');
376 if ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_MAIL) {
377 return TRUE;
378 }
379 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_SMTP) {
380 if (!isset($mailingInfo['smtpServer']) || $mailingInfo['smtpServer'] == '' ||
381 $mailingInfo['smtpServer'] == 'YOUR SMTP SERVER' ||
382 ($mailingInfo['smtpAuth'] && ($mailingInfo['smtpUsername'] == '' || $mailingInfo['smtpPassword'] == ''))
383 ) {
384 return FALSE;
385 }
386 return TRUE;
387 }
388 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_SENDMAIL) {
389 if (!$mailingInfo['sendmail_path'] || !$mailingInfo['sendmail_args']) {
390 return FALSE;
391 }
392 return TRUE;
393 }
394 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_REDIRECT_TO_DB) {
395 return TRUE;
396 }
397 return FALSE;
398 }
399
400 /**
401 * @param $message
402 * @param array $params
403 *
404 * @return mixed
405 */
406 public static function &setMimeParams(&$message, $params = NULL) {
407 static $mimeParams = NULL;
408 if (!$params) {
409 if (!$mimeParams) {
410 $mimeParams = array(
411 'text_encoding' => '8bit',
412 'html_encoding' => '8bit',
413 'head_charset' => 'utf-8',
414 'text_charset' => 'utf-8',
415 'html_charset' => 'utf-8',
416 );
417 }
418 $params = $mimeParams;
419 }
420 return $message->get($params);
421 }
422
423 /**
424 * @param string $name
425 * @param $email
426 * @param bool $useQuote
427 *
428 * @return null|string
429 */
430 public static function formatRFC822Email($name, $email, $useQuote = FALSE) {
431 $result = NULL;
432
433 $name = trim($name);
434
435 // strip out double quotes if present at the beginning AND end
436 if (substr($name, 0, 1) == '"' &&
437 substr($name, -1, 1) == '"'
438 ) {
439 $name = substr($name, 1, -1);
440 }
441
442 if (!empty($name)) {
443 // escape the special characters
444 $name = str_replace(array('<', '"', '>'),
445 array('\<', '\"', '\>'),
446 $name
447 );
448 if (strpos($name, ',') !== FALSE ||
449 $useQuote
450 ) {
451 // quote the string if it has a comma
452 $name = '"' . $name . '"';
453 }
454
455 $result = "$name ";
456 }
457
458 $result .= "<{$email}>";
459 return $result;
460 }
461
462 /**
463 * Takes a string and checks to see if it needs to be escaped / double quoted
464 * and if so does the needful and return the formatted name
465 *
466 * This code has been copied and adapted from ezc/Mail/src/tools.php
467 *
468 * @param string $name
469 *
470 * @return string
471 */
472 public static function formatRFC2822Name($name) {
473 $name = trim($name);
474 if (!empty($name)) {
475 // remove the quotes around the name part if they are already there
476 if (substr($name, 0, 1) == '"' && substr($name, -1) == '"') {
477 $name = substr($name, 1, -1);
478 }
479
480 // add slashes to " and \ and surround the name part with quotes
481 if (strpbrk($name, ",@<>:;'\"") !== FALSE) {
482 $name = '"' . addcslashes($name, '\\"') . '"';
483 }
484 }
485
486 return $name;
487 }
488
489 /**
490 * @param string $fileName
491 * @param string $html
492 * @param string $format
493 *
494 * @return array
495 */
496 public static function appendPDF($fileName, $html, $format = NULL) {
497 $pdf_filename = CRM_Core_Config::singleton()->templateCompileDir . CRM_Utils_File::makeFileName($fileName);
498
499 // FIXME : CRM-7894
500 // xmlns attribute is required in XHTML but it is invalid in HTML,
501 // Also the namespace "xmlns=http://www.w3.org/1999/xhtml" is default,
502 // and will be added to the <html> tag even if you do not include it.
503 $html = preg_replace('/(<html)(.+?xmlns=["\'].[^\s]+["\'])(.+)?(>)/', '\1\3\4', $html);
504
505 file_put_contents($pdf_filename, CRM_Utils_PDF_Utils::html2pdf($html,
506 $fileName,
507 TRUE,
508 $format)
509 );
510 return array(
511 'fullPath' => $pdf_filename,
512 'mime_type' => 'application/pdf',
513 'cleanName' => $fileName,
514 );
515 }
516
517 }