Merge branch 'delete_orphaned_activities' into develop
[akkoma] / lib / pleroma / formatter.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2021 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Formatter do
6 alias Pleroma.HTML
7 alias Pleroma.User
8
9 @safe_mention_regex ~r/^(\s*(?<mentions>(@.+?\s+){1,})+)(?<rest>.*)/s
10 @link_regex ~r"((?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~%:/?#[\]@!\$&'\(\)\*\+,;=.]+)|[0-9a-z+\-\.]+:[0-9a-z$-_.+!*'(),]+"ui
11 @markdown_characters_regex ~r/(`|\*|_|{|}|[|]|\(|\)|#|\+|-|\.|!)/
12
13 defp linkify_opts do
14 Pleroma.Config.get(Pleroma.Formatter) ++
15 [
16 hashtag: true,
17 hashtag_handler: &Pleroma.Formatter.hashtag_handler/4,
18 mention: true,
19 mention_handler: &Pleroma.Formatter.mention_handler/4
20 ]
21 end
22
23 def escape_mention_handler("@" <> nickname = mention, buffer, _, _) do
24 case User.get_cached_by_nickname(nickname) do
25 %User{} ->
26 # escape markdown characters with `\\`
27 # (we don't want something like @user__name to be parsed by markdown)
28 String.replace(mention, @markdown_characters_regex, "\\\\\\1")
29
30 _ ->
31 buffer
32 end
33 end
34
35 def mention_tag(%User{id: id} = user, nickname, opts \\ []) do
36 user_url = user.uri || user.ap_id
37 nickname_text = get_nickname_text(nickname, opts)
38
39 :span
40 |> Phoenix.HTML.Tag.content_tag(
41 Phoenix.HTML.Tag.content_tag(
42 :a,
43 ["@", Phoenix.HTML.Tag.content_tag(:span, nickname_text)],
44 "data-user": id,
45 class: "u-url mention",
46 href: user_url,
47 rel: "ugc"
48 ),
49 class: "h-card"
50 )
51 |> Phoenix.HTML.safe_to_string()
52 end
53
54 def mention_handler("@" <> nickname, buffer, opts, acc) do
55 case User.get_cached_by_nickname(nickname) do
56 %User{id: _id} = user ->
57 link = mention_tag(user, nickname, opts)
58
59 {link, %{acc | mentions: MapSet.put(acc.mentions, {"@" <> nickname, user})}}
60
61 _ ->
62 {buffer, acc}
63 end
64 end
65
66 def hashtag_handler("#" <> tag = tag_text, _buffer, _opts, acc) do
67 tag = String.downcase(tag)
68 url = "#{Pleroma.Web.Endpoint.url()}/tag/#{tag}"
69
70 link =
71 Phoenix.HTML.Tag.content_tag(:a, tag_text,
72 class: "hashtag",
73 "data-tag": tag,
74 href: url,
75 rel: "tag ugc"
76 )
77 |> Phoenix.HTML.safe_to_string()
78
79 {link, %{acc | tags: MapSet.put(acc.tags, {tag_text, tag})}}
80 end
81
82 @doc """
83 Parses a text and replace plain text links with HTML. Returns a tuple with a result text, mentions, and hashtags.
84
85 If the 'safe_mention' option is given, only consecutive mentions at the start the post are actually mentioned.
86 """
87 @spec linkify(String.t(), keyword()) ::
88 {String.t(), [{String.t(), User.t()}], [{String.t(), String.t()}]}
89 def linkify(text, options \\ []) do
90 options = linkify_opts() ++ options
91
92 if options[:safe_mention] && Regex.named_captures(@safe_mention_regex, text) do
93 %{"mentions" => mentions, "rest" => rest} = Regex.named_captures(@safe_mention_regex, text)
94 acc = %{mentions: MapSet.new(), tags: MapSet.new()}
95
96 {text_mentions, %{mentions: mentions}} = Linkify.link_map(mentions, acc, options)
97 {text_rest, %{tags: tags}} = Linkify.link_map(rest, acc, options)
98
99 {text_mentions <> text_rest, MapSet.to_list(mentions), MapSet.to_list(tags)}
100 else
101 acc = %{mentions: MapSet.new(), tags: MapSet.new()}
102 {text, %{mentions: mentions, tags: tags}} = Linkify.link_map(text, acc, options)
103
104 {text, MapSet.to_list(mentions), MapSet.to_list(tags)}
105 end
106 end
107
108 @doc """
109 Escapes a special characters in mention names.
110 """
111 def mentions_escape(text, options \\ []) do
112 options =
113 Keyword.merge(options,
114 mention: true,
115 url: false,
116 mention_handler: &Pleroma.Formatter.escape_mention_handler/4
117 )
118
119 if options[:safe_mention] && Regex.named_captures(@safe_mention_regex, text) do
120 %{"mentions" => mentions, "rest" => rest} = Regex.named_captures(@safe_mention_regex, text)
121 Linkify.link(mentions, options) <> Linkify.link(rest, options)
122 else
123 Linkify.link(text, options)
124 end
125 end
126
127 def markdown_to_html(text, opts \\ %{}) do
128 Earmark.as_html!(text, %Earmark.Options{compact_output: true} |> Map.merge(opts))
129 end
130
131 def html_escape({text, mentions, hashtags}, type) do
132 {html_escape(text, type), mentions, hashtags}
133 end
134
135 def html_escape(text, "text/html") do
136 HTML.filter_tags(text)
137 end
138
139 def html_escape(text, "text/x.misskeymarkdown") do
140 text
141 |> HTML.filter_tags()
142 end
143
144 def html_escape(text, "text/plain") do
145 Regex.split(@link_regex, text, include_captures: true)
146 |> Enum.map_every(2, fn chunk ->
147 {:safe, part} = Phoenix.HTML.html_escape(chunk)
148 part
149 end)
150 |> Enum.join("")
151 end
152
153 def truncate(text, max_length \\ 200, omission \\ "...") do
154 # Remove trailing whitespace
155 text = Regex.replace(~r/([^ \t\r\n])([ \t]+$)/u, text, "\\g{1}")
156
157 if String.length(text) < max_length do
158 text
159 else
160 length_with_omission = max_length - String.length(omission)
161 String.slice(text, 0, length_with_omission) <> omission
162 end
163 end
164
165 defp get_nickname_text(nickname, %{mentions_format: :full}), do: User.full_nickname(nickname)
166 defp get_nickname_text(nickname, _), do: User.local_nickname(nickname)
167 end