.
*
*/
namespace Friendica\Content\Text;
use DOMDocument;
use DOMXPath;
use Exception;
use Friendica\Content\ContactSelector;
use Friendica\Content\Item;
use Friendica\Content\OEmbed;
use Friendica\Content\PageInfo;
use Friendica\Content\Smilies;
use Friendica\Core\Hook;
use Friendica\Core\Logger;
use Friendica\Core\Protocol;
use Friendica\Core\Renderer;
use Friendica\DI;
use Friendica\Model\Contact;
use Friendica\Model\Event;
use Friendica\Model\Post;
use Friendica\Model\Tag;
use Friendica\Network\HTTPClient\Client\HttpClientAccept;
use Friendica\Network\HTTPClient\Client\HttpClientOptions;
use Friendica\Util\Map;
use Friendica\Util\ParseUrl;
use Friendica\Util\Proxy;
use Friendica\Util\Strings;
use Friendica\Util\XML;
class BBCode
{
// Update this value to the current date whenever changes are made to BBCode::convert
const VERSION = '2021-07-28';
const INTERNAL = 0;
const EXTERNAL = 1;
const MASTODON_API = 2;
const DIASPORA = 3;
const CONNECTORS = 4;
const TWITTER_API = 5;
const NPF = 6;
const OSTATUS = 7;
const TWITTER = 8;
const BACKLINK = 8;
const ACTIVITYPUB = 9;
const BLUESKY = 10;
const SHARED_ANCHOR = '
';
const TOP_ANCHOR = ' ';
const BOTTOM_ANCHOR = ' ';
const PREVIEW_NONE = 0;
const PREVIEW_NO_IMAGE = 1;
const PREVIEW_LARGE = 2;
const PREVIEW_SMALL = 3;
/**
* Fetches attachment data that were generated with the "attachment" element
*
* @param string $body Message body
* @return array
* 'type' -> Message type ('link', 'video', 'photo')
* 'text' -> Text before the shared message
* 'after' -> Text after the shared message
* 'image' -> Preview image of the message
* 'url' -> Url to the attached message
* 'title' -> Title of the attachment
* 'description' -> Description of the attachment
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function getAttachmentData(string $body): array
{
DI::profiler()->startRecording('rendering');
$data = [
'type' => '',
'text' => '',
'after' => '',
'image' => null,
'url' => '',
'author_name' => '',
'author_url' => '',
'provider_name' => '',
'provider_url' => '',
'title' => '',
'description' => '',
];
if (!preg_match("/(.*)\[attachment(.*?)\](.*?)\[\/attachment\](.*)/ism", $body, $match)) {
DI::profiler()->stopRecording();
return [];
}
$attributes = $match[2];
$data['text'] = trim($match[1]);
foreach (['type', 'url', 'title', 'image', 'preview', 'publisher_name', 'publisher_url', 'author_name', 'author_url'] as $field) {
preg_match('/' . preg_quote($field, '/') . '=("|\')(.*?)\1/ism', $attributes, $matches);
$value = $matches[2] ?? '';
if ($value != '') {
switch ($field) {
case 'publisher_name':
$data['provider_name'] = html_entity_decode($value, ENT_QUOTES, 'UTF-8');
break;
case 'publisher_url':
$data['provider_url'] = html_entity_decode($value, ENT_QUOTES, 'UTF-8');
break;
case 'author_name':
$data['author_name'] = html_entity_decode($value, ENT_QUOTES, 'UTF-8');
if ($data['provider_name'] == $data['author_name']) {
$data['author_name'] = '';
}
break;
case 'author_url':
$data['author_url'] = html_entity_decode($value, ENT_QUOTES, 'UTF-8');
if ($data['provider_url'] == $data['author_url']) {
$data['author_url'] = '';
}
break;
case 'title':
$value = self::toPlaintext(html_entity_decode($value, ENT_QUOTES, 'UTF-8'));
$value = html_entity_decode($value, ENT_QUOTES, 'UTF-8');
$value = str_replace(['[', ']'], ['[', ']'], $value);
$data['title'] = $value;
default:
$data[$field] = html_entity_decode($value, ENT_QUOTES, 'UTF-8');
break;
}
}
}
if (!in_array($data['type'], ['link', 'audio', 'photo', 'video'])) {
DI::profiler()->stopRecording();
return [];
}
$data['description'] = trim($match[3]);
$data['after'] = trim($match[4]);
$parts = parse_url($data['url']);
if (!empty($parts['scheme']) && !empty($parts['host'])) {
if (empty($data['provider_name'])) {
$data['provider_name'] = $parts['host'];
}
if (empty($data['provider_url']) || empty(parse_url($data['provider_url'], PHP_URL_SCHEME))) {
$data['provider_url'] = $parts['scheme'] . '://' . $parts['host'];
if (!empty($parts['port'])) {
$data['provider_url'] .= ':' . $parts['port'];
}
}
}
DI::profiler()->stopRecording();
return $data;
}
/**
* Remove [attachment] BBCode and replaces it with a regular [url]
*
* @param string $body
* @param boolean $no_link_desc No link description
* @return string with replaced body
*/
public static function replaceAttachment(string $body, bool $no_link_desc = false): string
{
return preg_replace_callback(
"/\s*\[attachment (.*?)\](.*?)\[\/attachment\]\s*/ism",
function ($match) use ($body, $no_link_desc) {
$attach_data = self::getAttachmentData($match[0]);
if (empty($attach_data['url'])) {
return $match[0];
} elseif (strpos(str_replace($match[0], '', $body), $attach_data['url']) !== false) {
return '';
} elseif (empty($attach_data['title']) || $no_link_desc) {
return " \n[url]" . $attach_data['url'] . "[/url]\n";
} else {
return " \n[url=" . $attach_data['url'] . ']' . $attach_data['title'] . "[/url]\n";
}
},
$body
);
}
/**
* Remove [attachment] BBCode
*
* @param string $body
* @return string with removed attachment
*/
public static function removeAttachment(string $body): string
{
return trim(preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body));
}
/**
* Converts a BBCode text into plaintext
*
* @param string $text
* @param bool $keep_urls Whether to keep URLs in the resulting plaintext
* @return string
*/
public static function toPlaintext(string $text, bool $keep_urls = true): string
{
DI::profiler()->startRecording('rendering');
// Remove pictures in advance to avoid unneeded proxy calls
$text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", ' ', $text);
$text = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", ' $2 ', $text);
$text = preg_replace("/\[img.*?\[\/img\]/ism", ' ', $text);
// Remove attachment
$text = self::replaceAttachment($text);
$naked_text = HTML::toPlaintext(self::convert($text, false, self::EXTERNAL, true), 0, !$keep_urls);
DI::profiler()->stopRecording();
return $naked_text;
}
/**
* Converts text into a format that can be used for the channel search and the language detection.
*
* @param string $text
* @param integer $uri_id
* @return string
*/
public static function toSearchText(string $text, int $uri_id): string
{
// Removes attachments
$text = self::removeAttachment($text);
// Add images because of possible alt texts
if (!empty($uri_id)) {
$text = Post\Media::addAttachmentsToBody($uri_id, $text, [Post\Media::IMAGE]);
}
if (empty($text)) {
return '';
}
// Remove links without a link description
$text = preg_replace("~\[url\=.*\]https?:.*\[\/url\]~", ' ', $text);
// Remove pictures
$text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", ' ', $text);
// Replace picture with the alt description
$text = preg_replace("/\[img\=.*?\](.*?)\[\/img\]/ism", ' $1 ', $text);
// Remove the other pictures
$text = preg_replace("/\[img.*?\[\/img\]/ism", ' ', $text);
// Removes mentions, remove links from hashtags
$text = preg_replace('/[@!]\[url\=.*?\].*?\[\/url\]/ism', ' ', $text);
$text = preg_replace('/[#]\[url\=.*?\](.*?)\[\/url\]/ism', ' #$1 ', $text);
$text = preg_replace('/[@!#]?\[url.*?\[\/url\]/ism', ' ', $text);
$text = preg_replace("/\[url=[^\[\]]*\](.*)\[\/url\]/Usi", ' $1 ', $text);
// Convert it to plain text
$text = self::toPlaintext($text, false);
// Remove possibly remaining links
$text = preg_replace(Strings::autoLinkRegEx(), '', $text);
// Remove all unneeded white space
do {
$oldtext = $text;
$text = str_replace([' ', "\n", "\r", '"'], ' ', $text);
} while ($oldtext != $text);
return trim($text);
}
private static function proxyUrl(string $image, int $simplehtml = self::INTERNAL, int $uriid = 0, string $size = ''): string
{
// Only send proxied pictures to API and for internal display
if (!in_array($simplehtml, [self::INTERNAL, self::MASTODON_API, self::TWITTER_API])) {
return $image;
} elseif ($uriid > 0) {
return Post\Link::getByLink($uriid, $image, $size);
} else {
return Proxy::proxifyUrl($image, $size);
}
}
/**
* Truncates imported message body string length to max_import_size
*
* The purpose of this function is to apply system message length limits to
* imported messages without including any embedded photos in the length
*
* @param string $body
* @return string
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function limitBodySize(string $body): string
{
DI::profiler()->startRecording('rendering');
$maxlen = DI::config()->get('config', 'max_import_size', 0);
// If the length of the body, including the embedded images, is smaller
// than the maximum, then don't waste time looking for the images
if ($maxlen && (strlen($body) > $maxlen)) {
Logger::info('the total body length exceeds the limit', ['maxlen' => $maxlen, 'body_len' => strlen($body)]);
$orig_body = $body;
$new_body = '';
$textlen = 0;
$img_start = strpos($orig_body, '[img');
$img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
$img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
while (($img_st_close !== false) && ($img_end !== false)) {
$img_st_close++; // make it point to AFTER the closing bracket
$img_end += $img_start;
$img_end += strlen('[/img]');
if (!strcmp(substr($orig_body, $img_start + $img_st_close, 5), 'data:')) {
// This is an embedded image
if (($textlen + $img_start) > $maxlen) {
if ($textlen < $maxlen) {
Logger::debug('the limit happens before an embedded image');
$new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
$textlen = $maxlen;
}
} else {
$new_body = $new_body . substr($orig_body, 0, $img_start);
$textlen += $img_start;
}
$new_body = $new_body . substr($orig_body, $img_start, $img_end - $img_start);
} else {
if (($textlen + $img_end) > $maxlen) {
if ($textlen < $maxlen) {
Logger::debug('the limit happens before the end of a non-embedded image');
$new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
$textlen = $maxlen;
}
} else {
$new_body = $new_body . substr($orig_body, 0, $img_end);
$textlen += $img_end;
}
}
$orig_body = substr($orig_body, $img_end);
if ($orig_body === false) {
// in case the body ends on a closing image tag
$orig_body = '';
}
$img_start = strpos($orig_body, '[img');
$img_st_close = ($img_start !== false ? strpos(substr($orig_body, $img_start), ']') : false);
$img_end = ($img_start !== false ? strpos(substr($orig_body, $img_start), '[/img]') : false);
}
if (($textlen + strlen($orig_body)) > $maxlen) {
if ($textlen < $maxlen) {
Logger::debug('the limit happens after the end of the last image');
$new_body = $new_body . substr($orig_body, 0, $maxlen - $textlen);
}
} else {
Logger::debug('the text size with embedded images extracted did not violate the limit');
$new_body = $new_body . $orig_body;
}
DI::profiler()->stopRecording();
return $new_body;
} else {
DI::profiler()->stopRecording();
return $body;
}
}
/**
* Processes [attachment] tags
*
* Note: Can produce a [bookmark] tag in the returned string
*
* @param string $text
* @param integer $simplehtml
* @param bool $tryoembed
* @param array $data
* @param int $uriid
* @return string
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function convertAttachment(string $text, int $simplehtml = self::INTERNAL, bool $tryoembed = true, array $data = [], int $uriid = 0, int $preview_mode = self::PREVIEW_LARGE): string
{
DI::profiler()->startRecording('rendering');
$data = $data ?: self::getAttachmentData($text);
if (empty($data) || empty($data['url'])) {
DI::profiler()->stopRecording();
return $text;
}
if (isset($data['title'])) {
$data['title'] = strip_tags($data['title']);
$data['title'] = str_replace(['http://', 'https://'], '', $data['title']);
} else {
$data['title'] = '';
}
if (((strpos($data['text'], '[img=') !== false) || (strpos($data['text'], '[img]') !== false) || DI::config()->get('system', 'always_show_preview')) && !empty($data['image'])) {
$data['preview'] = $data['image'];
$data['image'] = '';
}
$return = '';
try {
if ($tryoembed && OEmbed::isAllowedURL($data['url'])) {
$return = OEmbed::getHTML($data['url'], $data['title']);
} else {
throw new Exception('OEmbed is disabled for this attachment.');
}
} catch (Exception $e) {
$data['title'] = ($data['title'] ?? '') ?: $data['url'];
if ($simplehtml != self::CONNECTORS) {
$return = sprintf('
';
} else {
$return = '' . htmlentities($matches[2], ENT_NOQUOTES, 'UTF-8') . '';
}
return $return;
},
$text
);
// Default iframe allowed domains/path
$allowedIframeDomains = [
DI::baseUrl()->getHost()
. (DI::baseUrl()->getPath() ? '/' . DI::baseUrl()->getPath() : '')
. '/oembed/', # The path part has to change with the source in Content\Oembed::iframe
'www.youtube.com/embed/',
'player.vimeo.com/video/',
];
$allowedIframeDomains = array_merge(
$allowedIframeDomains,
DI::config()->get('system', 'allowed_oembed') ?
explode(',', DI::config()->get('system', 'allowed_oembed'))
: []
);
if (strpos($text, '
') !== false || strpos($text, '
') !== false) {
$text = '
' . $text . '
';
}
$text = HTML::purify($text, $allowedIframeDomains);
DI::profiler()->stopRecording();
return trim($text);
}
/**
* Strips the "abstract" tag from the provided text
*
* @param string $text The text with BBCode
* @return string The same text - but without "abstract" element
*/
public static function stripAbstract(string $text): string
{
DI::profiler()->startRecording('rendering');
$text = self::performWithEscapedTags($text, ['code', 'noparse', 'nobb', 'pre'], function ($text) {
$text = preg_replace("/[\s|\n]*\[abstract\].*?\[\/abstract\][\s|\n]*/ism", ' ', $text);
$text = preg_replace("/[\s|\n]*\[abstract=.*?\].*?\[\/abstract][\s|\n]*/ism", ' ', $text);
return $text;
});
DI::profiler()->stopRecording();
return $text;
}
/**
* Returns the value of the "abstract" element
*
* @param string $text The text that maybe contains the element
* @param string $addon The addon for which the abstract is meant for
* @return string The abstract
*/
public static function getAbstract(string $text, string $addon = ''): string
{
DI::profiler()->startRecording('rendering');
$addon = strtolower($addon);
$abstract = self::performWithEscapedTags($text, ['code', 'noparse', 'nobb', 'pre'], function ($text) use ($addon) {
if ($addon && preg_match('#\[abstract=' . preg_quote($addon, '#') . '](.*?)\[/abstract]#ism', $text, $matches)) {
return $matches[1];
}
if (preg_match("#\[abstract](.*?)\[/abstract]#ism", $text, $matches)) {
return $matches[1];
}
return '';
});
DI::profiler()->stopRecording();
return $abstract;
}
/**
* Callback function to replace a Friendica style mention in a mention for Diaspora
*
* @param array $match Matching values for the callback
* [1] = Mention type (! or @)
* [2] = Name
* [3] = Address
* @return string Replaced mention
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
private static function bbCodeMention2DiasporaCallback(array $match): string
{
$contact = Contact::getByURL($match[3], false, ['addr']);
if (empty($contact['addr'])) {
return $match[0];
}
$mention = $match[1] . '{' . $match[2] . '; ' . $contact['addr'] . '}';
return $mention;
}
/**
* Converts a BBCode text into Markdown
*
* This function converts a BBCode item body to be sent to Markdown-enabled
* systems like Diaspora and Libertree
*
* @param string $text
* @param bool $for_diaspora Diaspora requires more changes than Libertree
* @return string
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
public static function toMarkdown(string $text, bool $for_diaspora = true): string
{
DI::profiler()->startRecording('rendering');
$original_text = $text;
// Since Diaspora is creating a summary for links, this function removes them before posting
if ($for_diaspora) {
$text = self::removeShareInformation($text);
}
/**
* Transform #tags, strip off the [url] and replace spaces with underscore
*/
$url_search_string = "^\[\]";
$text = preg_replace_callback(
"/#\[url\=([$url_search_string]*)\](.*?)\[\/url\]/i",
function ($matches) {
return '#' . str_replace(' ', '_', $matches[2]);
},
$text
);
// Converting images with size parameters to simple images. Markdown doesn't know it.
$text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
// Convert it to HTML - don't try oembed
if ($for_diaspora) {
$text = self::convertForUriId(0, $text, self::DIASPORA);
// Add all tags that maybe were removed
if (preg_match_all("/#\[url\=([$url_search_string]*)\](.*?)\[\/url\]/ism", $original_text, $tags)) {
$tagline = '';
foreach ($tags[2] as $tag) {
$tag = html_entity_decode($tag, ENT_QUOTES, 'UTF-8');
if (!strpos(html_entity_decode($text, ENT_QUOTES, 'UTF-8'), '#' . $tag)) {
$tagline .= '#' . $tag . ' ';
}
}
$text = $text . ' ' . $tagline;
}
} else {
$text = self::convertForUriId(0, $text, self::CONNECTORS);
}
// If a link is followed by a quote then there should be a newline before it
// Maybe we should make this newline at every time before a quote.
$text = str_replace(['
'], ['
'], $text);
// The converter doesn't convert these elements
$text = str_replace(['
', '
'], ['
', '
'], $text);
// Now convert HTML to Markdown
$text = HTML::toMarkdown($text);
// Libertree has a problem with escaped hashtags.
$text = str_replace(['\#'], ['#'], $text);
// Remove any leading or trailing whitespace, as this will mess up
// the Diaspora signature verification and cause the item to disappear
$text = trim($text);
if ($for_diaspora) {
$url_search_string = "^\[\]";
$text = preg_replace_callback(
"/([@!])\[(.*?)\]\(([$url_search_string]*?)\)/ism",
[self::class, 'bbCodeMention2DiasporaCallback'],
$text
);
}
Hook::callAll('bb2diaspora', $text);
DI::profiler()->stopRecording();
return $text;
}
/**
* Pull out all #hashtags and @person tags from $string.
*
* We also get @person@domain.com - which would make
* the regex quite complicated as tags can also
* end a sentence. So we'll run through our results
* and strip the period from any tags which end with one.
* Returns array of tags found, or empty array.
*
* @param string $string Post content
* @return array List of tag and person names
*/
public static function getTags(string $string): array
{
DI::profiler()->startRecording('rendering');
$ret = [];
self::performWithEscapedTags($string, ['noparse', 'pre', 'code', 'img', 'attachment'], function ($string) use (&$ret) {
// Convert hashtag links to hashtags
$string = preg_replace('/#\[url\=([^\[\]]*)\](.*?)\[\/url\]/ism', '#$2 ', $string);
// Force line feeds at bbtags
$string = str_replace(['[', ']'], ["\n[", "]\n"], $string);
// ignore anything in a bbtag
$string = preg_replace('/\[(.*?)\]/sm', '', $string);
// Match full names against @tags including the space between first and last
// We will look these up afterward to see if they are full names or not recognisable.
if (preg_match_all('/(@[^ \x0D\x0A,:?]+ [^ \x0D\x0A@,:?]+)([ \x0D\x0A@,:?]|$)/', $string, $matches)) {
foreach ($matches[1] as $match) {
if (strstr($match, ']')) {
// we might be inside a bbcode color tag - leave it alone
continue;
}
if (substr($match, -1, 1) === '.') {
$ret[] = substr($match, 0, -1);
} else {
$ret[] = $match;
}
}
}
// Otherwise pull out single word tags. These can be @nickname, @first_last
// and #hash tags.
if (preg_match_all('/([!#@][^\^ \x0D\x0A,;:?\']*[^\^ \x0D\x0A,;:?!\'.])/', $string, $matches)) {
foreach ($matches[1] as $match) {
if (strstr($match, ']')) {
// we might be inside a bbcode color tag - leave it alone
continue;
}
// try not to catch url fragments
if (strpos($string, $match) && preg_match('/[a-zA-z0-9\/]/', substr($string, strpos($string, $match) - 1, 1))) {
continue;
}
$ret[] = $match;
}
}
});
DI::profiler()->stopRecording();
return array_unique($ret);
}
/**
* Expand tags to URLs, checks the tag is at the start of a line or preceded by a non-word character
*
* @param string $body HTML/BBCode
* @return string body with expanded tags
*/
public static function expandTags(string $body): string
{
return preg_replace_callback(
"/(?<=\W|^)([!#@])([^\^ \x0D\x0A,;:?'\"]*[^\^ \x0D\x0A,;:?!'\".])/",
function (array $match) {
switch ($match[1]) {
case '!':
case '@':
$contact = Contact::getByURL($match[2]);
if (!empty($contact)) {
return $match[1] . '[url=' . $contact['url'] . ']' . $contact['name'] . '[/url]';
} else {
return $match[1] . $match[2];
}
break;
case '#':
default:
return $match[1] . '[url=' . DI::baseUrl() . '/search?tag=' . $match[2] . ']' . $match[2] . '[/url]';
}
},
$body
);
}
/**
* Perform a custom function on a text after having escaped blocks enclosed in the provided tag list.
*
* @param string $text HTML/BBCode
* @param array $tagList A list of tag names, e.g ['noparse', 'nobb', 'pre']
* @param callable $callback
* @return string
* @see Strings::performWithEscapedBlocks
*/
public static function performWithEscapedTags(string $text, array $tagList, callable $callback): string
{
$tagList = array_map('preg_quote', $tagList);
return Strings::performWithEscapedBlocks($text, '#\[(?:' . implode('|', $tagList) . ').*?\[/(?:' . implode('|', $tagList) . ')]#ism', $callback);
}
/**
* Replaces mentions in the provided message body in BBCode links for the provided user and network if any
*
* @param string $body HTML/BBCode
* @param int $profile_uid Profile user id
* @param string $network Network name
* @return string HTML/BBCode with inserted images
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @throws \ImagickException
*/
public static function setMentions(string $body, $profile_uid = 0, $network = '')
{
DI::profiler()->startRecording('rendering');
$body = self::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) use ($profile_uid, $network) {
$tags = self::getTags($body);
$tagged = [];
foreach ($tags as $tag) {
$tag_type = substr($tag, 0, 1);
if ($tag_type == Tag::TAG_CHARACTER[Tag::HASHTAG]) {
continue;
}
/*
* If we already tagged 'Robert Johnson', don't try and tag 'Robert'.
* Robert Johnson should be first in the $tags array
*/
foreach ($tagged as $nextTag) {
if (stristr($nextTag, $tag . ' ')) {
continue 2;
}
}
if (($success = Item::replaceTag($body, $profile_uid, $tag, $network)) && $success['replaced']) {
$tagged[] = $tag;
}
}
return $body;
});
DI::profiler()->stopRecording();
return $body;
}
/**
* @param string $author Author display name
* @param string $profile Author profile URL
* @param string $avatar Author profile picture URL
* @param string $link Post source URL
* @param string $posted Post created date
* @param string|null $guid Post guid (if any)
* @param string|null $uri Post uri (if any)
* @return string
* @TODO Rewrite to handle over whole record array
*/
public static function getShareOpeningTag(string $author, string $profile, string $avatar, string $link, string $posted, string $guid = null, string $uri = null): string
{
DI::profiler()->startRecording('rendering');
$header = "[share author='" . str_replace(["'", "[", "]"], ["'", "[", "]"], $author) .
"' profile='" . str_replace(["'", "[", "]"], ["'", "[", "]"], $profile) .
"' avatar='" . str_replace(["'", "[", "]"], ["'", "[", "]"], $avatar) .
"' link='" . str_replace(["'", "[", "]"], ["'", "[", "]"], $link) .
"' posted='" . str_replace(["'", "[", "]"], ["'", "[", "]"], $posted);
if ($guid) {
$header .= "' guid='" . str_replace(["'", "[", "]"], ["'", "[", "]"], $guid);
}
if ($uri) {
$header .= "' message_id='" . str_replace(["'", "[", "]"], ["'", "[", "]"], $uri);
}
$header .= "']";
DI::profiler()->stopRecording();
return $header;
}
/**
* Returns the BBCode relevant to embed the provided URL in a post body.
* For media type, it will return [img], [video] and [audio] tags.
* For regular web pages, it will either output a [bookmark] tag if title and description were provided,
* an [attachment] tag or a simple [url] tag depending on $tryAttachment.
*
* @param string $url
* @param bool $tryAttachment
* @param string|null $title
* @param string|null $description
* @param string|null $tags
* @return string
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
* @see ParseUrl::getSiteinfoCached
*/
public static function embedURL(string $url, bool $tryAttachment = true, string $title = null, string $description = null, string $tags = null): string
{
DI::profiler()->startRecording('rendering');
DI::logger()->info($url);
// If there is already some content information submitted we don't
// need to parse the url for content.
if (!empty($title) && !empty($description)) {
$title = str_replace(["\r", "\n"], ['', ''], $title);
$description = '[quote]' . trim($description) . '[/quote]' . "\n";
$str_tags = '';
if (!empty($tags)) {
$arr_tags = ParseUrl::convertTagsToArray($tags);
if (count($arr_tags)) {
$str_tags = "\n" . implode(' ', $arr_tags) . "\n";
}
}
$result = sprintf('[bookmark=%s]%s[/bookmark]%s', $url, ($title) ? $title : $url, $description) . $str_tags;
DI::logger()->info('(unparsed): returns: ' . $result);
DI::profiler()->stopRecording();
return $result;
}
$siteinfo = ParseUrl::getSiteinfoCached($url);
if (in_array($siteinfo['type'], ['image', 'video', 'audio'])) {
switch ($siteinfo['type']) {
case 'video':
$bbcode = "\n" . '[video]' . $url . '[/video]' . "\n";
break;
case 'audio':
$bbcode = "\n" . '[audio]' . $url . '[/audio]' . "\n";
break;
default:
$bbcode = "\n" . '[img]' . $url . '[/img]' . "\n";
break;
}
DI::profiler()->stopRecording();
return $bbcode;
}
unset($siteinfo['keywords']);
// Bypass attachment if parse url for a comment
if (!$tryAttachment) {
DI::profiler()->stopRecording();
return "\n" . '[url=' . $url . ']' . ($siteinfo['title'] ?? $url) . '[/url]';
}
// Format it as BBCode attachment
$bbcode = "\n" . PageInfo::getFooterFromData($siteinfo);
DI::profiler()->stopRecording();
return $bbcode;
}
}