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