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