4 # :title: Standard classes extensions
6 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
7 # Copyright:: (C) 2006,2007 Giuseppe Bilotta
10 # This file collects extensions to standard Ruby classes and to some core rbot
11 # classes to be used by the various plugins
13 # Please note that global symbols have to be prefixed by :: because this plugin
14 # will be read into an anonymous module
16 # Extensions to the Module class
20 # Many plugins define Struct objects to hold their data. On rescans, lots of
21 # warnings are echoed because of the redefinitions. Using this method solves
22 # the problem, by checking if the Struct already exists, and if it has the
25 def define_structure(name, *members)
27 if Struct.const_defined?(sym)
28 kl = Struct.const_get(sym)
29 if kl.new.members.map { |member| member.intern } == members.map
30 debug "Struct #{sym} previously defined, skipping"
35 debug "Defining struct #{sym} with members #{members.inspect}"
36 const_set(sym, Struct.new(name.to_s, *members))
41 # Extensions to the Array class
45 # This method returns a random element from the array, or nil if the array is
49 return nil if self.empty?
50 self[rand(self.length)]
54 # Extensions to the Range class
58 # This method returns a random number between the lower and upper bound
61 len = self.last - self.first
62 len += 1 unless self.exclude_end?
63 self.first + Kernel::rand(len)
68 # Extensions for the Numeric classes
72 # This method forces a real number to be not more than a given positive
73 # number or not less than a given positive number, or between two any given
76 def clip(left,right=0)
77 raise ArgumentError unless left.kind_of?(Numeric) and right.kind_of?(Numeric)
86 # Extensions to the String class
88 # TODO make ircify_html() accept an Hash of options, and make riphtml() just
89 # call ircify_html() with stronger purify options.
93 # This method will return a purified version of the receiver, with all HTML
94 # stripped off and some of it converted to IRC formatting
96 def ircify_html(opts={})
100 txt.gsub!(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "")
103 txt.gsub!(/<style(?:\s+[^>]*)?>.*?<\/style>/im, "")
105 # bold and strong -> bold
106 txt.gsub!(/<\/?(?:b|strong)(?:\s+[^>]*)?>/im, "#{Bold}")
108 # italic, emphasis and underline -> underline
109 txt.gsub!(/<\/?(?:i|em|u)(?:\s+[^>]*)?>/im, "#{Underline}")
111 ## This would be a nice addition, but the results are horrible
112 ## Maybe make it configurable?
113 # txt.gsub!(/<\/?a( [^>]*)?>/, "#{Reverse}")
114 case val = opts[:a_href]
115 when Reverse, Bold, Underline
116 txt.gsub!(/<(?:\/a\s*|a (?:[^>]*\s+)?href\s*=\s*(?:[^>]*\s*)?)>/, val)
118 # Not good for nested links, but the best we can do without something like hpricot
119 txt.gsub!(/<a (?:[^>]*\s+)?href\s*=\s*(?:([^"'>][^\s>]*)\s+|"((?:[^"]|\\")*)"|'((?:[^']|\\')*)')(?:[^>]*\s+)?>(.*?)<\/a>/) { |match|
121 debug [$1, $2, $3, $4].inspect
122 link = $1 || $2 || $3
127 warn "unknown :a_href option #{val} passed to ircify_html" if val
130 # Paragraph and br tags are converted to whitespace
131 txt.gsub!(/<\/?(p|br)(?:\s+[^>]*)?\s*\/?\s*>/i, ' ')
135 # Superscripts and subscripts are turned into ^{...} and _{...}
136 # where the {} are omitted for single characters
137 txt.gsub!(/<sup>(.*?)<\/sup>/, '^{\1}')
138 txt.gsub!(/<sub>(.*?)<\/sub>/, '_{\1}')
139 txt.gsub!(/(^|_)\{(.)\}/, '\1\2')
141 # All other tags are just removed
142 txt.gsub!(/<[^>]+>/, '')
144 # Convert HTML entities. We do it now to be able to handle stuff
146 txt = Utils.decode_html_entities(txt)
148 # Remove double formatting options, since they only waste bytes
149 txt.gsub!(/#{Bold}(\s*)#{Bold}/, '\1')
150 txt.gsub!(/#{Underline}(\s*)#{Underline}/, '\1')
152 # Simplify whitespace that appears on both sides of a formatting option
153 txt.gsub!(/\s+(#{Bold}|#{Underline})\s+/, ' \1')
154 txt.sub!(/\s+(#{Bold}|#{Underline})\z/, '\1')
155 txt.sub!(/\A(#{Bold}|#{Underline})\s+/, '\1')
157 # And finally whitespace is squeezed
158 txt.gsub!(/\s+/, ' ')
160 # Decode entities and strip whitespace
164 # As above, but modify the receiver
166 def ircify_html!(opts={})
168 replace self.ircify_html(opts)
169 return self unless self.hash == old_hash
172 # This method will strip all HTML crud from the receiver
175 self.gsub(/<[^>]+>/, '').gsub(/&/,'&').gsub(/"/,'"').gsub(/</,'<').gsub(/>/,'>').gsub(/&ellip;/,'...').gsub(/'/, "'").gsub("\n",'')
180 # Extensions to the Regexp class, with some common and/or complex regular
185 # A method to build a regexp that matches a list of something separated by
186 # optional commas and/or the word "and", an optionally repeated prefix,
188 def Regexp.new_list(reg, pfx = "")
189 if pfx.kind_of?(String) and pfx.empty?
190 return %r(#{reg}(?:,?(?:\s+and)?\s+#{reg})*)
192 return %r(#{reg}(?:,?(?:\s+and)?(?:\s+#{pfx})?\s+#{reg})*)
199 # Match a list of channel anmes separated by optional commas, whitespace
200 # and optionally the word "and"
201 CHAN_LIST = Regexp.new_list(GEN_CHAN)
203 # Match "in #channel" or "on #channel" and/or "in private" (optionally
204 # shortened to "in pvt"), returning the channel name or the word 'private'
205 # or 'pvt' as capture
206 IN_CHAN = /#{IN_ON}\s+(#{GEN_CHAN})|(here)|/
207 IN_CHAN_PVT = /#{IN_CHAN}|in\s+(private|pvt)/
209 # As above, but with channel lists
210 IN_CHAN_LIST_SFX = Regexp.new_list(/#{GEN_CHAN}|here/, IN_ON)
211 IN_CHAN_LIST = /#{IN_ON}\s+#{IN_CHAN_LIST_SFX}|anywhere|everywhere/
212 IN_CHAN_LIST_PVT_SFX = Regexp.new_list(/#{GEN_CHAN}|here|private|pvt/, IN_ON)
213 IN_CHAN_LIST_PVT = /#{IN_ON}\s+#{IN_CHAN_LIST_PVT_SFX}|anywhere|everywhere/
215 # Match a list of nicknames separated by optional commas, whitespace and
216 # optionally the word "and"
217 NICK_LIST = Regexp.new_list(GEN_NICK)
227 class BasicUserMessage
229 # We extend the BasicUserMessage class with a method that parses a string
230 # which is a channel list as matched by IN_CHAN(_LIST) and co. The method
231 # returns an array of channel names, where 'private' or 'pvt' is replaced
232 # by the Symbol :"?", 'here' is replaced by the channel of the message or
233 # by :"?" (depending on whether the message target is the bot or a
234 # Channel), and 'anywhere' and 'everywhere' are replaced by Symbol :*
236 def parse_channel_list(string)
237 return [:*] if [:anywhere, :everywhere].include? string.to_sym
239 /(?:^|,?(?:\s+and)?\s+)(?:in|on\s+)?(#{Regexp::Irc::GEN_CHAN}|here|private|pvt)/