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