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