<?php
/**
- * @copyright Copyright (C) 2010-2022, the Friendica project
+ * @copyright Copyright (C) 2010-2023, the Friendica project
*
* @license GNU AGPL version 3 or any later version
*
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\HTTPClient\Client\HttpClientAccept;
use Friendica\Network\HTTPClient\Client\HttpClientOptions;
-use Friendica\Object\Image;
-use Friendica\Protocol\Activity;
-use Friendica\Util\Images;
use Friendica\Util\Map;
use Friendica\Util\ParseUrl;
use Friendica\Util\Proxy;
// 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 API = 2;
- const DIASPORA = 3;
- const CONNECTORS = 4;
- const OSTATUS = 7;
- const TWITTER = 8;
- const BACKLINK = 8;
- const ACTIVITYPUB = 9;
+ const INTERNAL = 0;
+ const EXTERNAL = 1;
+ const MASTODON_API = 2;
+ const DIASPORA = 3;
+ const CONNECTORS = 4;
+ const TWITTER_API = 5;
+ const OSTATUS = 7;
+ const TWITTER = 8;
+ const BACKLINK = 8;
+ const ACTIVITYPUB = 9;
const TOP_ANCHOR = '<br class="top-anchor">';
const BOTTOM_ANCHOR = '<br class="button-anchor">';
- /**
- * Fetches attachment data that were generated the old way
- *
- * @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
- */
- private static function getOldAttachmentData(string $body): array
- {
- $post = [];
-
- // Simplify image codes
- $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
-
- if (preg_match_all("(\[class=(.*?)\](.*?)\[\/class\])ism", $body, $attached, PREG_SET_ORDER)) {
- foreach ($attached as $data) {
- if (!in_array($data[1], ['type-link', 'type-video', 'type-photo'])) {
- continue;
- }
-
- $post['type'] = substr($data[1], 5);
- $pos = strpos($body, $data[0]);
- if ($pos > 0) {
- $post['text'] = trim(substr($body, 0, $pos));
- $post['after'] = trim(substr($body, $pos + strlen($data[0])));
- } else {
- $post['text'] = trim(str_replace($data[0], '', $body));
- $post['after'] = '';
- }
-
- $attacheddata = $data[2];
-
- if (preg_match("/\[img\](.*?)\[\/img\]/ism", $attacheddata, $matches)) {
-
- $picturedata = Images::getInfoFromURLCached($matches[1]);
-
- if ($picturedata) {
- if (($picturedata[0] >= 500) && ($picturedata[0] >= $picturedata[1])) {
- $post['image'] = $matches[1];
- } else {
- $post['preview'] = $matches[1];
- }
- }
- }
-
- if (preg_match("/\[bookmark\=(.*?)\](.*?)\[\/bookmark\]/ism", $attacheddata, $matches)) {
- $post['url'] = $matches[1];
- $post['title'] = $matches[2];
- }
- if (!empty($post['url']) && (in_array($post['type'], ['link', 'video']))
- && preg_match("/\[url\=(.*?)\](.*?)\[\/url\]/ism", $attacheddata, $matches)) {
- $post['url'] = $matches[1];
- }
-
- // Search for description
- if (preg_match("/\[quote\](.*?)\[\/quote\]/ism", $attacheddata, $matches)) {
- $post['description'] = $matches[1];
- }
- }
- }
- return $post;
- }
+ 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
if (!preg_match("/(.*)\[attachment(.*?)\](.*?)\[\/attachment\](.*)/ism", $body, $match)) {
DI::profiler()->stopRecording();
- return self::getOldAttachmentData($body);
+ return [];
}
$attributes = $match[2];
return $data;
}
- public static function getAttachedData(string $body, array $item = []): array
- {
- /*
- - text:
- - type: link, video, photo
- - title:
- - url:
- - image:
- - description:
- - (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=(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]];
- } else {
- $post['remote_images'][] = ['url' => $picture[1], 'description' => $picture[2]];
- }
- }
- if (!empty($post['images']) && !empty($post['images'][0]['description'])) {
- $post['image_description'] = $post['images'][0]['description'];
- }
- }
-
- if (preg_match_all("/\[img\]([^\[\]]*)\[\/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' => ''];
- } else {
- $post['remote_images'][] = ['url' => $picture[1], 'description' => ''];
- }
- }
- }
-
- if (!isset($post['type'])) {
- $post['text'] = $body;
- }
-
- // Simplify image codes
- $post['text'] = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $post['text']);
- $post['text'] = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $post['text']);
-
- // if nothing is found, it maybe having an image.
- if (!isset($post['type'])) {
- if (preg_match_all("#\[url=([^\]]+?)\]\s*\[img\]([^\[]+?)\[/img\]\s*\[/url\]#ism", $post['text'], $pictures, PREG_SET_ORDER)) {
- if ((count($pictures) == 1) && !$has_title) {
- if (!empty($item['object-type']) && ($item['object-type'] == Activity\ObjectType::IMAGE)) {
- // Replace the preview picture with the real picture
- $url = str_replace('-1.', '-0.', $pictures[0][2]);
- $data = ['url' => $url, 'type' => 'photo'];
- } else {
- // Checking, if the link goes to a picture
- $data = ParseUrl::getSiteinfoCached($pictures[0][1]);
- }
-
- // Workaround:
- // Sometimes photo posts to the own album are not detected at the start.
- // So we seem to cannot use the cache for these cases. That's strange.
- if (($data['type'] != 'photo') && strstr($pictures[0][1], '/photos/')) {
- $data = ParseUrl::getSiteinfo($pictures[0][1]);
- }
-
- if ($data['type'] == 'photo') {
- $post['type'] = 'photo';
- if (isset($data['images'][0])) {
- $post['image'] = $data['images'][0]['src'];
- $post['url'] = $data['url'];
- } else {
- $post['image'] = $data['url'];
- }
-
- $post['preview'] = $pictures[0][2];
- $post['text'] = trim(str_replace($pictures[0][0], '', $post['text']));
- } else {
- $imgdata = Images::getInfoFromURLCached($pictures[0][1]);
- if (($imgdata) && substr($imgdata['mime'], 0, 6) == 'image/') {
- $post['type'] = 'photo';
- $post['image'] = $pictures[0][1];
- $post['preview'] = $pictures[0][2];
- $post['text'] = trim(str_replace($pictures[0][0], '', $post['text']));
- }
- }
- } elseif (count($pictures) > 0) {
- if (count($pictures) > 4) {
- $post['type'] = 'link';
- $post['url'] = $plink;
- } else {
- $post['type'] = 'photo';
- }
-
- $post['image'] = $pictures[0][2];
-
- foreach ($pictures as $picture) {
- $post['text'] = trim(str_replace($picture[0], '', $post['text']));
- }
- }
- } elseif (preg_match_all("(\[img\](.*?)\[\/img\])ism", $post['text'], $pictures, PREG_SET_ORDER)) {
- if ($has_title) {
- $post['type'] = 'link';
- $post['url'] = $plink;
- } else {
- $post['type'] = 'photo';
- }
-
- $post['image'] = $pictures[0][1];
- foreach ($pictures as $picture) {
- $post['text'] = trim(str_replace($picture[0], '', $post['text']));
- }
- }
-
- // Test for the external links
- preg_match_all("(\[url\](.*?)\[\/url\])ism", $post['text'], $links1, PREG_SET_ORDER);
- preg_match_all("(\[url\=(.*?)\].*?\[\/url\])ism", $post['text'], $links2, PREG_SET_ORDER);
-
- $links = array_merge($links1, $links2);
-
- // If there is only a single one, then use it.
- // This should cover link posts via API.
- if ((count($links) == 1) && !isset($post['preview']) && !$has_title) {
- $post['type'] = 'link';
- $post['url'] = $links[0][1];
- }
-
- // Simplify "video" element
- $post['text'] = preg_replace('(\[video.*?\ssrc\s?=\s?([^\s\]]+).*?\].*?\[/video\])ism', '[video]$1[/video]', $post['text']);
-
- // Now count the number of external media links
- preg_match_all("(\[vimeo\](.*?)\[\/vimeo\])ism", $post['text'], $links1, PREG_SET_ORDER);
- preg_match_all("(\[youtube\\](.*?)\[\/youtube\\])ism", $post['text'], $links2, PREG_SET_ORDER);
- preg_match_all("(\[video\\](.*?)\[\/video\\])ism", $post['text'], $links3, PREG_SET_ORDER);
- preg_match_all("(\[audio\\](.*?)\[\/audio\\])ism", $post['text'], $links4, PREG_SET_ORDER);
-
- // Add them to the other external links
- $links = array_merge($links, $links1, $links2, $links3, $links4);
-
- // Are there more than one?
- if (count($links) > 1) {
- // The post will be the type "text", which means a blog post
- unset($post['type']);
- $post['url'] = $plink;
- }
-
- if (!isset($post['type'])) {
- $post['type'] = 'text';
- }
-
- if (($post['type'] == 'photo') && empty($post['images']) && !empty($post['remote_images'])) {
- $post['images'] = $post['remote_images'];
- $post['image'] = $post['images'][0]['url'];
- if (!empty($post['images']) && !empty($post['images'][0]['description'])) {
- $post['image_description'] = $post['images'][0]['description'];
- }
- }
- unset($post['remote_images']);
- } elseif (isset($post['url']) && ($post['type'] == 'video')) {
- $data = ParseUrl::getSiteinfoCached($post['url']);
-
- if (isset($data['images'][0])) {
- $post['image'] = $data['images'][0]['src'];
- }
- } elseif (preg_match_all("#\[url=([^\]]+?)\]\s*\[img\]([^\[]+?)\[/img\]\s*\[/url\]#ism", $post['text'], $pictures, PREG_SET_ORDER)) {
- foreach ($pictures as $picture) {
- $post['text'] = trim(str_replace($picture[0], '', $post['text']));
- }
- }
-
- DI::profiler()->stopRecording();
- return $post;
- }
-
/**
* Remove [attachment] BBCode and replaces it with a regular [url]
*
* @param boolean $no_link_desc No link description
* @return string with replaced body
*/
- public static function removeAttachment(string $body, bool $no_link_desc = false): string
+ public static function replaceAttachment(string $body, bool $no_link_desc = false): string
{
- return preg_replace_callback("/\s*\[attachment (.*?)\](.*?)\[\/attachment\]\s*/ism",
+ 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'])) {
} else {
return " \n[url=" . $attach_data['url'] . ']' . $attach_data['title'] . "[/url]\n";
}
- }, $body);
+ },
+ $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));
}
/**
$text = preg_replace("/\[img.*?\[\/img\]/ism", ' ', $text);
// Remove attachment
- $text = self::removeAttachment($text);
+ $text = self::replaceAttachment($text);
$naked_text = HTML::toPlaintext(self::convert($text, false, 0, true), 0, !$keep_urls);
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::API])) {
+ if (!in_array($simplehtml, [self::INTERNAL, self::MASTODON_API, self::TWITTER_API])) {
return $image;
} elseif ($uriid > 0) {
return Post\Link::getByLink($uriid, $image, $size);
}
}
- /**
- * This function changing the visual size (not the real size) of images.
- * The function does not work for pictures with an alternate text description.
- * This could only be changed by using some new "img" BBCode format.
- *
- * @param string $srctext The body with images
- * @return string The body with possibly scaled images
- */
- public static function scaleExternalImages(string $srctext): string
- {
- DI::profiler()->startRecording('rendering');
- $s = $srctext;
-
- // Simplify image links
- $s = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $s);
-
- $matches = null;
- $c = preg_match_all('/\[img.*?\](.*?)\[\/img\]/ism', $s, $matches, PREG_SET_ORDER);
- if ($c) {
- foreach ($matches as $mtch) {
- Logger::debug('scale_external_image', ['image' => $mtch[1]]);
-
- $hostname = str_replace('www.', '', substr(DI::baseUrl(), strpos(DI::baseUrl(), '://') + 3));
- if (stristr($mtch[1], $hostname)) {
- continue;
- }
-
- $curlResult = DI::httpClient()->get($mtch[1], HttpClientAccept::IMAGE);
- if (!$curlResult->isSuccess()) {
- continue;
- }
-
- Logger::debug('Got picture', ['Content-Type' => $curlResult->getHeader('Content-Type'), 'url' => $mtch[1]]);
-
- $i = $curlResult->getBody();
- $type = $curlResult->getContentType();
- $type = Images::getMimeTypeByData($i, $mtch[1], $type);
-
- if ($i) {
- $Image = new Image($i, $type);
- if ($Image->isValid()) {
- $orig_width = $Image->getWidth();
- $orig_height = $Image->getHeight();
-
- if ($orig_width > 640 || $orig_height > 640) {
- $Image->scaleDown(640);
- $new_width = $Image->getWidth();
- $new_height = $Image->getHeight();
- Logger::debug('External images scaled', ['orig_width' => $orig_width, 'new_width' => $new_width, 'orig_height' => $orig_height, 'new_height' => $new_height, 'match' => $mtch[0]]);
- $s = str_replace(
- $mtch[0],
- '[img=' . $new_width . 'x' . $new_height. ']' . $mtch[1] . '[/img]'
- . "\n",
- $s
- );
- Logger::debug('New string', ['image' => $s]);
- }
- }
- }
- }
- }
-
- DI::profiler()->stopRecording();
- return $s;
- }
-
/**
* Truncates imported message body string length to max_import_size
*
* @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): string
+ 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);
$return = sprintf('<div class="type-%s">', $data['type']);
}
+ if ($preview_mode == self::PREVIEW_NO_IMAGE) {
+ unset($data['image']);
+ unset($data['preview']);
+ }
+
if (!empty($data['title']) && !empty($data['url'])) {
+ $preview_class = $preview_mode == self::PREVIEW_LARGE ? 'attachment-image' : 'attachment-preview';
if (!empty($data['image']) && empty($data['text']) && ($data['type'] == 'photo')) {
- $return .= sprintf('<a href="%s" target="_blank" rel="noopener noreferrer"><img src="%s" alt="" title="%s" class="attachment-image" /></a>', $data['url'], self::proxyUrl($data['image'], $simplehtml, $uriid), $data['title']);
+ $return .= sprintf('<a href="%s" target="_blank" rel="noopener noreferrer"><img src="%s" alt="" title="%s" class="' . $preview_class . '" /></a>', $data['url'], self::proxyUrl($data['image'], $simplehtml, $uriid), $data['title']);
} else {
if (!empty($data['image'])) {
- $return .= sprintf('<a href="%s" target="_blank" rel="noopener noreferrer"><img src="%s" alt="" title="%s" class="attachment-image" /></a><br>', $data['url'], self::proxyUrl($data['image'], $simplehtml, $uriid), $data['title']);
+ $return .= sprintf('<a href="%s" target="_blank" rel="noopener noreferrer"><img src="%s" alt="" title="%s" class="' . $preview_class . '" /></a><br>', $data['url'], self::proxyUrl($data['image'], $simplehtml, $uriid), $data['title']);
} elseif (!empty($data['preview'])) {
$return .= sprintf('<a href="%s" target="_blank" rel="noopener noreferrer"><img src="%s" alt="" title="%s" class="attachment-preview" /></a><br>', $data['url'], self::proxyUrl($data['preview'], $simplehtml, $uriid), $data['title']);
}
// We're depending on the property of 'foreach' (specified on the PHP website) that
// it loops over the array starting from the first element and going sequentially
// to the last element
- $newbody = str_replace('[$#saved_image' . $cnt . '#$]',
- '<img src="' . self::proxyUrl($image, self::INTERNAL, $uriid) . '" alt="' . DI::l10n()->t('Image/photo') . '" />', $newbody);
+ $newbody = str_replace(
+ '[$#saved_image' . $cnt . '#$]',
+ '<img src="' . self::proxyUrl($image, self::INTERNAL, $uriid) . '" alt="' . DI::l10n()->t('Image/photo') . '" />',
+ $newbody
+ );
$cnt++;
}
{
DI::profiler()->startRecording('rendering');
if (preg_match('~(.*?)\[share](.*)\[/share]~ism', $text, $matches)) {
+ DI::profiler()->stopRecording();
return [
'author' => '',
'profile' => '',
return $attributes;
}
- /**
- * Replace the share block with a link
- *
- * @param string $body
- * @return string
- */
- public static function replaceSharedData(string $body): string
- {
- return BBCode::convertShare(
- $body,
- function (array $attributes) {
- return '♲ ' . $attributes['link'];
- }
- );
- }
-
/**
* Remove the share block
*
*/
public static function removeSharedData(string $body): string
{
- return BBCode::convertShare(
- $body,
- function (array $attributes) {
- return '';
- }
- );
+ return trim(preg_replace("/\s*\[share.*?\].*?\[\/share\]\s*/ism", '', $body));
}
/**
$attributes[$field] = html_entity_decode($matches[2] ?? '', ENT_QUOTES, 'UTF-8');
}
- $img_str = '<img src="' .
- self::proxyUrl($match[2], $simplehtml, $uriid) . '"';
+ $img_str = '<img src="' . self::proxyUrl($match[2], $simplehtml, $uriid) . '"';
foreach ($attributes as $key => $value) {
if (!empty($value)) {
$img_str .= ' ' . $key . '="' . htmlspecialchars($value, ENT_COMPAT) . '"';
$mention = $attributes['author'] . ' (' . ($author_contact['addr'] ?? '') . ')';
switch ($simplehtml) {
- case self::API:
- $text = ($is_quote_share? '<br>' : '') .
- '<b><a href="' . $attributes['link'] . '">' . html_entity_decode('♲', ENT_QUOTES, 'UTF-8') . ' ' . $author_contact['addr'] . "</a>:</b><br>\n" .
- '<blockquote class="shared_content" dir="auto">' . $content . '</blockquote>';
+ case self::MASTODON_API:
+ case self::TWITTER_API:
+ $text = ($is_quote_share ? '<br>' : '') .
+ '<b><a href="' . $attributes['link'] . '">' . html_entity_decode('♲', ENT_QUOTES, 'UTF-8') . ' ' . $author_contact['addr'] . "</a>:</b><br>\n" .
+ '<blockquote class="shared_content" dir="auto">' . $content . '</blockquote>';
break;
case self::DIASPORA:
if (stripos(Strings::normaliseLink($attributes['link']), 'http://twitter.com/') === 0) {
- $text = ($is_quote_share? '<hr />' : '') . '<p><a href="' . $attributes['link'] . '">' . $attributes['link'] . '</a></p>' . "\n";
+ $text = ($is_quote_share ? '<hr />' : '') . '<p><a href="' . $attributes['link'] . '">' . $attributes['link'] . '</a></p>' . "\n";
} else {
$headline = '<p><b>♲ <a href="' . $attributes['profile'] . '">' . $attributes['author'] . '</a>:</b></p>' . "\n";
$headline = '<p><b>♲ <a href="' . $attributes['profile'] . '">' . $attributes['author'] . '</a></b> - <a href="' . $attributes['link'] . '">' . $attributes['posted'] . ' GMT</a></p>' . "\n";
}
- $text = ($is_quote_share? '<hr />' : '') . $headline . '<blockquote>' . trim($content) . '</blockquote>' . "\n";
+ $text = ($is_quote_share ? '<hr />' : '') . $headline . '<blockquote>' . trim($content) . '</blockquote>' . "\n";
if (empty($attributes['posted']) && !empty($attributes['link'])) {
$text .= '<p><a href="' . $attributes['link'] . '">[Source]</a></p>' . "\n";
$headline .= DI::l10n()->t('<a href="%1$s" target="_blank" rel="noopener noreferrer">%2$s</a> %3$s', $attributes['link'], $mention, $attributes['posted']);
$headline .= ':</b></p>' . "\n";
- $text = ($is_quote_share? '<hr />' : '') . $headline . '<blockquote class="shared_content" dir="auto">' . trim($content) . '</blockquote>' . "\n";
+ $text = ($is_quote_share ? '<hr />' : '') . $headline . '<blockquote class="shared_content" dir="auto">' . trim($content) . '</blockquote>' . "\n";
break;
case self::OSTATUS:
- $text = ($is_quote_share? '<br>' : '') . '<p>' . html_entity_decode('♲ ', ENT_QUOTES, 'UTF-8') . ' @' . $author_contact['addr'] . ': ' . $content . '</p>' . "\n";
+ $text = ($is_quote_share ? '<br>' : '') . '<p>' . html_entity_decode('♲ ', ENT_QUOTES, 'UTF-8') . ' @' . $author_contact['addr'] . ': ' . $content . '</p>' . "\n";
break;
case self::ACTIVITYPUB:
$author = '@<span class="vcard"><a href="' . $author_contact['url'] . '" class="url u-url mention" title="' . $author_contact['addr'] . '"><span class="fn nickname mention">' . $author_contact['addr'] . '</span></a>:</span>';
$text = '<div><a href="' . $attributes['link'] . '">' . html_entity_decode('♲', ENT_QUOTES, 'UTF-8') . '</a> ' . $author . '<blockquote>' . $content . '</blockquote></div>' . "\n";
break;
default:
- $text = ($is_quote_share? "\n" : '');
+ $text = ($is_quote_share ? "\n" : '');
$contact = Contact::getByURL($attributes['profile'], false, ['network']);
$network = $contact['network'] ?? Protocol::PHANTOM;
/**
* Callback: Expands links from given $match array
*
- * @param arrat $match Array with link match
+ * @param array $match Array with link match
* @return string BBCode
*/
private static function expandLinksCallback(array $match): string
/**
* Callback: Cleans picture links
*
- * @param arrat $match Array with link match
+ * @param array $match Array with link match
* @return string BBCode
*/
private static function cleanPictureLinksCallback(array $match): string
{
// When the picture link is the own photo path then we can avoid fetching the link
- $own_photo_url = preg_quote(Strings::normaliseLink(DI::baseUrl()->get()) . '/photos/');
+ $own_photo_url = preg_quote(Strings::normaliseLink(DI::baseUrl()) . '/photos/');
if (preg_match('|' . $own_photo_url . '.*?/image/|', Strings::normaliseLink($match[1]))) {
if (!empty($match[3])) {
$text = '[img=' . str_replace('-1.', '-0.', $match[2]) . ']' . $match[3] . '[/img]';
public static function cleanPictureLinks(string $text): string
{
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);
+ $return = preg_replace_callback("&\[url=([^\[\]]*)\]\[img=(.*)\](.*)\[\/img\]\[\/url\]&Usi", [self::class, 'cleanPictureLinksCallback'], $text);
+ $return = preg_replace_callback("&\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]&Usi", [self::class, 'cleanPictureLinksCallback'], $return);
DI::profiler()->stopRecording();
return $return;
}
{
DI::profiler()->startRecording('rendering');
$regexp = "/([@!])\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
- $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
+ $body = preg_replace_callback($regexp, [self::class, 'mentionCallback'], $body);
DI::profiler()->stopRecording();
return $body;
}
* $match[1] = $url
* $match[2] = $title or absent
*/
- $try_oembed_callback = function (array $match)
- {
+ $try_oembed_callback = function (array $match) {
$url = $match[1];
$title = $match[2] ?? '';
$text = str_replace(">", ">", $text);
// remove some newlines before the general conversion
- $text = preg_replace("/\s?\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "[share$1]$2[/share]", $text);
- $text = preg_replace("/\s?\[quote(.*?)\]\s?(.*?)\s?\[\/quote\]\s?/ism", "[quote$1]$2[/quote]", $text);
+ $text = preg_replace("/\s?\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "\n[share$1]$2[/share]\n", $text);
+ $text = preg_replace("/\s?\[quote(.*?)\]\s?(.*?)\s?\[\/quote\]\s?/ism", "\n[quote$1]$2[/quote]\n", $text);
// when the content is meant exporting to other systems then remove the avatar picture since this doesn't really look good on these systems
if (!$try_oembed) {
}
// Remove linefeeds inside of the table elements. See issue #6799
- $search = ["\n[th]", "[th]\n", " [th]", "\n[/th]", "[/th]\n", "[/th] ",
+ $search = [
+ "\n[th]", "[th]\n", " [th]", "\n[/th]", "[/th]\n", "[/th] ",
"\n[td]", "[td]\n", " [td]", "\n[/td]", "[/td]\n", "[/td] ",
"\n[tr]", "[tr]\n", " [tr]", "[tr] ", "\n[/tr]", "[/tr]\n", " [/tr]", "[/tr] ",
"\n[hr]", "[hr]\n", " [hr]", "[hr] ",
"\n[attachment ", " [attachment ", "\n[/attachment]", "[/attachment]\n", " [/attachment]", "[/attachment] ",
- "[table]\n", "[table] ", " [table]", "\n[/table]", " [/table]", "[/table] "];
- $replace = ["[th]", "[th]", "[th]", "[/th]", "[/th]", "[/th]",
+ "[table]\n", "[table] ", " [table]", "\n[/table]", " [/table]", "[/table] ",
+ " \n", "\t\n", "[/li]\n", "\n[li]", "\n[*]",
+ ];
+ $replace = [
+ "[th]", "[th]", "[th]", "[/th]", "[/th]", "[/th]",
"[td]", "[td]", "[td]", "[/td]", "[/td]", "[/td]",
"[tr]", "[tr]", "[tr]", "[tr]", "[/tr]", "[/tr]", "[/tr]", "[/tr]",
"[hr]", "[hr]", "[hr]", "[hr]",
"[attachment ", "[attachment ", "[/attachment]", "[/attachment]", "[/attachment]", "[/attachment]",
- "[table]", "[table]", "[table]", "[/table]", "[/table]", "[/table]"];
+ "[table]", "[table]", "[table]", "[/table]", "[/table]", "[/table]",
+ "\n", "\n", "[/li]", "[li]", "[*]",
+ ];
do {
$oldtext = $text;
$text = str_replace($search, $replace, $text);
// removing multiplicated newlines
if (DI::config()->get('system', 'remove_multiplicated_lines')) {
- $search = ["\n\n\n", "\n ", " \n", "[/quote]\n\n", "\n[/quote]", "[/li]\n", "\n[li]", "\n[*]", "\n[ul]", "[/ul]\n", "\n\n[share ", "[/attachment]\n",
- "\n[h1]", "[/h1]\n", "\n[h2]", "[/h2]\n", "\n[h3]", "[/h3]\n", "\n[h4]", "[/h4]\n", "\n[h5]", "[/h5]\n", "\n[h6]", "[/h6]\n"];
- $replace = ["\n\n", "\n", "\n", "[/quote]\n", "[/quote]", "[/li]", "[li]", "[*]", "[ul]", "[/ul]", "\n[share ", "[/attachment]",
- "[h1]", "[/h1]", "[h2]", "[/h2]", "[h3]", "[/h3]", "[h4]", "[/h4]", "[h5]", "[/h5]", "[h6]", "[/h6]"];
+ $search = [
+ "\n\n\n", "[/quote]\n\n", "\n[/quote]", "\n[ul]", "[/ul]\n", "\n[ol]", "[/ol]\n", "\n\n[share ", "[/attachment]\n",
+ "\n[h1]", "[/h1]\n", "\n[h2]", "[/h2]\n", "\n[h3]", "[/h3]\n", "\n[h4]", "[/h4]\n", "\n[h5]", "[/h5]\n", "\n[h6]", "[/h6]\n"
+ ];
+ $replace = [
+ "\n\n", "[/quote]\n", "[/quote]", "[ul]", "[/ul]", "[ol]", "[/ol]", "\n[share ", "[/attachment]",
+ "[h1]", "[/h1]", "[h2]", "[/h2]", "[h3]", "[/h3]", "[h4]", "[/h4]", "[h5]", "[/h5]", "[h6]", "[/h6]"
+ ];
do {
$oldtext = $text;
$text = str_replace($search, $replace, $text);
/// @todo Have a closer look at the different html modes
// Handle attached links or videos
- if (in_array($simple_html, [self::API, self::ACTIVITYPUB])) {
- $text = self::removeAttachment($text);
+ if (in_array($simple_html, [self::MASTODON_API, self::TWITTER_API, self::ACTIVITYPUB])) {
+ $text = self::replaceAttachment($text);
} elseif (!in_array($simple_html, [self::INTERNAL, self::EXTERNAL, self::CONNECTORS])) {
- $text = self::removeAttachment($text, true);
+ $text = self::replaceAttachment($text, true);
} else {
$text = self::convertAttachment($text, $simple_html, $try_oembed, [], $uriid);
}
}
// Check for headers
- $text = preg_replace("(\[h1\](.*?)\[\/h1\])ism", '<h1>$1</h1>', $text);
- $text = preg_replace("(\[h2\](.*?)\[\/h2\])ism", '<h2>$1</h2>', $text);
- $text = preg_replace("(\[h3\](.*?)\[\/h3\])ism", '<h3>$1</h3>', $text);
- $text = preg_replace("(\[h4\](.*?)\[\/h4\])ism", '<h4>$1</h4>', $text);
- $text = preg_replace("(\[h5\](.*?)\[\/h5\])ism", '<h5>$1</h5>', $text);
- $text = preg_replace("(\[h6\](.*?)\[\/h6\])ism", '<h6>$1</h6>', $text);
+ $text = preg_replace("(\[h1\](.*?)\[\/h1\])ism", '</p><h1>$1</h1><p>', $text);
+ $text = preg_replace("(\[h2\](.*?)\[\/h2\])ism", '</p><h2>$1</h2><p>', $text);
+ $text = preg_replace("(\[h3\](.*?)\[\/h3\])ism", '</p><h3>$1</h3><p>', $text);
+ $text = preg_replace("(\[h4\](.*?)\[\/h4\])ism", '</p><h4>$1</h4><p>', $text);
+ $text = preg_replace("(\[h5\](.*?)\[\/h5\])ism", '</p><h5>$1</h5><p>', $text);
+ $text = preg_replace("(\[h6\](.*?)\[\/h6\])ism", '</p><h6>$1</h6><p>', $text);
// Check for paragraph
$text = preg_replace("(\[p\](.*?)\[\/p\])ism", '<p>$1</p>', $text);
// @deprecated since 2021.12, left for backward-compatibility reasons
$text = preg_replace("(\[class=(.*?)\](.*?)\[\/class\])ism", '<span class="$1">$2</span>', $text);
// Add HTML new lines
+ $text = str_replace("\n\n", '</p><p>', $text);
$text = str_replace("\n", '<br>', $text);
// handle nested lists
$endlessloop = 0;
while ((((strpos($text, "[/list]") !== false) && (strpos($text, "[list") !== false)) ||
- ((strpos($text, "[/ol]") !== false) && (strpos($text, "[ol]") !== false)) ||
- ((strpos($text, "[/ul]") !== false) && (strpos($text, "[ul]") !== false)) ||
- ((strpos($text, "[/li]") !== false) && (strpos($text, "[li]") !== false))) && (++$endlessloop < 20)) {
- $text = preg_replace("/\[list\](.*?)\[\/list\]/ism", '<ul class="listbullet" style="list-style-type: circle;">$1</ul>', $text);
- $text = preg_replace("/\[list=\](.*?)\[\/list\]/ism", '<ul class="listnone" style="list-style-type: none;">$1</ul>', $text);
- $text = preg_replace("/\[list=1\](.*?)\[\/list\]/ism", '<ul class="listdecimal" style="list-style-type: decimal;">$1</ul>', $text);
- $text = preg_replace("/\[list=((?-i)i)\](.*?)\[\/list\]/ism", '<ul class="listlowerroman" style="list-style-type: lower-roman;">$2</ul>', $text);
- $text = preg_replace("/\[list=((?-i)I)\](.*?)\[\/list\]/ism", '<ul class="listupperroman" style="list-style-type: upper-roman;">$2</ul>', $text);
- $text = preg_replace("/\[list=((?-i)a)\](.*?)\[\/list\]/ism", '<ul class="listloweralpha" style="list-style-type: lower-alpha;">$2</ul>', $text);
- $text = preg_replace("/\[list=((?-i)A)\](.*?)\[\/list\]/ism", '<ul class="listupperalpha" style="list-style-type: upper-alpha;">$2</ul>', $text);
- $text = preg_replace("/\[ul\](.*?)\[\/ul\]/ism", '<ul class="listbullet" style="list-style-type: circle;">$1</ul>', $text);
- $text = preg_replace("/\[ol\](.*?)\[\/ol\]/ism", '<ul class="listdecimal" style="list-style-type: decimal;">$1</ul>', $text);
+ ((strpos($text, "[/ol]") !== false) && (strpos($text, "[ol]") !== false)) ||
+ ((strpos($text, "[/ul]") !== false) && (strpos($text, "[ul]") !== false)) ||
+ ((strpos($text, "[/li]") !== false) && (strpos($text, "[li]") !== false))) && (++$endlessloop < 20)) {
+ $text = preg_replace("/\[list\](.*?)\[\/list\]/ism", '</p><ul class="listbullet" style="list-style-type: circle;">$1</ul><p>', $text);
+ $text = preg_replace("/\[list=\](.*?)\[\/list\]/ism", '</p><ul class="listnone" style="list-style-type: none;">$1</ul><p>', $text);
+ $text = preg_replace("/\[list=1\](.*?)\[\/list\]/ism", '</p><ul class="listdecimal" style="list-style-type: decimal;">$1</ul><p>', $text);
+ $text = preg_replace("/\[list=((?-i)i)\](.*?)\[\/list\]/ism", '</p><ul class="listlowerroman" style="list-style-type: lower-roman;">$2</ul><p>', $text);
+ $text = preg_replace("/\[list=((?-i)I)\](.*?)\[\/list\]/ism", '</p><ul class="listupperroman" style="list-style-type: upper-roman;">$2</ul><p>', $text);
+ $text = preg_replace("/\[list=((?-i)a)\](.*?)\[\/list\]/ism", '</p><ul class="listloweralpha" style="list-style-type: lower-alpha;">$2</ul><p>', $text);
+ $text = preg_replace("/\[list=((?-i)A)\](.*?)\[\/list\]/ism", '</p><ul class="listupperalpha" style="list-style-type: upper-alpha;">$2</ul><p>', $text);
+ $text = preg_replace("/\[ul\](.*?)\[\/ul\]/ism", '</p><ul>$1</ul><p>', $text);
+ $text = preg_replace("/\[ol\](.*?)\[\/ol\]/ism", '</p><ol>$1</ol><p>', $text);
$text = preg_replace("/\[li\](.*?)\[\/li\]/ism", '<li>$1</li>', $text);
}
$text = preg_replace("/\[th\](.*?)\[\/th\]/sm", '<th>$1</th>', $text);
$text = preg_replace("/\[td\](.*?)\[\/td\]/sm", '<td>$1</td>', $text);
$text = preg_replace("/\[tr\](.*?)\[\/tr\]/sm", '<tr>$1</tr>', $text);
- $text = preg_replace("/\[table\](.*?)\[\/table\]/sm", '<table>$1</table>', $text);
+ $text = preg_replace("/\[table\](.*?)\[\/table\]/sm", '</p><table>$1</table><p>', $text);
- $text = preg_replace("/\[table border=1\](.*?)\[\/table\]/sm", '<table border="1" >$1</table>', $text);
- $text = preg_replace("/\[table border=0\](.*?)\[\/table\]/sm", '<table border="0" >$1</table>', $text);
+ $text = preg_replace("/\[table border=1\](.*?)\[\/table\]/sm", '</p><table border="1" >$1</table><p>', $text);
+ $text = preg_replace("/\[table border=0\](.*?)\[\/table\]/sm", '</p><table border="0" >$1</table><p>', $text);
- $text = str_replace('[hr]', '<hr />', $text);
+ $text = str_replace('[hr]', '</p><hr /><p>', $text);
if (!$for_plaintext) {
$text = self::performWithEscapedTags($text, ['url', 'img', 'audio', 'video', 'youtube', 'vimeo', 'share', 'attachment', 'iframe', 'bookmark'], function ($text) {
// handle nested quotes
$endlessloop = 0;
- while ((strpos($text, "[/spoiler]")!== false) && (strpos($text, "[spoiler=") !== false) && (++$endlessloop < 20)) {
- $text = preg_replace("/\[spoiler=[\"\']*(.*?)[\"\']*\](.*?)\[\/spoiler\]/ism",
+ while ((strpos($text, "[/spoiler]") !== false) && (strpos($text, "[spoiler=") !== false) && (++$endlessloop < 20)) {
+ $text = preg_replace(
+ "/\[spoiler=[\"\']*(.*?)[\"\']*\](.*?)\[\/spoiler\]/ism",
'<details class="spoiler"><summary>$1</summary>$2</details>',
- $text);
+ $text
+ );
}
// Declare the format for [quote] layout
- $QuoteLayout = '<blockquote>$1</blockquote>';
+ $QuoteLayout = '</p><blockquote>$1</blockquote><p>';
// Check for [quote] text
// handle nested quotes
// handle nested quotes
$endlessloop = 0;
- while ((strpos($text, "[/quote]")!== false) && (strpos($text, "[quote=") !== false) && (++$endlessloop < 20)) {
- $text = preg_replace("/\[quote=[\"\']*(.*?)[\"\']*\](.*?)\[\/quote\]/ism",
- "<p><strong class=".'"author"'.">" . $t_wrote . "</strong></p><blockquote>$2</blockquote>",
- $text);
+ while ((strpos($text, "[/quote]") !== false) && (strpos($text, "[quote=") !== false) && (++$endlessloop < 20)) {
+ $text = preg_replace(
+ "/\[quote=[\"\']*(.*?)[\"\']*\](.*?)\[\/quote\]/ism",
+ "<p><strong class=" . '"author"' . ">" . $t_wrote . "</strong></p><blockquote>$2</blockquote>",
+ $text
+ );
}
$text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '<img src="$3" style="width: $1px;" >', $text);
$text = preg_replace("/\[zmg\=([0-9]*)x([0-9]*)\](.*?)\[\/zmg\]/ism", '<img class="zrl" src="$3" style="width: $1px;" >', $text);
- $text = preg_replace_callback("/\[img\=(.*?)\](.*?)\[\/img\]/ism",
+ $text = preg_replace_callback(
+ "/\[[iz]mg\=(.*?)\](.*?)\[\/[iz]mg\]/ism",
function ($matches) use ($simple_html, $uriid) {
$matches[1] = self::proxyUrl($matches[1], $simple_html, $uriid);
- $matches[2] = htmlspecialchars($matches[2], ENT_COMPAT);
- return '<img src="' . $matches[1] . '" alt="' . $matches[2] . '" title="' . $matches[2] . '">';
+ $alt = htmlspecialchars($matches[2], ENT_COMPAT);
+ // Fix for Markdown problems with Diaspora, see issue #12701
+ if (($simple_html != self::DIASPORA) || strpos($matches[2], '"') === false) {
+ return '<img src="' . $matches[1] . '" alt="' . $alt . '" title="' . $alt . '">';
+ } else {
+ return '<img src="' . $matches[1] . '" alt="' . $alt . '">';
+ }
},
- $text);
+ $text
+ );
// Images
// [img]pathtoimage[/img]
$text = preg_replace_callback(
- "/\[img\](.*?)\[\/img\]/ism",
+ "/\[[iz]mg\](.*?)\[\/[iz]mg\]/ism",
function ($matches) use ($simple_html, $uriid) {
if (strpos($matches[1], "data:image/") === 0) {
return $matches[0];
$text = self::convertImages($text, $simple_html, $uriid);
- $text = preg_replace("/\[crypt\](.*?)\[\/crypt\]/ism", '<br><img src="' .DI::baseUrl() . '/images/lock_icon.gif" alt="' . DI::l10n()->t('Encrypted content') . '" title="' . DI::l10n()->t('Encrypted content') . '" /><br>', $text);
- $text = preg_replace("/\[crypt(.*?)\](.*?)\[\/crypt\]/ism", '<br><img src="' .DI::baseUrl() . '/images/lock_icon.gif" alt="' . DI::l10n()->t('Encrypted content') . '" title="' . '$1' . ' ' . DI::l10n()->t('Encrypted content') . '" /><br>', $text);
+ $text = preg_replace("/\[crypt\](.*?)\[\/crypt\]/ism", '<br><img src="' . DI::baseUrl() . '/images/lock_icon.gif" alt="' . DI::l10n()->t('Encrypted content') . '" title="' . DI::l10n()->t('Encrypted content') . '" /><br>', $text);
+ $text = preg_replace("/\[crypt(.*?)\](.*?)\[\/crypt\]/ism", '<br><img src="' . DI::baseUrl() . '/images/lock_icon.gif" alt="' . DI::l10n()->t('Encrypted content') . '" title="' . '$1' . ' ' . DI::l10n()->t('Encrypted content') . '" /><br>', $text);
//$text = preg_replace("/\[crypt=(.*?)\](.*?)\[\/crypt\]/ism", '<br><img src="' .DI::baseUrl() . '/images/lock_icon.gif" alt="' . DI::l10n()->t('Encrypted content') . '" title="' . '$1' . ' ' . DI::l10n()->t('Encrypted content') . '" /><br>', $text);
// Simplify "video" element
if ($try_oembed) {
// html5 video and audio
- $text = preg_replace("/\[video\](.*?\.(ogg|ogv|oga|ogm|webm|mp4).*?)\[\/video\]/ism",
- '<video src="$1" controls width="100%" height="auto"><a href="$1">$1</a></video>', $text);
+ $text = preg_replace(
+ "/\[video\](.*?\.(ogg|ogv|oga|ogm|webm|mp4).*?)\[\/video\]/ism",
+ '<video src="$1" controls width="100%" height="auto"><a href="$1">$1</a></video>',
+ $text
+ );
$text = preg_replace_callback("/\[video\](.*?)\[\/video\]/ism", $try_oembed_callback, $text);
$text = preg_replace_callback("/\[audio\](.*?)\[\/audio\]/ism", $try_oembed_callback, $text);
- $text = preg_replace("/\[video\](.*?)\[\/video\]/ism",
- '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>', $text);
+ $text = preg_replace(
+ "/\[video\](.*?)\[\/video\]/ism",
+ '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>',
+ $text
+ );
$text = preg_replace("/\[audio\](.*?)\[\/audio\]/ism", '<audio src="$1" controls><a href="$1">$1</a></audio>', $text);
} else {
- $text = preg_replace("/\[video\](.*?)\[\/video\]/ism",
- '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>', $text);
- $text = preg_replace("/\[audio\](.*?)\[\/audio\]/ism",
- '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>', $text);
+ $text = preg_replace(
+ "/\[video\](.*?)\[\/video\]/ism",
+ '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>',
+ $text
+ );
+ $text = preg_replace(
+ "/\[audio\](.*?)\[\/audio\]/ism",
+ '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>',
+ $text
+ );
}
// Backward compatibility, [iframe] support has been removed in version 2020.12
if ($try_oembed) {
$text = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism", '<iframe width="' . $a->getThemeInfoValue('videowidth') . '" height="' . $a->getThemeInfoValue('videoheight') . '" src="https://www.youtube.com/embed/$1" frameborder="0" ></iframe>', $text);
} else {
- $text = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
- '<a href="https://www.youtube.com/watch?v=$1" target="_blank" rel="noopener noreferrer">https://www.youtube.com/watch?v=$1</a>', $text);
+ $text = preg_replace(
+ "/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
+ '<a href="https://www.youtube.com/watch?v=$1" target="_blank" rel="noopener noreferrer">https://www.youtube.com/watch?v=$1</a>',
+ $text
+ );
}
if ($try_oembed) {
if ($try_oembed) {
$text = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism", '<iframe width="' . $a->getThemeInfoValue('videowidth') . '" height="' . $a->getThemeInfoValue('videoheight') . '" src="https://player.vimeo.com/video/$1" frameborder="0" ></iframe>', $text);
} else {
- $text = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
- '<a href="https://vimeo.com/$1" target="_blank" rel="noopener noreferrer">https://vimeo.com/$1</a>', $text);
+ $text = preg_replace(
+ "/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
+ '<a href="https://vimeo.com/$1" target="_blank" rel="noopener noreferrer">https://vimeo.com/$1</a>',
+ $text
+ );
}
// oembed tag
// Handle mentions and hashtag links
if ($simple_html == self::DIASPORA) {
// The ! is converted to @ since Diaspora only understands the @
- $text = preg_replace("/([@!])\[url\=(.*?)\](.*?)\[\/url\]/ism",
+ $text = preg_replace(
+ "/([@!])\[url\=(.*?)\](.*?)\[\/url\]/ism",
'@<a href="$2">$3</a>',
- $text);
+ $text
+ );
} elseif (in_array($simple_html, [self::OSTATUS, self::ACTIVITYPUB])) {
- $text = preg_replace("/([@!])\[url\=(.*?)\](.*?)\[\/url\]/ism",
+ $text = preg_replace(
+ "/([@!])\[url\=(.*?)\](.*?)\[\/url\]/ism",
'<span class="h-card"><a href="$2" class="u-url mention">$1<span>$3</span></a></span>',
- $text);
- $text = preg_replace("/([#])\[url\=(.*?)\](.*?)\[\/url\]/ism",
+ $text
+ );
+ $text = preg_replace(
+ "/([#])\[url\=(.*?)\](.*?)\[\/url\]/ism",
'<a href="$2" class="mention hashtag" rel="tag">$1<span>$3</span></a>',
- $text);
- } elseif (in_array($simple_html, [self::INTERNAL, self::EXTERNAL, self::API])) {
- $text = preg_replace("/([@!])\[url\=(.*?)\](.*?)\[\/url\]/ism",
+ $text
+ );
+ } elseif (in_array($simple_html, [self::INTERNAL, self::EXTERNAL, self::TWITTER_API])) {
+ $text = preg_replace(
+ "/([@!])\[url\=(.*?)\](.*?)\[\/url\]/ism",
'<bdi>$1<a href="$2" class="userinfo mention" title="$3">$3</a></bdi>',
- $text);
+ $text
+ );
+ } elseif ($simple_html == self::MASTODON_API) {
+ $text = preg_replace(
+ "/([@!])\[url\=(.*?)\](.*?)\[\/url\]/ism",
+ '<a class="u-url mention status-link" href="$2" rel="nofollow noopener noreferrer" target="_blank" title="$3">$1<span>$3</span></a>',
+ $text
+ );
+ $text = preg_replace(
+ "/([#])\[url\=(.*?)\](.*?)\[\/url\]/ism",
+ '<a class="mention hashtag status-link" href="$2" rel="tag">$1<span>$3</span></a>',
+ $text
+ );
} else {
$text = preg_replace("/([#@!])\[url\=(.*?)\](.*?)\[\/url\]/ism", '$1$3', $text);
}
if (!$for_plaintext) {
- if (in_array($simple_html, [self::OSTATUS, self::API, self::ACTIVITYPUB])) {
- $text = preg_replace_callback("/\[url\](.*?)\[\/url\]/ism", 'self::convertUrlForActivityPubCallback', $text);
- $text = preg_replace_callback("/\[url\=(.*?)\](.*?)\[\/url\]/ism", 'self::convertUrlForActivityPubCallback', $text);
+ if (in_array($simple_html, [self::OSTATUS, self::MASTODON_API, self::TWITTER_API, self::ACTIVITYPUB])) {
+ $text = preg_replace_callback("/\[url\](.*?)\[\/url\]/ism", [self::class, 'convertUrlForActivityPubCallback'], $text);
+ $text = preg_replace_callback("/\[url\=(.*?)\](.*?)\[\/url\]/ism", [self::class, 'convertUrlForActivityPubCallback'], $text);
}
} else {
$text = preg_replace("(\[url\](.*?)\[\/url\])ism", " $1 ", $text);
- $text = preg_replace_callback("&\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]&Usi", 'self::removePictureLinksCallback', $text);
+ $text = preg_replace_callback("&\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]&Usi", [self::class, 'removePictureLinksCallback'], $text);
}
// Bookmarks in red - will be converted to bookmarks in friendica
$text = preg_replace("/#\^\[url\](.*?)\[\/url\]/ism", '[bookmark=$1]$1[/bookmark]', $text);
$text = preg_replace("/#\^\[url\=(.*?)\](.*?)\[\/url\]/ism", '[bookmark=$1]$2[/bookmark]', $text);
- $text = preg_replace("/#\[url\=.*?\]\^\[\/url\]\[url\=(.*?)\](.*?)\[\/url\]/i",
- "[bookmark=$1]$2[/bookmark]", $text);
+ $text = preg_replace(
+ "/#\[url\=.*?\]\^\[\/url\]\[url\=(.*?)\](.*?)\[\/url\]/i",
+ "[bookmark=$1]$2[/bookmark]",
+ $text
+ );
if (in_array($simple_html, [self::OSTATUS, self::TWITTER])) {
- $text = preg_replace_callback("/([^#@!])\[url\=([^\]]*)\](.*?)\[\/url\]/ism", "self::expandLinksCallback", $text);
+ $text = preg_replace_callback("/([^#@!])\[url\=([^\]]*)\](.*?)\[\/url\]/ism", [self::class, 'expandLinksCallback'], $text);
//$text = preg_replace("/[^#@!]\[url\=([^\]]*)\](.*?)\[\/url\]/ism", ' $2 [url]$1[/url]', $text);
$text = preg_replace("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism", ' $2 [url]$1[/url]', $text);
}
"&\[url=/?posts/([^\[\]]*)\](.*)\[\/url\]&Usi",
function ($match) {
return "[url=" . DI::baseUrl() . "/display/" . $match[1] . "]" . $match[2] . "[/url]";
- }, $text
+ },
+ $text
);
$text = preg_replace_callback(
"&\[url=/people\?q\=(.*)\](.*)\[\/url\]&Usi",
function ($match) {
return "[url=" . DI::baseUrl() . "/search?search=%40" . $match[1] . "]" . $match[2] . "[/url]";
- }, $text
+ },
+ $text
);
// Server independent link to posts and comments
// See issue: https://github.com/diaspora/diaspora_federation/issues/75
$expression = "=diaspora://.*?/post/([0-9A-Za-z\-_@.:]{15,254}[0-9A-Za-z])=ism";
- $text = preg_replace($expression, DI::baseUrl()."/display/$1", $text);
+ $text = preg_replace($expression, DI::baseUrl() . "/display/$1", $text);
/* Tag conversion
* Supports:
* - [url=<anything>]#<term>[/url]
*/
self::performWithEscapedTags($text, ['url', 'share'], function ($text) use ($simple_html) {
- $text = preg_replace_callback("/(?:#\[url\=[^\[\]]*\]|\[url\=[^\[\]]*\]#)(.*?)\[\/url\]/ism", function($matches) use ($simple_html) {
+ $text = preg_replace_callback("/(?:#\[url\=[^\[\]]*\]|\[url\=[^\[\]]*\]#)(.*?)\[\/url\]/ism", function ($matches) use ($simple_html) {
if ($simple_html == self::ACTIVITYPUB) {
return '<a href="' . DI::baseUrl() . '/search?tag=' . rawurlencode($matches[1])
. '" data-tag="' . XML::escape($matches[1]) . '" rel="tag ugc">#'
// We need no target="_blank" rel="noopener noreferrer" for local links
// convert links start with DI::baseUrl() as local link without the target="_blank" rel="noopener noreferrer" attribute
$escapedBaseUrl = preg_quote(DI::baseUrl(), '/');
- $text = preg_replace("/\[url\](".$escapedBaseUrl.".*?)\[\/url\]/ism", '<a href="$1">$1</a>', $text);
- $text = preg_replace("/\[url\=(".$escapedBaseUrl.".*?)\](.*?)\[\/url\]/ism", '<a href="$1">$2</a>', $text);
+ $text = preg_replace("/\[url\](" . $escapedBaseUrl . ".*?)\[\/url\]/ism", '<a href="$1">$1</a>', $text);
+ $text = preg_replace("/\[url\=(" . $escapedBaseUrl . ".*?)\](.*?)\[\/url\]/ism", '<a href="$1">$2</a>', $text);
$text = preg_replace("/\[url\](.*?)\[\/url\]/ism", '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>', $text);
$text = preg_replace("/\[url\=(.*?)\](.*?)\[\/url\]/ism", '<a href="$1" target="_blank" rel="noopener noreferrer">$2</a>', $text);
$text = preg_replace('/\<([^>]*?)(src|href)=(.*?)\&\;(.*?)\>/ism', '<$1$2=$3&$4>', $text);
// sanitizes src attributes (http and redir URLs for displaying in a web page, cid used for inline images in emails)
- $allowed_src_protocols = ['//', 'http://', 'https://', 'redir/', 'cid:'];
+ $allowed_src_protocols = ['//', 'http://', 'https://', 'contact/redir/', 'cid:'];
- array_walk($allowed_src_protocols, function(&$value) { $value = preg_quote($value, '#');});
+ array_walk($allowed_src_protocols, function (&$value) {
+ $value = preg_quote($value, '#');
+ });
- $text = preg_replace('#<([^>]*?)(src)="(?!' . implode('|', $allowed_src_protocols) . ')(.*?)"(.*?)>#ism',
- '<$1$2=""$4 data-original-src="$3" class="invalid-src" title="' . DI::l10n()->t('Invalid source protocol') . '">', $text);
+ $text = preg_replace(
+ '#<([^>]*?)(src)="(?!' . implode('|', $allowed_src_protocols) . ')(.*?)"(.*?)>#ism',
+ '<$1$2=""$4 data-original-src="$3" class="invalid-src" title="' . DI::l10n()->t('Invalid source protocol') . '">',
+ $text
+ );
// sanitize href attributes (only allowlisted protocols URLs)
// default value for backward compatibility
$allowed_link_protocols[] = '//';
$allowed_link_protocols[] = 'http://';
$allowed_link_protocols[] = 'https://';
- $allowed_link_protocols[] = 'redir/';
+ $allowed_link_protocols[] = 'contact/redir/';
- array_walk($allowed_link_protocols, function(&$value) { $value = preg_quote($value, '#');});
+ array_walk($allowed_link_protocols, function (&$value) {
+ $value = preg_quote($value, '#');
+ });
$regex = '#<([^>]*?)(href)="(?!' . implode('|', $allowed_link_protocols) . ')(.*?)"(.*?)>#ism';
$text = preg_replace($regex, '<$1$2="javascript:void(0)"$4 data-original-href="$3" class="invalid-href" title="' . DI::l10n()->t('Invalid link protocol') . '">', $text);
$text,
function (array $attributes, array $author_contact, $content, $is_quote_share) use ($simple_html) {
return self::convertShareCallback($attributes, $author_contact, $content, $is_quote_share, $simple_html);
- }, $uriid
+ },
+ $uriid
);
$text = self::interpolateSavedImagesIntoItemBody($uriid, $text, $saved_image);
// Additionally, [pre] tags preserve spaces
$text = preg_replace_callback("/\[pre\](.*?)\[\/pre\]/ism", function ($match) {
- return str_replace([' ', "\n"], [' ', "<br>"], htmlentities($match[1], ENT_NOQUOTES,'UTF-8'));
+ return str_replace([' ', "\n"], [' ', "<br>"], htmlentities($match[1], ENT_NOQUOTES, 'UTF-8'));
}, $text);
return $text;
}); // Escaped code
- $text = preg_replace_callback("#\[code(?:=([^\]]*))?\](.*?)\[\/code\]#ism",
+ $text = preg_replace_callback(
+ "#\[code(?:=([^\]]*))?\](.*?)\[\/code\]#ism",
function ($matches) {
if (strpos($matches[2], "\n") !== false) {
$return = '<pre><code class="language-' . trim($matches[1]) . '">' . htmlentities(trim($matches[2], "\n\r"), ENT_NOQUOTES, 'UTF-8') . '</code></pre>';
// Default iframe allowed domains/path
$allowedIframeDomains = [
- DI::baseUrl()->getHostname()
- . (DI::baseUrl()->getUrlPath() ? '/' . DI::baseUrl()->getUrlPath() : '')
- . '/oembed/', # The path part has to change with the source in Content\Oembed::iframe
+ 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/',
];
: []
);
+ if (strpos($text, '<p>') !== false || strpos($text, '</p>') !== false) {
+ $text = '<p>' . $text . '</p>';
+ }
+
$text = HTML::purify($text, $allowedIframeDomains);
DI::profiler()->stopRecording();
* Transform #tags, strip off the [url] and replace spaces with underscore
*/
$url_search_string = "^\[\]";
- $text = preg_replace_callback("/#\[url\=([$url_search_string]*)\](.*?)\[\/url\]/i",
+ $text = preg_replace_callback(
+ "/#\[url\=([$url_search_string]*)\](.*?)\[\/url\]/i",
function ($matches) {
return '#' . str_replace(' ', '_', $matches[2]);
},
$url_search_string = "^\[\]";
$text = preg_replace_callback(
"/([@!])\[(.*?)\]\(([$url_search_string]*?)\)/ism",
- ['self', 'bbCodeMention2DiasporaCallback'],
+ [self::class, 'bbCodeMention2DiasporaCallback'],
$text
);
}
DI::profiler()->startRecording('rendering');
$ret = [];
- self::performWithEscapedTags($string, ['noparse', 'pre', 'code', 'img'], function ($string) use (&$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);
*/
public static function expandTags(string $body): string
{
- return preg_replace_callback("/(?<=\W|^)([!#@])([^\^ \x0D\x0A,;:?'\"]*[^\^ \x0D\x0A,;:?!'\".])/",
+ return preg_replace_callback(
+ "/(?<=\W|^)([!#@])([^\^ \x0D\x0A,;:?'\"]*[^\^ \x0D\x0A,;:?!'\".])/",
function (array $match) {
switch ($match[1]) {
case '!':
default:
return $match[1] . '[url=' . DI::baseUrl() . '/search?tag=' . $match[2] . ']' . $match[2] . '[/url]';
}
- }, $body);
+ },
+ $body
+ );
}
/**
// Bypass attachment if parse url for a comment
if (!$tryAttachment) {
DI::profiler()->stopRecording();
- return "\n" . '[url=' . $url . ']' . $siteinfo['title'] . '[/url]';
+ return "\n" . '[url=' . $url . ']' . ($siteinfo['title'] ?? $url) . '[/url]';
}
// Format it as BBCode attachment