]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/core/utils/extends.rb
fix charset detection
[user/henk/code/ruby/rbot.git] / lib / rbot / core / utils / extends.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: Standard classes extensions
5 #
6 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
7 # Copyright:: (C) 2006,2007 Giuseppe Bilotta
8 # License:: GPL v2
9 #
10 # This file collects extensions to standard Ruby classes and to some core rbot
11 # classes to be used by the various plugins
12 #
13 # Please note that global symbols have to be prefixed by :: because this plugin
14 # will be read into an anonymous module
15
16
17 # Extensions to the Array class
18 #
19 class ::Array
20
21   # This method returns a random element from the array, or nil if the array is
22   # empty
23   #
24   def pick_one
25     return nil if self.empty?
26     self[rand(self.length)]
27   end
28 end
29
30 begin
31   require 'iconv'
32   $we_have_iconv = true
33 rescue LoadError
34   $we_have_iconv = false
35 end
36
37 # Extensions to the String class
38 #
39 # TODO make ircify_html() accept an Hash of options, and make riphtml() just
40 # call ircify_html() with stronger purify options.
41 #
42 class ::String
43
44   # This method will try to transcode a String supposed to hold an XML or HTML
45   # document from the original charset to UTF-8.
46   #
47   # To find the original encoding, it will first see if the String responds to
48   # #http_headers(), and if it does it will assume that the charset indicated
49   # there is the correct one. Otherwise, it will try to detect the charset from
50   # some typical XML and HTML headers
51   def utfy_xml
52     return self unless $we_have_iconv
53
54     charset = nil
55
56     if self.respond_to?(:http_headers) and headers = self.http_headers
57       if headers['content-type'].first.match(/charset=(\S+?)\s*(?:;|\Z)/i)
58         debug "charset #{charset} set from header"
59         charset = $1
60       end
61     end
62
63     if not charset
64       case self
65       when /<\?xml.*encoding="(\S+)".*\?>/i
66         charset = $1
67       when /<meta\s+http-equiv\s*=\s*["']?Content-Type["']?.*charset\s*=\s*(\S+?)(?:;|["']|\s).*>/i
68         charset = $1
69       end
70       debug "charset #{charset} set from string"
71     end
72
73     if charset
74       return Iconv.iconv('utf-8', charset, self).join rescue self
75     else
76       debug "Couldn't find charset for #{self.inspect}"
77       return self
78     end
79
80   end
81
82   # This method will return a purified version of the receiver, with all HTML
83   # stripped off and some of it converted to IRC formatting
84   #
85   def ircify_html
86     txt = self
87
88     # remove scripts
89     txt.gsub!(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "")
90
91     # remove styles
92     txt.gsub!(/<style(?:\s+[^>]*)?>.*?<\/style>/im, "")
93
94     # bold and strong -> bold
95     txt.gsub!(/<\/?(?:b|strong)(?:\s+[^>]*)?>/im, "#{Bold}")
96
97     # italic, emphasis and underline -> underline
98     txt.gsub!(/<\/?(?:i|em|u)(?:\s+[^>]*)?>/im, "#{Underline}")
99
100     ## This would be a nice addition, but the results are horrible
101     ## Maybe make it configurable?
102     # txt.gsub!(/<\/?a( [^>]*)?>/, "#{Reverse}")
103
104     # Paragraph and br tags are converted to whitespace
105     txt.gsub!(/<\/?(p|br)(?:\s+[^>]*)?\s*\/?\s*>/, ' ')
106     txt.gsub!("\n", ' ')
107     txt.gsub!("\r", ' ')
108
109     # All other tags are just removed
110     txt.gsub!(/<[^>]+>/, '')
111
112     # Convert HTML entities. We do it now to be able to handle stuff
113     # such as &nbsp;
114     txt = Utils.decode_html_entities(txt)
115
116     # Remove double formatting options, since they only waste bytes
117     txt.gsub!(/#{Bold}(\s*)#{Bold}/, '\1')
118     txt.gsub!(/#{Underline}(\s*)#{Underline}/, '\1')
119
120     # Simplify whitespace that appears on both sides of a formatting option
121     txt.gsub!(/\s+(#{Bold}|#{Underline})\s+/, ' \1')
122     txt.sub!(/\s+(#{Bold}|#{Underline})\z/, '\1')
123     txt.sub!(/\A(#{Bold}|#{Underline})\s+/, '\1')
124
125     # And finally whitespace is squeezed
126     txt.gsub!(/\s+/, ' ')
127
128     # Decode entities and strip whitespace
129     return txt.strip
130   end
131
132   # This method will strip all HTML crud from the receiver
133   #
134   def riphtml
135     self.gsub(/<[^>]+>/, '').gsub(/&amp;/,'&').gsub(/&quot;/,'"').gsub(/&lt;/,'<').gsub(/&gt;/,'>').gsub(/&ellip;/,'...').gsub(/&apos;/, "'").gsub("\n",'')
136   end
137 end
138
139
140 # Extensions to the Regexp class, with some common and/or complex regular
141 # expressions.
142 #
143 class ::Regexp
144
145   # A method to build a regexp that matches a list of something separated by
146   # optional commas and/or the word "and", an optionally repeated prefix,
147   # and whitespace.
148   def Regexp.new_list(reg, pfx = "")
149     if pfx.kind_of?(String) and pfx.empty?
150       return %r(#{reg}(?:,?(?:\s+and)?\s+#{reg})*)
151     else
152       return %r(#{reg}(?:,?(?:\s+and)?(?:\s+#{pfx})?\s+#{reg})*)
153     end
154   end
155
156   IN_ON = /in|on/
157
158   module Irc
159     # Match a list of channel anmes separated by optional commas, whitespace
160     # and optionally the word "and"
161     CHAN_LIST = Regexp.new_list(GEN_CHAN)
162
163     # Match "in #channel" or "on #channel" and/or "in private" (optionally
164     # shortened to "in pvt"), returning the channel name or the word 'private'
165     # or 'pvt' as capture
166     IN_CHAN = /#{IN_ON}\s+(#{GEN_CHAN})|(here)|/
167     IN_CHAN_PVT = /#{IN_CHAN}|in\s+(private|pvt)/
168
169     # As above, but with channel lists
170     IN_CHAN_LIST_SFX = Regexp.new_list(/#{GEN_CHAN}|here/, IN_ON)
171     IN_CHAN_LIST = /#{IN_ON}\s+#{IN_CHAN_LIST_SFX}|anywhere|everywhere/
172     IN_CHAN_LIST_PVT_SFX = Regexp.new_list(/#{GEN_CHAN}|here|private|pvt/, IN_ON)
173     IN_CHAN_LIST_PVT = /#{IN_ON}\s+#{IN_CHAN_LIST_PVT_SFX}|anywhere|everywhere/
174
175     # Match a list of nicknames separated by optional commas, whitespace and
176     # optionally the word "and"
177     NICK_LIST = Regexp.new_list(GEN_NICK)
178
179   end
180
181 end
182
183
184 module ::Irc
185
186
187   class BasicUserMessage
188
189     # We extend the BasicUserMessage class with a method that parses a string
190     # which is a channel list as matched by IN_CHAN(_LIST) and co. The method
191     # returns an array of channel names, where 'private' or 'pvt' is replaced
192     # by the Symbol :"?", 'here' is replaced by the channel of the message or
193     # by :"?" (depending on whether the message target is the bot or a
194     # Channel), and 'anywhere' and 'everywhere' are replaced by Symbol :*
195     #
196     def parse_channel_list(string)
197       return [:*] if [:anywhere, :everywhere].include? string.to_sym
198       string.scan(
199       /(?:^|,?(?:\s+and)?\s+)(?:in|on\s+)?(#{Regexp::Irc::GEN_CHAN}|here|private|pvt)/
200                  ).map { |chan_ar|
201         chan = chan_ar.first
202         case chan.to_sym
203         when :private, :pvt
204           :"?"
205         when :here
206           case self.target
207           when Channel
208             self.target.name
209           else
210             :"?"
211           end
212         else
213           chan
214         end
215       }.uniq
216     end
217   end
218 end