]> git.mxchange.org Git - friendica.git/blob - src/Content/Text/Markdown.php
Merge pull request #11230 from annando/account-type
[friendica.git] / src / Content / Text / Markdown.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, 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\DI;
25 use Friendica\Model\Contact;
26
27 /**
28  * Friendica-specific usage of Markdown
29  */
30 class Markdown
31 {
32         /**
33          * Converts a Markdown string into HTML. The hardwrap parameter maximizes
34          * compatibility with Diaspora in spite of the Markdown standard.
35          *
36          * @param string $text
37          * @param bool   $hardwrap Enables line breaks on \n without two trailing spaces
38          * @param string $baseuri  Optional. Prepend anchor links with this URL
39          * @return string
40          */
41         public static function convert($text, $hardwrap = true, $baseuri = null) {
42                 DI::profiler()->startRecording('rendering');
43
44                 $MarkdownParser = new MarkdownParser();
45                 $MarkdownParser->code_class_prefix  = 'language-';
46                 $MarkdownParser->hard_wrap          = $hardwrap;
47                 $MarkdownParser->hashtag_protection = true;
48                 $MarkdownParser->url_filter_func    = function ($url) use ($baseuri) {
49                         if (!empty($baseuri) && strpos($url, '#') === 0) {
50                                 $url = ltrim($baseuri, '/') . $url;
51                         }
52                         return  $url;
53                 };
54
55                 $text = self::convertDiasporaMentionsToHtml($text);
56
57                 $html = $MarkdownParser->transform($text);
58
59                 DI::profiler()->stopRecording();
60
61                 return $html;
62         }
63
64         /**
65          * Replace Diaspora-style mentions in a text since they trip the Markdown parser autolinker.
66          *
67          * @param string $text
68          * @return string
69          */
70         private static function convertDiasporaMentionsToHtml(string $text)
71         {
72                 return preg_replace_callback(
73                         '/([@!]){(?:([^}]+?); ?)?([^} ]+)}/',
74                         /*
75                          * Matching values for the callback
76                          * [1] = mention type (@ or !)
77                          * [2] = name (optional)
78                          * [3] = profile URL
79                          */
80                         function ($matches) {
81                                 if ($matches[3] == '') {
82                                         return '';
83                                 }
84
85                                 $data = Contact::getByURL($matches[3]);
86
87                                 if (empty($data)) {
88                                         return '';
89                                 }
90
91                                 $name = $matches[2];
92
93                                 if ($name == '') {
94                                         $name = $data['name'];
95                                 }
96
97                                 return $matches[1] . '<a href="' . $data['url'] . '">' . $name . '</a>';
98                         },
99                         $text
100                 );
101         }
102
103         /*
104          * we don't want to support a bbcode specific markdown interpreter
105          * and the markdown library we have is pretty good, but provides HTML output.
106          * So we'll use that to convert to HTML, then convert the HTML back to bbcode,
107          * and then clean up a few Diaspora specific constructs.
108          */
109         public static function toBBCode($s)
110         {
111                 DI::profiler()->startRecording('rendering');
112
113                 // The parser cannot handle paragraphs correctly
114                 $s = str_replace(['</p>', '<p>', '<p dir="ltr">'], ['<br>', '<br>', '<br>'], $s);
115
116                 // Escaping hashtags that could be titles
117                 $s = preg_replace('/^\#([^\s\#])/im', '\#$1', $s);
118
119                 $s = self::convert($s);
120
121                 $s = HTML::toBBCode($s);
122
123                 // protect the recycle symbol from turning into a tag, but without unescaping angles and naked ampersands
124                 $s = str_replace('&#x2672;', html_entity_decode('&#x2672;', ENT_QUOTES, 'UTF-8'), $s);
125
126                 //$s = preg_replace("/([^\]\=]|^)(https?\:\/\/)(vimeo|youtu|www\.youtube|soundcloud)([a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2$3$4]$2$3$4[/url]',$s);
127                 $s = BBCode::pregReplaceInTag('/\[url\=?(.*?)\]https?:\/\/www.youtube.com\/watch\?v\=(.*?)\[\/url\]/ism', '[youtube]$2[/youtube]', 'url', $s);
128                 $s = BBCode::pregReplaceInTag('/\[url\=https?:\/\/www.youtube.com\/watch\?v\=(.*?)\].*?\[\/url\]/ism'   , '[youtube]$1[/youtube]', 'url', $s);
129                 $s = BBCode::pregReplaceInTag('/\[url\=?(.*?)\]https?:\/\/vimeo.com\/([0-9]+)(.*?)\[\/url\]/ism'        , '[vimeo]$2[/vimeo]'    , 'url', $s);
130                 $s = BBCode::pregReplaceInTag('/\[url\=https?:\/\/vimeo.com\/([0-9]+)\](.*?)\[\/url\]/ism'              , '[vimeo]$1[/vimeo]'    , 'url', $s);
131
132                 // remove duplicate adjacent code tags
133                 $s = preg_replace('/(\[code\])+(.*?)(\[\/code\])+/ism', '[code]$2[/code]', $s);
134
135                 // Don't show link to full picture (until it is fixed)
136                 $s = BBCode::scaleExternalImages($s);
137
138                 DI::profiler()->stopRecording();
139                 return $s;
140         }
141 }