]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/core/utils/extends.rb
extends: Arraydata/rbot/plugins/factoids.rbdelete_one to remove a random element...
[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 # Extensions to the Module class
17 #
18 class ::Module
19
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
23   # same attributes
24   #
25   def define_structure(name, *members)
26     sym = name.to_sym
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"
31         const_set(sym, kl)
32         return
33       end
34     end
35     debug "Defining struct #{sym} with members #{members.inspect}"
36     const_set(sym, Struct.new(name.to_s, *members))
37   end
38 end
39
40
41 # Extensions to the Array class
42 #
43 class ::Array
44
45   # This method returns a random element from the array, or nil if the array is
46   # empty
47   #
48   def pick_one
49     return nil if self.empty?
50     self[rand(self.length)]
51   end
52
53   # This method returns a random element from the array, deleting it from the
54   # array itself. The method returns nil if the array is empty
55   #
56   def delete_one
57     return nil if self.empty?
58     self.delete_at(rand(self.length))
59   end
60 end
61
62 # Extensions to the Range class
63 #
64 class ::Range
65
66   # This method returns a random number between the lower and upper bound
67   #
68   def pick_one
69     len = self.last - self.first
70     len += 1 unless self.exclude_end?
71     self.first + Kernel::rand(len)
72   end
73   alias :rand :pick_one
74 end
75
76 # Extensions for the Numeric classes
77 #
78 class ::Numeric
79
80   # This method forces a real number to be not more than a given positive
81   # number or not less than a given positive number, or between two any given
82   # numbers
83   #
84   def clip(left,right=0)
85     raise ArgumentError unless left.kind_of?(Numeric) and right.kind_of?(Numeric)
86     l = [left,right].min
87     u = [left,right].max
88     return l if self < l
89     return u if self > u
90     return self
91   end
92 end
93
94 # Extensions to the String class
95 #
96 # TODO make riphtml() just call ircify_html() with stronger purify options.
97 #
98 class ::String
99
100   # This method will return a purified version of the receiver, with all HTML
101   # stripped off and some of it converted to IRC formatting
102   #
103   def ircify_html(opts={})
104     txt = self.dup
105
106     # remove scripts
107     txt.gsub!(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "")
108
109     # remove styles
110     txt.gsub!(/<style(?:\s+[^>]*)?>.*?<\/style>/im, "")
111
112     # bold and strong -> bold
113     txt.gsub!(/<\/?(?:b|strong)(?:\s+[^>]*)?>/im, "#{Bold}")
114
115     # italic, emphasis and underline -> underline
116     txt.gsub!(/<\/?(?:i|em|u)(?:\s+[^>]*)?>/im, "#{Underline}")
117
118     ## This would be a nice addition, but the results are horrible
119     ## Maybe make it configurable?
120     # txt.gsub!(/<\/?a( [^>]*)?>/, "#{Reverse}")
121     case val = opts[:a_href]
122     when Reverse, Bold, Underline
123       txt.gsub!(/<(?:\/a\s*|a (?:[^>]*\s+)?href\s*=\s*(?:[^>]*\s*)?)>/, val)
124     when :link_out
125       # Not good for nested links, but the best we can do without something like hpricot
126       txt.gsub!(/<a (?:[^>]*\s+)?href\s*=\s*(?:([^"'>][^\s>]*)\s+|"((?:[^"]|\\")*)"|'((?:[^']|\\')*)')(?:[^>]*\s+)?>(.*?)<\/a>/) { |match|
127         debug match
128         debug [$1, $2, $3, $4].inspect
129         link = $1 || $2 || $3
130         str = $4
131         str + ": " + link
132       }
133     else
134       warning "unknown :a_href option #{val} passed to ircify_html" if val
135     end
136
137     # Paragraph and br tags are converted to whitespace
138     txt.gsub!(/<\/?(p|br)(?:\s+[^>]*)?\s*\/?\s*>/i, ' ')
139     txt.gsub!("\n", ' ')
140     txt.gsub!("\r", ' ')
141
142     # Superscripts and subscripts are turned into ^{...} and _{...}
143     # where the {} are omitted for single characters
144     txt.gsub!(/<sup>(.*?)<\/sup>/, '^{\1}')
145     txt.gsub!(/<sub>(.*?)<\/sub>/, '_{\1}')
146     txt.gsub!(/(^|_)\{(.)\}/, '\1\2')
147
148     # List items are converted to *). We don't have special support for
149     # nested or ordered lists.
150     txt.gsub!(/<li>/, ' *) ')
151
152     # All other tags are just removed
153     txt.gsub!(/<[^>]+>/, '')
154
155     # Convert HTML entities. We do it now to be able to handle stuff
156     # such as &nbsp;
157     txt = Utils.decode_html_entities(txt)
158
159     # Keep unbreakable spaces or conver them to plain spaces?
160     case val = opts[:nbsp]
161     when :space, ' '
162       txt.gsub!([160].pack('U'), ' ')
163     else
164       warning "unknown :nbsp option #{val} passed to ircify_html" if val
165     end
166
167     # Remove double formatting options, since they only waste bytes
168     txt.gsub!(/#{Bold}(\s*)#{Bold}/, '\1')
169     txt.gsub!(/#{Underline}(\s*)#{Underline}/, '\1')
170
171     # Simplify whitespace that appears on both sides of a formatting option
172     txt.gsub!(/\s+(#{Bold}|#{Underline})\s+/, ' \1')
173     txt.sub!(/\s+(#{Bold}|#{Underline})\z/, '\1')
174     txt.sub!(/\A(#{Bold}|#{Underline})\s+/, '\1')
175
176     # And finally whitespace is squeezed
177     txt.gsub!(/\s+/, ' ')
178     txt.strip!
179
180     if opts[:limit] && txt.size > opts[:limit]
181       txt = txt.slice(0, opts[:limit]) + "#{Reverse}...#{Reverse}"
182     end
183
184     # Decode entities and strip whitespace
185     return txt
186   end
187
188   # As above, but modify the receiver
189   #
190   def ircify_html!(opts={})
191     old_hash = self.hash
192     replace self.ircify_html(opts)
193     return self unless self.hash == old_hash
194   end
195
196   # This method will strip all HTML crud from the receiver
197   #
198   def riphtml
199     self.gsub(/<[^>]+>/, '').gsub(/&amp;/,'&').gsub(/&quot;/,'"').gsub(/&lt;/,'<').gsub(/&gt;/,'>').gsub(/&ellip;/,'...').gsub(/&apos;/, "'").gsub("\n",'')
200   end
201
202   # This method tries to find an HTML title in the string,
203   # and returns it if found
204   def get_html_title
205     if defined? ::Hpricot
206       Hpricot(self).at("title").inner_html
207     else
208       return unless Irc::Utils::TITLE_REGEX.match(self)
209       $1
210     end
211   end
212
213   # This method returns the IRC-formatted version of an
214   # HTML title found in the string
215   def ircify_html_title
216     self.get_html_title.ircify_html rescue nil
217   end
218 end
219
220
221 # Extensions to the Regexp class, with some common and/or complex regular
222 # expressions.
223 #
224 class ::Regexp
225
226   # A method to build a regexp that matches a list of something separated by
227   # optional commas and/or the word "and", an optionally repeated prefix,
228   # and whitespace.
229   def Regexp.new_list(reg, pfx = "")
230     if pfx.kind_of?(String) and pfx.empty?
231       return %r(#{reg}(?:,?(?:\s+and)?\s+#{reg})*)
232     else
233       return %r(#{reg}(?:,?(?:\s+and)?(?:\s+#{pfx})?\s+#{reg})*)
234     end
235   end
236
237   IN_ON = /in|on/
238
239   module Irc
240     # Match a list of channel anmes separated by optional commas, whitespace
241     # and optionally the word "and"
242     CHAN_LIST = Regexp.new_list(GEN_CHAN)
243
244     # Match "in #channel" or "on #channel" and/or "in private" (optionally
245     # shortened to "in pvt"), returning the channel name or the word 'private'
246     # or 'pvt' as capture
247     IN_CHAN = /#{IN_ON}\s+(#{GEN_CHAN})|(here)|/
248     IN_CHAN_PVT = /#{IN_CHAN}|in\s+(private|pvt)/
249
250     # As above, but with channel lists
251     IN_CHAN_LIST_SFX = Regexp.new_list(/#{GEN_CHAN}|here/, IN_ON)
252     IN_CHAN_LIST = /#{IN_ON}\s+#{IN_CHAN_LIST_SFX}|anywhere|everywhere/
253     IN_CHAN_LIST_PVT_SFX = Regexp.new_list(/#{GEN_CHAN}|here|private|pvt/, IN_ON)
254     IN_CHAN_LIST_PVT = /#{IN_ON}\s+#{IN_CHAN_LIST_PVT_SFX}|anywhere|everywhere/
255
256     # Match a list of nicknames separated by optional commas, whitespace and
257     # optionally the word "and"
258     NICK_LIST = Regexp.new_list(GEN_NICK)
259
260   end
261
262 end
263
264
265 module ::Irc
266
267
268   class BasicUserMessage
269
270     # We extend the BasicUserMessage class with a method that parses a string
271     # which is a channel list as matched by IN_CHAN(_LIST) and co. The method
272     # returns an array of channel names, where 'private' or 'pvt' is replaced
273     # by the Symbol :"?", 'here' is replaced by the channel of the message or
274     # by :"?" (depending on whether the message target is the bot or a
275     # Channel), and 'anywhere' and 'everywhere' are replaced by Symbol :*
276     #
277     def parse_channel_list(string)
278       return [:*] if [:anywhere, :everywhere].include? string.to_sym
279       string.scan(
280       /(?:^|,?(?:\s+and)?\s+)(?:in|on\s+)?(#{Regexp::Irc::GEN_CHAN}|here|private|pvt)/
281                  ).map { |chan_ar|
282         chan = chan_ar.first
283         case chan.to_sym
284         when :private, :pvt
285           :"?"
286         when :here
287           case self.target
288           when Channel
289             self.target.name
290           else
291             :"?"
292           end
293         else
294           chan
295         end
296       }.uniq
297     end
298   end
299 end