]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Email.php
"getStyledURL" is now public
[friendica.git] / src / Protocol / Email.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Protocol;
23
24 use Friendica\Core\Hook;
25 use Friendica\Core\Logger;
26 use Friendica\Content\Text\BBCode;
27 use Friendica\Content\Text\HTML;
28 use Friendica\Model\Item;
29 use Friendica\Util\Strings;
30 use \IMAP\Connection;
31
32 /**
33  * Email class
34  */
35 class Email
36 {
37         /**
38          * @param string $mailbox  The mailbox name
39          * @param string $username The username
40          * @param string $password The password
41          * @return Connection|resource|bool
42          * @throws \Exception
43          */
44         public static function connect(string $mailbox, string $username, string $password)
45         {
46                 if (!function_exists('imap_open')) {
47                         return false;
48                 }
49
50                 $mbox = @imap_open($mailbox, $username, $password);
51
52                 $errors = imap_errors();
53                 if (!empty($errors)) {
54                         Logger::notice('IMAP Errors occurred', ['errors' => $errors]);
55                 }
56
57                 $alerts = imap_alerts();
58                 if (!empty($alerts)) {
59                         Logger::notice('IMAP Alerts occurred: ', ['alerts' => $alerts]);
60                 }
61
62                 return $mbox;
63         }
64
65         /**
66          * @param Connection|resource $mbox       mailbox
67          * @param string              $email_addr email
68          * @return array
69          * @throws \Exception
70          */
71         public static function poll($mbox, string $email_addr): array
72         {
73                 if (!$mbox || !$email_addr) {
74                         return [];
75                 }
76
77                 $search1 = @imap_search($mbox, 'UNDELETED FROM "' . $email_addr . '"', SE_UID);
78                 if (!$search1) {
79                         $search1 = [];
80                 } else {
81                         Logger::debug("Found mails from ".$email_addr);
82                 }
83
84                 $search2 = @imap_search($mbox, 'UNDELETED TO "' . $email_addr . '"', SE_UID);
85                 if (!$search2) {
86                         $search2 = [];
87                 } else {
88                         Logger::debug("Found mails to ".$email_addr);
89                 }
90
91                 $search3 = @imap_search($mbox, 'UNDELETED CC "' . $email_addr . '"', SE_UID);
92                 if (!$search3) {
93                         $search3 = [];
94                 } else {
95                         Logger::debug("Found mails cc ".$email_addr);
96                 }
97
98                 $res = array_unique(array_merge($search1, $search2, $search3));
99
100                 return $res;
101         }
102
103         /**
104          * Returns mailbox name
105          *
106          * @param array   $mailacct mail account
107          * @return string
108          */
109         public static function constructMailboxName(array $mailacct): string
110         {
111                 $ret = '{' . $mailacct['server'] . ((intval($mailacct['port'])) ? ':' . $mailacct['port'] : '');
112                 $ret .= (($mailacct['ssltype']) ?  '/' . $mailacct['ssltype'] . '/novalidate-cert' : '');
113                 $ret .= '}' . $mailacct['mailbox'];
114                 return $ret;
115         }
116
117         /**
118          * @param Connection|resource $mbox     mailbox
119          * @param string              $sequence
120          * @return mixed
121          */
122         public static function messageMeta($mbox, string $sequence)
123         {
124                 $ret = (($mbox && $sequence) ? @imap_fetch_overview($mbox, $sequence, FT_UID) : [[]]); // POSSIBLE CLEANUP --> array(array()) is probably redundant now
125                 return (count($ret)) ? $ret : [];
126         }
127
128         /**
129          * @param Connection|resource $mbox  mailbox
130          * @param integer             $uid   user id
131          * @param string              $reply reply
132          * @param array               $item  Item
133          * @return array
134          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
135          */
136         public static function getMessage($mbox, int $uid, string $reply, array $item): array
137         {
138                 $ret = $item;
139
140                 $struc = (($mbox && $uid) ? @imap_fetchstructure($mbox, $uid, FT_UID) : null);
141
142                 if (!$struc) {
143                         Logger::notice("IMAP structure couldn't be fetched", ['uid' => $uid]);
144                         return $ret;
145                 }
146
147                 if (empty($struc->parts)) {
148                         $html = trim(self::messageGetPart($mbox, $uid, $struc, 0, 'html'));
149
150                         if (!empty($html)) {
151                                 $message = ['text' => '', 'html' => $html, 'item' => $ret];
152                                 Hook::callAll('email_getmessage', $message);
153                                 $ret = $message['item'];
154                                 if (empty($ret['body'])) {
155                                         $ret['body'] = HTML::toBBCode($message['html']);
156                                 }
157                         }
158
159                         if (empty($ret['body'])) {
160                                 $text = self::messageGetPart($mbox, $uid, $struc, 0, 'plain');
161
162                                 $message = ['text' => $text, 'html' => '', 'item' => $ret];
163                                 Hook::callAll('email_getmessage', $message);
164                                 $ret = $message['item'];
165                                 $ret['body'] = $message['text'];
166                         }
167                 } else {
168                         $text = '';
169                         $html = '';
170                         foreach ($struc->parts as $ptop => $p) {
171                                 $x = self::messageGetPart($mbox, $uid, $p, $ptop + 1, 'plain');
172                                 if ($x) {
173                                         $text .= $x;
174                                 }
175
176                                 $x = self::messageGetPart($mbox, $uid, $p, $ptop + 1, 'html');
177                                 if ($x) {
178                                         $html .= $x;
179                                 }
180                         }
181
182                         $message = ['text' => trim($text), 'html' => trim($html), 'item' => $ret];
183                         Hook::callAll('email_getmessage', $message);
184                         $ret = $message['item'];
185
186                         if (empty($ret['body']) && !empty($message['html'])) {
187                                 $ret['body'] = HTML::toBBCode($message['html']);
188                         }
189
190                         if (empty($ret['body'])) {
191                                 $ret['body'] = $message['text'];
192                         }
193                 }
194
195                 $ret['body'] = self::removeGPG($ret['body']);
196                 $msg = self::removeSig($ret['body']);
197                 $ret['body'] = $msg['body'];
198                 $ret['body'] = self::convertQuote($ret['body'], $reply);
199
200                 if (trim($html) != '') {
201                         $ret['body'] = self::removeLinebreak($ret['body']);
202                 }
203
204                 $ret['body'] = self::unifyAttributionLine($ret['body']);
205
206                 $ret['body'] = Strings::escapeHtml($ret['body']);
207                 $ret['body'] = BBCode::limitBodySize($ret['body']);
208
209                 Hook::callAll('email_getmessage_end', $ret);
210
211                 return $ret;
212         }
213
214         /**
215          * fetch the specified message part number with the specified subtype
216          *
217          * @param Connection|resource $mbox    mailbox
218          * @param integer             $uid     user id
219          * @param object              $p       parts
220          * @param integer             $partno  part number
221          * @param string              $subtype sub type
222          * @return string
223          */
224         private static function messageGetPart($mbox, int $uid, $p, int $partno, string $subtype): string
225         {
226                 // $partno = '1', '2', '2.1', '2.1.3', etc for multipart, 0 if simple
227                 global $htmlmsg,$plainmsg,$charset,$attachments;
228
229                 // DECODE DATA
230                 $data = ($partno)
231                         ? @imap_fetchbody($mbox, $uid, $partno, FT_UID|FT_PEEK)
232                 : @imap_body($mbox, $uid, FT_UID|FT_PEEK);
233
234                 // Any part may be encoded, even plain text messages, so check everything.
235                 if ($p->encoding == 4) {
236                         $data = quoted_printable_decode($data);
237                 } elseif ($p->encoding == 3) {
238                         $data = base64_decode($data);
239                 }
240
241                 // PARAMETERS
242                 // get all parameters, like charset, filenames of attachments, etc.
243                 $params = [];
244                 if ($p->parameters) {
245                         foreach ($p->parameters as $x) {
246                                 $params[strtolower($x->attribute)] = $x->value;
247                         }
248                 }
249
250                 if (isset($p->dparameters) && $p->dparameters) {
251                         foreach ($p->dparameters as $x) {
252                                 $params[strtolower($x->attribute)] = $x->value;
253                         }
254                 }
255
256                 // ATTACHMENT
257                 // Any part with a filename is an attachment,
258                 // so an attached text file (type 0) is not mistaken as the message.
259
260                 if ((isset($params['filename']) && $params['filename']) || (isset($params['name']) && $params['name'])) {
261                         // filename may be given as 'Filename' or 'Name' or both
262                         $filename = ($params['filename'])? $params['filename'] : $params['name'];
263                         // filename may be encoded, so see imap_mime_header_decode()
264                         $attachments[$filename] = $data;  // this is a problem if two files have same name
265                 }
266
267                 // TEXT
268                 if ($p->type == 0 && $data) {
269                         // Messages may be split in different parts because of inline attachments,
270                         // so append parts together with blank row.
271                         if (strtolower($p->subtype)==$subtype) {
272                                 $data = iconv($params['charset'], 'UTF-8//IGNORE', $data);
273                                 return (trim($data) ."\n\n");
274                         } else {
275                                 $data = '';
276                         }
277
278                         // $htmlmsg .= $data ."<br><br>";
279                         $charset = $params['charset'];  // assume all parts are same charset
280                 }
281
282                 // EMBEDDED MESSAGE
283                 // Many bounce notifications embed the original message as type 2,
284                 // but AOL uses type 1 (multipart), which is not handled here.
285                 // There are no PHP functions to parse embedded messages,
286                 // so this just appends the raw source to the main message.
287                 //      elseif ($p->type==2 && $data) {
288                 //              $plainmsg .= $data."\n\n";
289                 //      }
290
291                 // SUBPART RECURSION
292                 if (isset($p->parts) && $p->parts) {
293                         $x = "";
294                         foreach ($p->parts as $partno0 => $p2) {
295                                 $x .=  self::messageGetPart($mbox, $uid, $p2, $partno . '.' . ($partno0+1), $subtype);  // 1.2, 1.2.1, etc.
296                         }
297                         return $x;
298                 }
299                 return '';
300         }
301
302         /**
303          * Returns encoded header
304          *
305          * @param string $in_str  in string
306          * @param string $charset character set
307          * @return string
308          */
309         public static function encodeHeader(string $in_str, string $charset): string
310         {
311                 $out_str = $in_str;
312                 $need_to_convert = false;
313
314                 for ($x = 0; $x < strlen($in_str); $x ++) {
315                         if ((ord($in_str[$x]) == 0) || ((ord($in_str[$x]) > 128))) {
316                                 $need_to_convert = true;
317                         }
318                 }
319
320                 if (!$need_to_convert) {
321                         return $in_str;
322                 }
323
324                 if ($out_str && $charset) {
325                         // define start delimiter, end delimiter and spacer
326                         $end = "?=";
327                         $start = "=?" . $charset . "?B?";
328                         $spacer = $end . "\r\n " . $start;
329
330                         // determine length of encoded text within chunks
331                         // and ensure length is even
332                         $length = 75 - strlen($start) - strlen($end);
333
334                         /*
335                                 [EDIT BY danbrown AT php DOT net: The following
336                                 is a bugfix provided by (gardan AT gmx DOT de)
337                                 on 31-MAR-2005 with the following note:
338                                 "This means: $length should not be even,
339                                 but divisible by 4. The reason is that in
340                                 base64-encoding 3 8-bit-chars are represented
341                                 by 4 6-bit-chars. These 4 chars must not be
342                                 split between two encoded words, according
343                                 to RFC-2047.
344                         */
345                         $length = $length - ($length % 4);
346
347                         // encode the string and split it into chunks
348                         // with spacers after each chunk
349                         $out_str = base64_encode($out_str);
350                         $out_str = chunk_split($out_str, $length, $spacer);
351
352                         // remove trailing spacer and
353                         // add start and end delimiters
354                         $spacer = preg_quote($spacer, '/');
355                         $out_str = preg_replace("/" . $spacer . "$/", "", $out_str);
356                         $out_str = $start . $out_str . $end;
357                 }
358                 return $out_str;
359         }
360
361         /**
362          * Function send is used by Protocol::EMAIL code
363          * (not to notify the user, but to send items to email contacts)
364          *
365          * @param string $addr    address
366          * @param string $subject subject
367          * @param string $headers headers
368          * @param array  $item    item
369          * @return bool Status from mail()
370          *
371          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
372          * @throws \ImagickException
373          * @todo This could be changed to use the Emailer class
374          */
375         public static function send(string $addr, string $subject, string $headers, array$item)
376         {
377                 //$headers .= 'MIME-Version: 1.0' . "\n";
378                 //$headers .= 'Content-Type: text/html; charset=UTF-8' . "\n";
379                 //$headers .= 'Content-Type: text/plain; charset=UTF-8' . "\n";
380                 //$headers .= 'Content-Transfer-Encoding: 8bit' . "\n\n";
381
382                 $part = uniqid('', true);
383
384                 $html    = Item::prepareBody($item);
385
386                 $headers .= "Mime-Version: 1.0\n";
387                 $headers .= 'Content-Type: multipart/alternative; boundary="=_'.$part.'"'."\n\n";
388
389                 $body = "\n--=_".$part."\n";
390                 $body .= "Content-Transfer-Encoding: 8bit\n";
391                 $body .= "Content-Type: text/plain; charset=utf-8; format=flowed\n\n";
392
393                 $body .= HTML::toPlaintext($html)."\n";
394
395                 $body .= "--=_".$part."\n";
396                 $body .= "Content-Transfer-Encoding: 8bit\n";
397                 $body .= "Content-Type: text/html; charset=utf-8\n\n";
398
399                 $body .= '<html><head></head><body style="word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space; ">'.$html."</body></html>\n";
400
401                 $body .= "--=_".$part."--";
402
403                 //$message = '<html><body>' . $html . '</body></html>';
404                 //$message = html2plain($html);
405                 Logger::notice('notifier: email delivery to ' . $addr);
406                 return mail($addr, $subject, $body, $headers);
407         }
408
409         /**
410          * Convert item URI to message id
411          *
412          * @param string $itemUri Item URI
413          * @return string Message id
414          */
415         public static function iri2msgid(string $itemUri): string
416         {
417                 $msgid = $itemUri;
418
419                 if (!strpos($itemUri, '@')) {
420                         $msgid = preg_replace("/urn:(\S+):(\S+)\.(\S+):(\d+):(\S+)/i", "urn!$1!$4!$5@$2.$3", $itemUri);
421                 }
422
423                 return $msgid;
424         }
425
426         /**
427          * Converts message id to item URI
428          *
429          * @param string $msgid Message id
430          * @return string Item URI
431          */
432         public static function msgid2iri(string $msgid): string
433         {
434                 $itemUri = $msgid;
435
436                 if (strpos($msgid, '@')) {
437                         $itemUri = preg_replace("/urn!(\S+)!(\d+)!(\S+)@(\S+)\.(\S+)/i", "urn:$1:$4.$5:$2:$3", $msgid);
438                 }
439
440                 return $itemUri;
441         }
442
443         /**
444          * Invokes preg_replace() but does return full text from parameter if it
445          * returned an empty message.
446          *
447          * @param string $pattern Pattern to match
448          * @param string $replace String to replace with
449          * @param string $text String to check
450          * @return string Replaced string
451          */
452         private static function saveReplace(string $pattern, string $replace, string $text): string
453         {
454                 $return = preg_replace($pattern, $replace, $text);
455
456                 if ($return == '') {
457                         $return = $text;
458                 }
459
460                 return $return;
461         }
462
463         /**
464          * Unifies attribution line(s)
465          *
466          * @param string $message Unfiltered message
467          * @return string Message with unified attribution line(s)
468          */
469         private static function unifyAttributionLine(string $message): string
470         {
471                 $quotestr = ['quote', 'spoiler'];
472                 foreach ($quotestr as $quote) {
473                         $message = self::saveReplace('/----- Original Message -----\s.*?From: "([^<"].*?)" <(.*?)>\s.*?To: (.*?)\s*?Cc: (.*?)\s*?Sent: (.*?)\s.*?Subject: ([^\n].*)\s*\['.$quote.'\]/i', "[".$quote."='$1']\n", $message);
474                         $message = self::saveReplace('/----- Original Message -----\s.*?From: "([^<"].*?)" <(.*?)>\s.*?To: (.*?)\s*?Sent: (.*?)\s.*?Subject: ([^\n].*)\s*\['.$quote.'\]/i', "[".$quote."='$1']\n", $message);
475
476                         $message = self::saveReplace('/-------- Original-Nachricht --------\s*\['.$quote.'\]\nDatum: (.*?)\nVon: (.*?) <(.*?)>\nAn: (.*?)\nBetreff: (.*?)\n/i', "[".$quote."='$2']\n", $message);
477                         $message = self::saveReplace('/-------- Original-Nachricht --------\s*\['.$quote.'\]\sDatum: (.*?)\s.*Von: "([^<"].*?)" <(.*?)>\s.*An: (.*?)\n.*/i', "[".$quote."='$2']\n", $message);
478                         $message = self::saveReplace('/-------- Original-Nachricht --------\s*\['.$quote.'\]\nDatum: (.*?)\nVon: (.*?)\nAn: (.*?)\nBetreff: (.*?)\n/i', "[".$quote."='$2']\n", $message);
479
480                         $message = self::saveReplace('/-----Urspr.*?ngliche Nachricht-----\sVon: "([^<"].*?)" <(.*?)>\s.*Gesendet: (.*?)\s.*An: (.*?)\s.*Betreff: ([^\n].*?).*:\s*\['.$quote.'\]/i', "[".$quote."='$1']\n", $message);
481                         $message = self::saveReplace('/-----Urspr.*?ngliche Nachricht-----\sVon: "([^<"].*?)" <(.*?)>\s.*Gesendet: (.*?)\s.*An: (.*?)\s.*Betreff: ([^\n].*?)\s*\['.$quote.'\]/i', "[".$quote."='$1']\n", $message);
482
483                         $message = self::saveReplace('/Am (.*?), schrieb (.*?):\s*\['.$quote.'\]/i', "[".$quote."='$2']\n", $message);
484
485                         $message = self::saveReplace('/Am .*?, \d+ .*? \d+ \d+:\d+:\d+ \+\d+\sschrieb\s(.*?)\s<(.*?)>:\s*\['.$quote.'\]/i', "[".$quote."='$1']\n", $message);
486
487                         $message = self::saveReplace('/Am (.*?) schrieb (.*?) <(.*?)>:\s*\['.$quote.'\]/i', "[".$quote."='$2']\n", $message);
488                         $message = self::saveReplace('/Am (.*?) schrieb <(.*?)>:\s*\['.$quote.'\]/i', "[".$quote."='$2']\n", $message);
489                         $message = self::saveReplace('/Am (.*?) schrieb (.*?):\s*\['.$quote.'\]/i', "[".$quote."='$2']\n", $message);
490                         $message = self::saveReplace('/Am (.*?) schrieb (.*?)\n(.*?):\s*\['.$quote.'\]/i', "[".$quote."='$2']\n", $message);
491
492                         $message = self::saveReplace('/(\d+)\/(\d+)\/(\d+) ([^<"].*?) <(.*?)>\s*\['.$quote.'\]/i', "[".$quote."='$4']\n", $message);
493
494                         $message = self::saveReplace('/On .*?, \d+ .*? \d+ \d+:\d+:\d+ \+\d+\s(.*?)\s<(.*?)>\swrote:\s*\['.$quote.'\]/i', "[".$quote."='$1']\n", $message);
495
496                         $message = self::saveReplace('/On (.*?) at (.*?), (.*?)\s<(.*?)>\swrote:\s*\['.$quote.'\]/i', "[".$quote."='$3']\n", $message);
497                         $message = self::saveReplace('/On (.*?)\n([^<].*?)\s<(.*?)>\swrote:\s*\['.$quote.'\]/i', "[".$quote."='$2']\n", $message);
498                         $message = self::saveReplace('/On (.*?), (.*?), (.*?)\s<(.*?)>\swrote:\s*\['.$quote.'\]/i', "[".$quote."='$3']\n", $message);
499                         $message = self::saveReplace('/On ([^,].*?), (.*?)\swrote:\s*\['.$quote.'\]/i', "[".$quote."='$2']\n", $message);
500                         $message = self::saveReplace('/On (.*?), (.*?)\swrote\s*\['.$quote.'\]/i', "[".$quote."='$2']\n", $message);
501
502                         // Der loescht manchmal den Body - was eigentlich unmoeglich ist
503                         $message = self::saveReplace('/On (.*?),(.*?),(.*?),(.*?), (.*?) wrote:\s*\['.$quote.'\]/i', "[".$quote."='$5']\n", $message);
504
505                         $message = self::saveReplace('/Zitat von ([^<].*?) <(.*?)>:\s*\['.$quote.'\]/i', "[".$quote."='$1']\n", $message);
506
507                         $message = self::saveReplace('/Quoting ([^<].*?) <(.*?)>:\s*\['.$quote.'\]/i', "[".$quote."='$1']\n", $message);
508
509                         $message = self::saveReplace('/From: "([^<"].*?)" <(.*?)>\s*\['.$quote.'\]/i', "[".$quote."='$1']\n", $message);
510                         $message = self::saveReplace('/From: <(.*?)>\s*\['.$quote.'\]/i', "[".$quote."='$1']\n", $message);
511
512                         $message = self::saveReplace('/Du \(([^)].*?)\) schreibst:\s*\['.$quote.'\]/i', "[".$quote."='$1']\n", $message);
513
514                         $message = self::saveReplace('/--- (.*?) <.*?> schrieb am (.*?):\s*\['.$quote.'\]/i', "[".$quote."='$1']\n", $message);
515                         $message = self::saveReplace('/--- (.*?) schrieb am (.*?):\s*\['.$quote.'\]/i', "[".$quote."='$1']\n", $message);
516
517                         $message = self::saveReplace('/\* (.*?) <(.*?)> hat geschrieben:\s*\['.$quote.'\]/i', "[".$quote."='$1']\n", $message);
518
519                         $message = self::saveReplace('/(.*?) <(.*?)> schrieb (.*?)\):\s*\['.$quote.'\]/i', "[".$quote."='$1']\n", $message);
520                         $message = self::saveReplace('/(.*?) <(.*?)> schrieb am (.*?) um (.*):\s*\['.$quote.'\]/i', "[".$quote."='$1']\n", $message);
521                         $message = self::saveReplace('/(.*?) schrieb am (.*?) um (.*):\s*\['.$quote.'\]/i', "[".$quote."='$1']\n", $message);
522                         $message = self::saveReplace('/(.*?) \((.*?)\) schrieb:\s*\['.$quote.'\]/i', "[".$quote."='$2']\n", $message);
523                         $message = self::saveReplace('/(.*?) schrieb:\s*\['.$quote.'\]/i', "[".$quote."='$1']\n", $message);
524
525                         $message = self::saveReplace('/(.*?) <(.*?)> writes:\s*\['.$quote.'\]/i', "[".$quote."='$1']\n", $message);
526                         $message = self::saveReplace('/(.*?) \((.*?)\) writes:\s*\['.$quote.'\]/i', "[".$quote."='$2']\n", $message);
527                         $message = self::saveReplace('/(.*?) writes:\s*\['.$quote.'\]/i', "[".$quote."='$1']\n", $message);
528
529                         $message = self::saveReplace('/\* (.*?) wrote:\s*\['.$quote.'\]/i', "[".$quote."='$1']\n", $message);
530                         $message = self::saveReplace('/(.*?) wrote \(.*?\):\s*\['.$quote.'\]/i', "[".$quote."='$1']\n", $message);
531                         $message = self::saveReplace('/(.*?) wrote:\s*\['.$quote.'\]/i', "[".$quote."='$1']\n", $message);
532
533                         $message = self::saveReplace('/([^<].*?) <.*?> hat am (.*?)\sum\s(.*)\sgeschrieben:\s*\['.$quote.'\]/i', "[".$quote."='$1']\n", $message);
534
535                         $message = self::saveReplace('/(\d+)\/(\d+)\/(\d+) ([^<"].*?) <(.*?)>:\s*\['.$quote.'\]/i', "[".$quote."='$4']\n", $message);
536                         $message = self::saveReplace('/(\d+)\/(\d+)\/(\d+) (.*?) <(.*?)>\s*\['.$quote.'\]/i', "[".$quote."='$4']\n", $message);
537                         $message = self::saveReplace('/(\d+)\/(\d+)\/(\d+) <(.*?)>:\s*\['.$quote.'\]/i', "[".$quote."='$4']\n", $message);
538                         $message = self::saveReplace('/(\d+)\/(\d+)\/(\d+) <(.*?)>\s*\['.$quote.'\]/i', "[".$quote."='$4']\n", $message);
539
540                         $message = self::saveReplace('/(.*?) <(.*?)> schrubselte:\s*\['.$quote.'\]/i', "[".$quote."='$1']\n", $message);
541                         $message = self::saveReplace('/(.*?) \((.*?)\) schrubselte:\s*\['.$quote.'\]/i', "[".$quote."='$2']\n", $message);
542                 }
543                 return $message;
544         }
545
546         /**
547          * Removes GPG part from message
548          *
549          * @param string $message Unfiltered message
550          * @return string Message with GPG part
551          */
552         private static function removeGPG(string $message): string
553         {
554                 $pattern = '/(.*)\s*-----BEGIN PGP SIGNED MESSAGE-----\s*[\r\n].*Hash:.*?[\r\n](.*)'.
555                         '[\r\n]\s*-----BEGIN PGP SIGNATURE-----\s*[\r\n].*'.
556                         '[\r\n]\s*-----END PGP SIGNATURE-----(.*)/is';
557
558                 if (preg_match($pattern, $message, $result)) {
559                         $cleaned = trim($result[1].$result[2].$result[3]);
560
561                         $cleaned = str_replace(["\n- --\n", "\n- -"], ["\n-- \n", "\n-"], $cleaned);
562                 } else {
563                         $cleaned = $message;
564                 }
565
566                 return $cleaned;
567         }
568
569         /**
570          * Removes signature from message
571          *
572          * @param string $message Unfiltered message
573          * @return array Message array with no signature (elements "body" and "sig")
574          */
575         private static function removeSig(string $message): array
576         {
577                 $sigpos = strrpos($message, "\n-- \n");
578                 $quotepos = strrpos($message, "[/quote]");
579
580                 if ($sigpos == 0) {
581                         // Especially for web.de who are using that as a separator
582                         $message = str_replace("\n___________________________________________________________\n", "\n-- \n", $message);
583                         $sigpos = strrpos($message, "\n-- \n");
584                         $quotepos = strrpos($message, "[/quote]");
585                 }
586
587                 // When the signature separator is inside a quote, we don't separate
588                 if (($sigpos < $quotepos) && ($sigpos != 0)) {
589                         return ['body' => $message, 'sig' => ''];
590                 }
591
592                 $pattern = '/(.*)[\r\n]-- [\r\n](.*)/is';
593
594                 preg_match($pattern, $message, $result);
595
596                 if (!empty($result[1]) && !empty($result[2])) {
597                         $cleaned = trim($result[1])."\n";
598                         $sig = trim($result[2]);
599                 } else {
600                         $cleaned = $message;
601                         $sig = '';
602                 }
603
604                 return ['body' => $cleaned, 'sig' => $sig];
605         }
606
607         /**
608          * Removes lines breaks from message
609          *
610          * @param string $message Unfiltered message
611          * @return string Message with no line breaks
612          */
613         private static function removeLinebreak(string $message): string
614         {
615                 $arrbody = explode("\n", trim($message));
616
617                 $lines = [];
618                 $lineno = 0;
619
620                 foreach ($arrbody as $i => $line) {
621                         $currquotelevel = 0;
622                         $currline = $line;
623                         while ((strlen($currline)>0) && ((substr($currline, 0, 1) == '>')
624                                 || (substr($currline, 0, 1) == ' '))) {
625                                 if (substr($currline, 0, 1) == '>') {
626                                         $currquotelevel++;
627                                 }
628
629                                 $currline = ltrim(substr($currline, 1));
630                         }
631
632                         $quotelevel = 0;
633                         $nextline = trim($arrbody[$i + 1] ?? '');
634                         while ((strlen($nextline)>0) && ((substr($nextline, 0, 1) == '>')
635                                 || (substr($nextline, 0, 1) == ' '))) {
636                                 if (substr($nextline, 0, 1) == '>') {
637                                         $quotelevel++;
638                                 }
639
640                                 $nextline = ltrim(substr($nextline, 1));
641                         }
642
643                         if (!empty($lines[$lineno])) {
644                                 if (substr($lines[$lineno], -1) != ' ') {
645                                         $lines[$lineno] .= ' ';
646                                 }
647
648                                 while ((strlen($line)>0) && ((substr($line, 0, 1) == '>')
649                                         || (substr($line, 0, 1) == ' '))) {
650
651                                         $line = ltrim(substr($line, 1));
652                                 }
653                         } else {
654                                 $lines[$lineno] = '';
655                         }
656
657                         $lines[$lineno] .= $line;
658                         if (((substr($line, -1, 1) != ' '))
659                                 || ($quotelevel != $currquotelevel)) {
660                                 $lineno++;
661                         }
662                 }
663                 return implode("\n", $lines);
664         }
665
666         private static function convertQuote(string $body, string $reply): string
667         {
668                 // Convert Quotes
669                 $arrbody = explode("\n", trim($body));
670                 $arrlevel = [];
671
672                 for ($i = 0; $i < count($arrbody); $i++) {
673                         $quotelevel = 0;
674                         $quoteline = $arrbody[$i];
675
676                         while ((strlen($quoteline)>0) and ((substr($quoteline, 0, 1) == '>')
677                                 || (substr($quoteline, 0, 1) == ' '))) {
678                                 if (substr($quoteline, 0, 1) == '>')
679                                         $quotelevel++;
680
681                                 $quoteline = ltrim(substr($quoteline, 1));
682                         }
683
684                         $arrlevel[$i] = $quotelevel;
685                         $arrbody[$i] = $quoteline;
686                 }
687
688                 $quotelevel = 0;
689                 $arrbodyquoted = [];
690
691                 for ($i = 0; $i < count($arrbody); $i++) {
692                         $previousquote = $quotelevel;
693                         $quotelevel = $arrlevel[$i];
694
695                         while ($previousquote < $quotelevel) {
696                                 $quote = "[quote]";
697                                 $arrbody[$i] = $quote.$arrbody[$i];
698                                 $previousquote++;
699                         }
700
701                         while ($previousquote > $quotelevel) {
702                                 $arrbody[$i] = '[/quote]'.$arrbody[$i];
703                                 $previousquote--;
704                         }
705
706                         $arrbodyquoted[] = $arrbody[$i];
707                 }
708                 while ($quotelevel > 0) {
709                         $arrbodyquoted[] = '[/quote]';
710                         $quotelevel--;
711                 }
712
713                 $body = implode("\n", $arrbodyquoted);
714
715                 if (strlen($body) > 0) {
716                         $body = $body."\n\n";
717                 }
718
719                 if ($reply) {
720                         $body = self::removeToFu($body);
721                 }
722
723                 return $body;
724         }
725
726         private static function removeToFu(string $message): string
727         {
728                 $message = trim($message);
729
730                 do {
731                         $oldmessage = $message;
732                         $message = preg_replace('=\[/quote\][\s](.*?)\[quote\]=i', '$1', $message);
733                         $message = str_replace('[/quote][quote]', '', $message);
734                 } while ($message != $oldmessage);
735
736                 $quotes = [];
737
738                 $startquotes = 0;
739
740                 $start = 0;
741
742                 while (($pos = strpos($message, '[quote', $start)) > 0) {
743                         $quotes[$pos] = -1;
744                         $start = $pos + 7;
745                         $startquotes++;
746                 }
747
748                 $endquotes = 0;
749                 $start = 0;
750
751                 while (($pos = strpos($message, '[/quote]', $start)) > 0) {
752                         $start = $pos + 7;
753                         $endquotes++;
754                 }
755
756                 while ($endquotes < $startquotes) {
757                         $message .= '[/quote]';
758                         ++$endquotes;
759                 }
760
761                 $start = 0;
762
763                 while (($pos = strpos($message, '[/quote]', $start)) > 0) {
764                         $quotes[$pos] = 1;
765                         $start = $pos + 7;
766                 }
767
768                 if (strtolower(substr($message, -8)) != '[/quote]') {
769                         return($message);
770                 }
771
772                 krsort($quotes);
773
774                 $quotelevel = 0;
775                 $quotestart = 0;
776                 foreach ($quotes as $index => $quote) {
777                         $quotelevel += $quote;
778
779                         if (($quotelevel == 0) and ($quotestart == 0))
780                                 $quotestart = $index;
781                 }
782
783                 if ($quotestart != 0) {
784                         $message = trim(substr($message, 0, $quotestart))."\n[spoiler]".substr($message, $quotestart+7, -8) . '[/spoiler]';
785                 }
786
787                 return $message;
788         }
789 }