Merge pull request #17736 from civicrm/5.27
[civicrm-core.git] / ext / flexmailer / src / MailParams.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 namespace Civi\FlexMailer;
12
13 /**
14 * Class MailParams
15 *
16 * Within CiviMail, we have a few competing data-structures to chose from when
17 * representing a mail message:
18 *
19 * - ezcMail
20 * - Mail_mime
21 * - $mailParams (from Hook::alterMailParams)
22 *
23 * The $mailParams data-structure is probably the quirkiest, but it's also
24 * the one for which we have the strongest obligation (e.g. it's part of
25 * a published hook). This class includes helper functions for
26 * converting or validating the $mailParams format.
27 *
28 * @see \CRM_Utils_Hook::alterMailParams
29 */
30 class MailParams {
31
32 /**
33 * Convert from "mail params" to PEAR's Mail_mime.
34 *
35 * The data-structure which represents a message for purposes of
36 * hook_civicrm_alterMailParams does not match the data structure for
37 * Mail_mime.
38 *
39 * @param array $mailParams
40 * @return \Mail_mime
41 * @see \CRM_Utils_Hook::alterMailParams
42 */
43 public static function convertMailParamsToMime($mailParams) {
44 // The general assumption is that key-value pairs in $mailParams should
45 // pass through as email headers, but there are several special-cases
46 // (e.g. 'toName', 'toEmail', 'text', 'html', 'attachments', 'headers').
47
48 $message = new \Mail_mime("\n");
49
50 // 1. Consolidate: 'toName' and 'toEmail' should be 'To'.
51 $toName = trim($mailParams['toName']);
52 $toEmail = trim($mailParams['toEmail']);
53 if ($toName == $toEmail || strpos($toName, '@') !== FALSE) {
54 $toName = NULL;
55 }
56 else {
57 $toName = \CRM_Utils_Mail::formatRFC2822Name($toName);
58 }
59 unset($mailParams['toName']);
60 unset($mailParams['toEmail']);
61 $mailParams['To'] = "$toName <$toEmail>";
62
63 // 2. Apply the other fields.
64 foreach ($mailParams as $key => $value) {
65 if (empty($value)) {
66 continue;
67 }
68
69 switch ($key) {
70 case 'text':
71 $message->setTxtBody($mailParams['text']);
72 break;
73
74 case 'html':
75 $message->setHTMLBody($mailParams['html']);
76 break;
77
78 case 'attachments':
79 foreach ($mailParams['attachments'] as $fileID => $attach) {
80 $message->addAttachment($attach['fullPath'],
81 $attach['mime_type'],
82 $attach['cleanName']
83 );
84 }
85 break;
86
87 case 'headers':
88 $message->headers($value);
89 break;
90
91 default:
92 $message->headers(array($key => $value), TRUE);
93 }
94 }
95
96 \CRM_Utils_Mail::setMimeParams($message);
97
98 return $message;
99 }
100
101 }