]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/core/utils/extends.rb
plugin(search): fix search and gcalc, closes #28, #29
[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 #
8 # This file collects extensions to standard Ruby classes and to some core rbot
9 # classes to be used by the various plugins
10 #
11 # Please note that global symbols have to be prefixed by :: because this plugin
12 # will be read into an anonymous module
13
14 # Extensions to the Module class
15 #
16 class ::Module
17
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
21   # same attributes
22   #
23   def define_structure(name, *members)
24     sym = name.to_sym
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"
29         const_set(sym, kl)
30         return
31       end
32     end
33     debug "Defining struct #{sym} with members #{members.inspect}"
34     const_set(sym, Struct.new(name.to_s, *members))
35   end
36 end
37
38
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)
42 #
43 # You have to define the single_retrieve(_key_) and
44 # single_assign(_key_,_value_) methods (usually aliased at the
45 # original :[] and :[]= methods)
46 #
47 module ::DottedIndex
48   def rbot_index_split(*ar)
49     keys = ([] << ar).flatten
50     keys.map! { |k|
51       k.to_s.split('.').map { |kk| kk.to_sym rescue nil }.compact
52     }.flatten
53   end
54
55   def [](*ar)
56     keys = self.rbot_index_split(ar)
57     return self.single_retrieve(keys.first) if keys.length == 1
58     h = self
59     while keys.length > 1
60       k = keys.shift
61       h[k] ||= self.class.new
62       h = h[k]
63     end
64     h[keys.last]
65   end
66
67   def []=(*arr)
68     val = arr.last
69     ar = arr[0..-2]
70     keys = self.rbot_index_split(ar)
71     return self.single_assign(keys.first, val) if keys.length == 1
72     h = self
73     while keys.length > 1
74       k = keys.shift
75       h[k] ||= self.class.new
76       h = h[k]
77     end
78     h[keys.last] = val
79   end
80 end
81
82
83 # Extensions to the Array class
84 #
85 class ::Array
86
87   # This method returns a random element from the array, or nil if the array is
88   # empty
89   #
90   def pick_one
91     return nil if self.empty?
92     self[rand(self.length)]
93   end
94
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.
97   #
98   # If nil is specified, a random element is returned and deleted.
99   #
100   def delete_one(val=nil)
101     return nil if self.empty?
102     if val.nil?
103       index = rand(self.length)
104     else
105       index = self.index(val)
106       return nil unless index
107     end
108     self.delete_at(index)
109   end
110
111   # This method deletes a given object _el_ if it's found at the given
112   # position _pos_. The position can be either an integer or a range.
113   def delete_if_at(el, pos)
114     idx = self.index(el)
115     if pos === idx
116       self.delete_at(idx)
117     else
118       nil
119     end
120   end
121
122   # Taken from Ruby backports:
123   # shuffle and shuffle! are defined in Ruby >= 1.8.7
124
125   # This method returns a new array with the
126   # same items as the receiver, but shuffled
127   def shuffle
128     dup.shuffle!
129   end unless method_defined? :shuffle
130
131   def shuffle!
132     size.times do |i|
133       r = i + Kernel.rand(size - i)
134       self[i], self[r] = self[r], self[i]
135     end
136     self
137   end unless method_defined? :shuffle!
138 end
139
140 module ::Enumerable
141   # This method is an advanced version of #join
142   # allowing fine control of separators:
143   #
144   #   [1,2,3].conjoin(', ', ' and ')
145   #   => "1, 2 and 3
146   #
147   #   [1,2,3,4].conjoin{ |i, a, b| i % 2 == 0 ? '.' : '-' }
148   #   => "1.2-3.4"
149   #
150   # Code lifted from the ruby facets project:
151   # <http://facets.rubyforge.org>
152   # git-rev: c8b7395255b977d3c7de268ff563e3c5bc7f1441
153   # file: lib/core/facets/array/conjoin.rb
154   def conjoin(*args, &block)
155     num = count - 1
156
157     return first.to_s if num < 1
158
159     sep = []
160
161     if block_given?
162       num.times do |i|
163         sep << yield(i, *slice(i, 2))
164       end
165     else
166       options = (Hash === args.last) ? args.pop : {}
167       separator = args.shift || ""
168       options[-1] = args.shift unless args.empty?
169
170       sep = [separator] * num
171
172       if options.key?(:last)
173         options[-1] = options.delete(:last)
174       end
175       options[-1] ||= _(" and ")
176
177       options.each{ |i, s| sep[i] = s }
178     end
179
180     zip(sep).join
181   end
182 end
183
184 # Extensions to the Range class
185 #
186 class ::Range
187
188   # This method returns a random number between the lower and upper bound
189   #
190   def pick_one
191     len = self.last - self.first
192     len += 1 unless self.exclude_end?
193     self.first + Kernel::rand(len)
194   end
195   alias :rand :pick_one
196 end
197
198 # Extensions for the Numeric classes
199 #
200 class ::Numeric
201
202   # This method forces a real number to be not more than a given positive
203   # number or not less than a given positive number, or between two any given
204   # numbers
205   #
206   def clip(left,right=0)
207     raise ArgumentError unless left.kind_of?(Numeric) and right.kind_of?(Numeric)
208     l = [left,right].min
209     u = [left,right].max
210     return l if self < l
211     return u if self > u
212     return self
213   end
214 end
215
216 # Extensions to the String class
217 #
218 # TODO make riphtml() just call ircify_html() with stronger purify options.
219 #
220 class ::String
221
222   # This method will return a purified version of the receiver, with all HTML
223   # stripped off and some of it converted to IRC formatting
224   #
225   def ircify_html(opts={})
226     txt = self.dup
227
228     # remove scripts
229     txt.gsub!(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "")
230
231     # remove styles
232     txt.gsub!(/<style(?:\s+[^>]*)?>.*?<\/style>/im, "")
233
234     # bold and strong -> bold
235     txt.gsub!(/<\/?(?:b|strong)(?:\s+[^>]*)?>/im, "#{Bold}")
236
237     # italic, emphasis and underline -> underline
238     txt.gsub!(/<\/?(?:i|em|u)(?:\s+[^>]*)?>/im, "#{Underline}")
239
240     ## This would be a nice addition, but the results are horrible
241     ## Maybe make it configurable?
242     # txt.gsub!(/<\/?a( [^>]*)?>/, "#{Reverse}")
243     case val = opts[:a_href]
244     when Reverse, Bold, Underline
245       txt.gsub!(/<(?:\/a\s*|a (?:[^>]*\s+)?href\s*=\s*(?:[^>]*\s*)?)>/, val)
246     when :link_out
247       # Not good for nested links, but the best we can do without something like hpricot
248       txt.gsub!(/<a (?:[^>]*\s+)?href\s*=\s*(?:([^"'>][^\s>]*)\s+|"((?:[^"]|\\")*)"|'((?:[^']|\\')*)')(?:[^>]*\s+)?>(.*?)<\/a>/) { |match|
249         debug match
250         debug [$1, $2, $3, $4].inspect
251         link = $1 || $2 || $3
252         str = $4
253         str + ": " + link
254       }
255     else
256       warning "unknown :a_href option #{val} passed to ircify_html" if val
257     end
258
259     # If opts[:img] is defined, it should be a String. Each image
260     # will be replaced by the string itself, replacing occurrences of
261     # %{alt} %{dimensions} and %{src} with the alt text, image dimensions
262     # and URL
263     if val = opts[:img]
264       if val.kind_of? String
265         txt.gsub!(/<img\s+(.*?)\s*\/?>/) do |imgtag|
266           attrs = Hash.new
267           imgtag.scan(/([[:alpha:]]+)\s*=\s*(['"])?(.*?)\2/) do |key, quote, value|
268             k = key.downcase.intern rescue 'junk'
269             attrs[k] = value
270           end
271           attrs[:alt] ||= attrs[:title]
272           attrs[:width] ||= '...'
273           attrs[:height] ||= '...'
274           attrs[:dimensions] ||= "#{attrs[:width]}x#{attrs[:height]}"
275           val % attrs
276         end
277       else
278         warning ":img option is not a string"
279       end
280     end
281
282     # Paragraph and br tags are converted to whitespace
283     txt.gsub!(/<\/?(p|br)(?:\s+[^>]*)?\s*\/?\s*>/i, ' ')
284     txt.gsub!("\n", ' ')
285     txt.gsub!("\r", ' ')
286
287     # Superscripts and subscripts are turned into ^{...} and _{...}
288     # where the {} are omitted for single characters
289     txt.gsub!(/<sup>(.*?)<\/sup>/, '^{\1}')
290     txt.gsub!(/<sub>(.*?)<\/sub>/, '_{\1}')
291     txt.gsub!(/(^|_)\{(.)\}/, '\1\2')
292
293     # List items are converted to *). We don't have special support for
294     # nested or ordered lists.
295     txt.gsub!(/<li>/, ' *) ')
296
297     # All other tags are just removed
298     txt.gsub!(/<[^>]+>/, '')
299
300     # Convert HTML entities. We do it now to be able to handle stuff
301     # such as &nbsp;
302     txt = Utils.decode_html_entities(txt)
303
304     # Keep unbreakable spaces or conver them to plain spaces?
305     case val = opts[:nbsp]
306     when :space, ' '
307       txt.gsub!([160].pack('U'), ' ')
308     else
309       warning "unknown :nbsp option #{val} passed to ircify_html" if val
310     end
311
312     # Remove double formatting options, since they only waste bytes
313     txt.gsub!(/#{Bold}(\s*)#{Bold}/, '\1')
314     txt.gsub!(/#{Underline}(\s*)#{Underline}/, '\1')
315
316     # Simplify whitespace that appears on both sides of a formatting option
317     txt.gsub!(/\s+(#{Bold}|#{Underline})\s+/, ' \1')
318     txt.sub!(/\s+(#{Bold}|#{Underline})\z/, '\1')
319     txt.sub!(/\A(#{Bold}|#{Underline})\s+/, '\1')
320
321     # And finally whitespace is squeezed
322     txt.gsub!(/\s+/, ' ')
323     txt.strip!
324
325     if opts[:limit] && txt.size > opts[:limit]
326       txt = txt.slice(0, opts[:limit]) + "#{Reverse}...#{Reverse}"
327     end
328
329     # Decode entities and strip whitespace
330     return txt
331   end
332
333   # As above, but modify the receiver
334   #
335   def ircify_html!(opts={})
336     old_hash = self.hash
337     replace self.ircify_html(opts)
338     return self unless self.hash == old_hash
339   end
340
341   # This method will strip all HTML crud from the receiver
342   #
343   def riphtml
344     Utils.decode_html_entities(self.gsub("\n",' ').gsub(/<\s*br\s*\/?\s*>/, ' ').gsub(/<[^>]+>/, '')).gsub(/\s+/,' ')
345   end
346
347   # This method tries to find an HTML title in the string,
348   # and returns it if found
349   def get_html_title
350     if defined? ::Hpricot
351       Hpricot(self).at("title").inner_html
352     else
353       return unless Irc::Utils::TITLE_REGEX.match(self)
354       $1
355     end
356   end
357
358   # This method returns the IRC-formatted version of an
359   # HTML title found in the string
360   def ircify_html_title
361     self.get_html_title.ircify_html rescue nil
362   end
363
364   # This method is used to wrap a nonempty String by adding
365   # the prefix and postfix
366   def wrap_nonempty(pre, post, opts={})
367     if self.empty?
368       String.new
369     else
370       "#{pre}#{self}#{post}"
371     end
372   end
373
374   # Format a string using IRC colors
375   #
376   def colorformat
377     txt = self.dup
378
379     txt.gsub!(/\*([^\*]+)\*/, Bold + '\\1' + NormalText)
380
381     return txt
382   end
383   
384   # Removes non-ASCII symbols from string
385   def remove_nonascii(replace='')
386     encoding_options = {
387       :invalid           => :replace,  # Replace invalid byte sequences
388       :undef             => :replace,  # Replace anything not defined in ASCII
389       :replace           => replace,   
390       :universal_newline => true       # Always break lines with \n
391     }
392
393     self.encode(Encoding.find('ASCII'), encoding_options)
394   end
395 end
396
397 # Extensions to the Regexp class, with some common and/or complex regular
398 # expressions.
399 #
400 class ::Regexp
401
402   # A method to build a regexp that matches a list of something separated by
403   # optional commas and/or the word "and", an optionally repeated prefix,
404   # and whitespace.
405   def Regexp.new_list(reg, pfx = "")
406     if pfx.kind_of?(String) and pfx.empty?
407       return %r(#{reg}(?:,?(?:\s+and)?\s+#{reg})*)
408     else
409       return %r(#{reg}(?:,?(?:\s+and)?(?:\s+#{pfx})?\s+#{reg})*)
410     end
411   end
412
413   IN_ON = /in|on/
414
415   module Irc
416     # Match a list of channel anmes separated by optional commas, whitespace
417     # and optionally the word "and"
418     CHAN_LIST = Regexp.new_list(GEN_CHAN)
419
420     # Match "in #channel" or "on #channel" and/or "in private" (optionally
421     # shortened to "in pvt"), returning the channel name or the word 'private'
422     # or 'pvt' as capture
423     IN_CHAN = /#{IN_ON}\s+(#{GEN_CHAN})|(here)|/
424     IN_CHAN_PVT = /#{IN_CHAN}|in\s+(private|pvt)/
425
426     # As above, but with channel lists
427     IN_CHAN_LIST_SFX = Regexp.new_list(/#{GEN_CHAN}|here/, IN_ON)
428     IN_CHAN_LIST = /#{IN_ON}\s+#{IN_CHAN_LIST_SFX}|anywhere|everywhere/
429     IN_CHAN_LIST_PVT_SFX = Regexp.new_list(/#{GEN_CHAN}|here|private|pvt/, IN_ON)
430     IN_CHAN_LIST_PVT = /#{IN_ON}\s+#{IN_CHAN_LIST_PVT_SFX}|anywhere|everywhere/
431
432     # Match a list of nicknames separated by optional commas, whitespace and
433     # optionally the word "and"
434     NICK_LIST = Regexp.new_list(GEN_NICK)
435
436   end
437
438 end
439
440
441 module ::Irc
442
443
444   class BasicUserMessage
445
446     # We extend the BasicUserMessage class with a method that parses a string
447     # which is a channel list as matched by IN_CHAN(_LIST) and co. The method
448     # returns an array of channel names, where 'private' or 'pvt' is replaced
449     # by the Symbol :"?", 'here' is replaced by the channel of the message or
450     # by :"?" (depending on whether the message target is the bot or a
451     # Channel), and 'anywhere' and 'everywhere' are replaced by Symbol :*
452     #
453     def parse_channel_list(string)
454       return [:*] if [:anywhere, :everywhere].include? string.to_sym
455       string.scan(
456       /(?:^|,?(?:\s+and)?\s+)(?:in|on\s+)?(#{Regexp::Irc::GEN_CHAN}|here|private|pvt)/
457                  ).map { |chan_ar|
458         chan = chan_ar.first
459         case chan.to_sym
460         when :private, :pvt
461           :"?"
462         when :here
463           case self.target
464           when Channel
465             self.target.name
466           else
467             :"?"
468           end
469         else
470           chan
471         end
472       }.uniq
473     end
474
475     # The recurse depth of a message, for fake messages. 0 means an original
476     # message
477     def recurse_depth
478       unless defined? @recurse_depth
479         @recurse_depth = 0
480       end
481       @recurse_depth
482     end
483
484     # Set the recurse depth of a message, for fake messages. 0 should only
485     # be used by original messages
486     def recurse_depth=(val)
487       @recurse_depth = val
488     end
489   end
490
491   class Bot
492     module Plugins
493
494       # Maximum fake message recursion
495       MAX_RECURSE_DEPTH = 10
496
497       class RecurseTooDeep < RuntimeError
498       end
499
500       class BotModule
501         # Sometimes plugins need to create a new fake message based on an existing
502         # message: for example, this is done by alias, linkbot, reaction and remotectl.
503         #
504         # This method simplifies the message creation, including a recursion depth
505         # check.
506         #
507         # In the options you can specify the :bot, the :server, the :source,
508         # the :target, the message :class and whether or not to :delegate. To
509         # initialize these entries from an existing message, you can use :from
510         #
511         # Additionally, if :from is given, the reply method of created message
512         # is overriden to reply to :from instead. The #in_thread attribute
513         # for created mesage is also copied from :from
514         #
515         # If you don't specify a :from you should specify a :source.
516         #
517         def fake_message(string, opts={})
518           if from = opts[:from]
519             o = {
520               :bot => from.bot, :server => from.server, :source => from.source,
521               :target => from.target, :class => from.class, :delegate => true,
522               :depth => from.recurse_depth + 1
523             }.merge(opts)
524           else
525             o = {
526               :bot => @bot, :server => @bot.server, :target => @bot.myself,
527               :class => PrivMessage, :delegate => true, :depth => 1
528             }.merge(opts)
529           end
530           raise RecurseTooDeep if o[:depth] > MAX_RECURSE_DEPTH
531           new_m = o[:class].new(o[:bot], o[:server], o[:source], o[:target], string)
532           new_m.recurse_depth = o[:depth]
533           if from
534             # the created message will reply to the originating message, but we
535             # must remember to set 'replied' on the fake message too, to
536             # prevent infinite loops that could be created for example with the reaction
537             # plugin by setting up a reaction to ping with cmd:ping
538             class << new_m
539               self
540             end.send(:define_method, :reply) do |*args|
541               debug "replying to '#{from.message}' with #{args.first}"
542               from.reply(*args)
543               new_m.replied = true
544             end
545             # the created message will follow originating message's in_thread
546             new_m.in_thread = from.in_thread if from.respond_to?(:in_thread)
547           end
548           return new_m unless o[:delegate]
549           method = o[:class].to_s.gsub(/^Irc::|Message$/,'').downcase
550           method = 'privmsg' if method == 'priv'
551           o[:bot].plugins.irc_delegate(method, new_m)
552         end
553       end
554     end
555   end
556 end