]> git.mxchange.org Git - friendica.git/blob - src/Content/Text/Plaintext.php
Merge pull request #12134 from Quix0r/fixes/type-hints
[friendica.git] / src / Content / Text / Plaintext.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Content\Text;
23
24 use Friendica\Core\Protocol;
25 use Friendica\DI;
26 use Friendica\Util\Network;
27
28 class Plaintext
29 {
30         // Assumed length of an URL when shortened via the network's own url shortener (e.g. Twitter)
31         const URL_LENGTH = 23;
32
33         /**
34          * Shortens message
35          *
36          * @param  string $msg
37          * @param  int    $limit
38          * @param  int    $uid
39          * @return string
40          *
41          * @todo For Twitter URLs aren't shortened, but they have to be calculated as if.
42          */
43         public static function shorten(string $msg, int $limit, int $uid = 0): string
44         {
45                 $ellipsis = html_entity_decode("&#x2026;", ENT_QUOTES, 'UTF-8');
46
47                 if (!empty($uid) && DI::pConfig()->get($uid, 'system', 'simple_shortening')) {
48                         return mb_substr(mb_substr(trim($msg), 0, $limit), 0, -3) . $ellipsis;
49                 }
50
51                 $lines = explode("\n", $msg);
52                 $msg = "";
53                 $recycle = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8');
54                 foreach ($lines as $row => $line) {
55                         if (mb_strlen(trim($msg . "\n" . $line)) <= $limit) {
56                                 $msg = trim($msg . "\n" . $line);
57                         } elseif (($msg == "") || (($row == 1) && (substr($msg, 0, 4) == $recycle))) {
58                                 // Is the new message empty by now or is it a reshared message?
59                                 $msg = mb_substr(mb_substr(trim($msg . "\n" . $line), 0, $limit), 0, -3) . $ellipsis;
60                         } else {
61                                 break;
62                         }
63                 }
64
65                 return $msg;
66         }
67
68         /**
69          * Returns the character positions of the provided boundaries, optionally skipping a number of first occurrences
70          *
71          * @param string $text        Text to search
72          * @param string $open        Left boundary
73          * @param string $close       Right boundary
74          * @param int    $occurrences Number of first occurrences to skip
75          * @return boolean|array
76          */
77         public static function getBoundariesPosition($text, $open, $close, $occurrences = 0)
78         {
79                 if ($occurrences < 0) {
80                         $occurrences = 0;
81                 }
82
83                 $start_pos = -1;
84                 for ($i = 0; $i <= $occurrences; $i++) {
85                         if ($start_pos !== false) {
86                                 $start_pos = strpos($text, $open, $start_pos + 1);
87                         }
88                 }
89
90                 if ($start_pos === false) {
91                         return false;
92                 }
93
94                 $end_pos = strpos($text, $close, $start_pos);
95
96                 if ($end_pos === false) {
97                         return false;
98                 }
99
100                 $res = ['start' => $start_pos, 'end' => $end_pos];
101
102                 return $res;
103         }
104
105         /**
106          * Convert a message into plaintext for connectors to other networks
107          *
108          * @param array  $item           The message array that is about to be posted
109          * @param int    $limit          The maximum number of characters when posting to that network
110          * @param bool   $includedlinks  Has an attached link to be included into the message?
111          * @param int    $htmlmode       This controls the behavior of the BBCode conversion
112          * @param string $target_network Name of the network where the post should go to.
113          *
114          * @return array Same array structure than \Friendica\Content\Text\BBCode::getAttachedData
115          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
116          * @see   \Friendica\Content\Text\BBCode::getAttachedData
117          */
118         public static function getPost(array $item, int $limit = 0, bool $includedlinks = false, int $htmlmode = BBCode::MASTODON_API, string $target_network = '')
119         {
120                 // Remove hashtags
121                 $URLSearchString = '^\[\]';
122                 $body = preg_replace("/([#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $item['body']);
123
124                 // Add an URL element if the text contains a raw link
125                 $body = preg_replace('/([^\]\=\'"]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism',
126                         '$1[url]$2[/url]', $body);
127
128                 // Remove the abstract
129                 $body = BBCode::stripAbstract($body);
130
131                 // At first look at data that is attached via "type-..." stuff
132                 $post = BBCode::getAttachedData($body, $item);
133
134                 if (($item['title'] != '') && ($post['text'] != '')) {
135                         $post['text'] = trim($item['title'] . "\n\n" . $post['text']);
136                 } elseif ($item['title'] != '') {
137                         $post['text'] = trim($item['title']);
138                 }
139
140                 $abstract = '';
141
142                 // Fetch the abstract from the given target network
143                 if ($target_network != '') {
144                         $default_abstract = BBCode::getAbstract($item['body']);
145                         $abstract = BBCode::getAbstract($item['body'], $target_network);
146
147                         // If we post to a network with no limit we only fetch
148                         // an abstract exactly for this network
149                         if (($limit == 0) && ($abstract == $default_abstract)) {
150                                 $abstract = '';
151                         }
152                 } else {// Try to guess the correct target network
153                         switch ($htmlmode) {
154                                 case BBCode::TWITTER:
155                                         $abstract = BBCode::getAbstract($item['body'], Protocol::TWITTER);
156                                         break;
157
158                                 case BBCode::OSTATUS:
159                                         $abstract = BBCode::getAbstract($item['body'], Protocol::STATUSNET);
160                                         break;
161
162                                 default: // We don't know the exact target.
163                                         // We fetch an abstract since there is a posting limit.
164                                         if ($limit > 0) {
165                                                 $abstract = BBCode::getAbstract($item['body']);
166                                         }
167                         }
168                 }
169
170                 if ($abstract != '') {
171                         $post['text'] = $abstract;
172
173                         if ($post['type'] == 'text') {
174                                 $post['type'] = 'link';
175                                 $post['url'] = $item['plink'];
176                         }
177                 }
178
179                 $html = BBCode::convertForUriId($item['uri-id'], $post['text'] . ($post['after'] ?? ''), $htmlmode);
180                 $msg = HTML::toPlaintext($html, 0, true);
181                 $msg = trim(html_entity_decode($msg, ENT_QUOTES, 'UTF-8'));
182
183                 $complete_msg = $msg;
184
185                 $link = '';
186                 if ($includedlinks) {
187                         if ($post['type'] == 'link') {
188                                 $link = $post['url'];
189                         } elseif ($post['type'] == 'text') {
190                                 $link = $post['url'] ?? '';
191                         } elseif ($post['type'] == 'video') {
192                                 $link = $post['url'];
193                         } elseif ($post['type'] == 'photo') {
194                                 $link = $post['image'];
195                         }
196
197                         if (($msg == '') && isset($post['title'])) {
198                                 $msg = trim($post['title']);
199                         }
200
201                         if (($msg == '') && isset($post['description'])) {
202                                 $msg = trim($post['description']);
203                         }
204
205                         // If the link is already contained in the post, then it neeedn't to be added again
206                         // But: if the link is beyond the limit, then it has to be added.
207                         if (($link != '') && strstr($msg, $link)) {
208                                 $pos = strpos($msg, $link);
209
210                                 // Will the text be shortened in the link?
211                                 // Or is the link the last item in the post?
212                                 if (($limit > 0) && ($pos < $limit) && (($pos + self::URL_LENGTH > $limit) || ($pos + mb_strlen($link) == mb_strlen($msg)))) {
213                                         $msg = trim(str_replace($link, '', $msg));
214                                 } elseif (($limit == 0) || ($pos < $limit)) {
215                                         // The limit has to be increased since it will be shortened - but not now
216                                         // Only do it with Twitter
217                                         if (($limit > 0) && (mb_strlen($link) > self::URL_LENGTH) && ($htmlmode == BBCode::TWITTER)) {
218                                                 $limit = $limit - self::URL_LENGTH + mb_strlen($link);
219                                         }
220
221                                         $link = '';
222
223                                         if ($post['type'] == 'text') {
224                                                 unset($post['url']);
225                                         }
226                                 }
227                         }
228                 }
229
230                 if ($limit > 0) {
231                         // Reduce multiple spaces
232                         // When posted to a network with limited space, we try to gain space where possible
233                         while (strpos($msg, '  ') !== false) {
234                                 $msg = str_replace('  ', ' ', $msg);
235                         }
236
237                         if (!in_array($link, ['', $item['plink']]) && ($post['type'] != 'photo') && (strpos($complete_msg, $link) === false)) {
238                                 $complete_msg .= "\n" . $link;
239                         }
240
241                         $post['parts'] = self::getParts(trim($complete_msg), $limit);
242
243                         // Twitter is using its own limiter, so we always assume that shortened links will have this length
244                         if (mb_strlen($link) > 0) {
245                                 $limit = $limit - self::URL_LENGTH;
246                         }
247
248                         if (mb_strlen($msg) > $limit) {
249                                 if (($post['type'] == 'text') && isset($post['url'])) {
250                                         $post['url'] = $item['plink'];
251                                 } elseif (!isset($post['url'])) {
252                                         $limit = $limit - self::URL_LENGTH;
253                                         $post['url'] = $item['plink'];
254                                 } elseif (strpos($item['body'], '[share') !== false) {
255                                         $post['url'] = $item['plink'];
256                                 } elseif (DI::pConfig()->get($item['uid'], 'system', 'no_intelligent_shortening')) {
257                                         $post['url'] = $item['plink'];
258                                 }
259                                 $msg = self::shorten($msg, $limit, $item['uid']);
260                         }
261                 }
262
263                 $post['text'] = trim($msg);
264
265                 return $post;
266         }
267
268         /**
269          * Split the message in parts
270          *
271          * @param string  $message
272          * @param integer $baselimit
273          * @return array
274          */
275         private static function getParts(string $message, int $baselimit): array
276         {
277                 $parts = [];
278                 $part = '';
279
280                 $limit = $baselimit;
281
282                 while ($message) {
283                         $pos1 = strpos($message, ' ');
284                         $pos2 = strpos($message, "\n");
285
286                         if (($pos1 !== false) && ($pos2 !== false)) {
287                                 $pos = min($pos1, $pos2) + 1;
288                         } elseif ($pos1 !== false) {
289                                 $pos = $pos1 + 1;
290                         } elseif ($pos2 !== false) {
291                                 $pos = $pos2 + 1;
292                         } else {
293                                 $word = $message;
294                                 $message = '';
295                         }
296
297                         if (trim($message)) {
298                                 $word    = substr($message, 0, $pos);
299                                 $message = trim(substr($message, $pos));
300                         }
301
302                         if (Network::isValidHttpUrl(trim($word))) {
303                                 $limit += mb_strlen(trim($word)) - self::URL_LENGTH;
304                         }
305
306                         if ((mb_strlen($part . $word) > $limit - 8) && (mb_strlen($part . $word . $message) > $limit)) {
307                                 $parts[] = trim($part);
308                                 $part    = '';
309                                 $limit   = $baselimit;
310                         }
311                         $part .= $word;
312                 }
313                 $parts[] = trim($part);
314
315                 if (count($parts) > 1) {
316                         foreach ($parts as $key => $part) {
317                                 $parts[$key] .= ' (' . ($key + 1) . '/' . count($parts) . ')';
318                         }
319                 }
320
321                 return $parts;
322         }
323 }