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