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