[TASK] Remove unused use statements
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Utility / MailUtility.php
1 <?php
2 namespace TYPO3\CMS\Core\Utility;
3
4 /**
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 /**
18 * Class to handle mail specific functionality
19 *
20 * @author Tolleiv Nietsch <nietsch@aoemedia.de>
21 */
22 class MailUtility {
23
24 /**
25 * Proxy for the PHP mail() function. Adds possibility to hook in and send the mails in a different way.
26 * The hook can be used by adding function to the configuration array:
27 * $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/utility/class.t3lib_utility_mail.php']['substituteMailDelivery']
28 *
29 * @param string $to Email address to send to.
30 * @param string $subject Subject line, non-encoded. (see PHP function mail())
31 * @param string $messageBody Message content, non-encoded. (see PHP function mail())
32 * @param string $additionalHeaders Additional headers for the mail (see PHP function mail())
33 * @param string $additionalParameters Additional flags for the sending mail tool (see PHP function mail())
34 * @return boolean Indicates whether the mail has been sent or not
35 * @see PHP function mail() []
36 * @link http://www.php.net/manual/en/function.mail.php
37 * @deprecated since 6.1, will be removed two versions later - Use \TYPO3\CMS\Core\Mail\Mailer instead
38 */
39 static public function mail($to, $subject, $messageBody, $additionalHeaders = NULL, $additionalParameters = NULL) {
40 GeneralUtility::logDeprecatedFunction();
41 $success = TRUE;
42 // If the mail does not have a From: header, fall back to the default in TYPO3_CONF_VARS.
43 if (!preg_match('/^From:/im', $additionalHeaders) && $GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailFromAddress']) {
44 if (!is_null($additionalHeaders) && substr($additionalHeaders, -1) != LF) {
45 $additionalHeaders .= LF;
46 }
47 if ($GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailFromName']) {
48 $additionalHeaders .= 'From: "' . $GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailFromName'] . '" <' . $GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailFromAddress'] . '>';
49 } else {
50 $additionalHeaders .= 'From: ' . $GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailFromAddress'];
51 }
52 }
53 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/utility/class.t3lib_utility_mail.php']['substituteMailDelivery'])) {
54 $parameters = array(
55 'to' => $to,
56 'subject' => $subject,
57 'messageBody' => $messageBody,
58 'additionalHeaders' => $additionalHeaders,
59 'additionalParameters' => $additionalParameters
60 );
61 $fakeThis = FALSE;
62 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/utility/class.t3lib_utility_mail.php']['substituteMailDelivery'] as $hookSubscriber) {
63 $hookSubscriberContainsArrow = strpos($hookSubscriber, '->');
64 if ($hookSubscriberContainsArrow !== FALSE) {
65 throw new \RuntimeException($hookSubscriber . ' is an invalid hook implementation. Please consider using an implementation of TYPO3\\CMS\\Core\\Mail\\MailerAdapter.', 1322287600);
66 } else {
67 $mailerAdapter = GeneralUtility::makeInstance($hookSubscriber);
68 if ($mailerAdapter instanceof \TYPO3\CMS\Core\Mail\MailerAdapterInterface) {
69 $success = $success && $mailerAdapter->mail($to, $subject, $messageBody, $additionalHeaders, $additionalParameters, $fakeThis);
70 } else {
71 throw new \RuntimeException($hookSubscriber . ' is not an implementation of TYPO3\\CMS\\Core\\Mail\\MailerAdapter,
72 but must implement that interface to be used in the substituteMailDelivery hook.', 1294062286);
73 }
74 }
75 }
76 } else {
77 if (is_null($additionalParameters)) {
78 $success = @mail($to, $subject, $messageBody, $additionalHeaders);
79 } else {
80 $success = @mail($to, $subject, $messageBody, $additionalHeaders, $additionalParameters);
81 }
82 }
83 if (!$success) {
84 GeneralUtility::sysLog('Mail to "' . $to . '" could not be sent (Subject: "' . $subject . '").', 'Core', GeneralUtility::SYSLOG_SEVERITY_ERROR);
85 }
86 return $success;
87 }
88
89 /**
90 * Gets a valid "from" for mail messages (email and name).
91 *
92 * Ready to be passed to $mail->setFrom()
93 *
94 * @return array key=Valid email address which can be used as sender, value=Valid name which can be used as a sender. NULL if no address is configured
95 */
96 static public function getSystemFrom() {
97 $address = self::getSystemFromAddress();
98 $name = self::getSystemFromName();
99 if (!$address) {
100 return NULL;
101 } elseif ($name) {
102 return array($address => $name);
103 } else {
104 return array($address);
105 }
106 }
107
108 /**
109 * Creates a valid "from" name for mail messages.
110 *
111 * As configured in Install Tool.
112 *
113 * @return string The name (unquoted, unformatted). NULL if none is set
114 */
115 static public function getSystemFromName() {
116 if ($GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailFromName']) {
117 return $GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailFromName'];
118 } else {
119 return NULL;
120 }
121 }
122
123 /**
124 * Creates a valid email address for the sender of mail messages.
125 *
126 * Uses a fallback chain:
127 * $TYPO3_CONF_VARS['MAIL']['defaultMailFromAddress'] ->
128 * no-reply@FirstDomainRecordFound ->
129 * no-reply@php_uname('n') ->
130 * no-reply@example.com
131 *
132 * Ready to be passed to $mail->setFrom()
133 *
134 * @return string An email address
135 */
136 static public function getSystemFromAddress() {
137 // default, first check the localconf setting
138 $address = $GLOBALS['TYPO3_CONF_VARS']['MAIL']['defaultMailFromAddress'];
139 if (!GeneralUtility::validEmail($address)) {
140 // just get us a domain record we can use as the host
141 $host = '';
142 $domainRecord = $GLOBALS['TYPO3_DB']->exec_SELECTgetSingleRow('domainName', 'sys_domain', 'hidden = 0', '', 'pid ASC, sorting ASC');
143 if (!empty($domainRecord['domainName'])) {
144 $tempUrl = $domainRecord['domainName'];
145 if (!GeneralUtility::isFirstPartOfStr($tempUrl, 'http')) {
146 // shouldn't be the case anyways, but you never know
147 // ... there're crazy people out there
148 $tempUrl = 'http://' . $tempUrl;
149 }
150 $host = parse_url($tempUrl, PHP_URL_HOST);
151 }
152 $address = 'no-reply@' . $host;
153 if (!GeneralUtility::validEmail($address)) {
154 // still nothing, get host name from server
155 $address = 'no-reply@' . php_uname('n');
156 if (!GeneralUtility::validEmail($address)) {
157 // if everything fails use a dummy address
158 $address = 'no-reply@example.com';
159 }
160 }
161 }
162 return $address;
163 }
164
165 /**
166 * Breaks up a single line of text for emails
167 * Words - longer than $lineWidth - will not be split into parts
168 *
169 * @param string $str The string to break up
170 * @param string $newlineChar The string to implode the broken lines with (default/typically \n)
171 * @param integer $lineWidth The line width
172 * @return string Reformated text
173 */
174 static public function breakLinesForEmail($str, $newlineChar = LF, $lineWidth = 76) {
175 $lines = array();
176 $substrStart = 0;
177 while (strlen($str) > $substrStart) {
178 $substr = substr($str, $substrStart, $lineWidth);
179 // has line exceeded (reached) the maximum width?
180 if (strlen($substr) == $lineWidth) {
181 // find last space-char
182 $spacePos = strrpos(rtrim($substr), ' ');
183 // space-char found?
184 if ($spacePos !== FALSE) {
185 // take everything up to last space-char
186 $theLine = substr($substr, 0, $spacePos);
187 $substrStart++;
188 } else {
189 // search for space-char in remaining text
190 // makes this line longer than $lineWidth!
191 $afterParts = explode(' ', substr($str, $lineWidth + $substrStart), 2);
192 $theLine = $substr . $afterParts[0];
193 }
194 if (!strlen($theLine)) {
195 // prevent endless loop because of empty line
196 break;
197 }
198 } else {
199 $theLine = $substr;
200 }
201 $lines[] = trim($theLine);
202 $substrStart += strlen($theLine);
203 if (trim(substr($str, $substrStart, $lineWidth)) === '') {
204 // no more text
205 break;
206 }
207 }
208 return implode($newlineChar, $lines);
209 }
210
211 /**
212 * Parses mailbox headers and turns them into an array.
213 *
214 * Mailbox headers are a comma separated list of 'name <email@example.org>' combinations
215 * or plain email addresses (or a mix of these).
216 * The resulting array has key-value pairs where the key is either a number
217 * (no display name in the mailbox header) and the value is the email address,
218 * or the key is the email address and the value is the display name.
219 *
220 * @param string $rawAddresses Comma separated list of email addresses (optionally with display name)
221 * @return array Parsed list of addresses.
222 */
223 static public function parseAddresses($rawAddresses) {
224 /** @var $addressParser \TYPO3\CMS\Core\Mail\Rfc822AddressesParser */
225 $addressParser = GeneralUtility::makeInstance(
226 'TYPO3\\CMS\\Core\\Mail\\Rfc822AddressesParser',
227 $rawAddresses
228 );
229 $addresses = $addressParser->parseAddressList();
230 $addressList = array();
231 foreach ($addresses as $address) {
232 if ($address->mailbox === '') {
233 continue;
234 }
235 if ($address->personal) {
236 // item with name found ( name <email@example.org> )
237 $addressList[$address->mailbox . '@' . $address->host] = $address->personal;
238 } else {
239 // item without name found ( email@example.org )
240 $addressList[] = $address->mailbox . '@' . $address->host;
241 }
242 }
243 return $addressList;
244 }
245 }