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