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;
26 use Friendica\Util\Network;
30 // Assumed length of an URL when shortened via the network's own url shortener (e.g. Twitter)
31 const URL_LENGTH = 23;
41 * @todo For Twitter URLs aren't shortened, but they have to be calculated as if.
43 public static function shorten(string $msg, int $limit, int $uid = 0): string
45 $ellipsis = html_entity_decode("…", ENT_QUOTES, 'UTF-8');
47 if (!empty($uid) && DI::pConfig()->get($uid, 'system', 'simple_shortening')) {
48 return mb_substr(mb_substr(trim($msg), 0, $limit), 0, -3) . $ellipsis;
51 $lines = explode("\n", $msg);
53 $recycle = html_entity_decode("♲ ", 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;
69 * Returns the character positions of the provided boundaries, optionally skipping a number of first occurrences
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
77 public static function getBoundariesPosition($text, $open, $close, $occurrences = 0)
79 if ($occurrences < 0) {
84 for ($i = 0; $i <= $occurrences; $i++) {
85 if ($start_pos !== false) {
86 $start_pos = strpos($text, $open, $start_pos + 1);
90 if ($start_pos === false) {
94 $end_pos = strpos($text, $close, $start_pos);
96 if ($end_pos === false) {
100 $res = ['start' => $start_pos, 'end' => $end_pos];
106 * Convert a message into plaintext for connectors to other networks
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.
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
119 public static function getPost($item, $limit = 0, $includedlinks = false, $htmlmode = BBCode::API, $target_network = '')
122 $URLSearchString = '^\[\]';
123 $body = preg_replace("/([#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1$3', $item['body']);
125 // Add an URL element if the text contains a raw link
126 $body = preg_replace('/([^\]\=\'"]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism',
127 '$1[url]$2[/url]', $body);
129 // Remove the abstract
130 $body = BBCode::stripAbstract($body);
132 // At first look at data that is attached via "type-..." stuff
133 $post = BBCode::getAttachedData($body, $item);
135 if (($item['title'] != '') && ($post['text'] != '')) {
136 $post['text'] = trim($item['title'] . "\n\n" . $post['text']);
137 } elseif ($item['title'] != '') {
138 $post['text'] = trim($item['title']);
143 // Fetch the abstract from the given target network
144 if ($target_network != '') {
145 $default_abstract = BBCode::getAbstract($item['body']);
146 $abstract = BBCode::getAbstract($item['body'], $target_network);
148 // If we post to a network with no limit we only fetch
149 // an abstract exactly for this network
150 if (($limit == 0) && ($abstract == $default_abstract)) {
153 } else {// Try to guess the correct target network
155 case BBCode::TWITTER:
156 $abstract = BBCode::getAbstract($item['body'], Protocol::TWITTER);
159 case BBCode::OSTATUS:
160 $abstract = BBCode::getAbstract($item['body'], Protocol::STATUSNET);
163 default: // We don't know the exact target.
164 // We fetch an abstract since there is a posting limit.
166 $abstract = BBCode::getAbstract($item['body']);
171 if ($abstract != '') {
172 $post['text'] = $abstract;
174 if ($post['type'] == 'text') {
175 $post['type'] = 'link';
176 $post['url'] = $item['plink'];
180 $html = BBCode::convertForUriId($item['uri-id'], $post['text'] . ($post['after'] ?? ''), $htmlmode);
181 $msg = HTML::toPlaintext($html, 0, true);
182 $msg = trim(html_entity_decode($msg, ENT_QUOTES, 'UTF-8'));
184 $complete_msg = $msg;
187 if ($includedlinks) {
188 if ($post['type'] == 'link') {
189 $link = $post['url'];
190 } elseif ($post['type'] == 'text') {
191 $link = $post['url'] ?? '';
192 } elseif ($post['type'] == 'video') {
193 $link = $post['url'];
194 } elseif ($post['type'] == 'photo') {
195 $link = $post['image'];
198 if (($msg == '') && isset($post['title'])) {
199 $msg = trim($post['title']);
202 if (($msg == '') && isset($post['description'])) {
203 $msg = trim($post['description']);
206 // If the link is already contained in the post, then it neeedn't to be added again
207 // But: if the link is beyond the limit, then it has to be added.
208 if (($link != '') && strstr($msg, $link)) {
209 $pos = strpos($msg, $link);
211 // Will the text be shortened in the link?
212 // Or is the link the last item in the post?
213 if (($limit > 0) && ($pos < $limit) && (($pos + self::URL_LENGTH > $limit) || ($pos + mb_strlen($link) == mb_strlen($msg)))) {
214 $msg = trim(str_replace($link, '', $msg));
215 } elseif (($limit == 0) || ($pos < $limit)) {
216 // The limit has to be increased since it will be shortened - but not now
217 // Only do it with Twitter
218 if (($limit > 0) && (mb_strlen($link) > self::URL_LENGTH) && ($htmlmode == BBCode::TWITTER)) {
219 $limit = $limit - self::URL_LENGTH + mb_strlen($link);
224 if ($post['type'] == 'text') {
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 if (!in_array($link, ['', $item['plink']]) && ($post['type'] != 'photo') && (strpos($complete_msg, $link) === false)) {
239 $complete_msg .= "\n" . $link;
242 $post['parts'] = self::getParts(trim($complete_msg), $limit);
244 // Twitter is using its own limiter, so we always assume that shortened links will have this length
245 if (mb_strlen($link) > 0) {
246 $limit = $limit - self::URL_LENGTH;
249 if (mb_strlen($msg) > $limit) {
250 if (($post['type'] == 'text') && isset($post['url'])) {
251 $post['url'] = $item['plink'];
252 } elseif (!isset($post['url'])) {
253 $limit = $limit - self::URL_LENGTH;
254 $post['url'] = $item['plink'];
255 } elseif (strpos($item['body'], '[share') !== false) {
256 $post['url'] = $item['plink'];
257 } elseif (DI::pConfig()->get($item['uid'], 'system', 'no_intelligent_shortening')) {
258 $post['url'] = $item['plink'];
260 $msg = self::shorten($msg, $limit, $item['uid']);
264 $post['text'] = trim($msg);
270 * Split the message in parts
272 * @param string $message
273 * @param integer $baselimit
276 private static function getParts(string $message, int $baselimit): array
284 $pos1 = strpos($message, ' ');
285 $pos2 = strpos($message, "\n");
287 if (($pos1 !== false) && ($pos2 !== false)) {
288 $pos = min($pos1, $pos2) + 1;
289 } elseif ($pos1 !== false) {
291 } elseif ($pos2 !== false) {
298 if (trim($message)) {
299 $word = substr($message, 0, $pos);
300 $message = trim(substr($message, $pos));
303 if (Network::isValidHttpUrl(trim($word))) {
304 $limit += mb_strlen(trim($word)) - self::URL_LENGTH;
307 if ((mb_strlen($part . $word) > $limit - 8) && (mb_strlen($part . $word . $message) > $limit)) {
308 $parts[] = trim($part);
314 $parts[] = trim($part);
316 if (count($parts) > 1) {
317 foreach ($parts as $key => $part) {
318 $parts[$key] .= ' (' . ($key + 1) . '/' . count($parts) . ')';