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