380a80ab83afe367b08a9770cac110440c6f4ccf
[anni] / lib / pleroma / web / xml.ex
1 # Pleroma: A lightweight social networking server
2 # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
3 # SPDX-License-Identifier: AGPL-3.0-only
4
5 defmodule Pleroma.Web.XML do
6   require Logger
7
8   def string_from_xpath(_, :error), do: nil
9
10   def string_from_xpath(xpath, doc) do
11     try do
12       {:xmlObj, :string, res} = :xmerl_xpath.string('string(#{xpath})', doc)
13
14       res =
15         res
16         |> to_string
17         |> String.trim()
18
19       if res == "", do: nil, else: res
20     catch
21       _e ->
22         Logger.debug("Couldn't find xpath #{xpath} in XML doc")
23         nil
24     end
25   end
26
27   def parse_document(text) do
28     try do
29       {doc, _rest} =
30         text
31         |> :binary.bin_to_list()
32         |> :xmerl_scan.string(
33           quiet: true,
34           fetch_fun: fn _, _ -> raise "Resolving external entities not supported" end
35         )
36
37       {:ok, doc}
38     rescue
39       _e ->
40         Logger.debug("Couldn't parse XML: #{inspect(text)}")
41         :error
42     catch
43       :exit, _error ->
44         Logger.debug("Couldn't parse XML: #{inspect(text)}")
45         :error
46     end
47   end
48 end