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