string.rb 17 KB

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