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