]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/core/utils/utils.rb
Add – to known HTML characters
[user/henk/code/ruby/rbot.git] / lib / rbot / core / utils / utils.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: rbot utilities provider
5 #
6 # Author:: Tom Gilbert <tom@linuxbrit.co.uk>
7 # Author:: Giuseppe "Oblomov" Bilotta <giuseppe.bilotta@gmail.com>
8 #
9 # TODO some of these Utils should be rewritten as extensions to the approriate
10 # standard Ruby classes and accordingly be moved to extends.rb
11
12 require 'tempfile'
13 require 'set'
14
15 # Try to load htmlentities, fall back to an HTML escape table.
16 begin
17   require 'htmlentities'
18 rescue LoadError
19     module ::Irc
20       module Utils
21         UNESCAPE_TABLE = {
22     'laquo' => '«',
23     'raquo' => '»',
24     'quot' => '"',
25     'apos' => '\'',
26     'deg' => '°',
27     'micro' => 'µ',
28     'copy' => '©',
29     'trade' => '™',
30     'reg' => '®',
31     'amp' => '&',
32     'lt' => '<',
33     'gt' => '>',
34     'hellip' => '…',
35     'nbsp' => ' ',
36     'ndash' => '–',
37     'Agrave' => 'À',
38     'Aacute' => 'Á',
39     'Acirc' => 'Â',
40     'Atilde' => 'Ã',
41     'Auml' => 'Ä',
42     'Aring' => 'Å',
43     'AElig' => 'Æ',
44     'OElig' => 'Œ',
45     'Ccedil' => 'Ç',
46     'Egrave' => 'È',
47     'Eacute' => 'É',
48     'Ecirc' => 'Ê',
49     'Euml' => 'Ë',
50     'Igrave' => 'Ì',
51     'Iacute' => 'Í',
52     'Icirc' => 'Î',
53     'Iuml' => 'Ï',
54     'ETH' => 'Ð',
55     'Ntilde' => 'Ñ',
56     'Ograve' => 'Ò',
57     'Oacute' => 'Ó',
58     'Ocirc' => 'Ô',
59     'Otilde' => 'Õ',
60     'Ouml' => 'Ö',
61     'Oslash' => 'Ø',
62     'Ugrave' => 'Ù',
63     'Uacute' => 'Ú',
64     'Ucirc' => 'Û',
65     'Uuml' => 'Ü',
66     'Yacute' => 'Ý',
67     'THORN' => 'Þ',
68     'szlig' => 'ß',
69     'agrave' => 'à',
70     'aacute' => 'á',
71     'acirc' => 'â',
72     'atilde' => 'ã',
73     'auml' => 'ä',
74     'aring' => 'å',
75     'aelig' => 'æ',
76     'oelig' => 'œ',
77     'ccedil' => 'ç',
78     'egrave' => 'è',
79     'eacute' => 'é',
80     'ecirc' => 'ê',
81     'euml' => 'ë',
82     'igrave' => 'ì',
83     'iacute' => 'í',
84     'icirc' => 'î',
85     'iuml' => 'ï',
86     'eth' => 'ð',
87     'ntilde' => 'ñ',
88     'ograve' => 'ò',
89     'oacute' => 'ó',
90     'ocirc' => 'ô',
91     'otilde' => 'õ',
92     'ouml' => 'ö',
93     'oslash' => 'ø',
94     'ugrave' => 'ù',
95     'uacute' => 'ú',
96     'ucirc' => 'û',
97     'uuml' => 'ü',
98     'yacute' => 'ý',
99     'thorn' => 'þ',
100     'yuml' => 'ÿ'
101         }
102       end
103     end
104 end
105
106 begin
107   require 'hpricot'
108   module ::Irc
109     module Utils
110       AFTER_PAR_PATH = /^(?:div|span)$/
111       AFTER_PAR_EX = /^(?:td|tr|tbody|table)$/
112       AFTER_PAR_CLASS = /body|message|text/i
113     end
114   end
115 rescue LoadError
116     module ::Irc
117       module Utils
118         # Some regular expressions to manage HTML data
119
120         # Title
121         TITLE_REGEX = /<\s*?title\s*?>(.+?)<\s*?\/title\s*?>/im
122
123         # H1, H2, etc
124         HX_REGEX = /<h(\d)(?:\s+[^>]*)?>(.*?)<\/h\1>/im
125         # A paragraph
126         PAR_REGEX = /<p(?:\s+[^>]*)?>.*?<\/?(?:p|div|html|body|table|td|tr)(?:\s+[^>]*)?>/im
127
128         # Some blogging and forum platforms use spans or divs with a 'body' or 'message' or 'text' in their class
129         # to mark actual text
130         AFTER_PAR1_REGEX = /<\w+\s+[^>]*(?:body|message|text)[^>]*>.*?<\/?(?:p|div|html|body|table|td|tr)(?:\s+[^>]*)?>/im
131
132         # At worst, we can try stuff which is comprised between two <br>
133         AFTER_PAR2_REGEX = /<br(?:\s+[^>]*)?\/?>.*?<\/?(?:br|p|div|html|body|table|td|tr)(?:\s+[^>]*)?\/?>/im
134       end
135     end
136 end
137
138 module ::Irc
139
140   # Miscellaneous useful functions
141   module Utils
142     @@bot = nil unless defined? @@bot
143     @@safe_save_dir = nil unless defined?(@@safe_save_dir)
144
145     # The bot instance
146     def Utils.bot
147       @@bot
148     end
149
150     # Set up some Utils routines which depend on the associated bot.
151     def Utils.bot=(b)
152       debug "initializing utils"
153       @@bot = b
154       @@safe_save_dir = @@bot.path('safe_save')
155     end
156
157
158     # Seconds per minute
159     SEC_PER_MIN = 60
160     # Seconds per hour
161     SEC_PER_HR = SEC_PER_MIN * 60
162     # Seconds per day
163     SEC_PER_DAY = SEC_PER_HR * 24
164     # Seconds per week
165     SEC_PER_WK = SEC_PER_DAY * 7
166     # Seconds per (30-day) month
167     SEC_PER_MNTH = SEC_PER_DAY * 30
168     # Second per (non-leap) year
169     SEC_PER_YR = SEC_PER_DAY * 365
170
171     # Auxiliary method needed by Utils.secs_to_string
172     def Utils.secs_to_string_case(array, var, string, plural)
173       case var
174       when 1
175         array << "1 #{string}"
176       else
177         array << "#{var} #{plural}"
178       end
179     end
180
181     # Turn a number of seconds into a human readable string, e.g
182     # 2 days, 3 hours, 18 minutes and 10 seconds
183     def Utils.secs_to_string(secs)
184       ret = []
185       years, secs = secs.divmod SEC_PER_YR
186       secs_to_string_case(ret, years, _("year"), _("years")) if years > 0
187       months, secs = secs.divmod SEC_PER_MNTH
188       secs_to_string_case(ret, months, _("month"), _("months")) if months > 0
189       days, secs = secs.divmod SEC_PER_DAY
190       secs_to_string_case(ret, days, _("day"), _("days")) if days > 0
191       hours, secs = secs.divmod SEC_PER_HR
192       secs_to_string_case(ret, hours, _("hour"), _("hours")) if hours > 0
193       mins, secs = secs.divmod SEC_PER_MIN
194       secs_to_string_case(ret, mins, _("minute"), _("minutes")) if mins > 0
195       secs = secs.to_i
196       secs_to_string_case(ret, secs, _("second"), _("seconds")) if secs > 0 or ret.empty?
197       case ret.length
198       when 0
199         raise "Empty ret array!"
200       when 1
201         return ret.to_s
202       else
203         return [ret[0, ret.length-1].join(", ") , ret[-1]].join(_(" and "))
204       end
205     end
206
207     # Turn a number of seconds into a hours:minutes:seconds e.g.
208     # 3:18:10 or 5'12" or 7s
209     #
210     def Utils.secs_to_short(seconds)
211       secs = seconds.to_i # make sure it's an integer
212       mins, secs = secs.divmod 60
213       hours, mins = mins.divmod 60
214       if hours > 0
215         return ("%s:%s:%s" % [hours, mins, secs])
216       elsif mins > 0
217         return ("%s'%s\"" % [mins, secs])
218       else
219         return ("%ss" % [secs])
220       end
221     end
222
223     # Returns human readable time.
224     # Like: 5 days ago
225     #       about one hour ago
226     # options
227     # :start_date, sets the time to measure against, defaults to now
228     # :date_format, used with <tt>to_formatted_s<tt>, default to :default
229     def Utils.timeago(time, options = {})
230       start_date = options.delete(:start_date) || Time.new
231       date_format = options.delete(:date_format) || "%x"
232       delta = (start_date - time).round
233       if delta.abs < 2
234         _("right now")
235       else
236         distance = Utils.age_string(delta)
237         if delta < 0
238           _("%{d} from now") % {:d => distance}
239         else
240           _("%{d} ago") % {:d => distance}
241         end
242       end
243     end
244
245     # Converts age in seconds to "nn units". Inspired by previous attempts
246     # but also gitweb's age_string() sub
247     def Utils.age_string(secs)
248       case
249       when secs < 0
250         Utils.age_string(-secs)
251       when secs > 2*SEC_PER_YR
252         _("%{m} years") % { :m => secs/SEC_PER_YR }
253       when secs > 2*SEC_PER_MNTH
254         _("%{m} months") % { :m => secs/SEC_PER_MNTH }
255       when secs > 2*SEC_PER_WK
256         _("%{m} weeks") % { :m => secs/SEC_PER_WK }
257       when secs > 2*SEC_PER_DAY
258         _("%{m} days") % { :m => secs/SEC_PER_DAY }
259       when secs > 2*SEC_PER_HR
260         _("%{m} hours") % { :m => secs/SEC_PER_HR }
261       when (20*SEC_PER_MIN..40*SEC_PER_MIN).include?(secs)
262         _("half an hour")
263       when (50*SEC_PER_MIN..70*SEC_PER_MIN).include?(secs)
264         # _("about one hour")
265         _("an hour")
266       when (80*SEC_PER_MIN..100*SEC_PER_MIN).include?(secs)
267         _("an hour and a half")
268       when secs > 2*SEC_PER_MIN
269         _("%{m} minutes") % { :m => secs/SEC_PER_MIN }
270       when secs > 1
271         _("%{m} seconds") % { :m => secs }
272       else
273         _("one second")
274       end
275     end
276
277     # Execute an external program, returning a String obtained by redirecting
278     # the program's standards errors and output
279     #
280     # TODO: find a way to expose some common errors (e.g. Errno::NOENT)
281     # to the caller
282     def Utils.safe_exec(command, *args)
283       output = IO.popen("-") { |p|
284         if p
285           break p.readlines.join("\n")
286         else
287           begin
288             $stderr.reopen($stdout)
289             exec(command, *args)
290           rescue Exception => e
291             puts "exception #{e.pretty_inspect} trying to run #{command}"
292             Kernel::exit! 1
293           end
294           puts "exec of #{command} failed"
295           Kernel::exit! 1
296         end
297       }
298       raise "safe execution of #{command} returned #{$?}" unless $?.success?
299       return output
300     end
301
302     # Try executing an external program, returning true if the run was successful
303     # and false otherwise
304     def Utils.try_exec(command, *args)
305       IO.popen("-") { |p|
306         if p.nil?
307           begin
308             $stderr.reopen($stdout)
309             exec(command, *args)
310           rescue Exception => e
311             Kernel::exit! 1
312           end
313           Kernel::exit! 1
314         else
315           debug p.readlines
316         end
317       }
318       debug $?
319       return $?.success?
320     end
321
322     # Safely (atomically) save to _file_, by passing a tempfile to the block
323     # and then moving the tempfile to its final location when done.
324     #
325     # call-seq: Utils.safe_save(file, &block)
326     #
327     def Utils.safe_save(file)
328       raise 'No safe save directory defined!' if @@safe_save_dir.nil?
329       basename = File.basename(file)
330       temp = Tempfile.new(basename,@@safe_save_dir)
331       temp.binmode
332       yield temp if block_given?
333       temp.close
334       File.rename(temp.path, file)
335     end
336
337
338     # Decode HTML entities in the String _str_, using HTMLEntities if the
339     # package was found, or UNESCAPE_TABLE otherwise.
340     #
341     def Utils.decode_html_entities(str)
342       if defined? ::HTMLEntities
343         return HTMLEntities.decode_entities(str)
344       else
345         str.gsub(/(&(.+?);)/) {
346           symbol = $2
347           # remove the 0-paddng from unicode integers
348           if symbol =~ /^#(\d+)$/
349             symbol = $1.to_i.to_s
350           end
351
352           # output the symbol's irc-translated character, or a * if it's unknown
353           UNESCAPE_TABLE[symbol] || (symbol.match(/^\d+$/) ? [symbol.to_i].pack("U") : '*')
354         }
355       end
356     end
357
358     # Try to grab and IRCify the first HTML par (<p> tag) in the given string.
359     # If possible, grab the one after the first heading
360     #
361     # It is possible to pass some options to determine how the stripping
362     # occurs. Currently supported options are
363     # strip:: Regex or String to strip at the beginning of the obtained
364     #         text
365     # min_spaces:: minimum number of spaces a paragraph should have
366     #
367     def Utils.ircify_first_html_par(xml_org, opts={})
368       if defined? ::Hpricot
369         Utils.ircify_first_html_par_wh(xml_org, opts)
370       else
371         Utils.ircify_first_html_par_woh(xml_org, opts)
372       end
373     end
374
375     # HTML first par grabber using hpricot
376     def Utils.ircify_first_html_par_wh(xml_org, opts={})
377       doc = Hpricot(xml_org)
378
379       # Strip styles and scripts
380       (doc/"style|script").remove
381
382       debug doc
383
384       strip = opts[:strip]
385       strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
386
387       min_spaces = opts[:min_spaces] || 8
388       min_spaces = 0 if min_spaces < 0
389
390       txt = String.new
391
392       pre_h = pars = by_span = nil
393
394       while true
395         debug "Minimum number of spaces: #{min_spaces}"
396
397         # Initial attempt: <p> that follows <h\d>
398         if pre_h.nil?
399           pre_h = Hpricot::Elements[]
400           found_h = false
401           doc.search("*") { |e|
402             next if e.bogusetag?
403             case e.pathname
404             when /^h\d/
405               found_h = true
406             when 'p'
407               pre_h << e if found_h
408             end
409           }
410           debug "Hx: found: #{pre_h.pretty_inspect}"
411         end
412
413         pre_h.each { |p|
414           debug p
415           txt = p.to_html.ircify_html
416           txt.sub!(strip, '') if strip
417           debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
418           break unless txt.empty? or txt.count(" ") < min_spaces
419         }
420
421         return txt unless txt.empty? or txt.count(" ") < min_spaces
422
423         # Second natural attempt: just get any <p>
424         pars = doc/"p" if pars.nil?
425         debug "par: found: #{pars.pretty_inspect}"
426         pars.each { |p|
427           debug p
428           txt = p.to_html.ircify_html
429           txt.sub!(strip, '') if strip
430           debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
431           break unless txt.empty? or txt.count(" ") < min_spaces
432         }
433
434         return txt unless txt.empty? or txt.count(" ") < min_spaces
435
436         # Nothing yet ... let's get drastic: we look for non-par elements too,
437         # but only for those that match something that we know is likely to
438         # contain text
439
440         # Some blogging and forum platforms use spans or divs with a 'body' or
441         # 'message' or 'text' in their class to mark actual text. Since we want
442         # the class match to be partial and case insensitive, we collect
443         # the common elements that may have this class and then filter out those
444         # we don't need. If no divs or spans are found, we'll accept additional
445         # elements too (td, tr, tbody, table).
446         if by_span.nil?
447           by_span = Hpricot::Elements[]
448           extra = Hpricot::Elements[]
449           doc.search("*") { |el|
450             next if el.bogusetag?
451             case el.pathname
452             when AFTER_PAR_PATH
453               by_span.push el if el[:class] =~ AFTER_PAR_CLASS or el[:id] =~ AFTER_PAR_CLASS
454             when AFTER_PAR_EX
455               extra.push el if el[:class] =~ AFTER_PAR_CLASS or el[:id] =~ AFTER_PAR_CLASS
456             end
457           }
458           if by_span.empty? and not extra.empty?
459             by_span.concat extra
460           end
461           debug "other \#1: found: #{by_span.pretty_inspect}"
462         end
463
464         by_span.each { |p|
465           debug p
466           txt = p.to_html.ircify_html
467           txt.sub!(strip, '') if strip
468           debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
469           break unless txt.empty? or txt.count(" ") < min_spaces
470         }
471
472         return txt unless txt.empty? or txt.count(" ") < min_spaces
473
474         # At worst, we can try stuff which is comprised between two <br>
475         # TODO
476
477         debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
478         return txt unless txt.count(" ") < min_spaces
479         break if min_spaces == 0
480         min_spaces /= 2
481       end
482     end
483
484     # HTML first par grabber without hpricot
485     def Utils.ircify_first_html_par_woh(xml_org, opts={})
486       xml = xml_org.gsub(/<!--.*?-->/m, '').gsub(/<script(?:\s+[^>]*)?>.*?<\/script>/im, "").gsub(/<style(?:\s+[^>]*)?>.*?<\/style>/im, "")
487
488       strip = opts[:strip]
489       strip = Regexp.new(/^#{Regexp.escape(strip)}/) if strip.kind_of?(String)
490
491       min_spaces = opts[:min_spaces] || 8
492       min_spaces = 0 if min_spaces < 0
493
494       txt = String.new
495
496       while true
497         debug "Minimum number of spaces: #{min_spaces}"
498         header_found = xml.match(HX_REGEX)
499         if header_found
500           header_found = $'
501           while txt.empty? or txt.count(" ") < min_spaces
502             candidate = header_found[PAR_REGEX]
503             break unless candidate
504             txt = candidate.ircify_html
505             header_found = $'
506             txt.sub!(strip, '') if strip
507             debug "(Hx attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
508           end
509         end
510
511         return txt unless txt.empty? or txt.count(" ") < min_spaces
512
513         # If we haven't found a first par yet, try to get it from the whole
514         # document
515         header_found = xml
516         while txt.empty? or txt.count(" ") < min_spaces
517           candidate = header_found[PAR_REGEX]
518           break unless candidate
519           txt = candidate.ircify_html
520           header_found = $'
521           txt.sub!(strip, '') if strip
522           debug "(par attempt) #{txt.inspect} has #{txt.count(" ")} spaces"
523         end
524
525         return txt unless txt.empty? or txt.count(" ") < min_spaces
526
527         # Nothing yet ... let's get drastic: we look for non-par elements too,
528         # but only for those that match something that we know is likely to
529         # contain text
530
531         # Attempt #1
532         header_found = xml
533         while txt.empty? or txt.count(" ") < min_spaces
534           candidate = header_found[AFTER_PAR1_REGEX]
535           break unless candidate
536           txt = candidate.ircify_html
537           header_found = $'
538           txt.sub!(strip, '') if strip
539           debug "(other attempt \#1) #{txt.inspect} has #{txt.count(" ")} spaces"
540         end
541
542         return txt unless txt.empty? or txt.count(" ") < min_spaces
543
544         # Attempt #2
545         header_found = xml
546         while txt.empty? or txt.count(" ") < min_spaces
547           candidate = header_found[AFTER_PAR2_REGEX]
548           break unless candidate
549           txt = candidate.ircify_html
550           header_found = $'
551           txt.sub!(strip, '') if strip
552           debug "(other attempt \#2) #{txt.inspect} has #{txt.count(" ")} spaces"
553         end
554
555         debug "Last candidate #{txt.inspect} has #{txt.count(" ")} spaces"
556         return txt unless txt.count(" ") < min_spaces
557         break if min_spaces == 0
558         min_spaces /= 2
559       end
560     end
561
562     # This method extracts title, content (first par) and extra
563     # information from the given document _doc_.
564     #
565     # _doc_ can be an URI, a Net::HTTPResponse or a String.
566     #
567     # If _doc_ is a String, only title and content information
568     # are retrieved (if possible), using standard methods.
569     #
570     # If _doc_ is an URI or a Net::HTTPResponse, additional
571     # information is retrieved, and special title/summary
572     # extraction routines are used if possible.
573     #
574     def Utils.get_html_info(doc, opts={})
575       case doc
576       when String
577         Utils.get_string_html_info(doc, opts)
578       when Net::HTTPResponse
579         Utils.get_resp_html_info(doc, opts)
580       when URI
581         ret = DataStream.new
582         @@bot.httputil.get_response(doc) { |resp|
583           ret.replace Utils.get_resp_html_info(resp, opts)
584         }
585         return ret
586       else
587         raise
588       end
589     end
590
591     class ::UrlLinkError < RuntimeError
592     end
593
594     # This method extracts title, content (first par) and extra
595     # information from the given Net::HTTPResponse _resp_.
596     #
597     # Currently, the only accepted options (in _opts_) are
598     # uri_fragment:: the URI fragment of the original request
599     # full_body::    get the whole body instead of
600     #                @@bot.config['http.info_bytes'] bytes only
601     #
602     # Returns a DataStream with the following keys:
603     # text:: the (partial) body
604     # title:: the title of the document (if any)
605     # content:: the first paragraph of the document (if any)
606     # headers::
607     #   the headers of the Net::HTTPResponse. The value is
608     #   a Hash whose keys are lowercase forms of the HTTP
609     #   header fields, and whose values are Arrays.
610     #
611     def Utils.get_resp_html_info(resp, opts={})
612       case resp
613       when Net::HTTPSuccess
614         loc = URI.parse(resp['x-rbot-location'] || resp['location']) rescue nil
615         if loc and loc.fragment and not loc.fragment.empty?
616           opts[:uri_fragment] ||= loc.fragment
617         end
618         ret = DataStream.new(opts.dup)
619         ret[:headers] = resp.to_hash
620         ret[:text] = partial = opts[:full_body] ? resp.body : resp.partial_body(@@bot.config['http.info_bytes'])
621
622         filtered = Utils.try_htmlinfo_filters(ret)
623
624         if filtered
625           return filtered
626         elsif resp['content-type'] =~ /^text\/|(?:x|ht)ml/
627           ret.merge!(Utils.get_string_html_info(partial, opts))
628         end
629         return ret
630       else
631         raise UrlLinkError, "getting link (#{resp.code} - #{resp.message})"
632       end
633     end
634
635     # This method runs an appropriately-crafted DataStream _ds_ through the
636     # filters in the :htmlinfo filter group, in order. If one of the filters
637     # returns non-nil, its results are merged in _ds_ and returned. Otherwise
638     # nil is returned.
639     #
640     # The input DataStream should have the downloaded HTML as primary key
641     # (:text) and possibly a :headers key holding the resonse headers.
642     #
643     def Utils.try_htmlinfo_filters(ds)
644       filters = @@bot.filter_names(:htmlinfo)
645       return nil if filters.empty?
646       cur = nil
647       # TODO filter priority
648       filters.each { |n|
649         debug "testing htmlinfo filter #{n}"
650         cur = @@bot.filter(@@bot.global_filter_name(n, :htmlinfo), ds)
651         debug "returned #{cur.pretty_inspect}"
652         break if cur
653       }
654       return ds.merge(cur) if cur
655     end
656
657     # HTML info filters often need to check if the webpage location
658     # of a passed DataStream _ds_ matches a given Regexp.
659     def Utils.check_location(ds, rx)
660       debug ds[:headers]
661       if h = ds[:headers]
662         loc = [h['x-rbot-location'],h['location']].flatten.grep(rx)
663       end
664       loc ||= []
665       debug loc
666       return loc.empty? ? nil : loc
667     end
668
669     # This method extracts title and content (first par)
670     # from the given HTML or XML document _text_, using
671     # standard methods (String#ircify_html_title,
672     # Utils.ircify_first_html_par)
673     #
674     # Currently, the only accepted option (in _opts_) is
675     # uri_fragment:: the URI fragment of the original request
676     #
677     def Utils.get_string_html_info(text, opts={})
678       debug "getting string html info"
679       txt = text.dup
680       title = txt.ircify_html_title
681       debug opts
682       if frag = opts[:uri_fragment] and not frag.empty?
683         fragreg = /<a\s+(?:[^>]+\s+)?(?:name|id)=["']?#{frag}["']?[^>]*>/im
684         debug fragreg
685         debug txt
686         if txt.match(fragreg)
687           # grab the post-match
688           txt = $'
689         end
690         debug txt
691       end
692       c_opts = opts.dup
693       c_opts[:strip] ||= title
694       content = Utils.ircify_first_html_par(txt, c_opts)
695       content = nil if content.empty?
696       return {:title => title, :content => content}
697     end
698
699     # Get the first pars of the first _count_ _urls_.
700     # The pages are downloaded using the bot httputil service.
701     # Returns an array of the first paragraphs fetched.
702     # If (optional) _opts_ :message is specified, those paragraphs are
703     # echoed as replies to the IRC message passed as _opts_ :message
704     #
705     def Utils.get_first_pars(urls, count, opts={})
706       idx = 0
707       msg = opts[:message]
708       retval = Array.new
709       while count > 0 and urls.length > 0
710         url = urls.shift
711         idx += 1
712
713         begin
714           info = Utils.get_html_info(URI.parse(url), opts)
715
716           par = info[:content]
717           retval.push(par)
718
719           if par
720             msg.reply "[#{idx}] #{par}", :overlong => :truncate if msg
721             count -=1
722           end
723         rescue
724           debug "Unable to retrieve #{url}: #{$!}"
725           next
726         end
727       end
728       return retval
729     end
730
731     # Returns a comma separated list except for the last element
732     # which is joined in with specified conjunction
733     #
734     def Utils.comma_list(words, options={})
735       defaults = { :join_with => ", ", :join_last_with => _(" and ") }
736       opts = defaults.merge(options)
737
738       if words.size < 2
739         words.last
740       else
741         [words[0..-2].join(opts[:join_with]), words.last].join(opts[:join_last_with])
742       end
743     end
744
745   end
746 end
747
748 Irc::Utils.bot = Irc::Bot::Plugins.manager.bot