]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/alias.rb
alias.rb:
[user/henk/code/ruby/rbot.git] / data / rbot / plugins / alias.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: Alias plugin for rbot
5 #
6 # Author:: Yaohan Chen <yaohan.chen@gmail.com>
7 # Copyright:: (C) 2007 Yaohan Chen
8 # License:: GPLv2
9 #
10 # This plugin allows defining aliases for rbot commands. Aliases are like normal rbot
11 # commands and can take parameters. When called, they will be substituted into an
12 # exisitng rbot command and that is run.
13 #
14 # == Example Session
15 #   < alias googlerbot *terms => google site:linuxbrit.co.uk/rbot/ <terms>
16 #   > okay
17 #   < googlerbot plugins
18 #   > Results for site:linuxbrit.co.uk/rbot/ plugins: ....
19 #
20 # == Security
21 # By default, only the owner can define and remove aliases, while everyone else can
22 # use and view them. When a command is executed with an alias, it's mapped normally with
23 # the alias user appearing to attempt to execute the command. Therefore it should be not
24 # possible to use aliases to circumvent permission sets. Care should be taken when
25 # defining aliases, due to these concerns:
26 # * Defined aliases can potentially override other plugins' maps, if this plugin is
27 #   loaded first
28 # * Aliases can cause infinite recursion of aliases and/or commands. The plugin attempts
29 #   to detect and stop this, but a few recursive calls can still cause spamming
30
31 require 'yaml'
32 require 'set'
33
34 class AliasPlugin < Plugin
35   # an exception raised when loading or getting input of invalid alias definitions
36   class AliasDefinitionError < ArgumentError
37   end
38
39   MAX_RECURSION_DEPTH = 10
40
41   def initialize
42     super
43     @data_path = "#{@bot.botclass}/alias/"
44     @data_file = "#{@data_path}/aliases.yaml"
45     # hash of alias => command entries
46     data = nil
47     aliases = if File.exist?(@data_file) &&
48                  (data = YAML.load_file(@data_file)) &&
49                  data.respond_to?(:each_pair)
50                 data
51               else
52                 warning _("Data file is not found or corrupt, reinitializing data")
53                 Hash.new
54                end
55     @aliases = Hash.new
56     aliases.each_pair do |a, c|
57       begin
58         add_alias(a, c)
59       rescue AliasDefinitionError
60         warning _("Invalid alias entry %{alias} : %{command} in %{filename}: %{reason}") %
61                 {:alias => a, :command => c, :filename => @data_file, :reason => $1}
62       end
63     end 
64   end 
65
66   def save 
67     FileUtils.mkdir_p(@data_path)
68     Utils.safe_save(@data_file) {|f| f.write @aliases.to_yaml}
69   end
70
71   def cmd_add(m, params)
72     begin
73       add_alias(params[:text].to_s, params[:command].to_s)
74       m.okay
75     rescue AliasDefinitionError
76       m.reply _('The definition you provided is invalid: %{reason}') % {:reason => $!}
77     end
78   end
79
80   def cmd_remove(m, params)
81     text = params[:text].to_s
82     if @aliases.has_key?(text)
83       @aliases.delete(text)
84       # TODO when rbot supports it, remove the mapping corresponding to the alias
85       m.okay
86     else
87       m.reply _('No such alias is defined')
88     end
89   end
90
91   def cmd_list(m, params)
92     if @aliases.empty?
93       m.reply _('No aliases defined')
94     else
95       m.reply @aliases.map {|a, c| "#{a} => #{c}"}.join(' | ')
96     end
97   end
98
99   def cmd_whatis(m, params)
100     text = params[:text].to_s
101     if @aliases.has_key?(text)
102       m.reply _('Alias of %{command}') % {:command => @aliases[text]}
103     else
104       m.reply _('No such alias is defined')
105     end
106   end
107
108   def add_alias(text, command)
109     # each alias is implemented by adding a message map, whose handler creates a message
110     # containing the aliased command
111
112     command.scan(/<(\w+)>/).flatten.to_set ==
113       text.split.grep(/\A[:*](\w+)\Z/) {$1}.to_set or
114       raise AliasDefinitionError.new(_('The arguments in alias must match the substitutions in command, and vice versa'))
115     
116     begin
117       map text, :action => :"alias_handle<#{text}>", :auth_path => 'run'
118     rescue
119       raise AliasDefinitionError.new(_('Error mapping %{text} as command: %{error}') %
120                                      {:text => text, :error => $!})
121     end
122     @aliases[text] = command
123   end
124
125   def respond_to?(name, include_private=false)
126     name.to_s =~ /\Aalias_handle<.+>\Z/ || super
127   end
128
129   def method_missing(name, *args, &block)
130     if name.to_s =~ /\Aalias_handle<(.+)>\Z/
131       text = $1
132       m, params = args
133       # messages created by alias handler will have a depth method, which returns the 
134       # depth of "recursion" caused by the message
135       current_depth = if m.respond_to?(:depth) then m.depth else 0 end
136       if current_depth > MAX_RECURSION_DEPTH
137         m.reply _('The alias seems to have caused infinite recursion. Please examine your alias definitions')
138         return
139       end
140
141       command = @aliases[text]
142       if command
143         # create a fake message containing the intended command
144         new_msg = PrivMessage.new(@bot, m.server, m.server.user(m.source), m.target,
145                   command.gsub(/<(\w+)>/) {|arg| params[:"#{$1}"].to_s})
146         # tag incremented depth on the message
147         class << new_msg
148           self
149         end.send(:define_method, :depth) {current_depth + 1}
150
151         @bot.plugins.privmsg(new_msg)
152       else
153         m.reply(_("Error handling the alias, The alias %{text} is not defined or has beeen removed. I will stop responding to it after rescan,") %
154                 {:text => text})
155       end
156     else
157       super(name, *args, &block)
158     end
159   end
160
161   def help(plugin, topic='')
162     case topic
163     when ''
164       if plugin == 'alias' # FIXME find out plugin name programmatically
165         _('Create and use aliases for commands. Topics: create, commands')
166       else
167         # show definition of all aliases whose first word is the parameter of the help
168         # command
169         @aliases.keys.select {|a| a[/\A(\w+)/, 1] == plugin}.map do |a|
170           "#{a} => #{@aliases[a]}"
171         end.join ' | '
172       end
173     when 'create'
174       _('"alias <text> => <command>" => add text as an alias of command. Text can contain placeholders marked with : or * for :words and *multiword arguments. The command can contain placeholders enclosed with < > which will be substituded with argument values. For example: alias googlerbot *terms => google site:linuxbrit.co.uk/rbot/ <terms>')
175     when 'commands'
176       _('alias list => list defined aliases | alias whatis <alias> => show definition of the alias | alias remove <alias> => remove defined alias | see the "create" topic about adding aliases')
177     end
178   end
179 end
180
181 plugin = AliasPlugin.new
182 plugin.default_auth('edit', false)
183 plugin.default_auth('run', true)
184 plugin.default_auth('list', true)
185
186 plugin.map 'alias list',
187            :action => :cmd_list,
188            :auth_path => 'view'
189 plugin.map 'alias whatis *text',
190            :action => :cmd_whatis,
191            :auth_path => 'view'
192 plugin.map 'alias remove *text',
193            :action => :cmd_remove,
194            :auth_path => 'edit'
195 plugin.map 'alias rm *text',
196            :action => :cmd_remove,
197            :auth_path => 'edit'
198 plugin.map 'alias *text => *command',
199            :action => :cmd_add,
200            :auth_path => 'edit'
201
202
203