X-Git-Url: https://git.mxchange.org/?a=blobdiff_plain;f=src%2FContent%2FText%2FBBCode.php;h=5a2b966dd57c2ce6501522409e111e84d9c263ed;hb=7fb9e1c7c8f5f4887e44aadf6115b68c6cc66d03;hp=af423a676a6d698ee81120828aa349c9f1a1469c;hpb=cac038639d9deb44ae07ed171037bcdf80ae3c1c;p=friendica.git
diff --git a/src/Content/Text/BBCode.php b/src/Content/Text/BBCode.php
index af423a676a..5a2b966dd5 100644
--- a/src/Content/Text/BBCode.php
+++ b/src/Content/Text/BBCode.php
@@ -37,7 +37,9 @@ use Friendica\DI;
use Friendica\Model\Contact;
use Friendica\Model\Event;
use Friendica\Model\Photo;
+use Friendica\Model\Post;
use Friendica\Model\Tag;
+use Friendica\Network\HTTPClientOptions;
use Friendica\Object\Image;
use Friendica\Protocol\Activity;
use Friendica\Util\Images;
@@ -50,7 +52,7 @@ use Friendica\Util\XML;
class BBCode
{
// Update this value to the current date whenever changes are made to BBCode::convert
- const VERSION = '2021-05-01';
+ const VERSION = '2021-07-28';
const INTERNAL = 0;
const EXTERNAL = 1;
@@ -151,6 +153,7 @@ class BBCode
*/
public static function getAttachmentData($body)
{
+ DI::profiler()->startRecording('rendering');
$data = [
'type' => '',
'text' => '',
@@ -166,6 +169,7 @@ class BBCode
];
if (!preg_match("/(.*)\[attachment(.*?)\](.*?)\[\/attachment\](.*)/ism", $body, $match)) {
+ DI::profiler()->stopRecording();
return self::getOldAttachmentData($body);
}
@@ -210,6 +214,7 @@ class BBCode
}
if (!in_array($data['type'], ['link', 'audio', 'photo', 'video'])) {
+ DI::profiler()->stopRecording();
return [];
}
@@ -231,6 +236,7 @@ class BBCode
}
}
+ DI::profiler()->stopRecording();
return $data;
}
@@ -246,12 +252,13 @@ class BBCode
- (thumbnail)
*/
+ DI::profiler()->startRecording('rendering');
$has_title = !empty($item['title']);
$plink = $item['plink'] ?? '';
$post = self::getAttachmentData($body);
// Get all linked images with alternative image description
- if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
+ if (preg_match_all("/\[img=(http[^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
foreach ($pictures as $picture) {
if (Photo::isLocal($picture[1])) {
$post['images'][] = ['url' => str_replace('-1.', '-0.', $picture[1]), 'description' => $picture[2]];
@@ -397,6 +404,7 @@ class BBCode
}
}
+ DI::profiler()->stopRecording();
return $post;
}
@@ -416,9 +424,9 @@ class BBCode
if (empty($attach_data['url'])) {
return $match[0];
} elseif (empty($attach_data['title']) || $no_link_desc) {
- return "\n[url]" . $attach_data['url'] . "[/url]\n";
+ return " \n[url]" . $attach_data['url'] . "[/url]\n";
} else {
- return "\n[url=" . $attach_data['url'] . ']' . $attach_data['title'] . "[/url]\n";
+ return " \n[url=" . $attach_data['url'] . ']' . $attach_data['title'] . "[/url]\n";
}
}, $body);
}
@@ -433,18 +441,29 @@ class BBCode
*/
public static function toPlaintext($text, $keep_urls = true)
{
+ DI::profiler()->startRecording('rendering');
+ // Remove pictures in advance to avoid unneeded proxy calls
+ $text = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", ' $2 ', $text);
+ $text = preg_replace("/\[img.*?\[\/img\]/ism", ' ', $text);
+
+ // Remove attachment
+ $text = self::removeAttachment($text);
+
$naked_text = HTML::toPlaintext(self::convert($text, false, 0, true), 0, !$keep_urls);
+ DI::profiler()->stopRecording();
return $naked_text;
}
- private static function proxyUrl($image, $simplehtml = self::INTERNAL)
+ private static function proxyUrl($image, $simplehtml = self::INTERNAL, $uriid = 0, $size = '')
{
// Only send proxied pictures to API and for internal display
- if (in_array($simplehtml, [self::INTERNAL, self::API])) {
- return ProxyUtils::proxifyUrl($image);
- } else {
+ if (!in_array($simplehtml, [self::INTERNAL, self::API])) {
return $image;
+ } elseif ($uriid > 0) {
+ return Post\Link::getByLink($uriid, $image, $size);
+ } else {
+ return ProxyUtils::proxifyUrl($image, $size);
}
}
@@ -458,6 +477,7 @@ class BBCode
*/
public static function scaleExternalImages(string $srctext)
{
+ DI::profiler()->startRecording('rendering');
$s = $srctext;
// Simplify image links
@@ -474,7 +494,7 @@ class BBCode
continue;
}
- $curlResult = DI::httpRequest()->get($mtch[1]);
+ $curlResult = DI::httpClient()->get($mtch[1]);
if (!$curlResult->isSuccess()) {
continue;
}
@@ -507,6 +527,7 @@ class BBCode
}
}
+ DI::profiler()->stopRecording();
return $s;
}
@@ -522,6 +543,7 @@ class BBCode
*/
public static function limitBodySize($body)
{
+ 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
@@ -593,8 +615,10 @@ class BBCode
$new_body = $new_body . $orig_body;
}
+ DI::profiler()->stopRecording();
return $new_body;
} else {
+ DI::profiler()->stopRecording();
return $body;
}
}
@@ -608,18 +632,19 @@ class BBCode
* @param integer $simplehtml
* @param bool $tryoembed
* @param array $data
+ * @param int $uriid
* @return string
* @throws \Friendica\Network\HTTPException\InternalServerErrorException
*/
- public static function convertAttachment($text, $simplehtml = self::INTERNAL, $tryoembed = true, array $data = [])
+ public static function convertAttachment($text, $simplehtml = self::INTERNAL, $tryoembed = true, array $data = [], $uriid = 0)
{
+ DI::profiler()->startRecording('rendering');
$data = $data ?: self::getAttachmentData($text);
if (empty($data) || empty($data['url'])) {
+ DI::profiler()->stopRecording();
return $text;
}
- $stamp1 = microtime(true);
-
if (isset($data['title'])) {
$data['title'] = strip_tags($data['title']);
$data['title'] = str_replace(['http://', 'https://'], '', $data['title']);
@@ -648,12 +673,12 @@ class BBCode
if (!empty($data['title']) && !empty($data['url'])) {
if (!empty($data['image']) && empty($data['text']) && ($data['type'] == 'photo')) {
- $return .= sprintf('', $data['url'], self::proxyUrl($data['image'], $simplehtml), $data['title']);
+ $return .= sprintf('', $data['url'], self::proxyUrl($data['image'], $simplehtml, $uriid), $data['title']);
} else {
if (!empty($data['image'])) {
- $return .= sprintf('
', $data['url'], self::proxyUrl($data['image'], $simplehtml), $data['title']);
+ $return .= sprintf('
', $data['url'], self::proxyUrl($data['image'], $simplehtml, $uriid), $data['title']);
} elseif (!empty($data['preview'])) {
- $return .= sprintf('
', $data['url'], self::proxyUrl($data['preview'], $simplehtml), $data['title']);
+ $return .= sprintf('
', $data['url'], self::proxyUrl($data['preview'], $simplehtml, $uriid), $data['title']);
}
$return .= sprintf('
' . html_entity_decode('♲ ', ENT_QUOTES, 'UTF-8') . ' ' . $author_contact['addr'] . ':
' . "\n" . $content; + $text = ($is_quote_share? '' . $content . ''; break; case self::DIASPORA: if (stripos(Strings::normaliseLink($attributes['link']), 'http://twitter.com/') === 0) { @@ -1105,9 +1194,9 @@ class BBCode $text = DI::cache()->get($cache_key); if (is_null($text)) { - $curlResult = DI::httpRequest()->head($match[1], ['timeout' => DI::config()->get('system', 'xrd_timeout')]); + $curlResult = DI::httpClient()->head($match[1], [HTTPClientOptions::TIMEOUT => DI::config()->get('system', 'xrd_timeout')]); if ($curlResult->isSuccess()) { - $mimetype = $curlResult->getHeader('Content-Type'); + $mimetype = $curlResult->getHeader('Content-Type')[0] ?? ''; } else { $mimetype = ''; } @@ -1118,7 +1207,7 @@ class BBCode $text = "[url=" . $match[2] . ']' . $match[2] . "[/url]"; // if its not a picture then look if its a page that contains a picture link - $body = DI::httpRequest()->fetch($match[1]); + $body = DI::httpClient()->fetch($match[1]); if (empty($body)) { DI::cache()->set($cache_key, $text); return $text; @@ -1176,9 +1265,9 @@ class BBCode return $text; } - $curlResult = DI::httpRequest()->head($match[1], ['timeout' => DI::config()->get('system', 'xrd_timeout')]); + $curlResult = DI::httpClient()->head($match[1], [HTTPClientOptions::TIMEOUT => DI::config()->get('system', 'xrd_timeout')]); if ($curlResult->isSuccess()) { - $mimetype = $curlResult->getHeader('Content-Type'); + $mimetype = $curlResult->getHeader('Content-Type')[0] ?? ''; } else { $mimetype = ''; } @@ -1194,7 +1283,7 @@ class BBCode } // if its not a picture then look if its a page that contains a picture link - $body = DI::httpRequest()->fetch($match[1]); + $body = DI::httpClient()->fetch($match[1]); if (empty($body)) { DI::cache()->set($cache_key, $text); return $text; @@ -1228,22 +1317,93 @@ class BBCode public static function cleanPictureLinks($text) { + DI::profiler()->startRecording('rendering'); $return = preg_replace_callback("&\[url=([^\[\]]*)\]\[img=(.*)\](.*)\[\/img\]\[\/url\]&Usi", 'self::cleanPictureLinksCallback', $text); $return = preg_replace_callback("&\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]&Usi", 'self::cleanPictureLinksCallback', $return); + DI::profiler()->stopRecording(); return $return; } public static function removeLinks(string $bbcode) { + DI::profiler()->startRecording('rendering'); $bbcode = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", ' $1 ', $bbcode); $bbcode = preg_replace("/\[img.*?\[\/img\]/ism", ' ', $bbcode); $bbcode = preg_replace('/[@!#]\[url\=.*?\].*?\[\/url\]/ism', '', $bbcode); $bbcode = preg_replace("/\[url=[^\[\]]*\](.*)\[\/url\]/Usi", ' $1 ', $bbcode); $bbcode = preg_replace('/[@!#]?\[url.*?\[\/url\]/ism', '', $bbcode); + DI::profiler()->stopRecording(); return $bbcode; } + /** + * Replace names in mentions with nicknames + * + * @param string $body + * @return string Body with replaced mentions + */ + public static function setMentionsToNicknames(string $body):string + { + DI::profiler()->startRecording('rendering'); + $regexp = "/([@!])\[url\=([^\[\]]*)\].*?\[\/url\]/ism"; + $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body); + DI::profiler()->stopRecording(); + return $body; + } + + /** + * Callback function to replace a Friendica style mention in a mention with the nickname + * + * @param array $match Matching values for the callback + * @return string Replaced mention + * @throws \Friendica\Network\HTTPException\InternalServerErrorException + */ + private static function mentionCallback($match) + { + if (empty($match[2])) { + return ''; + } + + $data = Contact::getByURL($match[2], false, ['url', 'nick']); + if (empty($data['nick'])) { + return $match[0]; + } + + return $match[1] . '[url=' . $data['url'] . ']' . $data['nick'] . '[/url]'; + } + + /** + * Converts a BBCode message for a given URI-ID to a HTML message + * + * BBcode 2 HTML was written by WAY2WEB.net + * extended to work with Mistpark/Friendica - Mike Macgirvin + * + * Simple HTML values meaning: + * - 0: Friendica display + * - 1: Unused + * - 2: Used for Windows Phone push, Friendica API + * - 3: Used before converting to Markdown in bb2diaspora.php + * - 4: Used for WordPress, Libertree (before Markdown), pump.io and tumblr + * - 5: Unused + * - 6: Unused + * - 7: Used for dfrn, OStatus + * - 8: Used for Twitter, WP backlink text setting + * - 9: ActivityPub + * + * @param int $uriid + * @param string $text + * @param int $simple_html + * @return string + * @throws \Friendica\Network\HTTPException\InternalServerErrorException + */ + public static function convertForUriId(int $uriid = null, string $text = null, int $simple_html = self::INTERNAL) + { + $try_oembed = ($simple_html == self::INTERNAL); + + return self::convert($text ?? '', $try_oembed, $simple_html, false, $uriid ?? 0); + } + /** * Converts a BBCode message to HTML message * @@ -1266,22 +1426,25 @@ class BBCode * @param bool $try_oembed * @param int $simple_html * @param bool $for_plaintext + * @param int $uriid * @return string * @throws \Friendica\Network\HTTPException\InternalServerErrorException */ - public static function convert(string $text = null, $try_oembed = true, $simple_html = self::INTERNAL, $for_plaintext = false) + public static function convert(string $text = null, $try_oembed = true, $simple_html = self::INTERNAL, $for_plaintext = false, $uriid = 0) { // Accounting for null default column values if (is_null($text) || $text === '') { return ''; } + DI::profiler()->startRecording('rendering'); + Hook::callAll('bbcode', $text); $a = DI::app(); - $text = self::performWithEscapedTags($text, ['code'], function ($text) use ($try_oembed, $simple_html, $for_plaintext, $a) { - $text = self::performWithEscapedTags($text, ['noparse', 'nobb', 'pre'], function ($text) use ($try_oembed, $simple_html, $for_plaintext, $a) { + $text = self::performWithEscapedTags($text, ['code'], function ($text) use ($try_oembed, $simple_html, $for_plaintext, $a, $uriid) { + $text = self::performWithEscapedTags($text, ['noparse', 'nobb', 'pre'], function ($text) use ($try_oembed, $simple_html, $for_plaintext, $a, $uriid) { /* * preg_match_callback function to replace potential Oembed tags with Oembed content * @@ -1380,19 +1543,19 @@ class BBCode } while ($oldtext != $text); } - // Add HTML new lines - $text = str_replace("\n", '
'], [''], $text); - $stamp1 = microtime(true); - // Now convert HTML to Markdown $text = HTML::toMarkdown($text); - DI::profiler()->saveTimestamp($stamp1, "parser"); - // Libertree has a problem with escaped hashtags. $text = str_replace(['\#'], ['#'], $text); @@ -2044,6 +2214,7 @@ class BBCode Hook::callAll('bb2diaspora', $text); + DI::profiler()->stopRecording(); return $text; } @@ -2062,9 +2233,10 @@ class BBCode */ public static function getTags($string) { + DI::profiler()->startRecording('rendering'); $ret = []; - BBCode::performWithEscapedTags($string, ['noparse', 'pre', 'code', 'img'], function ($string) use (&$ret) { + self::performWithEscapedTags($string, ['noparse', 'pre', 'code', 'img'], function ($string) use (&$ret) { // Convert hashtag links to hashtags $string = preg_replace('/#\[url\=([^\[\]]*)\](.*?)\[\/url\]/ism', '#$2 ', $string); @@ -2112,9 +2284,36 @@ class BBCode } }); + DI::profiler()->stopRecording(); return array_unique($ret); } + /** + * Expand tags to URLs + * + * @param string $body + * @return string body with expanded tags + */ + public static function expandTags(string $body) + { + return preg_replace_callback("/([!#@])([^\^ \x0D\x0A,;:?\']*[^\^ \x0D\x0A,;:?!\'.])/", + function ($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 '#': + return $match[1] . '[url=' . 'https://' . 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. * @@ -2145,8 +2344,9 @@ class BBCode */ public static function setMentions($body, $profile_uid = 0, $network = '') { - BBCode::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) use ($profile_uid, $network) { - $tags = BBCode::getTags($body); + DI::profiler()->startRecording('rendering'); + self::performWithEscapedTags($body, ['noparse', 'pre', 'code', 'img'], function ($body) use ($profile_uid, $network) { + $tags = self::getTags($body); $tagged = []; $inform = ''; @@ -2168,9 +2368,7 @@ class BBCode } } - $success = Item::replaceTag($body, $inform, $profile_uid, $tag, $network); - - if ($success['replaced']) { + if (($success = Item::replaceTag($body, $inform, $profile_uid, $tag, $network)) && $success['replaced']) { $tagged[] = $tag; } } @@ -2178,6 +2376,7 @@ class BBCode return $body; }); + DI::profiler()->stopRecording(); return $body; } @@ -2193,6 +2392,7 @@ class BBCode */ public static function getShareOpeningTag(string $author, string $profile, string $avatar, string $link, string $posted, string $guid = null) { + DI::profiler()->startRecording('rendering'); $header = "[share author='" . str_replace(["'", "[", "]"], ["'", "[", "]"], $author) . "' profile='" . str_replace(["'", "[", "]"], ["'", "[", "]"], $profile) . "' avatar='" . str_replace(["'", "[", "]"], ["'", "[", "]"], $avatar) . @@ -2205,6 +2405,7 @@ class BBCode $header .= "']"; + DI::profiler()->stopRecording(); return $header; } @@ -2226,6 +2427,7 @@ class BBCode */ 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 @@ -2247,6 +2449,7 @@ class BBCode DI::logger()->info('(unparsed): returns: ' . $result); + DI::profiler()->stopRecording(); return $result; } @@ -2265,6 +2468,7 @@ class BBCode break; } + DI::profiler()->stopRecording(); return $bbcode; } @@ -2272,10 +2476,13 @@ class BBCode // Bypass attachment if parse url for a comment if (!$tryAttachment) { + DI::profiler()->stopRecording(); return "\n" . '[url=' . $url . ']' . $siteinfo['title'] . '[/url]'; } // Format it as BBCode attachment - return "\n" . PageInfo::getFooterFromData($siteinfo); + $bbcode = "\n" . PageInfo::getFooterFromData($siteinfo); + DI::profiler()->stopRecording(); + return $bbcode; } }