Merge pull request #17981 from eileenmcnaughton/merge_form
[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
52f4ecb2
SL
155 * returnpath : email address for bounces to be sent to
156 * messageId : Message ID for this email mesage
6a488035
TO
157 * attachments: an associative array of
158 * fullPath : complete pathname to the file
159 * mime_type: mime type of the attachment
160 * cleanName: the user friendly name of the attachmment
161 *
77855840
TO
162 * @param array $params
163 * (by reference).
6a488035 164 *
ae5ffbb7
TO
165 * @return bool
166 * TRUE if a mail was sent, else FALSE.
6a488035 167 */
00be9182 168 public static function send(&$params) {
e633aba2 169 $defaultReturnPath = CRM_Core_BAO_MailSettings::defaultReturnPath();
6a488035 170 $includeMessageId = CRM_Core_BAO_MailSettings::includeMessageId();
353ffa53 171 $emailDomain = CRM_Core_BAO_MailSettings::defaultDomain();
9c1bc317 172 $from = $params['from'] ?? NULL;
e633aba2
OT
173 if (!$defaultReturnPath) {
174 $defaultReturnPath = self::pluckEmailFromHeader($from);
6a488035 175 }
6a488035
TO
176
177 // first call the mail alter hook
38108cce 178 CRM_Utils_Hook::alterMailParams($params, 'singleEmail');
6a488035
TO
179
180 // check if any module has aborted mail sending
8cc574cf 181 if (!empty($params['abortMailSend']) || empty($params['toEmail'])) {
6a488035
TO
182 return FALSE;
183 }
184
9c1bc317
CW
185 $textMessage = $params['text'] ?? NULL;
186 $htmlMessage = $params['html'] ?? NULL;
187 $attachments = $params['attachments'] ?? NULL;
6a488035
TO
188
189 // CRM-6224
190 if (trim(CRM_Utils_String::htmlToText($htmlMessage)) == '') {
191 $htmlMessage = FALSE;
192 }
193
be2fb01f 194 $headers = [];
6a488035 195 // CRM-10699 support custom email headers
a7488080 196 if (!empty($params['headers'])) {
6a488035
TO
197 $headers = array_merge($headers, $params['headers']);
198 }
199 $headers['From'] = $params['from'];
ae5ffbb7
TO
200 $headers['To'] = self::formatRFC822Email(
201 CRM_Utils_Array::value('toName', $params),
202 CRM_Utils_Array::value('toEmail', $params),
203 FALSE
204 );
c69abeee
MW
205
206 // On some servers mail() fails when 'Cc' or 'Bcc' headers are defined but empty.
207 foreach (['Cc', 'Bcc'] as $optionalHeader) {
9c1bc317 208 $headers[$optionalHeader] = $params[strtolower($optionalHeader)] ?? NULL;
c69abeee
MW
209 if (empty($headers[$optionalHeader])) {
210 unset($headers[$optionalHeader]);
211 }
212 }
213
9c1bc317 214 $headers['Subject'] = $params['subject'] ?? NULL;
6a488035
TO
215 $headers['Content-Type'] = $htmlMessage ? 'multipart/mixed; charset=utf-8' : 'text/plain; charset=utf-8';
216 $headers['Content-Disposition'] = 'inline';
217 $headers['Content-Transfer-Encoding'] = '8bit';
e633aba2 218 $headers['Return-Path'] = CRM_Utils_Array::value('returnPath', $params, $defaultReturnPath);
361fb6c0 219
6a488035 220 // CRM-11295: Omit reply-to headers if empty; this avoids issues with overzealous mailservers
2e35712a 221 $replyTo = CRM_Utils_Array::value('replyTo', $params, CRM_Utils_Array::value('from', $params));
361fb6c0 222
6a488035
TO
223 if (!empty($replyTo)) {
224 $headers['Reply-To'] = $replyTo;
225 }
226 $headers['Date'] = date('r');
227 if ($includeMessageId) {
52f4ecb2 228 $headers['Message-ID'] = $params['messageId'] ?? '<' . uniqid('civicrm_', TRUE) . "@$emailDomain>";
6a488035 229 }
a7488080 230 if (!empty($params['autoSubmitted'])) {
6a488035
TO
231 $headers['Auto-Submitted'] = "Auto-Generated";
232 }
233
50bfb460 234 // make sure we has to have space, CRM-6977
be2fb01f 235 foreach (['From', 'To', 'Cc', 'Bcc', 'Reply-To', 'Return-Path'] as $fld) {
6a488035
TO
236 if (isset($headers[$fld])) {
237 $headers[$fld] = str_replace('"<', '" <', $headers[$fld]);
238 }
239 }
240
241 // quote FROM, if comma is detected AND is not already quoted. CRM-7053
242 if (strpos($headers['From'], ',') !== FALSE) {
243 $from = explode(' <', $headers['From']);
244 $headers['From'] = self::formatRFC822Email(
245 $from[0],
246 substr(trim($from[1]), 0, -1),
247 TRUE
248 );
249 }
250
251 require_once 'Mail/mime.php';
252 $msg = new Mail_mime("\n");
253 if ($textMessage) {
254 $msg->setTxtBody($textMessage);
255 }
256
257 if ($htmlMessage) {
258 $msg->setHTMLBody($htmlMessage);
259 }
260
261 if (!empty($attachments)) {
262 foreach ($attachments as $fileID => $attach) {
263 $msg->addAttachment(
264 $attach['fullPath'],
265 $attach['mime_type'],
d0d1c38b 266 $attach['cleanName'],
267 TRUE,
268 'base64',
269 'attachment',
270 (isset($attach['charset']) ? $attach['charset'] : '')
6a488035
TO
271 );
272 }
273 }
274
275 $message = self::setMimeParams($msg);
b2c0dbe4 276 $headers = $msg->headers($headers);
6a488035 277
be2fb01f 278 $to = [$params['toEmail']];
e7292422 279 $result = NULL;
048222df 280 $mailer = \Civi::service('pear_mail');
cbcec379 281
8125eb18
NG
282 // CRM-3795, CRM-7355, CRM-7557, CRM-9058, CRM-9887, CRM-12883, CRM-19173 and others ...
283 // The PEAR library requires different parameters based on the mailer used:
284 // * Mail_mail requires the Cc/Bcc recipients listed ONLY in the $headers variable
285 // * All other mailers require that all be recipients be listed in the $to array AND that
286 // the Bcc must not be present in $header as otherwise it will be shown to all recipients
287 // ref: https://pear.php.net/bugs/bug.php?id=8047, full thread and answer [2011-04-19 20:48 UTC]
e4c75084
TO
288 // TODO: Refactor this quirk-handler as another filter in FilteredPearMailer. But that would merit review of impact on universe.
289 $driver = ($mailer instanceof CRM_Utils_Mail_FilteredPearMailer) ? $mailer->getDriver() : NULL;
290 $isPhpMail = (get_class($mailer) === "Mail_mail" || $driver === 'mail');
291 if (!$isPhpMail) {
ea2eebc3
NG
292 // get emails from headers, since these are
293 // combination of name and email addresses.
e7292422 294 if (!empty($headers['Cc'])) {
9c1bc317 295 $to[] = $headers['Cc'] ?? NULL;
e7292422
TO
296 }
297 if (!empty($headers['Bcc'])) {
9c1bc317 298 $to[] = $headers['Bcc'] ?? NULL;
d39f2583 299 unset($headers['Bcc']);
e7292422 300 }
6a488035 301 }
8125eb18 302
ea2eebc3 303 if (is_object($mailer)) {
6a4257d4 304 $errorScope = CRM_Core_TemporaryErrorScope::ignoreException();
6a488035 305 $result = $mailer->send($to, $headers, $message);
6a488035
TO
306 if (is_a($result, 'PEAR_Error')) {
307 $message = self::errorMessage($mailer, $result);
308 // append error message in case multiple calls are being made to
309 // this method in the course of sending a batch of messages.
361fb6c0 310 CRM_Core_Session::setStatus($message, ts('Mailing Error'), 'error');
6a488035
TO
311 return FALSE;
312 }
313 // CRM-10699
314 CRM_Utils_Hook::postEmailSend($params);
315 return TRUE;
316 }
317 return FALSE;
318 }
319
5bc392e6
EM
320 /**
321 * @param $mailer
322 * @param $result
323 *
324 * @return string
325 */
00be9182 326 public static function errorMessage($mailer, $result) {
be2fb01f 327 $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
328 1 => 'SMTP',
329 ]) . '</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
330
331 if (is_a($mailer, 'Mail_smtp')) {
332 $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>';
333 }
334 else {
335 $message .= '<ul>' . '<li>' . ts('Your Sendmail path is incorrect.') . '</li>' . '<li>' . ts('Your Sendmail argument is incorrect.') . '</li>';
336 }
337
be2fb01f 338 $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
339 1 => CRM_Utils_System::docURL2('user/advanced-configuration/email-system-configuration', TRUE),
340 ]) . '</p>';
6a488035
TO
341
342 return $message;
343 }
344
5bc392e6
EM
345 /**
346 * @param $to
347 * @param $headers
348 * @param $message
dee6e582 349 * @deprecated
5bc392e6 350 */
00be9182 351 public static function logger(&$to, &$headers, &$message) {
dee6e582 352 CRM_Utils_Mail_Logger::log($to, $headers, $message);
6a488035
TO
353 }
354
355 /**
356 * Get the email address itself from a formatted full name + address string
357 *
358 * Ugly but working.
359 *
77855840
TO
360 * @param string $header
361 * The full name + email address string.
6a488035 362 *
a6c01b45
CW
363 * @return string
364 * the plucked email address
6a488035 365 */
00be9182 366 public static function pluckEmailFromHeader($header) {
6a488035
TO
367 preg_match('/<([^<]*)>$/', $header, $matches);
368
369 if (isset($matches[1])) {
370 return $matches[1];
371 }
372 return NULL;
373 }
374
375 /**
fe482240 376 * Get the Active outBound email.
6a488035 377 *
ae5ffbb7
TO
378 * @return bool
379 * TRUE if valid outBound email configuration found, false otherwise.
6a488035 380 */
00be9182 381 public static function validOutBoundMail() {
aaffa79f 382 $mailingInfo = Civi::settings()->get('mailing_backend');
6a488035
TO
383 if ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_MAIL) {
384 return TRUE;
385 }
386 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_SMTP) {
387 if (!isset($mailingInfo['smtpServer']) || $mailingInfo['smtpServer'] == '' ||
388 $mailingInfo['smtpServer'] == 'YOUR SMTP SERVER' ||
389 ($mailingInfo['smtpAuth'] && ($mailingInfo['smtpUsername'] == '' || $mailingInfo['smtpPassword'] == ''))
390 ) {
391 return FALSE;
392 }
393 return TRUE;
394 }
395 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_SENDMAIL) {
396 if (!$mailingInfo['sendmail_path'] || !$mailingInfo['sendmail_args']) {
397 return FALSE;
398 }
399 return TRUE;
400 }
401 elseif ($mailingInfo['outBound_option'] == CRM_Mailing_Config::OUTBOUND_OPTION_REDIRECT_TO_DB) {
402 return TRUE;
403 }
404 return FALSE;
405 }
406
5bc392e6
EM
407 /**
408 * @param $message
100fef9d 409 * @param array $params
5bc392e6
EM
410 *
411 * @return mixed
412 */
ca807bbe 413 public static function setMimeParams($message, $params = NULL) {
6a488035
TO
414 static $mimeParams = NULL;
415 if (!$params) {
416 if (!$mimeParams) {
be2fb01f 417 $mimeParams = [
6a488035
TO
418 'text_encoding' => '8bit',
419 'html_encoding' => '8bit',
420 'head_charset' => 'utf-8',
421 'text_charset' => 'utf-8',
422 'html_charset' => 'utf-8',
be2fb01f 423 ];
6a488035
TO
424 }
425 $params = $mimeParams;
426 }
427 return $message->get($params);
428 }
429
5bc392e6 430 /**
100fef9d 431 * @param string $name
5bc392e6
EM
432 * @param $email
433 * @param bool $useQuote
434 *
435 * @return null|string
436 */
00be9182 437 public static function formatRFC822Email($name, $email, $useQuote = FALSE) {
6a488035
TO
438 $result = NULL;
439
440 $name = trim($name);
441
442 // strip out double quotes if present at the beginning AND end
443 if (substr($name, 0, 1) == '"' &&
444 substr($name, -1, 1) == '"'
445 ) {
446 $name = substr($name, 1, -1);
447 }
448
449 if (!empty($name)) {
450 // escape the special characters
be2fb01f
CW
451 $name = str_replace(['<', '"', '>'],
452 ['\<', '\"', '\>'],
6a488035
TO
453 $name
454 );
455 if (strpos($name, ',') !== FALSE ||
456 $useQuote
457 ) {
458 // quote the string if it has a comma
459 $name = '"' . $name . '"';
460 }
461
462 $result = "$name ";
463 }
464
465 $result .= "<{$email}>";
466 return $result;
467 }
468
469 /**
470 * Takes a string and checks to see if it needs to be escaped / double quoted
471 * and if so does the needful and return the formatted name
472 *
473 * This code has been copied and adapted from ezc/Mail/src/tools.php
50bfb460
SB
474 *
475 * @param string $name
476 *
477 * @return string
6a488035 478 */
00be9182 479 public static function formatRFC2822Name($name) {
6a488035
TO
480 $name = trim($name);
481 if (!empty($name)) {
482 // remove the quotes around the name part if they are already there
483 if (substr($name, 0, 1) == '"' && substr($name, -1) == '"') {
484 $name = substr($name, 1, -1);
485 }
486
487 // add slashes to " and \ and surround the name part with quotes
488 if (strpbrk($name, ",@<>:;'\"") !== FALSE) {
489 $name = '"' . addcslashes($name, '\\"') . '"';
490 }
491 }
492
493 return $name;
494 }
383c047b
DG
495
496 /**
383c047b
DG
497 * @param string $fileName
498 * @param string $html
499 * @param string $format
500 *
a6c01b45 501 * @return array
383c047b 502 */
00be9182 503 public static function appendPDF($fileName, $html, $format = NULL) {
383c047b
DG
504 $pdf_filename = CRM_Core_Config::singleton()->templateCompileDir . CRM_Utils_File::makeFileName($fileName);
505
50bfb460
SB
506 // FIXME : CRM-7894
507 // xmlns attribute is required in XHTML but it is invalid in HTML,
508 // Also the namespace "xmlns=http://www.w3.org/1999/xhtml" is default,
509 // and will be added to the <html> tag even if you do not include it.
383c047b
DG
510 $html = preg_replace('/(<html)(.+?xmlns=["\'].[^\s]+["\'])(.+)?(>)/', '\1\3\4', $html);
511
512 file_put_contents($pdf_filename, CRM_Utils_PDF_Utils::html2pdf($html,
353ffa53
TO
513 $fileName,
514 TRUE,
515 $format)
383c047b 516 );
be2fb01f 517 return [
383c047b
DG
518 'fullPath' => $pdf_filename,
519 'mime_type' => 'application/pdf',
520 'cleanName' => $fileName,
be2fb01f 521 ];
383c047b 522 }
96025800 523
2a7e1ddc
TS
524 /**
525 * Format an email string from email fields.
526 *
527 * @param array $fields
528 * The email fields.
529 * @return string
530 * The formatted email string.
531 */
532 public static function format($fields) {
533 $formattedEmail = '';
534 if (!empty($fields['email'])) {
535 $formattedEmail = $fields['email'];
536 }
537
be2fb01f 538 $formattedSuffix = [];
2a7e1ddc
TS
539 if (!empty($fields['is_bulkmail'])) {
540 $formattedSuffix[] = '(' . ts('Bulk') . ')';
541 }
542 if (!empty($fields['on_hold'])) {
543 if ($fields['on_hold'] == 2) {
544 $formattedSuffix[] = '(' . ts('On Hold - Opt Out') . ')';
545 }
546 else {
547 $formattedSuffix[] = '(' . ts('On Hold') . ')';
548 }
549 }
550 if (!empty($fields['signature_html']) || !empty($fields['signature_text'])) {
551 $formattedSuffix[] = '(' . ts('Signature') . ')';
552 }
553
554 // Add suffixes on a new line, if there is any.
555 if (!empty($formattedSuffix)) {
556 $formattedEmail .= "\n" . implode(' ', $formattedSuffix);
557 }
558
559 return $formattedEmail;
560 }
561
a7180974
JG
562 /**
563 * When passed a value, returns the value if it's non-numeric.
564 * If it's numeric, look up the display name and email of the corresponding
565 * contact ID in RFC822 format.
566 *
4335f229
JG
567 * @param string $from
568 * contact ID or formatted "From address", eg. 12 or "Fred Bloggs" <fred@example.org>
a7180974
JG
569 * @return string
570 * The RFC822-formatted email header (display name + address)
571 */
4335f229
JG
572 public static function formatFromAddress($from) {
573 if (is_numeric($from)) {
a7180974 574 $result = civicrm_api3('Email', 'get', [
4335f229 575 'id' => $from,
a7180974
JG
576 'return' => ['contact_id.display_name', 'email'],
577 'sequential' => 1,
578 ])['values'][0];
4335f229 579 $from = '"' . $result['contact_id.display_name'] . '" <' . $result['email'] . '>';
a7180974 580 }
4335f229 581 return $from;
a7180974
JG
582 }
583
6a488035 584}