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