]> git.mxchange.org Git - friendica.git/blob - src/Protocol/Email.php
cleanup sysloglogger
[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\Model\Item;
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 resource
21          * @throws \Exception
22          */
23         public static function connect($mailbox, $username, $password)
24         {
25                 if (!function_exists('imap_open')) {
26                         return false;
27                 }
28
29                 $mbox = @imap_open($mailbox, $username, $password);
30
31                 $errors = imap_errors();
32                 if (!empty($errors)) {
33                         Logger::log('IMAP Errors occured: ' . json_encode($errors));
34                 }
35
36                 $alerts = imap_alerts();
37                 if (!empty($alerts)) {
38                         Logger::log('IMAP Alerts occured: ' . json_encode($alerts));
39                 }
40
41                 return $mbox;
42         }
43
44         /**
45          * @param resource $mbox       mailbox
46          * @param string   $email_addr email
47          * @return array
48          * @throws \Exception
49          */
50         public static function poll($mbox, $email_addr)
51         {
52                 if (!$mbox || !$email_addr) {
53                         return [];
54                 }
55
56                 $search1 = @imap_search($mbox, 'FROM "' . $email_addr . '"', SE_UID);
57                 if (!$search1) {
58                         $search1 = [];
59                 } else {
60                         Logger::log("Found mails from ".$email_addr, Logger::DEBUG);
61                 }
62
63                 $search2 = @imap_search($mbox, 'TO "' . $email_addr . '"', SE_UID);
64                 if (!$search2) {
65                         $search2 = [];
66                 } else {
67                         Logger::log("Found mails to ".$email_addr, Logger::DEBUG);
68                 }
69
70                 $search3 = @imap_search($mbox, 'CC "' . $email_addr . '"', SE_UID);
71                 if (!$search3) {
72                         $search3 = [];
73                 } else {
74                         Logger::log("Found mails cc ".$email_addr, Logger::DEBUG);
75                 }
76
77                 $res = array_unique(array_merge($search1, $search2, $search3));
78
79                 return $res;
80         }
81
82         /**
83          * @param array   $mailacct mail account
84          * @return string
85          */
86         public static function constructMailboxName($mailacct)
87         {
88                 $ret = '{' . $mailacct['server'] . ((intval($mailacct['port'])) ? ':' . $mailacct['port'] : '');
89                 $ret .= (($mailacct['ssltype']) ?  '/' . $mailacct['ssltype'] . '/novalidate-cert' : '');
90                 $ret .= '}' . $mailacct['mailbox'];
91                 return $ret;
92         }
93
94         /**
95          * @param resource $mbox mailbox
96          * @param integer  $uid  user id
97          * @return mixed
98          */
99         public static function messageMeta($mbox, $uid)
100         {
101                 $ret = (($mbox && $uid) ? @imap_fetch_overview($mbox, $uid, FT_UID) : [[]]); // POSSIBLE CLEANUP --> array(array()) is probably redundant now
102                 return (count($ret)) ? $ret : [];
103         }
104
105         /**
106          * @param resource $mbox  mailbox
107          * @param integer  $uid   user id
108          * @param string   $reply reply
109          * @return array
110          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
111          */
112         public static function getMessage($mbox, $uid, $reply)
113         {
114                 $ret = [];
115
116                 $struc = (($mbox && $uid) ? @imap_fetchstructure($mbox, $uid, FT_UID) : null);
117
118                 if (!$struc) {
119                         return $ret;
120                 }
121
122                 if (empty($struc->parts)) {
123                         $ret['body'] = self::messageGetPart($mbox, $uid, $struc, 0, 'html');
124                         $html = $ret['body'];
125
126                         if (trim($ret['body']) == '') {
127                                 $ret['body'] = self::messageGetPart($mbox, $uid, $struc, 0, 'plain');
128                         } else {
129                                 $ret['body'] = HTML::toBBCode($ret['body']);
130                         }
131                 } else {
132                         $text = '';
133                         $html = '';
134                         foreach ($struc->parts as $ptop => $p) {
135                                 $x = self::messageGetPart($mbox, $uid, $p, $ptop + 1, 'plain');
136                                 if ($x) {
137                                         $text .= $x;
138                                 }
139
140                                 $x = self::messageGetPart($mbox, $uid, $p, $ptop + 1, 'html');
141                                 if ($x) {
142                                         $html .= $x;
143                                 }
144                         }
145                         if (trim($html) != '') {
146                                 $ret['body'] = HTML::toBBCode($html);
147                         } else {
148                                 $ret['body'] = $text;
149                         }
150                 }
151
152                 $ret['body'] = self::removeGPG($ret['body']);
153                 $msg = self::removeSig($ret['body']);
154                 $ret['body'] = $msg['body'];
155                 $ret['body'] = self::convertQuote($ret['body'], $reply);
156
157                 if (trim($html) != '') {
158                         $ret['body'] = self::removeLinebreak($ret['body']);
159                 }
160
161                 $ret['body'] = self::unifyAttributionLine($ret['body']);
162
163                 return $ret;
164         }
165
166         // At the moment - only return plain/text.
167         // Later we'll repackage inline images as data url's and make the HTML safe
168         /**
169          * @param resource $mbox    mailbox
170          * @param integer  $uid     user id
171          * @param object   $p       parts
172          * @param integer  $partno  part number
173          * @param string   $subtype sub type
174          * @return string
175          */
176         private static function messageGetPart($mbox, $uid, $p, $partno, $subtype)
177         {
178                 // $partno = '1', '2', '2.1', '2.1.3', etc for multipart, 0 if simple
179                 global $htmlmsg,$plainmsg,$charset,$attachments;
180
181                 // DECODE DATA
182                 $data = ($partno)
183                         ? @imap_fetchbody($mbox, $uid, $partno, FT_UID|FT_PEEK)
184                 : @imap_body($mbox, $uid, FT_UID|FT_PEEK);
185
186                 // Any part may be encoded, even plain text messages, so check everything.
187                 if ($p->encoding == 4) {
188                         $data = quoted_printable_decode($data);
189                 } elseif ($p->encoding == 3) {
190                         $data = base64_decode($data);
191                 }
192
193                 // PARAMETERS
194                 // get all parameters, like charset, filenames of attachments, etc.
195                 $params = [];
196                 if ($p->parameters) {
197                         foreach ($p->parameters as $x) {
198                                 $params[strtolower($x->attribute)] = $x->value;
199                         }
200                 }
201
202                 if (isset($p->dparameters) && $p->dparameters) {
203                         foreach ($p->dparameters as $x) {
204                                 $params[strtolower($x->attribute)] = $x->value;
205                         }
206                 }
207
208                 // ATTACHMENT
209                 // Any part with a filename is an attachment,
210                 // so an attached text file (type 0) is not mistaken as the message.
211
212                 if ((isset($params['filename']) && $params['filename']) || (isset($params['name']) && $params['name'])) {
213                         // filename may be given as 'Filename' or 'Name' or both
214                         $filename = ($params['filename'])? $params['filename'] : $params['name'];
215                         // filename may be encoded, so see imap_mime_header_decode()
216                         $attachments[$filename] = $data;  // this is a problem if two files have same name
217                 }
218
219                 // TEXT
220                 if ($p->type == 0 && $data) {
221                         // Messages may be split in different parts because of inline attachments,
222                         // so append parts together with blank row.
223                         if (strtolower($p->subtype)==$subtype) {
224                                 $data = iconv($params['charset'], 'UTF-8//IGNORE', $data);
225                                 return (trim($data) ."\n\n");
226                         } else {
227                                 $data = '';
228                         }
229
230                         // $htmlmsg .= $data ."<br><br>";
231                         $charset = $params['charset'];  // assume all parts are same charset
232                 }
233
234                 // EMBEDDED MESSAGE
235                 // Many bounce notifications embed the original message as type 2,
236                 // but AOL uses type 1 (multipart), which is not handled here.
237                 // There are no PHP functions to parse embedded messages,
238                 // so this just appends the raw source to the main message.
239                 //      elseif ($p->type==2 && $data) {
240                 //              $plainmsg .= $data."\n\n";
241                 //      }
242
243                 // SUBPART RECURSION
244                 if (isset($p->parts) && $p->parts) {
245                         $x = "";
246                         foreach ($p->parts as $partno0 => $p2) {
247                                 $x .=  self::messageGetPart($mbox, $uid, $p2, $partno . '.' . ($partno0+1), $subtype);  // 1.2, 1.2.1, etc.
248                         }
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 Protocol::EMAIL and Protocol::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          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
322          * @throws \ImagickException
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    = Item::prepareBody($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                 if (preg_match($pattern, $message, $result)) {
485                         $cleaned = trim($result[1].$result[2].$result[3]);
486
487                         $cleaned = str_replace(["\n- --\n", "\n- -"], ["\n-- \n", "\n-"], $cleaned);
488                 } else {
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 (!empty($result[1]) && !empty($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(defaults($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                         if (!empty($lines[$lineno])) {
558                                 if (substr($lines[$lineno], -1) != ' ') {
559                                         $lines[$lineno] .= ' ';
560                                 }
561
562                                 while ((strlen($line)>0) && ((substr($line, 0, 1) == '>')
563                                         || (substr($line, 0, 1) == ' '))) {
564
565                                         $line = ltrim(substr($line, 1));
566                                 }
567                         } else {
568                                 $lines[$lineno] = '';
569                         }
570
571                         $lines[$lineno] .= $line;
572                         if (((substr($line, -1, 1) != ' '))
573                                 || ($quotelevel != $currquotelevel)) {
574                                 $lineno++;
575                         }
576                 }
577                 return implode("\n", $lines);
578         }
579
580         private static function convertQuote($body, $reply)
581         {
582                 // Convert Quotes
583                 $arrbody = explode("\n", trim($body));
584                 $arrlevel = [];
585
586                 for ($i = 0; $i < count($arrbody); $i++) {
587                         $quotelevel = 0;
588                         $quoteline = $arrbody[$i];
589
590                         while ((strlen($quoteline)>0) and ((substr($quoteline, 0, 1) == '>')
591                                 || (substr($quoteline, 0, 1) == ' '))) {
592                                 if (substr($quoteline, 0, 1) == '>')
593                                         $quotelevel++;
594
595                                 $quoteline = ltrim(substr($quoteline, 1));
596                         }
597
598                         $arrlevel[$i] = $quotelevel;
599                         $arrbody[$i] = $quoteline;
600                 }
601
602                 $quotelevel = 0;
603                 $arrbodyquoted = [];
604
605                 for ($i = 0; $i < count($arrbody); $i++) {
606                         $previousquote = $quotelevel;
607                         $quotelevel = $arrlevel[$i];
608
609                         while ($previousquote < $quotelevel) {
610                                 $quote = "[quote]";
611                                 $arrbody[$i] = $quote.$arrbody[$i];
612                                 $previousquote++;
613                         }
614
615                         while ($previousquote > $quotelevel) {
616                                 $arrbody[$i] = '[/quote]'.$arrbody[$i];
617                                 $previousquote--;
618                         }
619
620                         $arrbodyquoted[] = $arrbody[$i];
621                 }
622                 while ($quotelevel > 0) {
623                         $arrbodyquoted[] = '[/quote]';
624                         $quotelevel--;
625                 }
626
627                 $body = implode("\n", $arrbodyquoted);
628
629                 if (strlen($body) > 0) {
630                         $body = $body."\n\n";
631                 }
632
633                 if ($reply) {
634                         $body = self::removeToFu($body);
635                 }
636
637                 return $body;
638         }
639
640         private static function removeToFu($message)
641         {
642                 $message = trim($message);
643
644                 do {
645                         $oldmessage = $message;
646                         $message = preg_replace('=\[/quote\][\s](.*?)\[quote\]=i', '$1', $message);
647                         $message = str_replace("[/quote][quote]", "", $message);
648                 } while ($message != $oldmessage);
649
650                 $quotes = [];
651
652                 $startquotes = 0;
653
654                 $start = 0;
655
656                 while (($pos = strpos($message, '[quote', $start)) > 0) {
657                         $quotes[$pos] = -1;
658                         $start = $pos + 7;
659                         $startquotes++;
660                 }
661
662                 $endquotes = 0;
663                 $start = 0;
664
665                 while (($pos = strpos($message, '[/quote]', $start)) > 0) {
666                         $start = $pos + 7;
667                         $endquotes++;
668                 }
669
670                 while ($endquotes < $startquotes) {
671                         $message .= '[/quote]';
672                         ++$endquotes;
673                 }
674
675                 $start = 0;
676
677                 while (($pos = strpos($message, '[/quote]', $start)) > 0) {
678                         $quotes[$pos] = 1;
679                         $start = $pos + 7;
680                 }
681
682                 if (strtolower(substr($message, -8)) != '[/quote]')
683                         return($message);
684
685                 krsort($quotes);
686
687                 $quotelevel = 0;
688                 $quotestart = 0;
689                 foreach ($quotes as $index => $quote) {
690                         $quotelevel += $quote;
691
692                         if (($quotelevel == 0) and ($quotestart == 0))
693                                 $quotestart = $index;
694                 }
695
696                 if ($quotestart != 0) {
697                         $message = trim(substr($message, 0, $quotestart))."\n[spoiler]".substr($message, $quotestart+7, -8).'[/spoiler]';
698                 }
699
700                 return $message;
701         }
702 }