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 # DottedIndex mixin: extend a Hash or Array class with this module
42 # to achieve [] and []= methods that automatically split indices
43 # at dots (indices are automatically converted to symbols, too)
45 # You have to define the single_retrieve(_key_) and
46 # single_assign(_key_,_value_) methods (usually aliased at the
47 # original :[] and :[]= methods)
50 def rbot_index_split(*ar)
51 keys = ([] << ar).flatten
53 k.to_s.split('.').map { |kk| kk.to_sym rescue nil }.compact
58 keys = self.rbot_index_split(ar)
59 return self.single_retrieve(keys.first) if keys.length == 1
63 h[k] ||= self.class.new
72 keys = self.rbot_index_split(ar)
73 return self.single_assign(keys.first, val) if keys.length == 1
77 h[k] ||= self.class.new
85 # Extensions to the Array class
89 # This method returns a random element from the array, or nil if the array is
93 return nil if self.empty?
94 self[rand(self.length)]
97 # This method returns a given element from the array, deleting it from the
98 # array itself. The method returns nil if the element couldn't be found.
100 # If nil is specified, a random element is returned and deleted.
102 def delete_one(val=nil)
103 return nil if self.empty?
105 index = rand(self.length)
107 index = self.index(val)
108 return nil unless index
110 self.delete_at(index)
113 # This method shuffles the items in the array
117 while item = base.delete_one
123 # This method returns a new array with the same items as
124 # the receiver, but shuffled
132 # Extensions to the Range class
136 # This method returns a random number between the lower and upper bound
139 len = self.last - self.first
140 len += 1 unless self.exclude_end?
141 self.first + Kernel::rand(len)
143 alias :rand :pick_one
146 # Extensions for the Numeric classes
150 # This method forces a real number to be not more than a given positive
151 # number or not less than a given positive number, or between two any given
154 def clip(left,right=0)
155 raise ArgumentError unless left.kind_of?(Numeric) and right.kind_of?(Numeric)
164 # Extensions to the String class
166 # TODO make riphtml() just call ircify_html() with stronger purify options.
170 # This method will return a purified version of the receiver, with all HTML
171 # stripped off and some of it converted to IRC formatting
173 def ircify_html(opts={})
177 txt.gsub!(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "")
180 txt.gsub!(/<style(?:\s+[^>]*)?>.*?<\/style>/im, "")
182 # bold and strong -> bold
183 txt.gsub!(/<\/?(?:b|strong)(?:\s+[^>]*)?>/im, "#{Bold}")
185 # italic, emphasis and underline -> underline
186 txt.gsub!(/<\/?(?:i|em|u)(?:\s+[^>]*)?>/im, "#{Underline}")
188 ## This would be a nice addition, but the results are horrible
189 ## Maybe make it configurable?
190 # txt.gsub!(/<\/?a( [^>]*)?>/, "#{Reverse}")
191 case val = opts[:a_href]
192 when Reverse, Bold, Underline
193 txt.gsub!(/<(?:\/a\s*|a (?:[^>]*\s+)?href\s*=\s*(?:[^>]*\s*)?)>/, val)
195 # Not good for nested links, but the best we can do without something like hpricot
196 txt.gsub!(/<a (?:[^>]*\s+)?href\s*=\s*(?:([^"'>][^\s>]*)\s+|"((?:[^"]|\\")*)"|'((?:[^']|\\')*)')(?:[^>]*\s+)?>(.*?)<\/a>/) { |match|
198 debug [$1, $2, $3, $4].inspect
199 link = $1 || $2 || $3
204 warning "unknown :a_href option #{val} passed to ircify_html" if val
207 # Paragraph and br tags are converted to whitespace
208 txt.gsub!(/<\/?(p|br)(?:\s+[^>]*)?\s*\/?\s*>/i, ' ')
212 # Superscripts and subscripts are turned into ^{...} and _{...}
213 # where the {} are omitted for single characters
214 txt.gsub!(/<sup>(.*?)<\/sup>/, '^{\1}')
215 txt.gsub!(/<sub>(.*?)<\/sub>/, '_{\1}')
216 txt.gsub!(/(^|_)\{(.)\}/, '\1\2')
218 # List items are converted to *). We don't have special support for
219 # nested or ordered lists.
220 txt.gsub!(/<li>/, ' *) ')
222 # All other tags are just removed
223 txt.gsub!(/<[^>]+>/, '')
225 # Convert HTML entities. We do it now to be able to handle stuff
227 txt = Utils.decode_html_entities(txt)
229 # Keep unbreakable spaces or conver them to plain spaces?
230 case val = opts[:nbsp]
232 txt.gsub!([160].pack('U'), ' ')
234 warning "unknown :nbsp option #{val} passed to ircify_html" if val
237 # Remove double formatting options, since they only waste bytes
238 txt.gsub!(/#{Bold}(\s*)#{Bold}/, '\1')
239 txt.gsub!(/#{Underline}(\s*)#{Underline}/, '\1')
241 # Simplify whitespace that appears on both sides of a formatting option
242 txt.gsub!(/\s+(#{Bold}|#{Underline})\s+/, ' \1')
243 txt.sub!(/\s+(#{Bold}|#{Underline})\z/, '\1')
244 txt.sub!(/\A(#{Bold}|#{Underline})\s+/, '\1')
246 # And finally whitespace is squeezed
247 txt.gsub!(/\s+/, ' ')
250 if opts[:limit] && txt.size > opts[:limit]
251 txt = txt.slice(0, opts[:limit]) + "#{Reverse}...#{Reverse}"
254 # Decode entities and strip whitespace
258 # As above, but modify the receiver
260 def ircify_html!(opts={})
262 replace self.ircify_html(opts)
263 return self unless self.hash == old_hash
266 # This method will strip all HTML crud from the receiver
269 self.gsub(/<[^>]+>/, '').gsub(/&/,'&').gsub(/"/,'"').gsub(/</,'<').gsub(/>/,'>').gsub(/&ellip;/,'...').gsub(/'/, "'").gsub("\n",'')
272 # This method tries to find an HTML title in the string,
273 # and returns it if found
275 if defined? ::Hpricot
276 Hpricot(self).at("title").inner_html
278 return unless Irc::Utils::TITLE_REGEX.match(self)
283 # This method returns the IRC-formatted version of an
284 # HTML title found in the string
285 def ircify_html_title
286 self.get_html_title.ircify_html rescue nil
291 # Extensions to the Regexp class, with some common and/or complex regular
296 # A method to build a regexp that matches a list of something separated by
297 # optional commas and/or the word "and", an optionally repeated prefix,
299 def Regexp.new_list(reg, pfx = "")
300 if pfx.kind_of?(String) and pfx.empty?
301 return %r(#{reg}(?:,?(?:\s+and)?\s+#{reg})*)
303 return %r(#{reg}(?:,?(?:\s+and)?(?:\s+#{pfx})?\s+#{reg})*)
310 # Match a list of channel anmes separated by optional commas, whitespace
311 # and optionally the word "and"
312 CHAN_LIST = Regexp.new_list(GEN_CHAN)
314 # Match "in #channel" or "on #channel" and/or "in private" (optionally
315 # shortened to "in pvt"), returning the channel name or the word 'private'
316 # or 'pvt' as capture
317 IN_CHAN = /#{IN_ON}\s+(#{GEN_CHAN})|(here)|/
318 IN_CHAN_PVT = /#{IN_CHAN}|in\s+(private|pvt)/
320 # As above, but with channel lists
321 IN_CHAN_LIST_SFX = Regexp.new_list(/#{GEN_CHAN}|here/, IN_ON)
322 IN_CHAN_LIST = /#{IN_ON}\s+#{IN_CHAN_LIST_SFX}|anywhere|everywhere/
323 IN_CHAN_LIST_PVT_SFX = Regexp.new_list(/#{GEN_CHAN}|here|private|pvt/, IN_ON)
324 IN_CHAN_LIST_PVT = /#{IN_ON}\s+#{IN_CHAN_LIST_PVT_SFX}|anywhere|everywhere/
326 # Match a list of nicknames separated by optional commas, whitespace and
327 # optionally the word "and"
328 NICK_LIST = Regexp.new_list(GEN_NICK)
338 class BasicUserMessage
340 # We extend the BasicUserMessage class with a method that parses a string
341 # which is a channel list as matched by IN_CHAN(_LIST) and co. The method
342 # returns an array of channel names, where 'private' or 'pvt' is replaced
343 # by the Symbol :"?", 'here' is replaced by the channel of the message or
344 # by :"?" (depending on whether the message target is the bot or a
345 # Channel), and 'anywhere' and 'everywhere' are replaced by Symbol :*
347 def parse_channel_list(string)
348 return [:*] if [:anywhere, :everywhere].include? string.to_sym
350 /(?:^|,?(?:\s+and)?\s+)(?:in|on\s+)?(#{Regexp::Irc::GEN_CHAN}|here|private|pvt)/
369 # The recurse depth of a message, for fake messages. 0 means an original
372 unless defined? @recurse_depth
378 # Set the recurse depth of a message, for fake messages. 0 should only
379 # be used by original messages
380 def recurse_depth=(val)
388 # Maximum fake message recursion
389 MAX_RECURSE_DEPTH = 10
391 class RecurseTooDeep < RuntimeError
395 # Sometimes plugins need to create a new fake message based on an existing
396 # message: for example, this is done by alias, linkbot, reaction and remotectl.
398 # This method simplifies the message creation, including a recursion depth
401 # In the options you can specify the :bot, the :server, the :source,
402 # the :target, the message :class and whether or not to :delegate. To
403 # initialize these entries from an existing message, you can use :from
405 # If you don't specify a :from you should specify a :source.
407 def fake_message(string, opts={})
408 if from = opts[:from]
410 :bot => from.bot, :server => from.server, :source => from.source,
411 :target => from.target, :class => from.class, :delegate => true,
412 :depth => from.recurse_depth + 1
416 :bot => @bot, :server => @bot.server, :target => @bot.myself,
417 :class => PrivMessage, :delegate => true, :depth => 1
420 raise RecurseTooDeep if o[:depth] > MAX_RECURSE_DEPTH
421 new_m = o[:class].new(o[:bot], o[:server], o[:source], o[:target], string)
422 new_m.recurse_depth = o[:depth]
423 return new_m unless o[:delegate]
424 method = o[:class].to_s.gsub(/^Irc::|Message$/,'').downcase
425 method = 'privmsg' if method == 'priv'
426 o[:bot].plugins.irc_delegate(method, new_m)