source: main/trunk/greenstone2/perllib/cgiactions/baseaction.pm@ 27374

Last change on this file since 27374 was 27366, checked in by ak19, 11 years ago
  1. Handling quotes and colons in user comments: since these are sent and retrieved from metadata-server.pl as JSON strings, the quotes and colons in user-added meta needs to be protected since JSON uses these characters for packaging up data. 2. Cosmetic changes to baseaction: clarified some comments.
File size: 17.8 KB
Line 
1###########################################################################
2#
3# baseaction.pm --
4# A component of the Greenstone digital library software
5# from the New Zealand Digital Library Project at the
6# University of Waikato, New Zealand.
7#
8# Copyright (C) 2009 New Zealand Digital Library Project
9#
10# This program is free software; you can redistr te it and/or modify
11# it under the terms of the GNU General Public License as published by
12# the Free Software Foundation; either version 2 of the License, or
13# (at your option) any later version.
14#
15# This program is distributed in the hope that it will be useful,
16# but WITHOUT ANY WARRANTY; without even the implied warranty of
17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18# GNU General Public License for more details.
19#
20# You should have received a copy of the GNU General Public License
21# along with this program; if not, write to the Free Software
22# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23#
24###########################################################################
25
26
27package baseaction;
28
29use strict;
30use util;
31use inexport;
32
33# for time conversion and formatting functions
34use Time::Local;
35use POSIX;
36
37our $authentication_enabled = 1; # debugging flag (can debug without authentication when set to 0)
38our $mail_enabled = 0;
39
40
41# change this to get these values from a config file
42my $mail_to_address = "user\@server"; # Set this appropriately
43my $mail_from_address = "user\@server"; # Set this appropriately
44my $mail_smtp_server = "smtp.server"; # Set this appropriately
45
46
47
48# Required CGI arguments: "a" for action
49# "c" for collection
50# Optional CGI arguemnts: "ts" for timestamp (auto generated is missing)
51# "site" (used by Greenstone3)
52
53# allow "un" for username to be optional for now
54
55sub new
56{
57 my $class = shift (@_);
58 my ($action_table,$gsdl_cgi,$iis6_mode) = @_;
59
60 my $self = { 'gsdl_cgi' => $gsdl_cgi,
61 'iis6_mode' => $iis6_mode,
62 'gsdlhome' => $ENV{'GSDLHOME'} };
63
64 # Retrieve the (required) command CGI argument
65 my $action = $gsdl_cgi->clean_param("a");
66
67 if (!defined $action) {
68 my $err_mess = "No action (a=...) specified.\n";
69 $err_mess .= "\nPossible actions are:\n";
70
71 $err_mess .= " check-installation\n\n";
72
73 foreach my $a (sort keys %$action_table) {
74 $err_mess .= " $a:\n";
75 $err_mess .= " Compulsory args: ";
76 my @comp_args = ("c");
77 push(@comp_args,"un") if ($authentication_enabled);
78 push(@comp_args,@{$action_table->{$a}->{'compulsory-args'}});
79 $err_mess .= join(", ", @comp_args);
80
81 $err_mess .= "\n";
82
83 my @opt_args = ();
84 push(@opt_args,"un") if (!$authentication_enabled);
85 push(@opt_args,@{$action_table->{$a}->{'optional-args'}});
86
87 if (scalar(@opt_args)>0) {
88
89 $err_mess .= " Optional args : ";
90 $err_mess .= join(", ", @opt_args);
91 $err_mess .= "\n";
92 }
93
94 my @help_examples = ();
95 if(defined $action_table->{$a}->{'help-string'}) {
96 push(@help_examples, @{$action_table->{$a}->{'help-string'}});
97 }
98 if (scalar(@help_examples)>0) {
99
100 if (scalar(@help_examples)>1) {
101 $err_mess .= " Example(s) :\n";
102 } else {
103 $err_mess .= " Example :\n";
104 }
105 $err_mess .= join(", \n\n", @help_examples);
106 $err_mess .= "\n\nTo be strictly CGI-compliant special chars like double-quotes,&,?,<,> must be URL encoded.\n";
107 }
108
109 $err_mess .= "\n";
110 }
111
112 $gsdl_cgi->generate_message($err_mess);
113 exit(-1);
114
115 }
116 $gsdl_cgi->delete("a");
117
118 $self = bless $self, $class;
119
120 # The check-installation command has no arguments
121 if ($action eq "check-installation") {
122 $self->check_installation($gsdl_cgi,$iis6_mode);
123 exit 0;
124 }
125
126
127 if (!defined $action_table->{$action}) {
128 my $valid_actions = join(", ", keys %$action_table);
129
130 my $err_mess = "Unrecognised action (a=$action) specified.\n";
131 $err_mess .= "Valid actions are: $valid_actions\n";
132
133 $gsdl_cgi->generate_error($err_mess);
134 }
135
136
137 my $collect = $gsdl_cgi->clean_param("c");
138 if ((!defined $collect) || ($collect =~ m/^\s*$/)) {
139 $gsdl_cgi->generate_error("No collection specified.");
140 }
141 $gsdl_cgi->delete("c");
142
143 # allow un to be optional for now
144 my $username = $gsdl_cgi->clean_param("un");
145
146
147 # Get then remove the ts (timestamp) argument (since this can mess up
148 # other scripts)
149 my $timestamp = $gsdl_cgi->clean_param("ts");
150 if ((!defined $timestamp) || ($timestamp =~ m/^\s*$/)) {
151 # Fall back to using the Perl time() function to generate a timestamp
152 $timestamp = time();
153 }
154 $gsdl_cgi->delete("ts");
155
156 my $site = undef;
157 if($gsdl_cgi->greenstone_version() != 2) {
158 # all GS versions after 2 may define site
159 $site = $gsdl_cgi->clean_param("site");
160 if (!defined $site) {
161 $gsdl_cgi->generate_error("No site specified.");
162 }
163 $gsdl_cgi->delete("site");
164 }
165
166
167 $self->{'action'} = $action;
168 $self->{'collect'} = $collect;
169 $self->{'username'} = $username;
170 $self->{'timestamp'} = $timestamp;
171 $self->{'site'} = $site;
172
173 # Locate and store compulsory arguments
174 my $comp_args = $action_table->{$action}->{'compulsory-args'};
175 foreach my $ca (@$comp_args) {
176 if (!defined $gsdl_cgi->param($ca)) {
177 $gsdl_cgi->generate_error("Compulsory argument '$ca' missing");
178 }
179 else {
180 $self->{$ca} = $gsdl_cgi->clean_param($ca);
181 $gsdl_cgi->delete($ca);
182 }
183 }
184
185 # Locate and store optional args if present
186 my $opt_args = $action_table->{$action}->{'optional-args'};
187 foreach my $oa (@$opt_args) {
188 if (defined $gsdl_cgi->param($oa)) {
189 $self->{$oa} = $gsdl_cgi->clean_param($oa);
190 $gsdl_cgi->delete($oa);
191 }
192 }
193
194
195
196 # Retrieve infodb-type
197 if (defined $collect) {
198
199 my $opt_site = $self->{'site'} || "";
200
201 my $inexport = newCGI inexport(ref $self,$collect,$gsdl_cgi,$opt_site);
202 my ($config_filename,$collect_cfg) = $inexport->read_collection_cfg($collect);
203 $self->{'infodbtype'} = $collect_cfg->{'infodbtype'};
204
205 }
206
207
208 return $self;
209}
210
211
212sub do_action
213{
214 my $self = shift @_;
215 my $action = $self->{'action'};
216
217 $action =~ s/-/_/g;
218
219
220 $self->$action();
221
222}
223
224
225sub authenticate_user
226{
227 my $self = shift @_;
228 my $username = shift(@_);
229 my $collection = shift(@_);
230
231 my $keydecay = 1800; # 30 mins same as in runtime-src/recpt/authentication.cpp
232
233 my $gsdl_cgi = $self->{'gsdl_cgi'};
234
235 # Remove the pw argument (since this can mess up other scripts)
236 my $user_password = $gsdl_cgi->clean_param("pw");
237 my $user_key = $gsdl_cgi->clean_param("ky");
238
239 $gsdl_cgi->delete("pw");
240 $gsdl_cgi->delete("ky");
241
242 if ((!defined $user_password || $user_password =~ m/^\s*$/) && (!defined $user_key || $user_key =~ m/^\s*$/)) {
243 $gsdl_cgi->generate_error("Authentication failed: no password or key specified.");
244 }
245
246 my $gsdlhome = $ENV{'GSDLHOME'};
247 my $etc_directory = &util::filename_cat($gsdlhome, "etc");
248 my $users_db_file_path = &util::filename_cat($etc_directory, "users.gdb");
249
250 # Use dbutil to get the user accounts information
251 # infodbtype can be different for different collections, but the userDB and keyDB are gdbm
252
253 my $user_rec = &dbutil::read_infodb_entry("gdbm", $users_db_file_path, $username);
254 # Check username
255 if (!defined $user_rec) {
256 $gsdl_cgi->generate_error("Authentication failed: no account for user '$username'.");
257 }
258
259 # Check password
260 if(defined $user_password) {
261 my $valid_user_password = $user_rec->{"password"}->[0];
262 if ($user_password ne $valid_user_password) {
263 $gsdl_cgi->generate_error("Authentication failed: incorrect password.");
264 }
265 }
266 else { # check $user_key #if(!defined $user_password && defined $user_key) {
267
268 # check to see if there is a key for this particular user in the database that hasn't decayed.
269 # if the key validates, refresh the key again by setting its timestamp to the present time.
270
271 # Use dbutil to get the key accounts information
272 my $key_db_file_path = &util::filename_cat($etc_directory, "key.gdb");
273 my $key_rec = &dbutil::read_infodb_entry("gdbm", $key_db_file_path, $user_key);
274
275 if (!defined $key_rec) {
276
277 #$gsdl_cgi->generate_error("Authentication failed: invalid key $user_key. Does not exist.");
278 $gsdl_cgi->generate_error("Authentication failed: invalid key. No entry for the given key.");
279 }
280 else {
281 my $valid_username = $key_rec->{"user"}->[0];
282 if ($username ne $valid_username) {
283 $gsdl_cgi->generate_error("Authentication failed: key does not belong to user.");
284 }
285
286 # http://stackoverflow.com/questions/12644322/how-to-write-the-current-timestamp-in-a-file-perl
287 # http://stackoverflow.com/questions/2149532/how-can-i-format-a-timestamp-in-perl
288 # http://stackoverflow.com/questions/7726514/how-to-convert-text-date-to-timestamp
289
290 my $current_timestamp = time; #localtime(time);
291
292 my $keycreation_time = $key_rec->{"time"}->[0]; # of the form: 2013/05/06 14:39:23
293 if ($keycreation_time !~ m/^\s*$/) { # not empty
294
295 my ($year,$mon,$mday,$hour,$min,$sec) = split(/[\s\/:]+/, $keycreation_time); # split by space, /, :
296 # (also ensures whitespace surrounding keycreateion_time is trimmed)
297 my $key_timestamp = timelocal($sec,$min,$hour,$mday,$mon-1,$year);
298
299 if(($current_timestamp - $key_timestamp) > $keydecay) {
300 $gsdl_cgi->generate_error("Authentication failed: key has expired.");
301 } else {
302 # succeeded, update the key's time in the database
303
304 # beware http://community.activestate.com/forum/posixstrftime-problem-e-numeric-day-month
305 my $current_time = strftime("%Y/%m/%d %H:%M:%S", localtime($current_timestamp)); # POSIX
306
307 # infodbtype can be different for different collections, but the key DB is gdbm
308 my $key_rec = &dbutil::read_infodb_entry("gdbm", $key_db_file_path, $user_key);
309 $key_rec->{"time"}->[0] = $current_time;
310 my $status = &dbutil::set_infodb_entry("gdbm", $key_db_file_path, $user_key, $key_rec);
311
312 if ($status != 0) {
313 $gsdl_cgi->generate_error("Error updating authentication key.");
314 }
315 }
316 } else {
317 $gsdl_cgi->generate_error("Authentication failed: Invalid key entry. No time stored for key.");
318 }
319 }
320 }
321
322 # The following code which tests whether the user is in the required group
323 # seems to have been copied over from gliserver.pl.
324 # But when user comments are added through the set-metadata functions for metadata-server.pl
325 # (which is the first feature for which baseaction::authenticate_user() is actually used)
326 # the user doesn't need to be a specific collection's editor in order to add comments to that collection.
327 # So we no longer check the user is in the group here.
328# $self->check_group($collection, $username, $user_data);
329}
330
331
332sub check_group
333{
334 my $self = shift @_;
335 my $collection = shift @_;
336 my $username = shift @_;
337 my $user_data = shift @_;
338
339
340 my $gsdl_cgi = $self->{'gsdl_cgi'};
341
342 # Check group
343 my ($user_groups) = ($user_data =~ /\<groups\>(.*)/);
344 if ($collection eq "") {
345 # If we're not editing a collection then the user doesn't need to be in a particular group
346 return $user_groups; # Authentication successful
347 }
348 foreach my $user_group (split(/\,/, $user_groups)) {
349 # Does this user have access to all collections?
350 if ($user_group eq "all-collections-editor") {
351 return $user_groups; # Authentication successful
352 }
353 # Does this user have access to personal collections, and is this one?
354 if ($user_group eq "personal-collections-editor" && $collection =~ /^$username\-/) {
355 return $user_groups; # Authentication successful
356 }
357 # Does this user have access to this collection
358 if ($user_group eq "$collection-collection-editor") {
359 return $user_groups; # Authentication successful
360 }
361 }
362
363 $gsdl_cgi->generate_error("Authentication failed: user is not in the required group.");
364}
365
366sub check_installation
367{
368 my $self = shift @_;
369 my $iis6_mode = shift(@_);
370
371 my $gsdl_cgi = $self->{'gsdl_cgi'};
372
373 my $installation_ok = 1;
374 my $installation_status = "";
375
376 print STDOUT "Content-type:text/plain\n\n";
377
378 # Check that Java is installed and accessible
379 my $java = $gsdl_cgi->get_java_path();
380 my $java_command = "$java -version 2>&1";
381
382 # IIS 6: redirecting output from STDERR to STDOUT just doesn't work, so we have to let it go
383 # directly out to the page
384 if ($iis6_mode)
385 {
386 $java_command = "java -version";
387 }
388
389 my $java_output = `$java_command`;
390 my $java_status = $?;
391 if ($java_status < 0) {
392 # The Java command failed
393 $installation_status = "Java failed -- do you have the Java run-time installed?\n" . $gsdl_cgi->check_java_home() . "\n";
394 $installation_ok = 0;
395 }
396 else {
397 $installation_status = "Java found: $java_output";
398 }
399
400 # Show the values of some important environment variables
401 $installation_status .= "\n";
402 $installation_status .= "GSDLHOME: " . $ENV{'GSDLHOME'} . "\n";
403 $installation_status .= "GSDLOS: " . $ENV{'GSDLOS'} . "\n";
404 $installation_status .= "PATH: " . $ENV{'PATH'} . "\n";
405
406 if ($installation_ok) {
407 print STDOUT $installation_status . "\nInstallation OK!";
408 }
409 else {
410 print STDOUT $installation_status;
411 }
412}
413
414sub lock_collection
415{
416 my $self = shift @_;
417 my $username = shift(@_);
418 my $collection = shift(@_);
419
420 my $gsdl_cgi = $self->{'gsdl_cgi'};
421
422 my $steal_lock = $gsdl_cgi->clean_param("steal_lock");
423 $gsdl_cgi->delete("steal_lock");
424
425 if (!defined $username) {
426 # don't have any user details for current user to compare with
427 # even if there is a lock file
428 # For now, allow the current user access. Might want to
429 # revisit this in the future.
430 return;
431 }
432
433 #my $gsdlhome = $ENV{'GSDLHOME'};
434 #my $collection_directory = &util::filename_cat($gsdlhome, "collect", $collection);
435 my $site = $self->{'site'};
436 my $collection_directory = $gsdl_cgi->get_collection_dir($site, $collection);
437 $gsdl_cgi->checked_chdir($collection_directory);
438
439 # Check if a lock file already exists for this collection
440 my $lock_file_name = "gli.lck";
441 if (-e $lock_file_name) {
442 # A lock file already exists... check if it's ours
443 my $lock_file_content = "";
444 open(LOCK_FILE, "<$lock_file_name");
445 while (<LOCK_FILE>) {
446 $lock_file_content .= $_;
447 }
448 close(LOCK_FILE);
449
450 # Pick out the owner of the lock file
451 $lock_file_content =~ /\<User\>(.*?)\<\/User\>/;
452 my $lock_file_owner = $1;
453
454 # The lock file is ours, so there is no problem
455 if ($lock_file_owner eq $username) {
456 return;
457 }
458
459 # The lock file is not ours, so throw an error unless "steal_lock" is set
460 unless (defined $steal_lock) {
461 $gsdl_cgi->generate_error("Collection is locked by: $lock_file_owner");
462 }
463 }
464
465 my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime(time);
466 my $current_time = sprintf("%02d/%02d/%d %02d:%02d:%02d", $mday, $mon + 1, $year + 1900, $hour, $min, $sec);
467
468 # Create a lock file for us (in the same format as the GLI) and we're done
469 open(LOCK_FILE, ">$lock_file_name");
470 print LOCK_FILE "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
471 print LOCK_FILE "<LockFile>\n";
472 print LOCK_FILE " <User>" . $username . "</User>\n";
473 print LOCK_FILE " <Machine>(Remote)</Machine>\n";
474 print LOCK_FILE " <Date>" . $current_time . "</Date>\n";
475 print LOCK_FILE "</LockFile>\n";
476 close(LOCK_FILE);
477}
478
479
480# Release the gli.lck otherwise no one else will be able to use the collection again.
481sub unlock_collection
482{
483 my $self = shift @_;
484 my ($username, $collection) = @_;
485 my $gsdl_cgi = $self->{'gsdl_cgi'};
486
487 # Obtain the path to the collection GLI lock file
488 my $lock_file_path = &util::filename_cat($ENV{'GSDLHOME'}, "collect", $collection, "gli.lck");
489
490 # If the lock file does exist, check if it is ours
491 if (-e $lock_file_path)
492 {
493 my $lock_file_content = "";
494 open(LOCK_FILE, "<$lock_file_path");
495 while (<LOCK_FILE>) {
496 $lock_file_content .= $_;
497 }
498 close(LOCK_FILE);
499
500 # Pick out the owner of the lock file
501 $lock_file_content =~ /\<User\>(.*?)\<\/User\>/;
502 my $lock_file_owner = $1;
503
504 # If we are the owner of this lock, we have the right to delete it
505 if ($lock_file_owner eq $username) {
506 unlink($lock_file_path );
507 }
508 else {
509 $gsdl_cgi->generate_error("Collection is locked by: $lock_file_owner. Cannot be unlocked");
510 }
511 }
512}
513
514
515sub send_mail
516{
517 my $self = shift @_;
518
519 my ($mail_subject,$mail_content) = @_;
520
521 my $gsdl_cgi = $self->{'gsdl_cgi'};
522
523 my $sendmail_command = "\"".&util::get_perl_exec()."\" -S sendmail.pl";
524 $sendmail_command .= " -to \"" . $mail_to_address . "\"";
525 $sendmail_command .= " -from \"" . $mail_from_address . "\"";
526 $sendmail_command .= " -smtp \"" . $mail_smtp_server . "\"";
527 $sendmail_command .= " -subject \"" . $mail_subject . "\"";
528
529 if (!open(POUT, "| $sendmail_command")) {
530 $gsdl_cgi->generate_error("Unable to execute command: $sendmail_command");
531 }
532 print POUT $mail_content . "\n";
533 close(POUT);
534}
535
536
537sub run_script
538{
539 my $self = shift @_;
540
541 my ($collect, $site, $script) = @_;
542
543 my $gsdl_cgi = $self->{'gsdl_cgi'};
544
545 my $perl_args = $collect;
546
547 my $collect_dir = $gsdl_cgi->get_collection_dir($site);
548 $perl_args = "-collectdir \"$collect_dir\" " . $perl_args;
549
550 my $perl_command = "\"".&util::get_perl_exec()."\" -S $script $perl_args";
551
552
553 # IIS 6: redirecting output from STDERR to STDOUT just doesn't work, so
554 # we have to let it go directly out to the page
555
556 if (!$self->{'iis6_mode'})
557 {
558 $perl_command .= " 2>&1";
559 }
560
561 if (!open(PIN, "$perl_command |")) {
562 $gsdl_cgi->generate_error("Unable to execute command: $perl_command");
563 }
564
565 print STDOUT "Content-type:text/plain\n\n";
566 print "$perl_command \n";
567
568 while (defined (my $perl_output_line = <PIN>)) {
569 print STDOUT $perl_output_line;
570 }
571 close(PIN);
572
573 my $perl_status = $?;
574 if ($perl_status > 0) {
575 $gsdl_cgi->generate_error("Perl failed: $perl_command\n--\nExit status: " . ($perl_status / 256));
576 }
577}
578
5791;
Note: See TracBrowser for help on using the repository browser.