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