]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/core/utils/wordlist.rb
81d7d775ef329f4058531cdb8444365a2d87a0a4
[user/henk/code/ruby/rbot.git] / lib / rbot / core / utils / wordlist.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: rbot wordlist provider
5 #
6 # Author:: Raine Virta <rane@kapsi.fi>
7
8 require "find"
9
10 module ::Irc
11 class Bot
12 class Wordlist
13   def self.wordlist_base
14     @@wordlist_base ||= Utils.bot.path 'wordlists'
15   end
16
17   def self.get(where, options={})
18     opts = { :spaces => false }.merge(options)
19
20     wordlist_path = File.join(wordlist_base, where)
21     raise "wordlist not found: #{wordlist_path}" unless File.exist?(wordlist_path)
22
23     # Location is a directory -> combine all lists beneath it
24     wordlist = if File.directory?(wordlist_path)
25       wordlists = []
26       Find.find(wordlist_path) do |path|
27         next if path == wordlist_path
28         wordlists << path unless File.directory?(path)
29       end
30
31       wordlists.map { |list| File.readlines(list) }.flatten
32     else
33       File.readlines(wordlist_path)
34     end
35
36     # wordlists are assumed to be UTF-8, but we need to strip the BOM, if present
37     wordlist.map! { |l| l.sub("\xef\xbb\xbf",'').strip }
38     wordlist.reject do |word|
39       word =~ /\s/ && !opts[:spaces] ||
40       word.empty?
41     end
42   end
43
44   # Return an array with the list of available wordlists.
45   # Available options:
46   # pattern:: pattern that should be matched by the wordlist filename
47   def self.list(options={})
48     pattern = options[:pattern] || "**"
49     # refuse patterns that contain ../
50     return [] if pattern =~ /\.\.\//
51     striplen = self.wordlist_base.length+1
52     Dir.glob(File.join(self.wordlist_base, pattern)).map { |name|
53       name[striplen..-1]
54     }
55   end
56
57   def self.exist?(path)
58     fn = path.to_s
59     # refuse to check outside of the wordlist base directory
60     return false if fn =~ /\.\.\//
61     File.exist?(File.join(self.wordlist_base, fn))
62   end
63
64 end
65 end
66 end