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