update doc block, work on `PDFLetterCommonTest` unit test compatibility with `contact...
[civicrm-core.git] / CRM / Utils / Mail.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17 class CRM_Utils_Mail {
18
19 /**
20 * Create a new mailer to send any mail from the application.
21 *
22 * Note: The mailer is opened in persistent mode.
23 *
24 * Note: You probably don't want to call this directly. Get a reference
25 * to the mailer through the container.
26 *
27 * @return Mail
28 *
29 * @throws CRM_Core_Exception
30 */
31 public static function createMailer() {
32 $mailingInfo = Civi::settings()->get('mailing_backend');
33
34 /*@var Mail $mailer*/
35 if ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_REDIRECT_TO_DB ||
36 (defined('CIVICRM_MAILER_SPOOL') && CIVICRM_MAILER_SPOOL)
37 ) {
38 $mailer = self::_createMailer('CRM_Mailing_BAO_Spool', []);
39 }
40 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_SMTP) {
41 if ($mailingInfo['smtpServer'] == '' || !$mailingInfo['smtpServer']) {
42 Civi::log()->error(ts('There is no valid smtp server setting. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the SMTP Server.', [1 => CRM_Utils_System::url('civicrm/admin/setting/smtp', 'reset=1')]));
43 throw new CRM_Core_Exception(ts('There is no valid smtp server setting. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the SMTP Server.', [1 => CRM_Utils_System::url('civicrm/admin/setting/smtp', 'reset=1')]));
44 }
45
46 $params['host'] = $mailingInfo['smtpServer'] ? $mailingInfo['smtpServer'] : 'localhost';
47 $params['port'] = $mailingInfo['smtpPort'] ? $mailingInfo['smtpPort'] : 25;
48
49 if ($mailingInfo['smtpAuth']) {
50 $params['username'] = $mailingInfo['smtpUsername'];
51 $params['password'] = \Civi::service('crypto.token')->decrypt($mailingInfo['smtpPassword']);
52 $params['auth'] = TRUE;
53 }
54 else {
55 $params['auth'] = FALSE;
56 }
57
58 /*
59 * Set the localhost value, CRM-3153
60 * Use the host name of the web server, falling back to the base URL
61 * (eg when using the PHP CLI), and then falling back to localhost.
62 */
63 $params['localhost'] = CRM_Utils_Array::value(
64 'SERVER_NAME',
65 $_SERVER,
66 CRM_Utils_Array::value(
67 'host',
68 parse_url(CIVICRM_UF_BASEURL),
69 'localhost'
70 )
71 );
72
73 // also set the timeout value, lets set it to 30 seconds
74 // CRM-7510
75 $params['timeout'] = 30;
76
77 // CRM-9349
78 $params['persist'] = TRUE;
79
80 $mailer = self::_createMailer('smtp', $params);
81 }
82 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_SENDMAIL) {
83 if ($mailingInfo['sendmail_path'] == '' ||
84 !$mailingInfo['sendmail_path']
85 ) {
86 Civi::log()->error(ts('There is no valid sendmail path setting. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the sendmail server.', [1 => CRM_Utils_System::url('civicrm/admin/setting/smtp', 'reset=1')]));
87 throw new CRM_Core_Exception(ts('There is no valid sendmail path setting. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the sendmail server.', [1 => CRM_Utils_System::url('civicrm/admin/setting/smtp', 'reset=1')]));
88 }
89 $params['sendmail_path'] = $mailingInfo['sendmail_path'];
90 $params['sendmail_args'] = $mailingInfo['sendmail_args'];
91
92 $mailer = self::_createMailer('sendmail', $params);
93 }
94 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_MAIL) {
95 $mailer = self::_createMailer('mail', []);
96 }
97 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_MOCK) {
98 $mailer = self::_createMailer('mock', $mailingInfo);
99 }
100 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_DISABLED) {
101 Civi::log()->info(ts('Outbound mail has been disabled. Click <a href=\'%1\'>Administer >> System Setting >> Outbound Email</a> to set the OutBound Email.', [1 => CRM_Utils_System::url('civicrm/admin/setting/smtp', 'reset=1')]));
102 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.', [1 => CRM_Utils_System::url('civicrm/admin/setting/smtp', 'reset=1')]));
103 }
104 else {
105 Civi::log()->error(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.', [1 => CRM_Utils_System::url('civicrm/admin/setting/smtp', 'reset=1')]));
106 CRM_Core_Error::debug_var('mailing_info', $mailingInfo);
107 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.', [1 => CRM_Utils_System::url('civicrm/admin/setting/smtp', 'reset=1')]));
108 }
109 return $mailer;
110 }
111
112 /**
113 * Create a new instance of a PEAR Mail driver.
114 *
115 * @param string $driver
116 * 'CRM_Mailing_BAO_Spool' or a name suitable for Mail::factory().
117 * @param array $params
118 * @return object
119 * More specifically, a class which implements the "send()" function
120 */
121 public static function _createMailer($driver, $params) {
122 if ($driver == 'CRM_Mailing_BAO_Spool') {
123 $mailer = new CRM_Mailing_BAO_Spool($params);
124 }
125 else {
126 $mailer = Mail::factory($driver, $params);
127 }
128
129 // Previously, CiviCRM bundled patches to change the behavior of 3 specific drivers. Use wrapper/filters to avoid patching.
130 $mailer = new CRM_Utils_Mail_FilteredPearMailer($driver, $params, $mailer);
131 if (in_array($driver, ['smtp', 'mail', 'sendmail'])) {
132 $mailer->addFilter('2000_log', ['CRM_Utils_Mail_Logger', 'filter']);
133 $mailer->addFilter('2100_validate', function ($mailer, &$recipients, &$headers, &$body) {
134 if (!is_array($headers)) {
135 return PEAR::raiseError('$headers must be an array');
136 }
137 });
138 }
139 CRM_Utils_Hook::alterMailer($mailer, $driver, $params);
140 return $mailer;
141 }
142
143 /**
144 * Wrapper function to send mail in CiviCRM. Hooks are called from this function. The input parameter
145 * is an associateive array which holds the values of field needed to send an email. These are:
146 *
147 * from : complete from envelope
148 * toName : name of person to send email
149 * toEmail : email address to send to
150 * cc : email addresses to cc
151 * bcc : email addresses to bcc
152 * subject : subject of the email
153 * text : text of the message
154 * html : html version of the message
155 * replyTo : reply-to header in the email
156 * returnpath : email address for bounces to be sent to
157 * messageId : Message ID for this email mesage
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 * contactId : contact id to send the email to (optional)
163 *
164 * @param array $params
165 * (by reference).
166 *
167 * @return bool
168 * TRUE if a mail was sent, else FALSE.
169 */
170 public static function send(array &$params): bool {
171 $defaultReturnPath = CRM_Core_BAO_MailSettings::defaultReturnPath();
172 $includeMessageId = CRM_Core_BAO_MailSettings::includeMessageId();
173 $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
174 $from = $params['from'] ?? NULL;
175 if (!$defaultReturnPath) {
176 $defaultReturnPath = self::pluckEmailFromHeader($from);
177 }
178
179 // first call the mail alter hook
180 CRM_Utils_Hook::alterMailParams($params, 'singleEmail');
181
182 // check if any module has aborted mail sending
183 if (!empty($params['abortMailSend']) || empty($params['toEmail'])) {
184 return FALSE;
185 }
186
187 $textMessage = $params['text'] ?? NULL;
188 $htmlMessage = $params['html'] ?? NULL;
189 $attachments = $params['attachments'] ?? NULL;
190
191 // CRM-6224
192 if (trim(CRM_Utils_String::htmlToText($htmlMessage)) == '') {
193 $htmlMessage = FALSE;
194 }
195
196 $headers = [];
197 // CRM-10699 support custom email headers
198 if (!empty($params['headers'])) {
199 $headers = array_merge($headers, $params['headers']);
200 }
201 $headers['From'] = $params['from'];
202 $headers['To'] = self::formatRFC822Email(
203 CRM_Utils_Array::value('toName', $params),
204 CRM_Utils_Array::value('toEmail', $params),
205 FALSE
206 );
207
208 // On some servers mail() fails when 'Cc' or 'Bcc' headers are defined but empty.
209 foreach (['Cc', 'Bcc'] as $optionalHeader) {
210 $headers[$optionalHeader] = $params[strtolower($optionalHeader)] ?? NULL;
211 if (empty($headers[$optionalHeader])) {
212 unset($headers[$optionalHeader]);
213 }
214 }
215
216 $headers['Subject'] = $params['subject'] ?? NULL;
217 $headers['Content-Type'] = $htmlMessage ? 'multipart/mixed; charset=utf-8' : 'text/plain; charset=utf-8';
218 $headers['Content-Disposition'] = 'inline';
219 $headers['Content-Transfer-Encoding'] = '8bit';
220 $headers['Return-Path'] = CRM_Utils_Array::value('returnPath', $params, $defaultReturnPath);
221
222 // CRM-11295: Omit reply-to headers if empty; this avoids issues with overzealous mailservers
223 $replyTo = CRM_Utils_Array::value('replyTo', $params, CRM_Utils_Array::value('from', $params));
224
225 if (!empty($replyTo)) {
226 $headers['Reply-To'] = $replyTo;
227 }
228 $headers['Date'] = date('r');
229 if ($includeMessageId) {
230 $headers['Message-ID'] = $params['messageId'] ?? '<' . uniqid('civicrm_', TRUE) . "@$emailDomain>";
231 }
232 if (!empty($params['autoSubmitted'])) {
233 $headers['Auto-Submitted'] = "Auto-Generated";
234 }
235
236 // make sure we has to have space, CRM-6977
237 foreach (['From', 'To', 'Cc', 'Bcc', 'Reply-To', 'Return-Path'] as $fld) {
238 if (isset($headers[$fld])) {
239 $headers[$fld] = str_replace('"<', '" <', $headers[$fld]);
240 }
241 }
242
243 // quote FROM, if comma is detected AND is not already quoted. CRM-7053
244 if (strpos($headers['From'], ',') !== FALSE) {
245 $from = explode(' <', $headers['From']);
246 $headers['From'] = self::formatRFC822Email(
247 $from[0],
248 substr(trim($from[1]), 0, -1),
249 TRUE
250 );
251 }
252
253 require_once 'Mail/mime.php';
254 $msg = new Mail_mime("\n");
255 if ($textMessage) {
256 $msg->setTxtBody($textMessage);
257 }
258
259 if ($htmlMessage) {
260 $msg->setHTMLBody($htmlMessage);
261 }
262
263 if (!empty($attachments)) {
264 foreach ($attachments as $attach) {
265 $msg->addAttachment(
266 $attach['fullPath'],
267 $attach['mime_type'],
268 $attach['cleanName'],
269 TRUE,
270 'base64',
271 'attachment',
272 (isset($attach['charset']) ? $attach['charset'] : '')
273 );
274 }
275 }
276
277 $message = self::setMimeParams($msg);
278 $headers = $msg->headers($headers);
279
280 $to = [$params['toEmail']];
281 $mailer = \Civi::service('pear_mail');
282
283 // CRM-3795, CRM-7355, CRM-7557, CRM-9058, CRM-9887, CRM-12883, CRM-19173 and others ...
284 // The PEAR library requires different parameters based on the mailer used:
285 // * Mail_mail requires the Cc/Bcc recipients listed ONLY in the $headers variable
286 // * All other mailers require that all be recipients be listed in the $to array AND that
287 // the Bcc must not be present in $header as otherwise it will be shown to all recipients
288 // ref: https://pear.php.net/bugs/bug.php?id=8047, full thread and answer [2011-04-19 20:48 UTC]
289 // TODO: Refactor this quirk-handler as another filter in FilteredPearMailer. But that would merit review of impact on universe.
290 $driver = ($mailer instanceof CRM_Utils_Mail_FilteredPearMailer) ? $mailer->getDriver() : NULL;
291 $isPhpMail = (get_class($mailer) === "Mail_mail" || $driver === 'mail');
292 if (!$isPhpMail) {
293 // get emails from headers, since these are
294 // combination of name and email addresses.
295 if (!empty($headers['Cc'])) {
296 $to[] = $headers['Cc'] ?? NULL;
297 }
298 if (!empty($headers['Bcc'])) {
299 $to[] = $headers['Bcc'] ?? NULL;
300 unset($headers['Bcc']);
301 }
302 }
303
304 if (is_object($mailer)) {
305 try {
306 $result = $mailer->send($to, $headers, $message);
307 }
308 catch (Exception $e) {
309 \Civi::log()->error('Mailing error: ' . $e->getMessage());
310 CRM_Core_Session::setStatus(ts('Unable to send email. Please report this message to the site administrator'), ts('Mailing Error'), 'error');
311 return FALSE;
312 }
313 if (is_a($result, 'PEAR_Error')) {
314 $message = self::errorMessage($mailer, $result);
315 // append error message in case multiple calls are being made to
316 // this method in the course of sending a batch of messages.
317 \Civi::log()->error('Mailing error: ' . $message);
318 CRM_Core_Session::setStatus(ts('Unable to send email. Please report this message to the site administrator'), ts('Mailing Error'), 'error');
319 return FALSE;
320 }
321 // CRM-10699
322 CRM_Utils_Hook::postEmailSend($params);
323 return TRUE;
324 }
325 return FALSE;
326 }
327
328 /**
329 * @param $mailer
330 * @param $result
331 *
332 * @return string
333 */
334 public static function errorMessage($mailer, $result) {
335 $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.', [
336 1 => 'SMTP',
337 ]) . '</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>';
338
339 if (is_a($mailer, 'Mail_smtp')) {
340 $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>';
341 }
342 else {
343 $message .= '<ul>' . '<li>' . ts('Your Sendmail path is incorrect.') . '</li>' . '<li>' . ts('Your Sendmail argument is incorrect.') . '</li>';
344 }
345
346 $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.', [
347 1 => CRM_Utils_System::docURL2('user/advanced-configuration/email-system-configuration', TRUE),
348 ]) . '</p>';
349
350 return $message;
351 }
352
353 /**
354 * @param $to
355 * @param $headers
356 * @param $message
357 * @deprecated
358 */
359 public static function logger(&$to, &$headers, &$message) {
360 CRM_Utils_Mail_Logger::log($to, $headers, $message);
361 }
362
363 /**
364 * Get the email address itself from a formatted full name + address string
365 *
366 * Ugly but working.
367 *
368 * @param string $header
369 * The full name + email address string.
370 *
371 * @return string
372 * the plucked email address
373 */
374 public static function pluckEmailFromHeader($header) {
375 preg_match('/<([^<]*)>$/', $header, $matches);
376
377 if (isset($matches[1])) {
378 return $matches[1];
379 }
380 return NULL;
381 }
382
383 /**
384 * Get the Active outBound email.
385 *
386 * @return bool
387 * TRUE if valid outBound email configuration found, false otherwise.
388 */
389 public static function validOutBoundMail() {
390 $mailingInfo = Civi::settings()->get('mailing_backend');
391 if ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_MAIL) {
392 return TRUE;
393 }
394 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_SMTP) {
395 if (!isset($mailingInfo['smtpServer']) || $mailingInfo['smtpServer'] == '' ||
396 $mailingInfo['smtpServer'] == 'YOUR SMTP SERVER' ||
397 ($mailingInfo['smtpAuth'] && ($mailingInfo['smtpUsername'] == '' || $mailingInfo['smtpPassword'] == ''))
398 ) {
399 return FALSE;
400 }
401 return TRUE;
402 }
403 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_SENDMAIL) {
404 if (!$mailingInfo['sendmail_path'] || !$mailingInfo['sendmail_args']) {
405 return FALSE;
406 }
407 return TRUE;
408 }
409 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_REDIRECT_TO_DB) {
410 return TRUE;
411 }
412 return FALSE;
413 }
414
415 /**
416 * @param $message
417 * @param array $params
418 *
419 * @return mixed
420 */
421 public static function setMimeParams($message, $params = NULL) {
422 static $mimeParams = NULL;
423 if (!$params) {
424 if (!$mimeParams) {
425 $mimeParams = [
426 'text_encoding' => '8bit',
427 'html_encoding' => '8bit',
428 'head_charset' => 'utf-8',
429 'text_charset' => 'utf-8',
430 'html_charset' => 'utf-8',
431 ];
432 }
433 $params = $mimeParams;
434 }
435 return $message->get($params);
436 }
437
438 /**
439 * @param string $name
440 * @param $email
441 * @param bool $useQuote
442 *
443 * @return null|string
444 */
445 public static function formatRFC822Email($name, $email, $useQuote = FALSE) {
446 $result = NULL;
447
448 $name = trim($name);
449
450 // strip out double quotes if present at the beginning AND end
451 if (substr($name, 0, 1) == '"' &&
452 substr($name, -1, 1) == '"'
453 ) {
454 $name = substr($name, 1, -1);
455 }
456
457 if (!empty($name)) {
458 // escape the special characters
459 $name = str_replace(['<', '"', '>'],
460 ['\<', '\"', '\>'],
461 $name
462 );
463 if (strpos($name, ',') !== FALSE ||
464 $useQuote
465 ) {
466 // quote the string if it has a comma
467 $name = '"' . $name . '"';
468 }
469
470 $result = "$name ";
471 }
472
473 $result .= "<{$email}>";
474 return $result;
475 }
476
477 /**
478 * Takes a string and checks to see if it needs to be escaped / double quoted
479 * and if so does the needful and return the formatted name
480 *
481 * This code has been copied and adapted from ezc/Mail/src/tools.php
482 *
483 * @param string $name
484 *
485 * @return string
486 */
487 public static function formatRFC2822Name($name) {
488 $name = trim($name);
489 if (!empty($name)) {
490 // remove the quotes around the name part if they are already there
491 if (substr($name, 0, 1) == '"' && substr($name, -1) == '"') {
492 $name = substr($name, 1, -1);
493 }
494
495 // add slashes to " and \ and surround the name part with quotes
496 if (strpbrk($name, ",@<>:;'\"") !== FALSE) {
497 $name = '"' . addcslashes($name, '\\"') . '"';
498 }
499 }
500
501 return $name;
502 }
503
504 /**
505 * @param string $fileName
506 * @param string $html
507 * @param string $format
508 *
509 * @return array
510 */
511 public static function appendPDF($fileName, $html, $format = NULL) {
512 $pdf_filename = CRM_Core_Config::singleton()->templateCompileDir . CRM_Utils_File::makeFileName($fileName);
513
514 // FIXME : CRM-7894
515 // xmlns attribute is required in XHTML but it is invalid in HTML,
516 // Also the namespace "xmlns=http://www.w3.org/1999/xhtml" is default,
517 // and will be added to the <html> tag even if you do not include it.
518 $html = preg_replace('/(<html)(.+?xmlns=["\'].[^\s]+["\'])(.+)?(>)/', '\1\3\4', $html);
519
520 file_put_contents($pdf_filename, CRM_Utils_PDF_Utils::html2pdf($html,
521 $fileName,
522 TRUE,
523 $format)
524 );
525 return [
526 'fullPath' => $pdf_filename,
527 'mime_type' => 'application/pdf',
528 'cleanName' => $fileName,
529 ];
530 }
531
532 /**
533 * Format an email string from email fields.
534 *
535 * @param array $fields
536 * The email fields.
537 * @return string
538 * The formatted email string.
539 */
540 public static function format($fields) {
541 $formattedEmail = '';
542 if (!empty($fields['email'])) {
543 $formattedEmail = $fields['email'];
544 }
545
546 $formattedSuffix = [];
547 if (!empty($fields['is_bulkmail'])) {
548 $formattedSuffix[] = '(' . ts('Bulk') . ')';
549 }
550 if (!empty($fields['on_hold'])) {
551 if ($fields['on_hold'] == 2) {
552 $formattedSuffix[] = '(' . ts('On Hold - Opt Out') . ')';
553 }
554 else {
555 $formattedSuffix[] = '(' . ts('On Hold') . ')';
556 }
557 }
558 if (!empty($fields['signature_html']) || !empty($fields['signature_text'])) {
559 $formattedSuffix[] = '(' . ts('Signature') . ')';
560 }
561
562 // Add suffixes on a new line, if there is any.
563 if (!empty($formattedSuffix)) {
564 $formattedEmail .= "\n" . implode(' ', $formattedSuffix);
565 }
566
567 return $formattedEmail;
568 }
569
570 /**
571 * When passed a value, returns the value if it's non-numeric.
572 * If it's numeric, look up the display name and email of the corresponding
573 * contact ID in RFC822 format.
574 *
575 * @param string $from
576 * civicrm_email.id or formatted "From address", eg. 12 or "Fred Bloggs" <fred@example.org>
577 * @return string
578 * The RFC822-formatted email header (display name + address)
579 */
580 public static function formatFromAddress($from) {
581 if (is_numeric($from)) {
582 $result = civicrm_api3('Email', 'get', [
583 'id' => $from,
584 'return' => ['contact_id.display_name', 'email'],
585 'sequential' => 1,
586 ])['values'][0];
587 $from = '"' . $result['contact_id.display_name'] . '" <' . $result['email'] . '>';
588 }
589 return $from;
590 }
591
592 }