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