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