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