3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Content\Text;
24 use Friendica\Core\Protocol;
37 * @todo For Twitter URLs aren't shortened, but they have to be calculated as if.
39 public static function shorten(string $msg, int $limit, int $uid = 0): string
41 $ellipsis = html_entity_decode("…", ENT_QUOTES, 'UTF-8');
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;
47 $lines = explode("\n", $msg);
49 $recycle = html_entity_decode("♲ ", 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;
65 * Returns the character positions of the provided boundaries, optionally skipping a number of first occurrences
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
73 public static function getBoundariesPosition($text, $open, $close, $occurrences = 0)
75 if ($occurrences < 0) {
80 for ($i = 0; $i <= $occurrences; $i++) {
81 if ($start_pos !== false) {
82 $start_pos = strpos($text, $open, $start_pos + 1);
86 if ($start_pos === false) {
90 $end_pos = strpos($text, $close, $start_pos);
92 if ($end_pos === false) {
96 $res = ['start' => $start_pos, 'end' => $end_pos];
102 * Convert a message into plaintext for connectors to other networks
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.
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
115 public static function getPost($item, $limit = 0, $includedlinks = false, $htmlmode = BBCode::API, $target_network = '')
118 $URLSearchString = '^\[\]';
119 $body = preg_replace("/([#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $item['body']);
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);
125 // Remove the abstract
126 $body = BBCode::stripAbstract($body);
128 // At first look at data that is attached via "type-..." stuff
129 // This will hopefully replaced with a dedicated bbcode later
130 //$post = self::getAttachedData($b['body']);
131 $post = BBCode::getAttachedData($body, $item);
133 if (($item['title'] != '') && ($post['text'] != '')) {
134 $post['text'] = trim($item['title'] . "\n\n" . $post['text']);
135 } elseif ($item['title'] != '') {
136 $post['text'] = trim($item['title']);
141 // Fetch the abstract from the given target network
142 if ($target_network != '') {
143 $default_abstract = BBCode::getAbstract($item['body']);
144 $abstract = BBCode::getAbstract($item['body'], $target_network);
146 // If we post to a network with no limit we only fetch
147 // an abstract exactly for this network
148 if (($limit == 0) && ($abstract == $default_abstract)) {
151 } else {// Try to guess the correct target network
153 case BBCode::TWITTER:
154 $abstract = BBCode::getAbstract($item['body'], Protocol::TWITTER);
157 case BBCode::OSTATUS:
158 $abstract = BBCode::getAbstract($item['body'], Protocol::STATUSNET);
161 default: // We don't know the exact target.
162 // We fetch an abstract since there is a posting limit.
164 $abstract = BBCode::getAbstract($item['body']);
169 if ($abstract != '') {
170 $post['text'] = $abstract;
172 if ($post['type'] == 'text') {
173 $post['type'] = 'link';
174 $post['url'] = $item['plink'];
178 $html = BBCode::convertForUriId($item['uri-id'], $post['text'] . ($post['after'] ?? ''), $htmlmode);
179 $msg = HTML::toPlaintext($html, 0, true);
180 $msg = trim(html_entity_decode($msg, ENT_QUOTES, 'UTF-8'));
182 $complete_msg = $msg;
185 if ($includedlinks) {
186 if ($post['type'] == 'link') {
187 $link = $post['url'];
188 } elseif ($post['type'] == 'text') {
189 $link = $post['url'] ?? '';
190 } elseif ($post['type'] == 'video') {
191 $link = $post['url'];
192 } elseif ($post['type'] == 'photo') {
193 $link = $post['image'];
196 if (($msg == '') && isset($post['title'])) {
197 $msg = trim($post['title']);
200 if (($msg == '') && isset($post['description'])) {
201 $msg = trim($post['description']);
204 // If the link is already contained in the post, then it neeedn't to be added again
205 // But: if the link is beyond the limit, then it has to be added.
206 if (($link != '') && strstr($msg, $link)) {
207 $pos = strpos($msg, $link);
209 // Will the text be shortened in the link?
210 // Or is the link the last item in the post?
211 if (($limit > 0) && ($pos < $limit) && (($pos + 23 > $limit) || ($pos + strlen($link) == strlen($msg)))) {
212 $msg = trim(str_replace($link, '', $msg));
213 } elseif (($limit == 0) || ($pos < $limit)) {
214 // The limit has to be increased since it will be shortened - but not now
215 // Only do it with Twitter
216 if (($limit > 0) && (strlen($link) > 23) && ($htmlmode == BBCode::TWITTER)) {
217 $limit = $limit - 23 + strlen($link);
222 if ($post['type'] == 'text') {
226 } elseif ($link != '') {
227 $complete_msg .= "\n" . $link;
232 // Reduce multiple spaces
233 // When posted to a network with limited space, we try to gain space where possible
234 while (strpos($msg, ' ') !== false) {
235 $msg = str_replace(' ', ' ', $msg);
238 // Twitter is using its own limiter, so we always assume that shortened links will have this length
239 if (iconv_strlen($link, 'UTF-8') > 0) {
240 $limit = $limit - 23;
243 if (iconv_strlen($msg, 'UTF-8') > $limit) {
244 if (($post['type'] == 'text') && isset($post['url'])) {
245 $post['url'] = $item['plink'];
246 } elseif (!isset($post['url'])) {
247 $limit = $limit - 23;
248 $post['url'] = $item['plink'];
249 } elseif (strpos($item['body'], '[share') !== false) {
250 $post['url'] = $item['plink'];
251 } elseif (DI::pConfig()->get($item['uid'], 'system', 'no_intelligent_shortening')) {
252 $post['url'] = $item['plink'];
254 $msg = self::shorten($msg, $limit, $item['uid']);
259 $post['parts'] = self::getParts(trim($complete_msg), $limit);
262 $post['text'] = trim($msg);
268 * Split the message in parts
270 * @param string $message
271 * @param integer $limit
274 private static function getParts(string $message, int $limit): array
279 while (trim($message)) {
280 $pos1 = strpos($message, ' ');
281 $pos2 = strpos($message, "\n");
283 if (($pos1 !== false) && ($pos2 !== false)) {
284 $pos = min($pos1, $pos2) + 1;
285 } elseif ($pos1 !== false) {
287 } elseif ($pos2 !== false) {
294 if (trim($message)) {
295 $word = substr($message, 0, $pos);
296 $message = trim(substr($message, $pos));
299 if (strlen($part . $word) > ($limit - 8)) {
300 $parts[] = trim($part);
307 if (count($parts) > 1) {
308 foreach ($parts as $key => $part) {
309 $parts[$key] .= ' (' . ($key + 1) . '/' . count($parts) . ')';