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