]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/core/utils/extends.rb
HTML IRCification: support options. currently only option is :a_href which can be...
[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
17 # Extensions to the Array class
18 #
19 class ::Array
20
21   # This method returns a random element from the array, or nil if the array is
22   # empty
23   #
24   def pick_one
25     return nil if self.empty?
26     self[rand(self.length)]
27   end
28 end
29
30 # Extensions for the Numeric classes
31 #
32 class ::Numeric
33
34   # This method forces a real number to be not more than a given positive
35   # number or not less than a given positive number, or between two any given
36   # numbers
37   #
38   def clip(left,right=0)
39     raise ArgumentError unless left.kind_of?(Numeric) and right.kind_of?(Numeric)
40     l = [left,right].min
41     u = [left,right].max
42     return l if self < l
43     return u if self > u
44     return self
45   end
46 end
47
48 # Extensions to the String class
49 #
50 # TODO make ircify_html() accept an Hash of options, and make riphtml() just
51 # call ircify_html() with stronger purify options.
52 #
53 class ::String
54
55   # This method will return a purified version of the receiver, with all HTML
56   # stripped off and some of it converted to IRC formatting
57   #
58   def ircify_html(opts={})
59     txt = self.dup
60
61     # remove scripts
62     txt.gsub!(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "")
63
64     # remove styles
65     txt.gsub!(/<style(?:\s+[^>]*)?>.*?<\/style>/im, "")
66
67     # bold and strong -> bold
68     txt.gsub!(/<\/?(?:b|strong)(?:\s+[^>]*)?>/im, "#{Bold}")
69
70     # italic, emphasis and underline -> underline
71     txt.gsub!(/<\/?(?:i|em|u)(?:\s+[^>]*)?>/im, "#{Underline}")
72
73     ## This would be a nice addition, but the results are horrible
74     ## Maybe make it configurable?
75     # txt.gsub!(/<\/?a( [^>]*)?>/, "#{Reverse}")
76     case val = opts[:a_href]
77     when Reverse, Bold, Underline
78       txt.gsub!(/<(?:\/a\s*|a (?:[^>]*\s+)?href\s*=\s*(?:[^>]*\s*)?)>/, val)
79     when :link_out
80       # Not good for nested links, but the best we can do without something like hpricot
81       txt.gsub!(/<a (?:[^>]*\s+)?href\s*=\s*(?:([^"'>][^\s>]*)\s+|"((?:[^"]|\\")*)"|'((?:[^']|\\')*)')(?:[^>]*\s+)?>(.*?)<\/a>/) { |match|
82         debug match
83         debug [$1, $2, $3, $4].inspect
84         link = $1 || $2 || $3
85         str = $4
86         str + ": " + link
87       }
88     else
89       warn "unknown :a_href option #{val} passed to ircify_html" if val
90     end
91
92     # Paragraph and br tags are converted to whitespace
93     txt.gsub!(/<\/?(p|br)(?:\s+[^>]*)?\s*\/?\s*>/i, ' ')
94     txt.gsub!("\n", ' ')
95     txt.gsub!("\r", ' ')
96
97     # Superscripts and subscripts are turned into ^{...} and _{...}
98     # where the {} are omitted for single characters
99     txt.gsub!(/<sup>(.*?)<\/sup>/, '^{\1}')
100     txt.gsub!(/<sub>(.*?)<\/sub>/, '_{\1}')
101     txt.gsub!(/(^|_)\{(.)\}/, '\1\2')
102
103     # All other tags are just removed
104     txt.gsub!(/<[^>]+>/, '')
105
106     # Convert HTML entities. We do it now to be able to handle stuff
107     # such as &nbsp;
108     txt = Utils.decode_html_entities(txt)
109
110     # Remove double formatting options, since they only waste bytes
111     txt.gsub!(/#{Bold}(\s*)#{Bold}/, '\1')
112     txt.gsub!(/#{Underline}(\s*)#{Underline}/, '\1')
113
114     # Simplify whitespace that appears on both sides of a formatting option
115     txt.gsub!(/\s+(#{Bold}|#{Underline})\s+/, ' \1')
116     txt.sub!(/\s+(#{Bold}|#{Underline})\z/, '\1')
117     txt.sub!(/\A(#{Bold}|#{Underline})\s+/, '\1')
118
119     # And finally whitespace is squeezed
120     txt.gsub!(/\s+/, ' ')
121
122     # Decode entities and strip whitespace
123     return txt.strip
124   end
125
126   # As above, but modify the receiver
127   #
128   def ircify_html!(opts={})
129     old_hash = self.hash
130     replace self.ircify_html(opts)
131     return self unless self.hash == old_hash
132   end
133
134   # This method will strip all HTML crud from the receiver
135   #
136   def riphtml
137     self.gsub(/<[^>]+>/, '').gsub(/&amp;/,'&').gsub(/&quot;/,'"').gsub(/&lt;/,'<').gsub(/&gt;/,'>').gsub(/&ellip;/,'...').gsub(/&apos;/, "'").gsub("\n",'')
138   end
139 end
140
141
142 # Extensions to the Regexp class, with some common and/or complex regular
143 # expressions.
144 #
145 class ::Regexp
146
147   # A method to build a regexp that matches a list of something separated by
148   # optional commas and/or the word "and", an optionally repeated prefix,
149   # and whitespace.
150   def Regexp.new_list(reg, pfx = "")
151     if pfx.kind_of?(String) and pfx.empty?
152       return %r(#{reg}(?:,?(?:\s+and)?\s+#{reg})*)
153     else
154       return %r(#{reg}(?:,?(?:\s+and)?(?:\s+#{pfx})?\s+#{reg})*)
155     end
156   end
157
158   IN_ON = /in|on/
159
160   module Irc
161     # Match a list of channel anmes separated by optional commas, whitespace
162     # and optionally the word "and"
163     CHAN_LIST = Regexp.new_list(GEN_CHAN)
164
165     # Match "in #channel" or "on #channel" and/or "in private" (optionally
166     # shortened to "in pvt"), returning the channel name or the word 'private'
167     # or 'pvt' as capture
168     IN_CHAN = /#{IN_ON}\s+(#{GEN_CHAN})|(here)|/
169     IN_CHAN_PVT = /#{IN_CHAN}|in\s+(private|pvt)/
170
171     # As above, but with channel lists
172     IN_CHAN_LIST_SFX = Regexp.new_list(/#{GEN_CHAN}|here/, IN_ON)
173     IN_CHAN_LIST = /#{IN_ON}\s+#{IN_CHAN_LIST_SFX}|anywhere|everywhere/
174     IN_CHAN_LIST_PVT_SFX = Regexp.new_list(/#{GEN_CHAN}|here|private|pvt/, IN_ON)
175     IN_CHAN_LIST_PVT = /#{IN_ON}\s+#{IN_CHAN_LIST_PVT_SFX}|anywhere|everywhere/
176
177     # Match a list of nicknames separated by optional commas, whitespace and
178     # optionally the word "and"
179     NICK_LIST = Regexp.new_list(GEN_NICK)
180
181   end
182
183 end
184
185
186 module ::Irc
187
188
189   class BasicUserMessage
190
191     # We extend the BasicUserMessage class with a method that parses a string
192     # which is a channel list as matched by IN_CHAN(_LIST) and co. The method
193     # returns an array of channel names, where 'private' or 'pvt' is replaced
194     # by the Symbol :"?", 'here' is replaced by the channel of the message or
195     # by :"?" (depending on whether the message target is the bot or a
196     # Channel), and 'anywhere' and 'everywhere' are replaced by Symbol :*
197     #
198     def parse_channel_list(string)
199       return [:*] if [:anywhere, :everywhere].include? string.to_sym
200       string.scan(
201       /(?:^|,?(?:\s+and)?\s+)(?:in|on\s+)?(#{Regexp::Irc::GEN_CHAN}|here|private|pvt)/
202                  ).map { |chan_ar|
203         chan = chan_ar.first
204         case chan.to_sym
205         when :private, :pvt
206           :"?"
207         when :here
208           case self.target
209           when Channel
210             self.target.name
211           else
212             :"?"
213           end
214         else
215           chan
216         end
217       }.uniq
218     end
219   end
220 end