4 # :title: Standard classes extensions
6 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
8 # This file collects extensions to standard Ruby classes and to some core rbot
9 # classes to be used by the various plugins
11 # Please note that global symbols have to be prefixed by :: because this plugin
12 # will be read into an anonymous module
14 # Extensions to the Module class
18 # Many plugins define Struct objects to hold their data. On rescans, lots of
19 # warnings are echoed because of the redefinitions. Using this method solves
20 # the problem, by checking if the Struct already exists, and if it has the
23 def define_structure(name, *members)
25 if Struct.const_defined?(sym)
26 kl = Struct.const_get(sym)
27 if kl.new.members.map { |member| member.intern } == members.map
28 debug "Struct #{sym} previously defined, skipping"
33 debug "Defining struct #{sym} with members #{members.inspect}"
34 const_set(sym, Struct.new(name.to_s, *members))
39 # DottedIndex mixin: extend a Hash or Array class with this module
40 # to achieve [] and []= methods that automatically split indices
41 # at dots (indices are automatically converted to symbols, too)
43 # You have to define the single_retrieve(_key_) and
44 # single_assign(_key_,_value_) methods (usually aliased at the
45 # original :[] and :[]= methods)
48 def rbot_index_split(*ar)
49 keys = ([] << ar).flatten
51 k.to_s.split('.').map { |kk| kk.to_sym rescue nil }.compact
56 keys = self.rbot_index_split(ar)
57 return self.single_retrieve(keys.first) if keys.length == 1
61 h[k] ||= self.class.new
70 keys = self.rbot_index_split(ar)
71 return self.single_assign(keys.first, val) if keys.length == 1
75 h[k] ||= self.class.new
83 # Extensions to the Array class
87 # This method returns a random element from the array, or nil if the array is
91 return nil if self.empty?
92 self[rand(self.length)]
95 # This method returns a given element from the array, deleting it from the
96 # array itself. The method returns nil if the element couldn't be found.
98 # If nil is specified, a random element is returned and deleted.
100 def delete_one(val=nil)
101 return nil if self.empty?
103 index = rand(self.length)
105 index = self.index(val)
106 return nil unless index
108 self.delete_at(index)
111 # shuffle and shuffle! are defined in Ruby >= 1.8.7
113 # This method returns a new array with the same items as
114 # the receiver, but shuffled
115 unless method_defined? :shuffle
121 # This method shuffles the items in the array
122 unless method_defined? :shuffle!
130 # This method is an advanced version of #join
131 # allowing fine control of separators:
133 # [1,2,3].conjoin(', ', ' and ')
136 # [1,2,3,4].conjoin{ |i, a, b| i % 2 == 0 ? '.' : '-' }
139 # Code lifted from the ruby facets project:
140 # <http://facets.rubyforge.org>
141 # git-rev: c8b7395255b977d3c7de268ff563e3c5bc7f1441
142 # file: lib/core/facets/array/conjoin.rb
143 def conjoin(*args, &block)
146 return first.to_s if num < 1
152 sep << yield(i, *slice(i, 2))
155 options = (Hash === args.last) ? args.pop : {}
156 separator = args.shift || ""
157 options[-1] = args.shift unless args.empty?
159 sep = [separator] * num
161 if options.key?(:last)
162 options[-1] = options.delete(:last)
164 options[-1] ||= _(" and ")
166 options.each{ |i, s| sep[i] = s }
173 # Extensions to the Range class
177 # This method returns a random number between the lower and upper bound
180 len = self.last - self.first
181 len += 1 unless self.exclude_end?
182 self.first + Kernel::rand(len)
184 alias :rand :pick_one
187 # Extensions for the Numeric classes
191 # This method forces a real number to be not more than a given positive
192 # number or not less than a given positive number, or between two any given
195 def clip(left,right=0)
196 raise ArgumentError unless left.kind_of?(Numeric) and right.kind_of?(Numeric)
205 # Extensions to the String class
207 # TODO make riphtml() just call ircify_html() with stronger purify options.
211 # This method will return a purified version of the receiver, with all HTML
212 # stripped off and some of it converted to IRC formatting
214 def ircify_html(opts={})
218 txt.gsub!(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "")
221 txt.gsub!(/<style(?:\s+[^>]*)?>.*?<\/style>/im, "")
223 # bold and strong -> bold
224 txt.gsub!(/<\/?(?:b|strong)(?:\s+[^>]*)?>/im, "#{Bold}")
226 # italic, emphasis and underline -> underline
227 txt.gsub!(/<\/?(?:i|em|u)(?:\s+[^>]*)?>/im, "#{Underline}")
229 ## This would be a nice addition, but the results are horrible
230 ## Maybe make it configurable?
231 # txt.gsub!(/<\/?a( [^>]*)?>/, "#{Reverse}")
232 case val = opts[:a_href]
233 when Reverse, Bold, Underline
234 txt.gsub!(/<(?:\/a\s*|a (?:[^>]*\s+)?href\s*=\s*(?:[^>]*\s*)?)>/, val)
236 # Not good for nested links, but the best we can do without something like hpricot
237 txt.gsub!(/<a (?:[^>]*\s+)?href\s*=\s*(?:([^"'>][^\s>]*)\s+|"((?:[^"]|\\")*)"|'((?:[^']|\\')*)')(?:[^>]*\s+)?>(.*?)<\/a>/) { |match|
239 debug [$1, $2, $3, $4].inspect
240 link = $1 || $2 || $3
245 warning "unknown :a_href option #{val} passed to ircify_html" if val
248 # Paragraph and br tags are converted to whitespace
249 txt.gsub!(/<\/?(p|br)(?:\s+[^>]*)?\s*\/?\s*>/i, ' ')
253 # Superscripts and subscripts are turned into ^{...} and _{...}
254 # where the {} are omitted for single characters
255 txt.gsub!(/<sup>(.*?)<\/sup>/, '^{\1}')
256 txt.gsub!(/<sub>(.*?)<\/sub>/, '_{\1}')
257 txt.gsub!(/(^|_)\{(.)\}/, '\1\2')
259 # List items are converted to *). We don't have special support for
260 # nested or ordered lists.
261 txt.gsub!(/<li>/, ' *) ')
263 # All other tags are just removed
264 txt.gsub!(/<[^>]+>/, '')
266 # Convert HTML entities. We do it now to be able to handle stuff
268 txt = Utils.decode_html_entities(txt)
270 # Keep unbreakable spaces or conver them to plain spaces?
271 case val = opts[:nbsp]
273 txt.gsub!([160].pack('U'), ' ')
275 warning "unknown :nbsp option #{val} passed to ircify_html" if val
278 # Remove double formatting options, since they only waste bytes
279 txt.gsub!(/#{Bold}(\s*)#{Bold}/, '\1')
280 txt.gsub!(/#{Underline}(\s*)#{Underline}/, '\1')
282 # Simplify whitespace that appears on both sides of a formatting option
283 txt.gsub!(/\s+(#{Bold}|#{Underline})\s+/, ' \1')
284 txt.sub!(/\s+(#{Bold}|#{Underline})\z/, '\1')
285 txt.sub!(/\A(#{Bold}|#{Underline})\s+/, '\1')
287 # And finally whitespace is squeezed
288 txt.gsub!(/\s+/, ' ')
291 if opts[:limit] && txt.size > opts[:limit]
292 txt = txt.slice(0, opts[:limit]) + "#{Reverse}...#{Reverse}"
295 # Decode entities and strip whitespace
299 # As above, but modify the receiver
301 def ircify_html!(opts={})
303 replace self.ircify_html(opts)
304 return self unless self.hash == old_hash
307 # This method will strip all HTML crud from the receiver
310 self.gsub(/<[^>]+>/, '').gsub(/&/,'&').gsub(/"/,'"').gsub(/</,'<').gsub(/>/,'>').gsub(/&ellip;/,'...').gsub(/'/, "'").gsub("\n",'')
313 # This method tries to find an HTML title in the string,
314 # and returns it if found
316 if defined? ::Hpricot
317 Hpricot(self).at("title").inner_html
319 return unless Irc::Utils::TITLE_REGEX.match(self)
324 # This method returns the IRC-formatted version of an
325 # HTML title found in the string
326 def ircify_html_title
327 self.get_html_title.ircify_html rescue nil
330 # This method is used to wrap a nonempty String by adding
331 # the prefix and postfix
332 def wrap_nonempty(pre, post, opts={})
336 "#{pre}#{self}#{post}"
342 # Extensions to the Regexp class, with some common and/or complex regular
347 # A method to build a regexp that matches a list of something separated by
348 # optional commas and/or the word "and", an optionally repeated prefix,
350 def Regexp.new_list(reg, pfx = "")
351 if pfx.kind_of?(String) and pfx.empty?
352 return %r(#{reg}(?:,?(?:\s+and)?\s+#{reg})*)
354 return %r(#{reg}(?:,?(?:\s+and)?(?:\s+#{pfx})?\s+#{reg})*)
361 # Match a list of channel anmes separated by optional commas, whitespace
362 # and optionally the word "and"
363 CHAN_LIST = Regexp.new_list(GEN_CHAN)
365 # Match "in #channel" or "on #channel" and/or "in private" (optionally
366 # shortened to "in pvt"), returning the channel name or the word 'private'
367 # or 'pvt' as capture
368 IN_CHAN = /#{IN_ON}\s+(#{GEN_CHAN})|(here)|/
369 IN_CHAN_PVT = /#{IN_CHAN}|in\s+(private|pvt)/
371 # As above, but with channel lists
372 IN_CHAN_LIST_SFX = Regexp.new_list(/#{GEN_CHAN}|here/, IN_ON)
373 IN_CHAN_LIST = /#{IN_ON}\s+#{IN_CHAN_LIST_SFX}|anywhere|everywhere/
374 IN_CHAN_LIST_PVT_SFX = Regexp.new_list(/#{GEN_CHAN}|here|private|pvt/, IN_ON)
375 IN_CHAN_LIST_PVT = /#{IN_ON}\s+#{IN_CHAN_LIST_PVT_SFX}|anywhere|everywhere/
377 # Match a list of nicknames separated by optional commas, whitespace and
378 # optionally the word "and"
379 NICK_LIST = Regexp.new_list(GEN_NICK)
389 class BasicUserMessage
391 # We extend the BasicUserMessage class with a method that parses a string
392 # which is a channel list as matched by IN_CHAN(_LIST) and co. The method
393 # returns an array of channel names, where 'private' or 'pvt' is replaced
394 # by the Symbol :"?", 'here' is replaced by the channel of the message or
395 # by :"?" (depending on whether the message target is the bot or a
396 # Channel), and 'anywhere' and 'everywhere' are replaced by Symbol :*
398 def parse_channel_list(string)
399 return [:*] if [:anywhere, :everywhere].include? string.to_sym
401 /(?:^|,?(?:\s+and)?\s+)(?:in|on\s+)?(#{Regexp::Irc::GEN_CHAN}|here|private|pvt)/
420 # The recurse depth of a message, for fake messages. 0 means an original
423 unless defined? @recurse_depth
429 # Set the recurse depth of a message, for fake messages. 0 should only
430 # be used by original messages
431 def recurse_depth=(val)
439 # Maximum fake message recursion
440 MAX_RECURSE_DEPTH = 10
442 class RecurseTooDeep < RuntimeError
446 # Sometimes plugins need to create a new fake message based on an existing
447 # message: for example, this is done by alias, linkbot, reaction and remotectl.
449 # This method simplifies the message creation, including a recursion depth
452 # In the options you can specify the :bot, the :server, the :source,
453 # the :target, the message :class and whether or not to :delegate. To
454 # initialize these entries from an existing message, you can use :from
456 # Additionally, if :from is given, the reply method of created message
457 # is overriden to reply to :from instead. The #in_thread attribute
458 # for created mesage is also copied from :from
460 # If you don't specify a :from you should specify a :source.
462 def fake_message(string, opts={})
463 if from = opts[:from]
465 :bot => from.bot, :server => from.server, :source => from.source,
466 :target => from.target, :class => from.class, :delegate => true,
467 :depth => from.recurse_depth + 1
471 :bot => @bot, :server => @bot.server, :target => @bot.myself,
472 :class => PrivMessage, :delegate => true, :depth => 1
475 raise RecurseTooDeep if o[:depth] > MAX_RECURSE_DEPTH
476 new_m = o[:class].new(o[:bot], o[:server], o[:source], o[:target], string)
477 new_m.recurse_depth = o[:depth]
479 # the created message will reply to the originating message
482 end.send(:define_method, :reply) do |*args|
483 debug "replying to '#{from.message}' with #{args.first}"
486 # the created message will follow originating message's in_thread
487 new_m.in_thread = from.in_thread if from.respond_to?(:in_thread)
489 return new_m unless o[:delegate]
490 method = o[:class].to_s.gsub(/^Irc::|Message$/,'').downcase
491 method = 'privmsg' if method == 'priv'
492 o[:bot].plugins.irc_delegate(method, new_m)