4 * Description: Parse Markdown code when creating new items
6 * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
9 use Friendica\Core\Hook;
10 use Friendica\Content\Text\Markdown;
11 use Friendica\Core\Renderer;
14 function markdown_install() {
15 Hook::register('post_local_start', __FILE__, 'markdown_post_local_start');
16 Hook::register('addon_settings', __FILE__, 'markdown_addon_settings');
17 Hook::register('addon_settings_post', __FILE__, 'markdown_addon_settings_post');
20 function markdown_addon_settings(array &$data)
22 if (!DI::userSession()->getLocalUserId()) {
26 $enabled = intval(DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'markdown', 'enabled'));
28 $t = Renderer::getMarkupTemplate('settings.tpl', 'addon/markdown/');
29 $html = Renderer::replaceMacros($t, [
30 '$enabled' => ['enabled', DI::l10n()->t('Enable Markdown parsing'), $enabled, DI::l10n()->t('If enabled, adds Markdown support to the Compose Post form.')],
34 'addon' => 'markdown',
35 'title' => DI::l10n()->t('Markdown Settings'),
40 function markdown_addon_settings_post(array &$b)
42 if (!DI::userSession()->getLocalUserId() || empty($_POST['markdown-submit'])) {
46 DI::pConfig()->set(DI::userSession()->getLocalUserId(), 'markdown', 'enabled', intval($_POST['enabled']));
49 function markdown_post_local_start(&$request) {
50 if (empty($request['body']) || !DI::pConfig()->get(DI::userSession()->getLocalUserId(), 'markdown', 'enabled')) {
54 // Escape elements that shouldn't be parsed
55 $request['body'] = \Friendica\Content\Text\BBCode::performWithEscapedTags(
57 ['code', 'noparse', 'nobb', 'pre', 'share', 'url', 'img', 'bookmark',
58 'audio', 'video', 'youtube', 'vimeo', 'attachment', 'iframe', 'map', 'mail'],
60 // Escape mentions which username can contain Markdown-like characters
61 // See https://github.com/friendica/friendica/issues/9486
62 return \Friendica\Util\Strings::performWithEscapedBlocks($body, '/[@!][^@\s]+@[^\s]+\w/', function ($text) {
63 // Markdown accepts literal HTML but we do not in post body, so we need to escape left chevrons
64 // (right chevrons are used for quoting in Markdown)
65 // See https://github.com/friendica/friendica/issues/10634
66 $text = strtr($text, ['<' => '<']);
68 return Markdown::toBBCode($text);