merging rt \3.8.8 to HEAD
[freeside.git] / rt / bin / rt-crontool
1 #!/usr/bin/perl
2 # BEGIN BPS TAGGED BLOCK {{{
3
4 # COPYRIGHT:
5
6 # This software is Copyright (c) 1996-2009 Best Practical Solutions, LLC
7 #                                          <jesse@bestpractical.com>
8
9 # (Except where explicitly superseded by other copyright notices)
10
11
12 # LICENSE:
13
14 # This work is made available to you under the terms of Version 2 of
15 # the GNU General Public License. A copy of that license should have
16 # been provided with this software, but in any event can be snarfed
17 # from www.gnu.org.
18
19 # This work is distributed in the hope that it will be useful, but
20 # WITHOUT ANY WARRANTY; without even the implied warranty of
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22 # General Public License for more details.
23
24 # You should have received a copy of the GNU General Public License
25 # along with this program; if not, write to the Free Software
26 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
27 # 02110-1301 or visit their web page on the internet at
28 # http://www.gnu.org/copyleft/gpl.html.
29
30
31 # CONTRIBUTION SUBMISSION POLICY:
32
33 # (The following paragraph is not intended to limit the rights granted
34 # to you to modify and distribute this software under the terms of
35 # the GNU General Public License and is only of importance to you if
36 # you choose to contribute your changes and enhancements to the
37 # community by submitting them to Best Practical Solutions, LLC.)
38
39 # By intentionally submitting any modifications, corrections or
40 # derivatives to this work, or any other work intended for use with
41 # Request Tracker, to Best Practical Solutions, LLC, you confirm that
42 # you are the copyright holder for those contributions and you grant
43 # Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
44 # royalty-free, perpetual, license to use, copy, create derivative
45 # works based on those contributions, and sublicense and distribute
46 # those contributions and any derivatives thereof.
47
48 # END BPS TAGGED BLOCK }}}
49 use strict;
50 use Carp;
51
52 # fix lib paths, some may be relative
53 BEGIN {
54     require File::Spec;
55     my @libs = ("lib", "local/lib");
56     my $bin_path;
57
58     for my $lib (@libs) {
59         unless ( File::Spec->file_name_is_absolute($lib) ) {
60             unless ($bin_path) {
61                 if ( File::Spec->file_name_is_absolute(__FILE__) ) {
62                     $bin_path = ( File::Spec->splitpath(__FILE__) )[1];
63                 }
64                 else {
65                     require FindBin;
66                     no warnings "once";
67                     $bin_path = $FindBin::Bin;
68                 }
69             }
70             $lib = File::Spec->catfile( $bin_path, File::Spec->updir, $lib );
71         }
72         unshift @INC, $lib;
73     }
74
75 }
76
77 use RT;
78
79 use Getopt::Long;
80
81 use RT::Interface::CLI qw(CleanEnv GetCurrentUser GetMessageContent loc);
82 use RT::Tickets;
83 use RT::Template;
84
85 #Clean out all the nasties from the environment
86 CleanEnv();
87
88 my ( $search, $condition, $action, $search_arg, $condition_arg, $action_arg,
89      $template, $template_id, $transaction, $transaction_type, $help, $log, $verbose );
90 GetOptions(
91     "search=s"           => \$search,
92     "search-arg=s"       => \$search_arg,
93     "condition=s"        => \$condition,
94     "condition-arg=s"    => \$condition_arg,
95     "action-arg=s"       => \$action_arg,
96     "action=s"           => \$action,
97     "template=s"         => \$template,
98     "template-id=s"      => \$template_id,
99     "transaction=s"      => \$transaction,
100     "transaction-type=s" => \$transaction_type,
101     "log=s"              => \$log,
102     "verbose|v"          => \$verbose,
103     "help"               => \$help,
104 );
105
106 # Load the config file
107 RT::LoadConfig();
108
109 # adjust logging to the screen according to options
110 RT->Config->Set( LogToScreen => $log ) if $log;
111
112 #Connect to the database and get RT::SystemUser and RT::Nobody loaded
113 RT::Init();
114
115 #Get the current user all loaded
116 my $CurrentUser = GetCurrentUser();
117
118 # show help even if there is no current user
119 help() if $help;
120
121 unless ( $CurrentUser->Id ) {
122     print loc("No RT user found. Please consult your RT administrator.\n");
123     exit(1);
124 }
125
126 help() unless $search && $action;
127
128 $transaction = lc( $transaction||'' );
129 if ( $transaction && $transaction !~ /^(first|all|last)$/i ) {
130     print STDERR loc("--transaction argument could be only 'first', 'last' or 'all'");
131     exit 1;
132 }
133
134 if ( $template && $template_id ) {
135     print STDERR loc("--template-id is deprecated argument and can not be used with --template");
136     exit 1;
137 }
138 elsif ( $template_id ) {
139 # don't warn
140     $template = $template_id;
141 }
142
143 # We _must_ have a search object
144 load_module($search);
145 load_module($action)    if ($action);
146 load_module($condition) if ($condition);
147
148 my $void_scrip = RT::Scrip->new( $CurrentUser );
149 my $void_scrip_action = RT::ScripAction->new( $CurrentUser );
150
151 #At the appointed time:
152
153 #find a bunch of tickets
154 my $tickets = RT::Tickets->new($CurrentUser);
155 my $search  = $search->new(
156     TicketsObj  => $tickets,
157     Argument    => $search_arg,
158     CurrentUser => $CurrentUser
159 );
160
161 $search->Prepare();
162
163 # TicketsFound is an RT::Tickets object
164 my $tickets = $search->TicketsObj;
165
166 #for each ticket we've found
167 while ( my $ticket = $tickets->Next() ) {
168     print $ticket->Id() . ": " if ($verbose);
169
170     my $template_obj = get_template( $ticket );
171
172     if ( $transaction ) {
173         my $txns = get_transactions($ticket);
174         my $found = 0;
175         while ( my $txn = $txns->Next ) {
176             print loc("Using transaction #[_1]...", $txn->id)
177                 if $verbose;
178             process($ticket, $txn, $template_obj);
179             $found = 1;
180         }
181         print loc("Couldn't find suitable transaction, skipping")
182             if $verbose && !$found;
183     } else {
184         print loc("Processing without transaction, some conditions and actions may fail. Consider using --transaction argument")
185             if $verbose;
186
187         process($ticket, undef, $template_obj);
188     }
189 }
190
191 sub process {
192     my $ticket = shift;
193     my $transaction = shift;
194     my $template_obj = shift;
195
196     # perform some more advanced check
197     if ($condition) {
198         my $condition_obj = $condition->new(
199             TransactionObj => $transaction,
200             TicketObj      => $ticket,
201             ScripObj       => $void_scrip,
202             TemplateObj    => $template_obj,
203             Argument       => $condition_arg,
204             CurrentUser    => $CurrentUser,
205         );
206
207         # if the condition doesn't apply, get out of here
208
209         return unless $condition_obj->IsApplicable;
210         print loc("Condition matches...") if $verbose;
211     }
212
213     #prepare our action
214     my $action_obj = $action->new(
215         TicketObj      => $ticket,
216         TransactionObj => $transaction,
217         TemplateObj    => $template_obj,
218         Argument       => $action_arg,
219         ScripObj       => $void_scrip,
220         ScripActionObj => $void_scrip_action,
221         CurrentUser    => $CurrentUser,
222     );
223
224     #if our preparation, move onto the next ticket
225     return unless $action_obj->Prepare;
226     print loc("Action prepared...") if $verbose;
227
228     #commit our action.
229     return unless $action_obj->Commit;
230     print loc("Action committed.\n") if $verbose;
231 }
232
233 =head2 get_transactions
234
235 Takes ticket and returns L<RT::Transactions> object with transactions
236 of the ticket according to command line arguments C<--transaction>
237 and <--transaction-type>.
238
239 =cut
240
241 sub get_transactions {
242     my $ticket = shift;
243     my $txns = $ticket->Transactions;
244     my $order = $transaction eq 'last'? 'DESC': 'ASC';
245     $txns->OrderByCols(
246         { FIELD => 'Created', ORDER => $order },
247         { FIELD => 'id', ORDER => $order },
248     );
249     if ( $transaction_type ) {
250         $transaction_type =~ s/^\s+//;
251         $transaction_type =~ s/\s+$//;
252         foreach my $type ( split /\s*,\s*/, $transaction_type ) {
253             $txns->Limit( FIELD => 'Type', VALUE => $type, ENTRYAGGREGATOR => 'OR' );
254         }
255     }
256     $txns->RowsPerPage(1) unless $transaction eq 'all';
257     return $txns;
258 }
259
260 =head2 get_template
261
262 Takes a ticket and returns a template according to command line options.
263
264 =cut
265
266 { my $cache = undef;
267 sub get_template {
268     my $ticket = shift;
269     return undef unless $template;
270
271     unless ( $template =~ /\D/ ) {
272         # by id
273         return $cache if $cache;
274
275         my $cache = RT::Template->new( $RT::SystemUser );
276         $cache->Load( $template );
277         die "Failed to load template '$template'"
278             unless $cache->id;
279         return $cache;
280     }
281
282     my $queue = $ticket->Queue;
283     return $cache->{ $queue } if $cache->{ $queue };
284
285     my $res = RT::Template->new( $RT::SystemUser );
286     $res->LoadQueueTemplate( Queue => $queue, Name => $template );
287     unless ( $res->id ) {
288         $res->LoadGlobalTemplate( $template );
289         die "Failed to load template '$template', either for queue #$queue or global"
290             unless $res->id;
291     }
292     return $cache->{ $queue } = $res;
293 } }
294
295 # {{{ load_module 
296
297 =head2 load_module
298
299 Loads a perl module, dying nicely if it can't find it.
300
301 =cut
302
303 sub load_module {
304     my $modname = shift;
305     eval "require $modname";
306     if ($@) {
307         die loc( "Failed to load module [_1]. ([_2])", $modname, $@ );
308     }
309
310 }
311
312 # }}}
313
314 # {{{ loc 
315
316 =head2 loc LIST
317
318 Localize this string, with the current user's currentuser object
319
320 =cut
321
322 sub loc {
323     $CurrentUser->loc(@_);
324 }
325
326 # }}}
327
328 sub help {
329
330     print loc( "[_1] is a tool to act on tickets from an external scheduling tool, such as cron.", $0 )
331       . "\n";
332     print loc("It takes several arguments:") . "\n\n";
333
334     print "     "
335       . loc( "[_1] - Specify the search module you want to use", "--search" )
336       . "\n";
337     print "     "
338       . loc( "[_1] - An argument to pass to [_2]", "--search-arg", "--search" )
339       . "\n";
340
341     print "     "
342       . loc( "[_1] - Specify the condition module you want to use", "--condition" )
343       . "\n";
344     print "     "
345       . loc( "[_1] - An argument to pass to [_2]", "--condition-arg", "--condition" )
346       . "\n";
347     print "     "
348       . loc( "[_1] - Specify the action module you want to use", "--action" )
349       . "\n";
350     print "     "
351       . loc( "[_1] - An argument to pass to [_2]", "--action-arg", "--action" )
352       . "\n";
353     print "     "
354       . loc( "[_1] - Specify name or id of template(s) you want to use", "--template" )
355       . "\n";
356     print "     "
357       . loc( "[_1] - Specify if you want to use either 'first', 'last' or 'all' transactions", "--transaction" )
358       . "\n";
359     print "     "
360       . loc( "[_1] - Specify the comma separated list of transactions' types you want to use", "--transaction-type" )
361       . "\n";
362     print "     "
363       . loc( "[_1] - Adjust LogToScreen config option", "--log" ) . "\n";
364     print "     "
365       . loc( "[_1] - Output status updates to STDOUT", "--verbose" ) . "\n";
366     print "\n";
367     print "\n";
368     print loc("Security:")."\n";
369     print loc("This tool allows the user to run arbitrary perl modules from within RT.")." ". 
370         loc("If this tool were setgid, a hostile local user could use this tool to gain administrative access to RT.")." ".
371         loc("It is incredibly important that nonprivileged users not be allowed to run this tool."). " " . 
372         loc("It is suggested that you create a non-privileged unix user with the correct group membership and RT access to run this tool.")."\n";
373     print "\n";
374     print loc("Example:");
375     print "\n";
376     print " "
377       . loc( "The following command will find all active tickets in the queue 'general' and set their priority to 99 if they haven't been touched in 4 hours:"
378       )
379       . "\n\n";
380
381     print " bin/rt-crontool \\\n";
382     print "  --search RT::Search::ActiveTicketsInQueue  --search-arg general \\\n";
383     print "  --condition RT::Condition::UntouchedInHours --condition-arg 4 \\\n";
384     print "  --action RT::Action::SetPriority --action-arg 99 \\\n";
385     print "  --verbose\n";
386
387     print "\n";
388     print loc("Escalate tickets"). "\n";
389     print " bin/rt-crontool \\\n";
390     print "  --search RT::Search::ActiveTicketsInQueue  --search-arg general \\\n";
391     print "  --action RT::Action::EscalatePriority\n";
392  
393  
394  
395
396
397
398     exit(0);
399 }