string.rb 16 KB

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