]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - data/rbot/plugins/alias.rb
* alias.rb: fixed precedence error which caused list of aliases be reset on rescan
[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.each_pair do |a, c|
56       begin
57         add_alias(a, c)
58       rescue AliasDefinitionError
59         warning _("Invalid alias entry %{alias} : %{command} in %{filename}: %{reason}") %
60                 {:alias => a, :command => c, :filename => @data_file, :reason => $1}
61       end
62     end 
63   end 
64
65   def save 
66     FileUtils.mkdir_p(@data_path)
67     Utils.safe_save(@data_file) {|f| f.write @aliases.to_yaml}
68   end
69
70   def cmd_add(m, params)
71     begin
72       add_alias(params[:text].to_s, params[:command].to_s)
73       m.okay
74     rescue AliasDefinitionError
75       m.reply _('The definition you provided is invalid: %{reason}') % {:reason => $!}
76     end
77   end
78
79   def cmd_remove(m, params)
80     text = params[:text].to_s
81     if @aliases.has_key?(text)
82       @aliases.delete(text)
83       # TODO when rbot supports it, remove the mapping corresponding to the alias
84       m.okay
85     else
86       m.reply _('No such alias is defined')
87     end
88   end
89
90   def cmd_list(m, params)
91     if @aliases.empty?
92       m.reply _('No aliases defined')
93     else
94       m.reply @aliases.map {|a, c| "#{a} => #{c}"}.join(' | ')
95     end
96   end
97
98   def cmd_whatis(m, params)
99     text = params[:text].to_s
100     if @aliases.has_key?(text)
101       m.reply _('Alias of %{command}') % {:command => @aliases[text]}
102     else
103       m.reply _('No such alias is defined')
104     end
105   end
106
107   def add_alias(text, command)
108     # each alias is implemented by adding a message map, whose handler creates a message
109     # containing the aliased command
110
111     command.grep(/<(\w+)>/) {$1}.to_set ==
112       text.grep(/(?:^|\s)[:*](\w+)(?:\s|$)/) {$1}.to_set or
113       raise AliasDefinitionError.new(_('The arguments in alias must match the substitutions in command, and vice versa'))
114     
115     @aliases[text] = command
116     map text, :action => :"alias_handle<#{text}>", :auth_path => 'run'
117   end
118
119   def respond_to?(name, include_private=false)
120     name.to_s =~ /\Aalias_handle<.+>\Z/ || super
121   end
122
123   def method_missing(name, *args, &block)
124     if name.to_s =~ /\Aalias_handle<(.+)>\Z/
125       m, params = args
126       # messages created by alias handler will have a depth method, which returns the 
127       # depth of "recursion" caused by the message
128       current_depth = if m.respond_to?(:depth) then m.depth else 0 end
129       if current_depth > MAX_RECURSION_DEPTH
130         m.reply _('The alias seems to have caused infinite recursion. Please examine your alias definitions')
131         return
132       end
133
134       command = @aliases[$1]
135       if command
136         # create a fake message containing the intended command
137         new_msg = PrivMessage.new(@bot, m.server, m.server.user(m.source), m.target,
138                                     command.gsub(/<(\w+)>/) {|arg| params[:"#{$1}"].to_s})
139         # tag incremented depth on the message
140         class << new_msg
141           self
142         end.send(:define_method, :depth) {current_depth + 1}
143
144         @bot.plugins.privmsg(new_msg)
145       else
146         m.reply _("Error handling the alias, the command is not defined")
147       end
148     else
149       super(name, *args, &block)
150     end
151   end
152
153   def help(plugin, topic='')
154     case topic
155     when ''
156       _('Create and use aliases for commands. Topics: create, commands')
157     when 'create'
158       _('"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>')
159     when 'commands'
160       _('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')
161     end
162   end
163 end
164
165 plugin = AliasPlugin.new
166 plugin.default_auth('edit', false)
167 plugin.default_auth('run', true)
168 plugin.default_auth('list', true)
169
170 plugin.map 'alias list',
171            :action => :cmd_list,
172            :auth_path => 'view'
173 plugin.map 'alias whatis *text',
174            :action => :cmd_whatis,
175            :auth_path => 'view'
176 plugin.map 'alias remove *text',
177            :action => :cmd_remove,
178            :auth_path => 'edit'
179 plugin.map 'alias rm *text',
180            :action => :cmd_remove,
181            :auth_path => 'edit'
182 plugin.map 'alias *text => *command',
183            :action => :cmd_add,
184            :auth_path => 'edit'
185
186
187