You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

html_parser.rb 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # frozen_string_literal: true
  2. # Redmine - project management software
  3. # Copyright (C) 2006-2017 Jean-Philippe Lang
  4. #
  5. # This program is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU General Public License
  7. # as published by the Free Software Foundation; either version 2
  8. # of the License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. require 'loofah/helpers'
  19. module Redmine
  20. module WikiFormatting
  21. class HtmlParser
  22. class_attribute :tags
  23. self.tags = {
  24. 'br' => {:post => "\n"},
  25. 'style' => ''
  26. }
  27. def self.to_text(html)
  28. html = html.gsub(/[\n\r]/, '').squeeze(' ')
  29. doc = Loofah.document(html)
  30. doc.scrub!(WikiTags.new(tags))
  31. doc.scrub!(:newline_block_elements)
  32. Loofah.remove_extraneous_whitespace(doc.text).strip
  33. end
  34. class WikiTags < ::Loofah::Scrubber
  35. def initialize(tags_to_text)
  36. @direction = :bottom_up
  37. @tags_to_text = tags_to_text || {}
  38. end
  39. def scrub(node)
  40. formatting = @tags_to_text[node.name]
  41. case formatting
  42. when Hash
  43. node.add_next_sibling Nokogiri::XML::Text.new("#{formatting[:pre]}#{node.content}#{formatting[:post]}", node.document)
  44. node.remove
  45. when String
  46. node.add_next_sibling Nokogiri::XML::Text.new(formatting, node.document)
  47. node.remove
  48. else
  49. CONTINUE
  50. end
  51. end
  52. end
  53. end
  54. end
  55. end