]> git.mxchange.org Git - friendica.git/blob - src/Content/Text/Markdown.php
spelling: occurred
[friendica.git] / src / Content / Text / Markdown.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Content\Text;
23
24 use Friendica\Core\Logger;
25 use Friendica\Core\System;
26 use Friendica\DI;
27 use Friendica\Model\Contact;
28
29 /**
30  * Friendica-specific usage of Markdown
31  */
32 class Markdown
33 {
34         /**
35          * Converts a Markdown string into HTML. The hardwrap parameter maximizes
36          * compatibility with Diaspora in spite of the Markdown standard.
37          *
38          * @param string $text
39          * @param bool   $hardwrap Enables line breaks on \n without two trailing spaces
40          * @param string $baseuri  Optional. Prepend anchor links with this URL
41          * @return string
42          */
43         public static function convert($text, $hardwrap = true, $baseuri = null) {
44                 DI::profiler()->startRecording('rendering');
45
46                 $MarkdownParser = new MarkdownParser();
47                 $MarkdownParser->code_class_prefix  = 'language-';
48                 $MarkdownParser->hard_wrap          = $hardwrap;
49                 $MarkdownParser->hashtag_protection = true;
50                 $MarkdownParser->url_filter_func    = function ($url) use ($baseuri) {
51                         if (!empty($baseuri) && strpos($url, '#') === 0) {
52                                 $url = ltrim($baseuri, '/') . $url;
53                         }
54                         return  $url;
55                 };
56
57                 $text = self::convertDiasporaMentionsToHtml($text);
58
59                 $html = $MarkdownParser->transform($text);
60
61                 DI::profiler()->stopRecording();
62
63                 return $html;
64         }
65
66         /**
67          * Replace Diaspora-style mentions in a text since they trip the Markdown parser autolinker.
68          *
69          * @param string $text
70          * @return string
71          */
72         private static function convertDiasporaMentionsToHtml(string $text)
73         {
74                 return preg_replace_callback(
75                         '/([@!]){(?:([^}]+?); ?)?([^} ]+)}/',
76                         /*
77                          * Matching values for the callback
78                          * [1] = mention type (@ or !)
79                          * [2] = name (optional)
80                          * [3] = profile URL
81                          */
82                         function ($matches) {
83                                 if ($matches[3] == '') {
84                                         return '';
85                                 }
86
87                                 $data = Contact::getByURL($matches[3]);
88
89                                 if (empty($data)) {
90                                         return '';
91                                 }
92
93                                 $name = $matches[2];
94
95                                 if ($name == '') {
96                                         $name = $data['name'];
97                                 }
98
99                                 return $matches[1] . '<a href="' . $data['url'] . '">' . $name . '</a>';
100                         },
101                         $text
102                 );
103         }
104
105         /*
106          * we don't want to support a bbcode specific markdown interpreter
107          * and the markdown library we have is pretty good, but provides HTML output.
108          * So we'll use that to convert to HTML, then convert the HTML back to bbcode,
109          * and then clean up a few Diaspora specific constructs.
110          */
111         public static function toBBCode($s): string
112         {
113                 // @TODO Temporary until we find the source of the null value to finally set the correct type-hint
114                 if (is_null($s)) {
115                         Logger::warning('Received null value', ['callstack' => System::callstack()]);
116                         return '';
117                 }
118
119                 if (!$s) {
120                         return $s;
121                 }
122
123                 DI::profiler()->startRecording('rendering');
124
125                 // The parser cannot handle paragraphs correctly
126                 $s = str_replace(['</p>', '<p>', '<p dir="ltr">'], ['<br>', '<br>', '<br>'], $s);
127
128                 // Escaping hashtags that could be titles
129                 $s = preg_replace('/^\#([^\s\#])/im', '\#$1', $s);
130
131                 $s = self::convert($s);
132
133                 $s = HTML::toBBCode($s);
134
135                 // protect the recycle symbol from turning into a tag, but without unescaping angles and naked ampersands
136                 $s = str_replace('&#x2672;', html_entity_decode('&#x2672;', ENT_QUOTES, 'UTF-8'), $s);
137
138                 //$s = preg_replace("/([^\]\=]|^)(https?\:\/\/)(vimeo|youtu|www\.youtube|soundcloud)([a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2$3$4]$2$3$4[/url]',$s);
139                 $s = BBCode::pregReplaceInTag('/\[url\=?(.*?)\]https?:\/\/www.youtube.com\/watch\?v\=(.*?)\[\/url\]/ism', '[youtube]$2[/youtube]', 'url', $s);
140                 $s = BBCode::pregReplaceInTag('/\[url\=https?:\/\/www.youtube.com\/watch\?v\=(.*?)\].*?\[\/url\]/ism'   , '[youtube]$1[/youtube]', 'url', $s);
141                 $s = BBCode::pregReplaceInTag('/\[url\=https?:\/\/www.youtube.com\/shorts\/(.*?)\].*?\[\/url\]/ism'     , '[youtube]$1[/youtube]', 'url', $s);
142                 $s = BBCode::pregReplaceInTag('/\[url\=?(.*?)\]https?:\/\/vimeo.com\/([0-9]+)(.*?)\[\/url\]/ism'        , '[vimeo]$2[/vimeo]'    , 'url', $s);
143                 $s = BBCode::pregReplaceInTag('/\[url\=https?:\/\/vimeo.com\/([0-9]+)\](.*?)\[\/url\]/ism'              , '[vimeo]$1[/vimeo]'    , 'url', $s);
144
145                 // remove duplicate adjacent code tags
146                 $s = preg_replace('/(\[code\])+(.*?)(\[\/code\])+/ism', '[code]$2[/code]', $s);
147
148                 DI::profiler()->stopRecording();
149                 return $s;
150         }
151 }