string.rb 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. require 'rchardet'
  3. class String
  4. alias old_strip strip
  5. alias old_strip! strip!
  6. def strip!
  7. begin
  8. sub!(%r{\A[[[:space:]]\u{200B}\u{FEFF}]+}, '')
  9. sub!(%r{[[[:space:]]\u{200B}\u{FEFF}]+\Z}, '')
  10. # if incompatible encoding regexp match (UTF-8 regexp with ASCII-8BIT string) (Encoding::CompatibilityError), use default
  11. rescue Encoding::CompatibilityError
  12. old_strip!
  13. end
  14. self
  15. end
  16. def strip
  17. begin
  18. new_string = sub(%r{\A[[[:space:]]\u{200B}\u{FEFF}]+}, '')
  19. new_string.sub!(%r{[[[:space:]]\u{200B}\u{FEFF}]+\Z}, '')
  20. # if incompatible encoding regexp match (UTF-8 regexp with ASCII-8BIT string) (Encoding::CompatibilityError), use default
  21. rescue Encoding::CompatibilityError
  22. new_string = old_strip
  23. end
  24. new_string
  25. end
  26. def message_quote
  27. quote = split("\n")
  28. body_quote = ''
  29. quote.each do |line|
  30. body_quote = "#{body_quote}> #{line}\n"
  31. end
  32. body_quote
  33. end
  34. def word_wrap(*args)
  35. options = args.extract_options!
  36. if args.present?
  37. options[:line_width] = args[0] || 82
  38. end
  39. options.reverse_merge!(line_width: 82)
  40. lines = self
  41. lines.split("\n").collect do |line|
  42. line.length > options[:line_width] ? line.gsub(%r{(.{1,#{options[:line_width]}})(\s+|$)}, "\\1\n").strip : line
  43. end * "\n"
  44. end
  45. =begin
  46. filename = 'Some::Module'.to_filename
  47. returns
  48. 'some/module'
  49. =end
  50. def to_filename
  51. camel_cased_word = dup
  52. camel_cased_word.gsub(%r{::}, '/')
  53. .gsub(%r{([A-Z]+)([A-Z][a-z])}, '\1_\2')
  54. .gsub(%r{([a-z\d])([A-Z])}, '\1_\2')
  55. .tr('-', '_').downcase
  56. end
  57. =begin
  58. filename = 'some/module.rb'.to_classname
  59. returns
  60. 'Some::Module'
  61. =end
  62. def to_classname
  63. camel_cased_word = dup
  64. camel_cased_word.delete_suffix!('.rb')
  65. camel_cased_word.split('/').map(&:camelize).join('::')
  66. end
  67. # because of mysql inno_db limitations, strip 4 bytes utf8 chars (e. g. emojis)
  68. # unfortunaly UTF8mb4 will raise other limitaions of max varchar and lower index sizes
  69. # More details: http://pjambet.github.io/blog/emojis-and-mysql/
  70. def utf8_to_3bytesutf8
  71. return self if Rails.application.config.db_4bytes_utf8
  72. each_char.select do |c|
  73. if c.bytes.count > 3
  74. Rails.logger.warn "strip out 4 bytes utf8 chars '#{c}' of '#{self}'"
  75. next
  76. end
  77. c
  78. end
  79. .join
  80. end
  81. =begin
  82. text = html_string.html2text
  83. returns
  84. 'string with text only'
  85. =end
  86. def html2text(string_only = false, strict = false)
  87. string = dup
  88. # in case of invalid encoding, strip invalid chars
  89. # see also test/data/mail/mail021.box
  90. # note: string.encode!('UTF-8', 'UTF-8', :invalid => :replace, :replace => '?') was not detecting invalid chars
  91. if !string.valid_encoding?
  92. string = string.chars.select(&:valid_encoding?).join
  93. end
  94. # remove html comments
  95. string.gsub!(%r{<!--.+?-->}m, '')
  96. # find <a href=....> and replace it with [x]
  97. link_list = ''
  98. counter = 0
  99. if string_only
  100. string.gsub!(%r{<a[[:space:]]+(|\S+[[:space:]]+)href=("|')(.+?)("|')([[:space:]]*|[[:space:]]+[^>]*)>(.+?)<[[:space:]]*/a[[:space:]]*>}mxi) do |_placeholder|
  101. link = $3
  102. text = $6
  103. text.gsub!(%r{<.+?>}, '')
  104. link_compare = link.dup
  105. if link_compare.present?
  106. link.strip!
  107. link_compare.strip!
  108. link_compare.downcase!
  109. link_compare.sub!(%r{/$}, '')
  110. end
  111. text_compare = text.dup
  112. if text_compare.present?
  113. text.strip!
  114. text_compare.strip!
  115. text_compare.downcase!
  116. text_compare.sub!(%r{/$}, '')
  117. end
  118. if link_compare.present? && text_compare.blank?
  119. link
  120. elsif (link_compare.blank? && text_compare.present?) || (link_compare && link_compare =~ %r{^mailto}i)
  121. text
  122. elsif link_compare.present? && text_compare.present? && (link_compare == text_compare || link_compare == "mailto:#{text}".downcase || link_compare == "http://#{text}".downcase)
  123. "######LINKEXT:#{link}/TEXT:#{text}######"
  124. elsif text !~ %r{^http}
  125. "#{text} (######LINKRAW:#{link}######)"
  126. else
  127. "#{link} (######LINKRAW:#{text}######)"
  128. end
  129. end
  130. elsif string.scan(%r{<a[[:space:]]}i).count < 5_000
  131. string.gsub!(%r{<a[[:space:]].*?href=("|')(.+?)("|').*?>}ix) do
  132. link = $2
  133. counter += 1
  134. link_list += "[#{counter}] #{link}\n"
  135. "[#{counter}] "
  136. end
  137. end
  138. # remove style tags with content
  139. string.gsub!(%r{<style(|[[:space:]].+?)>(.+?)</style>}im, '')
  140. # remove empty lines
  141. string.gsub!(%r{^[[:space:]]*}m, '')
  142. if strict
  143. string.gsub!(%r{< [[:space:]]* (/*) [[:space:]]* (b|i|ul|ol|li|u|h1|h2|h3|hr) ([[:space:]]*|[[:space:]]+[^>]*) >}mxi, '######\1\2######')
  144. end
  145. # pre/code handling 1/2
  146. string.gsub!(%r{<pre>(.+?)</pre>}m) do |placeholder|
  147. placeholder.gsub(%r{\n}, '###BR###')
  148. end
  149. string.gsub!(%r{<code>(.+?)</code>}m) do |placeholder|
  150. placeholder.gsub(%r{\n}, '###BR###')
  151. end
  152. # insert spaces on [A-z]\n[A-z]
  153. string.gsub!(%r{([A-z])[[:space:]]([A-z])}m, '\1 \2')
  154. # remove all new lines
  155. string.gsub!(%r{(\n\r|\r\r\n|\r\n|\n)}, '')
  156. # blockquote handling
  157. string.gsub!(%r{<blockquote(| [^>]*)>(.+?)</blockquote>}m) do
  158. "\n#{$2.html2text(true).gsub(%r{^(.*)$}, '&gt; \1')}\n"
  159. end
  160. # pre/code handling 2/2
  161. string.gsub!(%r{###BR###}, "\n")
  162. # add counting
  163. string.gsub!(%r{<li(| [^>]*)>}i, "\n* ")
  164. # add hr
  165. string.gsub!(%r{<hr(|/| [^>]*)>}i, "\n___\n")
  166. # add h\d
  167. string.gsub!(%r{</h\d>}i, "\n")
  168. # add new lines
  169. string.gsub!(%r{</div><div(|[[:space:]].+?)>}im, "\n")
  170. string.gsub!(%r{</p><p(|[[:space:]].+?)>}im, "\n")
  171. string.gsub!(%r{<(div|p|pre|br|table|tr|h)(|/| [^>]*)>}i, "\n")
  172. string.gsub!(%r{</(p|br|div)(|[[:space:]].+?)>}i, "\n")
  173. string.gsub!(%r{</td>}i, ' ')
  174. # strip all other tags
  175. string.gsub!(%r{<.+?>}, '')
  176. # replace multiple spaces with one
  177. string.gsub!(%r{ }, ' ')
  178. # add hyperlinks
  179. if strict
  180. string.gsub!(%r{([[:space:]])((http|https|ftp|tel)://.+?|(www..+?))([[:space:]]|\.[[:space:]]|,[[:space:]])}mxi) do |_placeholder|
  181. pre = $1
  182. content = $2
  183. post = $5
  184. if content.match?(%r{^www}i)
  185. content = "http://#{content}"
  186. end
  187. if content =~ %r{^(http|https|ftp|tel)}i
  188. "#{pre}######LINKRAW:#{content}#######{post}"
  189. else
  190. "#{pre}#{content}#{post}"
  191. end
  192. end
  193. end
  194. # try HTMLEntities, if it fails on invalid signes, use manual way
  195. begin
  196. coder = HTMLEntities.new
  197. string = coder.decode(string)
  198. rescue
  199. # strip all &amp; &lt; &gt; &quot;
  200. string.gsub!('&amp;', '&')
  201. string.gsub!('&lt;', '<')
  202. string.gsub!('&gt;', '>')
  203. string.gsub!('&quot;', '"')
  204. string.gsub!('&nbsp;', ' ')
  205. # encode html entities like "&#8211;"
  206. string.gsub!(%r{(&\#(\d+);?)}x) do
  207. $2.chr
  208. end
  209. # encode html entities like "&#3d;"
  210. string.gsub!(%r{(&\#[xX]([0-9a-fA-F]+);?)}x) do
  211. chr_orig = $1
  212. hex = $2.hex
  213. if hex
  214. chr = hex.chr
  215. if chr
  216. chr_orig = chr
  217. else
  218. chr_orig
  219. end
  220. else
  221. chr_orig
  222. end
  223. # check valid encoding
  224. begin
  225. if !chr_orig.encode('UTF-8').valid_encoding?
  226. chr_orig = '?'
  227. end
  228. rescue
  229. chr_orig = '?'
  230. end
  231. chr_orig
  232. end
  233. end
  234. string = string.utf8_encode(fallback: :read_as_sanitized_binary)
  235. # remove tailing empty spaces
  236. string.gsub!(%r{[[:blank:]]+$}, '')
  237. # remove double multiple empty lines
  238. string.gsub!(%r{\n\n\n+}, "\n\n")
  239. # add extracted links
  240. if link_list != ''
  241. string += "\n\n\n#{link_list}"
  242. end
  243. # remove double multiple empty lines
  244. string.gsub!(%r{\n\n\n+}, "\n\n")
  245. string.strip
  246. end
  247. =begin
  248. html = text_string.text2html
  249. =end
  250. def text2html
  251. text = CGI.escapeHTML(self)
  252. text.gsub!(%r{\n}, '<br>')
  253. text.chomp
  254. end
  255. =begin
  256. html = text_string.text2html
  257. =end
  258. def html2html_strict
  259. string = dup
  260. string = HtmlSanitizer.strict(string, true).strip
  261. string = HtmlSanitizer.cleanup(string).strip
  262. # as fallback, use html2text and text2html
  263. if string.blank?
  264. string = html2text.text2html
  265. string.signature_identify('text')
  266. marker_template = '<span class="js-signatureMarker"></span>'
  267. string.sub!(%r{######SIGNATURE_MARKER######}, marker_template)
  268. string.gsub!(%r{######SIGNATURE_MARKER######}, '')
  269. return string.chomp
  270. end
  271. string.gsub!(%r{(<p>[[:space:]]*</p>([[:space:]]*)){2,}}im, '<p>&nbsp;</p>\2')
  272. string.gsub!(%r\<div>[[:space:]]*(<br(|/)>([[:space:]]*)){2,}\im, '<div><br>\3')
  273. string.gsub!(%r\[[:space:]]*(<br>[[:space:]]*){3,}[[:space:]]*</div>\im, '<br><br></div>')
  274. string.gsub!(%r\<div>[[:space:]]*(<br>[[:space:]]*){1,}[[:space:]]*</div>\im, '<div>&nbsp;</div>')
  275. string.gsub!(%r\<div>[[:space:]]*(<div>[[:space:]]*</div>[[:space:]]*){2,}</div>\im, '<div>&nbsp;</div>')
  276. string.gsub!(%r\<p>[[:space:]]*</p>(<br(|/)>[[:space:]]*){2,}[[:space:]]*\im, '<p> </p><br>')
  277. string.gsub!(%r{<p>[[:space:]]*</p>(<br(|/)>[[:space:]]*)+<p>[[:space:]]*</p>}im, '<p> </p><p> </p>')
  278. string.gsub!(%r\(<div>[[:space:]]*</div>[[:space:]]*){2,}\im, '<div> </div>')
  279. string.gsub!(%r{<div>&nbsp;</div>[[:space:]]*(<div>&nbsp;</div>){1,}}im, '<div>&nbsp;</div>')
  280. string.gsub!(%r{(<br>[[:space:]]*){3,}}im, '<br><br>')
  281. string.gsub!(%r\(<br(|/)>[[:space:]]*){3,}\im, '<br/><br/>')
  282. string.gsub!(%r{<p>[[:space:]]+</p>}im, '<p>&nbsp;</p>')
  283. string.gsub!(%r{\A(<br(|/)>[[:space:]]*)*}i, '')
  284. string.gsub!(%r{[[:space:]]*(<br(|/)>[[:space:]]*)*\Z}i, '')
  285. string.gsub!(%r{(<p></p>){1,10}\Z}i, '')
  286. string.signature_identify('html')
  287. marker_template = '<span class="js-signatureMarker"></span>'
  288. string.sub!(%r{######SIGNATURE_MARKER######}, marker_template)
  289. string.gsub!(%r{######SIGNATURE_MARKER######}, '')
  290. string.chomp
  291. end
  292. def signature_identify(type = 'text', force = false)
  293. string = self
  294. marker = '######SIGNATURE_MARKER######'
  295. if type == 'html'
  296. map = [
  297. '<br(|\/)>[[:space:]]*(--|__)',
  298. '<\/div>[[:space:]]*(--|__)',
  299. '<p>[[:space:]]*(--|__)',
  300. '(<br(|\/)>|<p>|<div>)[[:space:]]*<b>(|<span[[:space:]]lang=".{1,6}">)(Von|From|De|от|Z|Od|Ze|Fra|Van|Mistä|Από|Dal|から|Из|од|iz|Från|จาก|з|Từ):[[:space:]]*(|</span>)</b>',
  301. '(<br>|<div>)[[:space:]]*<br>[[:space:]]*(Von|From|De|от|Z|Od|Ze|Fra|Van|Mistä|Από|Dal|から|Из|од|iz|Från|จาก|з|Từ):[[:space:]]+',
  302. '<blockquote(|.+?)>[[:space:]]*<div>[[:space:]]*(On|Am|Le|El|Den|Dňa|W dniu|Il|Op|Dne|Dana)[[:space:]]',
  303. '<div(|.+?)>[[:space:]]*<br>[[:space:]]*(On|Am|Le|El|Den|Dňa|W dniu|Il|Op|Dne|Dana)[[:space:]].{1,500}<blockquote',
  304. ]
  305. map.each do |regexp|
  306. string.sub!(%r{#{regexp}}m) do |placeholder|
  307. "#{marker}#{placeholder}"
  308. end
  309. end
  310. return string
  311. end
  312. # if we do have less then 10 lines and less then 300 chars ignore this
  313. if !force
  314. lines = string.split("\n")
  315. return if lines.count < 10 && string.length < 300
  316. end
  317. # search for signature separator "--\n"
  318. string.sub!(%r{^\s{0,2}--\s{0,2}$}) do |placeholder|
  319. "#{marker}#{placeholder}"
  320. end
  321. map = {}
  322. # Apple Mail
  323. # On 01/04/15 10:55, Bob Smith wrote:
  324. map['apple-en'] = '^(On)[[:space:]].{6,20}[[:space:]].{3,10}[[:space:]].{1,250}[[:space:]](wrote):'
  325. # Am 03.04.2015 um 20:58 schrieb Martin Edenhofer <me@znuny.ink>:
  326. map['apple-de'] = '^(Am)[[:space:]].{6,20}[[:space:]](um)[[:space:]].{3,10}[[:space:]](schrieb)[[:space:]].{1,250}:'
  327. # Thunderbird
  328. # Am 04.03.2015 um 12:47 schrieb Alf Aardvark:
  329. map['thunderbird-de'] = '^(Am)[[:space:]].{6,20}[[:space:]](um)[[:space:]].{3,10}[[:space:]](schrieb)[[:space:]].{1,250}:'
  330. # Thunderbird default - http://kb.mozillazine.org/Reply_header_settings
  331. # On 01-01-2007 11:00 AM, Alf Aardvark wrote:
  332. map['thunderbird-en-default'] = '^(On)[[:space:]].{6,20}[[:space:]].{3,10},[[:space:]].{1,250}(wrote):'
  333. # http://kb.mozillazine.org/Reply_header_settings
  334. # Alf Aardvark wrote, on 01-01-2007 11:00 AM:
  335. map['thunderbird-en'] = '^.{1,250}[[:space:]](wrote),[[:space:]]on[[:space:]].{3,20}:'
  336. # otrs
  337. # 25.02.2015 10:26 - edv hotline wrote:
  338. # 25.02.2015 10:26 - edv hotline schrieb:
  339. map['otrs-en-de'] = '^.{6,10}[[:space:]].{3,10}[[:space:]]-[[:space:]].{1,250}[[:space:]](wrote|schrieb):'
  340. # Ms
  341. # From: Martin Edenhofer via Znuny Support [mailto:support@znuny.inc]
  342. # Send: Donnerstag, 2. April 2015 10:00
  343. # To/Cc/Bcc: xxx
  344. # Subject: xxx
  345. # - or -
  346. # From: xxx
  347. # To/Cc/Bcc: xxx
  348. # Date: 01.04.2015 12:41
  349. # Subject: xxx
  350. # - or -
  351. # De : xxx
  352. # À/?/?: xxx
  353. # Envoyé : mercredi 29 avril 2015 17:31
  354. # Objet : xxx
  355. # en/de/fr | sometimes ms adds a space to "xx : value"
  356. map['ms-en-de-fr_from'] = '^(Von|From|De|от|Z|Od|Ze|Fra|Van|Mistä|Από|Dal|から|Из|од|iz|Från|จาก|з|Từ)( ?):[[:space:]].+?'
  357. map['ms-en-de-fr_from_html'] = "\n######b######(From|Von|De)([[:space:]]?):([[:space:]]?)(######\/b######)[[:space:]].+?"
  358. # word 14
  359. # edv hotline wrote:
  360. # edv hotline schrieb:
  361. # map['word-en-de'] = "[^#{marker}].{1,250}\s(wrote|schrieb):"
  362. map.each_value do |regexp|
  363. string.sub!(%r{#{regexp}}) do |placeholder|
  364. "#{marker}#{placeholder}"
  365. rescue
  366. # regexp was not possible because of some string encoding issue, use next
  367. Rails.logger.debug { "Invalid string/charset combination with regexp #{regexp} in string" }
  368. end
  369. end
  370. string
  371. end
  372. # Returns a copied string whose encoding is UTF-8.
  373. # If both the provided and current encodings are invalid,
  374. # an auto-detected encoding is tried.
  375. #
  376. # Supports some fallback strategies if a valid encoding cannot be found.
  377. #
  378. # Options:
  379. #
  380. # * from: An encoding to try first.
  381. # Takes precedence over the current and auto-detected encodings.
  382. #
  383. # * fallback: The strategy to follow if no valid encoding can be found.
  384. # * `:output_to_binary` returns an ASCII-8BIT-encoded string.
  385. # * `:read_as_sanitized_binary` returns a UTF-8-encoded string with all
  386. # invalid byte sequences replaced with "?" characters.
  387. def utf8_encode(...)
  388. dup.utf8_encode!(...)
  389. end
  390. def utf8_encode!(**options)
  391. return force_encoding('utf-8') if dup.force_encoding('utf-8').valid_encoding?
  392. # convert string to given charset, if valid_encoding? is true
  393. if options[:from].present?
  394. begin
  395. encoding = Encoding.find(options[:from])
  396. if encoding.present? && dup.force_encoding(encoding).valid_encoding?
  397. force_encoding(encoding)
  398. return encode!('utf-8', encoding)
  399. end
  400. rescue ArgumentError, EncodingError => e
  401. Rails.logger.error { e.inspect }
  402. end
  403. end
  404. # try to find valid encodings of string
  405. viable_encodings.each do |enc|
  406. return encode!('utf-8', enc)
  407. rescue EncodingError => e
  408. Rails.logger.error { e.inspect }
  409. end
  410. case options[:fallback]
  411. when :output_to_binary
  412. force_encoding('ascii-8bit')
  413. when :read_as_sanitized_binary
  414. encode!('utf-8', 'ascii-8bit', invalid: :replace, undef: :replace, replace: '?')
  415. else
  416. raise EncodingError, 'could not find a valid input encoding'
  417. end
  418. end
  419. private
  420. def viable_encodings(try_first: nil)
  421. return dup.viable_encodings(try_first: try_first) if frozen?
  422. provided = Encoding.find(try_first) if try_first.present?
  423. original = encoding
  424. detected = CharDet.detect(self)['encoding']
  425. [provided, original, detected]
  426. .compact
  427. .reject { |e| Encoding.find(e) == Encoding::ASCII_8BIT }
  428. .reject { |e| Encoding.find(e) == Encoding::UTF_8 }
  429. .select { |e| force_encoding(e).valid_encoding? }
  430. .tap { force_encoding(original) } # clean up changes from previous line
  431. # if `try_first` is not a valid encoding, try_first again without it
  432. rescue ArgumentError
  433. try_first.present? ? viable_encodings : raise
  434. end
  435. end