1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2020 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
5 defmodule Pleroma.HTML do
6 # Scrubbers are compiled on boot so they can be configured in OTP releases
7 # @on_load :compile_scrubbers
9 def compile_scrubbers do
10 dir = Path.join(:code.priv_dir(:pleroma), "scrubbers")
13 |> Pleroma.Utils.compile_dir()
15 {:error, _errors, _warnings} ->
16 raise "Compiling scrubbers failed"
18 {:ok, _modules, _warnings} ->
23 defp get_scrubbers(scrubber) when is_atom(scrubber), do: [scrubber]
24 defp get_scrubbers(scrubbers) when is_list(scrubbers), do: scrubbers
25 defp get_scrubbers(_), do: [Pleroma.HTML.Scrubber.Default]
28 Pleroma.Config.get([:markup, :scrub_policy])
32 def filter_tags(html, nil) do
33 filter_tags(html, get_scrubbers())
36 def filter_tags(html, scrubbers) when is_list(scrubbers) do
37 Enum.reduce(scrubbers, html, fn scrubber, html ->
38 filter_tags(html, scrubber)
42 def filter_tags(html, scrubber) do
43 {:ok, content} = FastSanitize.Sanitizer.scrub(html, scrubber)
47 def filter_tags(html), do: filter_tags(html, nil)
48 def strip_tags(html), do: filter_tags(html, FastSanitize.Sanitizer.StripTags)
50 def get_cached_scrubbed_html_for_activity(
55 callback \\ fn x -> x end
57 key = "#{key}#{generate_scrubber_signature(scrubbers)}|#{activity.id}"
59 Cachex.fetch!(:scrubber_cache, key, fn _key ->
60 object = Pleroma.Object.normalize(activity)
61 ensure_scrubbed_html(content, scrubbers, object.data["fake"] || false, callback)
65 def get_cached_stripped_html_for_activity(content, activity, key) do
66 get_cached_scrubbed_html_for_activity(
68 FastSanitize.Sanitizer.StripTags,
71 &HtmlEntities.decode/1
75 def ensure_scrubbed_html(
83 |> filter_tags(scrubbers)
93 defp generate_scrubber_signature(scrubber) when is_atom(scrubber) do
94 generate_scrubber_signature([scrubber])
97 defp generate_scrubber_signature(scrubbers) do
98 Enum.reduce(scrubbers, "", fn scrubber, signature ->
99 "#{signature}#{to_string(scrubber)}"
103 def extract_first_external_url(_, nil), do: {:error, "No content"}
105 def extract_first_external_url(object, content) do
106 key = "URL|#{object.id}"
108 Cachex.fetch!(:scrubber_cache, key, fn _key ->
111 |> Floki.parse_fragment!()
112 |> Floki.filter_out("a.mention,a.hashtag,a[rel~=\"tag\"]")
113 |> Floki.attribute("a", "href")
116 {:commit, {:ok, result}}