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