source: main/trunk/greenstone2/perllib/util.pm@ 24291

Last change on this file since 24291 was 24291, checked in by sjm84, 13 years ago

More changes to do with the way PDF files are parsed

  • Property svn:keywords set to Author Date Id Revision
File size: 43.1 KB
Line 
1###########################################################################
2#
3# util.pm -- various useful utilities
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) 1999 New Zealand Digital Library Project
9#
10# This program is free software; you can redistribute 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
26package util;
27
28use strict;
29
30use Encode;
31use File::Copy;
32use File::Basename;
33
34# removes files (but not directories)
35sub rm {
36 my (@files) = @_;
37
38 my @filefiles = ();
39
40 # make sure the files we want to delete exist
41 # and are regular files
42 foreach my $file (@files) {
43 if (!-e $file) {
44 print STDERR "util::rm $file does not exist\n";
45 } elsif ((!-f $file) && (!-l $file)) {
46 print STDERR "util::rm $file is not a regular (or symbolic) file\n";
47 } else {
48 push (@filefiles, $file);
49 }
50 }
51
52 # remove the files
53 my $numremoved = unlink @filefiles;
54
55 # check to make sure all of them were removed
56 if ($numremoved != scalar(@filefiles)) {
57 print STDERR "util::rm Not all files were removed\n";
58 }
59}
60
61# removes files (but not directories) - can rename this to the default
62# "rm" subroutine when debugging the deletion of individual files.
63sub rm_debug {
64 my (@files) = @_;
65 my @filefiles = ();
66
67 # make sure the files we want to delete exist
68 # and are regular files
69 foreach my $file (@files) {
70 if (!-e $file) {
71 print STDERR "util::rm $file does not exist\n";
72 } elsif ((!-f $file) && (!-l $file)) {
73 print STDERR "util::rm $file is not a regular (or symbolic) file\n";
74 } else { # debug message
75 unlink($file) or warn "Could not delete file $file: $!\n";
76 }
77 }
78}
79
80
81# recursive removal
82sub filtered_rm_r {
83 my ($files,$file_accept_re,$file_reject_re) = @_;
84
85# my ($cpackage,$cfilename,$cline,$csubr,$chas_args,$cwantarray) = caller(2);
86# my ($lcfilename) = ($cfilename =~ m/([^\\\/]*)$/);
87# print STDERR "** Calling method (2): $lcfilename:$cline $cpackage->$csubr\n";
88
89 my @files_array = (ref $files eq "ARRAY") ? @$files : ($files);
90
91 # recursively remove the files
92 foreach my $file (@files_array) {
93 $file =~ s/[\/\\]+$//; # remove trailing slashes
94
95 if (!-e $file) {
96 print STDERR "util::filtered_rm_r $file does not exist\n";
97
98 } elsif ((-d $file) && (!-l $file)) { # don't recurse down symbolic link
99 # get the contents of this directory
100 if (!opendir (INDIR, $file)) {
101 print STDERR "util::filtered_rm_r could not open directory $file\n";
102 } else {
103 my @filedir = grep (!/^\.\.?$/, readdir (INDIR));
104 closedir (INDIR);
105
106 # remove all the files in this directory
107 map {$_="$file/$_";} @filedir;
108 &filtered_rm_r (\@filedir,$file_accept_re,$file_reject_re);
109
110 if (!defined $file_accept_re && !defined $file_reject_re) {
111 # remove this directory
112 if (!rmdir $file) {
113 print STDERR "util::filtered_rm_r couldn't remove directory $file\n";
114 }
115 }
116 }
117 } else {
118 next if (defined $file_reject_re && ($file =~ m/$file_reject_re/));
119
120 if ((!defined $file_accept_re) || ($file =~ m/$file_accept_re/)) {
121 # remove this file
122 &rm ($file);
123 }
124 }
125 }
126}
127
128
129# recursive removal
130sub rm_r {
131 my (@files) = @_;
132
133 # use the more general (but reterospectively written function
134 # filtered_rm_r function()
135
136 filtered_rm_r(\@files,undef,undef); # no accept or reject expressions
137}
138
139
140
141
142# moves a file or a group of files
143sub mv {
144 my $dest = pop (@_);
145 my (@srcfiles) = @_;
146
147 # remove trailing slashes from source and destination files
148 $dest =~ s/[\\\/]+$//;
149 map {$_ =~ s/[\\\/]+$//;} @srcfiles;
150
151 # a few sanity checks
152 if (scalar (@srcfiles) == 0) {
153 print STDERR "util::mv no destination directory given\n";
154 return;
155 } elsif ((scalar (@srcfiles) > 1) && (!-d $dest)) {
156 print STDERR "util::mv if multiple source files are given the ".
157 "destination must be a directory\n";
158 return;
159 }
160
161 # move the files
162 foreach my $file (@srcfiles) {
163 my $tempdest = $dest;
164 if (-d $tempdest) {
165 my ($filename) = $file =~ /([^\\\/]+)$/;
166 $tempdest .= "/$filename";
167 }
168 if (!-e $file) {
169 print STDERR "util::mv $file does not exist\n";
170 } else {
171 rename ($file, $tempdest);
172 }
173 }
174}
175
176
177# copies a file or a group of files
178sub cp {
179 my $dest = pop (@_);
180 my (@srcfiles) = @_;
181
182 # remove trailing slashes from source and destination files
183 $dest =~ s/[\\\/]+$//;
184 map {$_ =~ s/[\\\/]+$//;} @srcfiles;
185
186 # a few sanity checks
187 if (scalar (@srcfiles) == 0) {
188 print STDERR "util::cp no destination directory given\n";
189 return;
190 } elsif ((scalar (@srcfiles) > 1) && (!-d $dest)) {
191 print STDERR "util::cp if multiple source files are given the ".
192 "destination must be a directory\n";
193 return;
194 }
195
196 # copy the files
197 foreach my $file (@srcfiles) {
198 my $tempdest = $dest;
199 if (-d $tempdest) {
200 my ($filename) = $file =~ /([^\\\/]+)$/;
201 $tempdest .= "/$filename";
202 }
203 if (!-e $file) {
204 print STDERR "util::cp $file does not exist\n";
205 } elsif (!-f $file) {
206 print STDERR "util::cp $file is not a plain file\n";
207 } else {
208 &File::Copy::copy ($file, $tempdest);
209 }
210 }
211}
212
213
214
215# recursively copies a file or group of files
216# syntax: cp_r (sourcefiles, destination directory)
217# destination must be a directory - to copy one file to
218# another use cp instead
219sub cp_r {
220 my $dest = pop (@_);
221 my (@srcfiles) = @_;
222
223 # a few sanity checks
224 if (scalar (@srcfiles) == 0) {
225 print STDERR "util::cp_r no destination directory given\n";
226 return;
227 } elsif (-f $dest) {
228 print STDERR "util::cp_r destination must be a directory\n";
229 return;
230 }
231
232 # create destination directory if it doesn't exist already
233 if (! -d $dest) {
234 my $store_umask = umask(0002);
235 mkdir ($dest, 0777);
236 umask($store_umask);
237 }
238
239 # copy the files
240 foreach my $file (@srcfiles) {
241
242 if (!-e $file) {
243 print STDERR "util::cp_r $file does not exist\n";
244
245 } elsif (-d $file) {
246 # make the new directory
247 my ($filename) = $file =~ /([^\\\/]*)$/;
248 $dest = &util::filename_cat ($dest, $filename);
249 my $store_umask = umask(0002);
250 mkdir ($dest, 0777);
251 umask($store_umask);
252
253 # get the contents of this directory
254 if (!opendir (INDIR, $file)) {
255 print STDERR "util::cp_r could not open directory $file\n";
256 } else {
257 my @filedir = readdir (INDIR);
258 closedir (INDIR);
259 foreach my $f (@filedir) {
260 next if $f =~ /^\.\.?$/;
261 # copy all the files in this directory
262 my $ff = &util::filename_cat ($file, $f);
263 &cp_r ($ff, $dest);
264 }
265 }
266
267 } else {
268 &cp($file, $dest);
269 }
270 }
271}
272# recursively copies a file or group of files
273# syntax: cp_r (sourcefiles, destination directory)
274# destination must be a directory - to copy one file to
275# another use cp instead
276sub cp_r_nosvn {
277 my $dest = pop (@_);
278 my (@srcfiles) = @_;
279
280 # a few sanity checks
281 if (scalar (@srcfiles) == 0) {
282 print STDERR "util::cp_r no destination directory given\n";
283 return;
284 } elsif (-f $dest) {
285 print STDERR "util::cp_r destination must be a directory\n";
286 return;
287 }
288
289 # create destination directory if it doesn't exist already
290 if (! -d $dest) {
291 my $store_umask = umask(0002);
292 mkdir ($dest, 0777);
293 umask($store_umask);
294 }
295
296 # copy the files
297 foreach my $file (@srcfiles) {
298
299 if (!-e $file) {
300 print STDERR "util::cp_r $file does not exist\n";
301
302 } elsif (-d $file) {
303 # make the new directory
304 my ($filename) = $file =~ /([^\\\/]*)$/;
305 $dest = &util::filename_cat ($dest, $filename);
306 my $store_umask = umask(0002);
307 mkdir ($dest, 0777);
308 umask($store_umask);
309
310 # get the contents of this directory
311 if (!opendir (INDIR, $file)) {
312 print STDERR "util::cp_r could not open directory $file\n";
313 } else {
314 my @filedir = readdir (INDIR);
315 closedir (INDIR);
316 foreach my $f (@filedir) {
317 next if $f =~ /^\.\.?$/;
318 next if $f =~ /^\.svn$/;
319 # copy all the files in this directory
320 my $ff = &util::filename_cat ($file, $f);
321 &cp_r ($ff, $dest);
322 }
323 }
324
325 } else {
326 &cp($file, $dest);
327 }
328 }
329}
330
331# copies a directory and its contents, excluding subdirectories, into a new directory
332sub cp_r_toplevel {
333 my $dest = pop (@_);
334 my (@srcfiles) = @_;
335
336 # a few sanity checks
337 if (scalar (@srcfiles) == 0) {
338 print STDERR "util::cp_r no destination directory given\n";
339 return;
340 } elsif (-f $dest) {
341 print STDERR "util::cp_r destination must be a directory\n";
342 return;
343 }
344
345 # create destination directory if it doesn't exist already
346 if (! -d $dest) {
347 my $store_umask = umask(0002);
348 mkdir ($dest, 0777);
349 umask($store_umask);
350 }
351
352 # copy the files
353 foreach my $file (@srcfiles) {
354
355 if (!-e $file) {
356 print STDERR "util::cp_r $file does not exist\n";
357
358 } elsif (-d $file) {
359 # make the new directory
360 my ($filename) = $file =~ /([^\\\/]*)$/;
361 $dest = &util::filename_cat ($dest, $filename);
362 my $store_umask = umask(0002);
363 mkdir ($dest, 0777);
364 umask($store_umask);
365
366 # get the contents of this directory
367 if (!opendir (INDIR, $file)) {
368 print STDERR "util::cp_r could not open directory $file\n";
369 } else {
370 my @filedir = readdir (INDIR);
371 closedir (INDIR);
372 foreach my $f (@filedir) {
373 next if $f =~ /^\.\.?$/;
374
375 # copy all the files in this directory, but not directories
376 my $ff = &util::filename_cat ($file, $f);
377 if (-f $ff) {
378 &cp($ff, $dest);
379 #&cp_r ($ff, $dest);
380 }
381 }
382 }
383
384 } else {
385 &cp($file, $dest);
386 }
387 }
388}
389
390sub mk_dir {
391 my ($dir) = @_;
392
393 my $store_umask = umask(0002);
394 my $mkdir_ok = mkdir ($dir, 0777);
395 umask($store_umask);
396
397 if (!$mkdir_ok)
398 {
399 print STDERR "util::mk_dir could not create directory $dir\n";
400 return;
401 }
402}
403
404# in case anyone cares - I did some testing (using perls Benchmark module)
405# on this subroutine against File::Path::mkpath (). mk_all_dir() is apparently
406# slightly faster (surprisingly) - Stefan.
407sub mk_all_dir {
408 my ($dir) = @_;
409
410 # use / for the directory separator, remove duplicate and
411 # trailing slashes
412 $dir=~s/[\\\/]+/\//g;
413 $dir=~s/[\\\/]+$//;
414
415 # make sure the cache directory exists
416 my $dirsofar = "";
417 my $first = 1;
418 foreach my $dirname (split ("/", $dir)) {
419 $dirsofar .= "/" unless $first;
420 $first = 0;
421
422 $dirsofar .= $dirname;
423
424 next if $dirname =~ /^(|[a-z]:)$/i;
425 if (!-e $dirsofar)
426 {
427 my $store_umask = umask(0002);
428 my $mkdir_ok = mkdir ($dirsofar, 0777);
429 umask($store_umask);
430 if (!$mkdir_ok)
431 {
432 print STDERR "util::mk_all_dir could not create directory $dirsofar\n";
433 return;
434 }
435 }
436 }
437}
438
439# make hard link to file if supported by OS, otherwise copy the file
440sub hard_link {
441 my ($src, $dest, $verbosity) = @_;
442
443 # remove trailing slashes from source and destination files
444 $src =~ s/[\\\/]+$//;
445 $dest =~ s/[\\\/]+$//;
446
447## print STDERR "**** src = ", unicode::debug_unicode_string($src),"\n";
448 # a few sanity checks
449 if (-e $dest) {
450 # destination file already exists
451 return;
452 }
453 elsif (!-e $src) {
454 print STDERR "util::hard_link source file \"$src\" does not exist\n";
455 return 1;
456 }
457 elsif (-d $src) {
458 print STDERR "util::hard_link source \"$src\" is a directory\n";
459 return 1;
460 }
461
462 my $dest_dir = &File::Basename::dirname($dest);
463 mk_all_dir($dest_dir) if (!-e $dest_dir);
464
465
466 if (!link($src, $dest)) {
467 if ((!defined $verbosity) || ($verbosity>2)) {
468 print STDERR "util::hard_link: unable to create hard link. ";
469 print STDERR " Copying file: $src -> $dest\n";
470 }
471 &File::Copy::copy ($src, $dest);
472 }
473 return 0;
474}
475
476# make soft link to file if supported by OS, otherwise copy file
477sub soft_link {
478 my ($src, $dest, $ensure_paths_absolute) = @_;
479
480 # remove trailing slashes from source and destination files
481 $src =~ s/[\\\/]+$//;
482 $dest =~ s/[\\\/]+$//;
483
484 # Ensure file paths are absolute IF requested to do so
485 # Soft_linking didn't work for relative paths
486 if(defined $ensure_paths_absolute && $ensure_paths_absolute) {
487 # We need to ensure that the src file is the absolute path
488 # See http://perldoc.perl.org/File/Spec.html
489 if(!File::Spec->file_name_is_absolute( $src )) { # it's relative
490 $src = File::Spec->rel2abs($src); # make absolute
491 }
492 # Might as well ensure that the destination file's absolute path is used
493 if(!File::Spec->file_name_is_absolute( $dest )) {
494 $dest = File::Spec->rel2abs($dest); # make absolute
495 }
496 }
497
498 # a few sanity checks
499 if (!-e $src) {
500 print STDERR "util::soft_link source file $src does not exist\n";
501 return 0;
502 }
503
504 my $dest_dir = &File::Basename::dirname($dest);
505 mk_all_dir($dest_dir) if (!-e $dest_dir);
506
507 if ($ENV{'GSDLOS'} =~ /^windows$/i) {
508
509 # symlink not supported on windows
510 &File::Copy::copy ($src, $dest);
511
512 } elsif (!eval {symlink($src, $dest)}) {
513 print STDERR "util::soft_link: unable to create soft link.\n";
514 return 0;
515 }
516
517 return 1;
518}
519
520# Primarily for filenames generated by processing
521# content of HTML files (which are mapped to UTF-8 internally)
522#
523# To turn this into an octet string that really exists on the file
524# system:
525# 1. don't need to do anything special for Unix-based systems
526# (as underlying file system is byte-code)
527# 2. need to map to short DOS filenames for Windows
528
529sub utf8_to_real_filename
530{
531 my ($utf8_filename) = @_;
532
533 my $real_filename;
534
535 if ($ENV{'GSDLOS'} =~ m/^windows$/i) {
536 require Win32;
537
538 print STDERR "***** utf8 filename = $utf8_filename\n\n\n";
539
540 my $unicode_filename = decode("utf8",$utf8_filename);
541 $real_filename = Win32::GetShortPathName($unicode_filename);
542 }
543 else {
544 $real_filename = $utf8_filename;
545 }
546
547 return $real_filename;
548}
549
550
551sub fd_exists
552{
553 my $filename_full_path = shift @_;
554 my $test_op = shift @_ || "-e";
555
556 # By default tests for existance of file or directory (-e)
557 # Can be made more specific by providing second parameter (e.g. -f or -d)
558
559 my $exists = 0;
560
561 if ($ENV{'GSDLOS'} =~ m/^windows$/i) {
562 require Win32;
563 my $filename_short_path = Win32::GetShortPathName($filename_full_path);
564 if (!defined $filename_short_path) {
565 # Was probably still in UTF8 form (not what is needed on Windows)
566 my $unicode_filename_full_path = eval "decode(\"utf8\",\$filename_full_path)";
567 if (defined $unicode_filename_full_path) {
568 $filename_short_path = Win32::GetShortPathName($unicode_filename_full_path);
569 }
570 }
571 $filename_full_path = $filename_short_path;
572 }
573
574 if (defined $filename_full_path) {
575 $exists = eval "($test_op \$filename_full_path)";
576 }
577
578 return $exists;
579}
580
581sub file_exists
582{
583 my ($filename_full_path) = @_;
584
585 return fd_exists($filename_full_path,"-f");
586}
587
588sub dir_exists
589{
590 my ($filename_full_path) = @_;
591
592 return fd_exists($filename_full_path,"-d");
593}
594
595
596
597# updates a copy of a directory in some other part of the filesystem
598# verbosity settings are: 0=low, 1=normal, 2=high
599# both $fromdir and $todir should be absolute paths
600sub cachedir {
601 my ($fromdir, $todir, $verbosity) = @_;
602 $verbosity = 1 unless defined $verbosity;
603
604 # use / for the directory separator, remove duplicate and
605 # trailing slashes
606 $fromdir=~s/[\\\/]+/\//g;
607 $fromdir=~s/[\\\/]+$//;
608 $todir=~s/[\\\/]+/\//g;
609 $todir=~s/[\\\/]+$//;
610
611 &mk_all_dir ($todir);
612
613 # get the directories in ascending order
614 if (!opendir (FROMDIR, $fromdir)) {
615 print STDERR "util::cachedir could not read directory $fromdir\n";
616 return;
617 }
618 my @fromdir = grep (!/^\.\.?$/, sort(readdir (FROMDIR)));
619 closedir (FROMDIR);
620
621 if (!opendir (TODIR, $todir)) {
622 print STDERR "util::cacedir could not read directory $todir\n";
623 return;
624 }
625 my @todir = grep (!/^\.\.?$/, sort(readdir (TODIR)));
626 closedir (TODIR);
627
628 my $fromi = 0;
629 my $toi = 0;
630
631 while ($fromi < scalar(@fromdir) || $toi < scalar(@todir)) {
632# print "fromi: $fromi toi: $toi\n";
633
634 # see if we should delete a file/directory
635 # this should happen if the file/directory
636 # is not in the from list or if its a different
637 # size, or has an older timestamp
638 if ($toi < scalar(@todir)) {
639 if (($fromi >= scalar(@fromdir)) ||
640 ($todir[$toi] lt $fromdir[$fromi] ||
641 ($todir[$toi] eq $fromdir[$fromi] &&
642 &differentfiles("$fromdir/$fromdir[$fromi]","$todir/$todir[$toi]",
643 $verbosity)))) {
644
645 # the files are different
646 &rm_r("$todir/$todir[$toi]");
647 splice(@todir, $toi, 1); # $toi stays the same
648
649 } elsif ($todir[$toi] eq $fromdir[$fromi]) {
650 # the files are the same
651 # if it is a directory, check its contents
652 if (-d "$todir/$todir[$toi]") {
653 &cachedir ("$fromdir/$fromdir[$fromi]",
654 "$todir/$todir[$toi]", $verbosity);
655 }
656
657 $toi++;
658 $fromi++;
659 next;
660 }
661 }
662
663 # see if we should insert a file/directory
664 # we should insert a file/directory if there
665 # is no tofiles left or if the tofile does not exist
666 if ($fromi < scalar(@fromdir) && ($toi >= scalar(@todir) ||
667 $todir[$toi] gt $fromdir[$fromi])) {
668 &cp_r ("$fromdir/$fromdir[$fromi]", "$todir/$fromdir[$fromi]");
669 splice (@todir, $toi, 0, $fromdir[$fromi]);
670
671 $toi++;
672 $fromi++;
673 }
674 }
675}
676
677# this function returns -1 if either file is not found
678# assumes that $file1 and $file2 are absolute file names or
679# in the current directory
680# $file2 is allowed to be newer than $file1
681sub differentfiles {
682 my ($file1, $file2, $verbosity) = @_;
683 $verbosity = 1 unless defined $verbosity;
684
685 $file1 =~ s/\/+$//;
686 $file2 =~ s/\/+$//;
687
688 my ($file1name) = $file1 =~ /\/([^\/]*)$/;
689 my ($file2name) = $file2 =~ /\/([^\/]*)$/;
690
691 return -1 unless (-e $file1 && -e $file2);
692 if ($file1name ne $file2name) {
693 print STDERR "filenames are not the same\n" if ($verbosity >= 2);
694 return 1;
695 }
696
697 my @file1stat = stat ($file1);
698 my @file2stat = stat ($file2);
699
700 if (-d $file1) {
701 if (! -d $file2) {
702 print STDERR "one file is a directory\n" if ($verbosity >= 2);
703 return 1;
704 }
705 return 0;
706 }
707
708 # both must be regular files
709 unless (-f $file1 && -f $file2) {
710 print STDERR "one file is not a regular file\n" if ($verbosity >= 2);
711 return 1;
712 }
713
714 # the size of the files must be the same
715 if ($file1stat[7] != $file2stat[7]) {
716 print STDERR "different sized files\n" if ($verbosity >= 2);
717 return 1;
718 }
719
720 # the second file cannot be older than the first
721 if ($file1stat[9] > $file2stat[9]) {
722 print STDERR "file is older\n" if ($verbosity >= 2);
723 return 1;
724 }
725
726 return 0;
727}
728
729
730sub get_tmp_filename
731{
732 my $file_ext = shift(@_) || undef;
733
734 my $opt_dot_file_ext = "";
735 if (defined $file_ext) {
736 if ($file_ext !~ m/\./) {
737 # no dot, so needs one added in at start
738 $opt_dot_file_ext = ".$file_ext"
739 }
740 else {
741 # allow for "extensions" such as _metadata.txt to be handled
742 # gracefully
743 $opt_dot_file_ext = $file_ext;
744 }
745 }
746
747 my $tmpdir = filename_cat($ENV{'GSDLHOME'}, "tmp");
748 &mk_all_dir ($tmpdir) unless -e $tmpdir;
749
750 my $count = 1000;
751 my $rand = int(rand $count);
752 my $full_tmp_filename = &filename_cat($tmpdir, "F$rand$opt_dot_file_ext");
753
754 while (-e $full_tmp_filename) {
755 $rand = int(rand $count);
756 $full_tmp_filename = &filename_cat($tmpdir, "F$rand$opt_dot_file_ext");
757 $count++;
758 }
759
760 return $full_tmp_filename;
761}
762
763sub get_timestamped_tmp_folder
764{
765
766 my $tmp_dirname;
767 if(defined $ENV{'GSDLCOLLECTDIR'}) {
768 $tmp_dirname = $ENV{'GSDLCOLLECTDIR'};
769 } elsif(defined $ENV{'GSDLHOME'}) {
770 $tmp_dirname = $ENV{'GSDLHOME'};
771 } else {
772 return undef;
773 }
774
775 $tmp_dirname = &util::filename_cat($tmp_dirname, "tmp");
776 &util::mk_dir($tmp_dirname) if (!-e $tmp_dirname);
777
778 # add the timestamp into the path otherwise we can run into problems
779 # if documents have the same name
780 my $timestamp = time;
781 my $time_tmp_dirname = &util::filename_cat($tmp_dirname, $timestamp);
782 $tmp_dirname = $time_tmp_dirname;
783 my $i = 1;
784 while (-e $tmp_dirname) {
785 $tmp_dirname = "$time_tmp_dirname$i";
786 $i++;
787 }
788 &util::mk_dir($tmp_dirname);
789
790 return $tmp_dirname;
791}
792
793sub get_timestamped_tmp_filename_in_collection
794{
795
796 my ($input_filename, $output_ext) = @_;
797 # derive tmp filename from input filename
798 my ($tailname, $dirname, $suffix)
799 = &File::Basename::fileparse($input_filename, "\\.[^\\.]+\$");
800
801 # softlink to collection tmp dir
802 my $tmp_dirname = &util::get_timestamped_tmp_folder();
803 $tmp_dirname = $dirname unless defined $tmp_dirname;
804
805 # following two steps copied from ConvertBinaryFile
806 # do we need them?? can't use them as is, as they use plugin methods.
807
808 #$tailname = $self->SUPER::filepath_to_utf8($tailname) unless &unicode::check_is_utf8($tailname);
809
810 # URLEncode this since htmls with images where the html filename is utf8 don't seem
811 # to work on Windows (IE or Firefox), as browsers are looking for filesystem-encoded
812 # files on the filesystem.
813 #$tailname = &util::rename_file($tailname, $self->{'file_rename_method'}, "without_suffix");
814 if (defined $output_ext) {
815 $output_ext = ".$output_ext"; # add the dot
816 } else {
817 $output_ext = $suffix;
818 }
819 $output_ext= lc($output_ext);
820 my $tmp_filename = &util::filename_cat($tmp_dirname, "$tailname$output_ext");
821
822 return $tmp_filename;
823}
824
825sub get_toplevel_tmp_dir
826{
827 return filename_cat($ENV{'GSDLHOME'}, "tmp");
828}
829
830
831sub filename_to_regex {
832 my $filename = shift (@_);
833
834 # need to put single backslash back to double so that regex works
835 if ($ENV{'GSDLOS'} =~ /^windows$/i) {
836 $filename =~ s/\\/\\\\/g;
837 }
838 return $filename;
839}
840
841sub filename_cat {
842 my $first_file = shift(@_);
843 my (@filenames) = @_;
844
845# Useful for debugging
846# -- might make sense to call caller(0) rather than (1)??
847# my ($cpackage,$cfilename,$cline,$csubr,$chas_args,$cwantarray) = caller(1);
848# print STDERR "Calling method: $cfilename:$cline $cpackage->$csubr\n";
849
850 # If first_file is not null or empty, then add it back into the list
851 if (defined $first_file && $first_file =~ /\S/) {
852 unshift(@filenames, $first_file);
853 }
854
855 my $filename = join("/", @filenames);
856
857 # remove duplicate slashes and remove the last slash
858 if ($ENV{'GSDLOS'} =~ /^windows$/i) {
859 $filename =~ s/[\\\/]+/\\/g;
860 } else {
861 $filename =~ s/[\/]+/\//g;
862 # DB: want a filename abc\de.html to remain like this
863 }
864 $filename =~ s/[\\\/]$//;
865
866 return $filename;
867}
868
869
870sub pathname_cat {
871 my $first_path = shift(@_);
872 my (@pathnames) = @_;
873
874 # If first_path is not null or empty, then add it back into the list
875 if (defined $first_path && $first_path =~ /\S/) {
876 unshift(@pathnames, $first_path);
877 }
878
879 my $join_char;
880 if ($ENV{'GSDLOS'} =~ /^windows$/i) {
881 $join_char = ";";
882 } else {
883 $join_char = ":";
884 }
885
886 my $pathname = join($join_char, @pathnames);
887
888 # remove duplicate slashes
889 if ($ENV{'GSDLOS'} =~ /^windows$/i) {
890 $pathname =~ s/[\\\/]+/\\/g;
891 } else {
892 $pathname =~ s/[\/]+/\//g;
893 # DB: want a pathname abc\de.html to remain like this
894 }
895
896 return $pathname;
897}
898
899
900sub tidy_up_oid {
901 my ($OID) = @_;
902 if ($OID =~ /\./) {
903 print STDERR "Warning, identifier $OID contains periods (.), removing them\n";
904 $OID =~ s/\.//g; #remove any periods
905 }
906 if ($OID =~ /^\s.*\s$/) {
907 print STDERR "Warning, identifier $OID starts or ends with whitespace. Removing it\n";
908 # remove starting and trailing whitespace
909 $OID =~ s/^\s+//;
910 $OID =~ s/\s+$//;
911 }
912 if ($OID =~ /^[\d]*$/) {
913 print STDERR "Warning, identifier $OID contains only digits. Prepending 'D'.\n";
914 $OID = "D" . $OID;
915 }
916
917 return $OID;
918}
919sub envvar_prepend {
920 my ($var,$val) = @_;
921
922 # do not prepend any value/path that's already in the environment variable
923 if ($ENV{'GSDLOS'} =~ /^windows$/i)
924 {
925 my $escaped_val = $val;
926 $escaped_val =~ s/\\/\\\\/g; # escape any Windows backslashes for upcoming regex
927 if (!defined($ENV{$var})) {
928 $ENV{$var} = "$val";
929 }
930 elsif($ENV{$var} !~ m/$escaped_val/) {
931 $ENV{$var} = "$val;".$ENV{$var};
932 }
933 }
934 else {
935 if (!defined($ENV{$var})) {
936 $ENV{$var} = "$val";
937 }
938 elsif($ENV{$var} !~ m/$val/) {
939 $ENV{$var} = "$val:".$ENV{$var};
940 }
941 }
942}
943
944sub envvar_append {
945 my ($var,$val) = @_;
946
947 # do not append any value/path that's already in the environment variable
948 if ($ENV{'GSDLOS'} =~ /^windows$/i)
949 {
950 my $escaped_val = $val;
951 $escaped_val =~ s/\\/\\\\/g; # escape any Windows backslashes for upcoming regex
952 if (!defined($ENV{$var})) {
953 $ENV{$var} = "$val";
954 }
955 elsif($ENV{$var} !~ m/$escaped_val/) {
956 $ENV{$var} .= ";$val";
957 }
958 }
959 else {
960 if (!defined($ENV{$var})) {
961 $ENV{$var} = "$val";
962 }
963 elsif($ENV{$var} !~ m/$val/) {
964 $ENV{$var} .= ":$val";
965 }
966 }
967}
968
969
970# splits a filename into a prefix and a tail extension using the tail_re, or
971# if that fails, splits on the file_extension . (dot)
972sub get_prefix_and_tail_by_regex {
973
974 my ($filename,$tail_re) = @_;
975
976 my ($file_prefix,$file_ext) = ($filename =~ m/^(.*?)($tail_re)$/);
977 if ((!defined $file_prefix) || (!defined $file_ext)) {
978 ($file_prefix,$file_ext) = ($filename =~ m/^(.*)(\..*?)$/);
979 }
980
981 return ($file_prefix,$file_ext);
982}
983
984# get full path and file only path from a base_dir (which may be empty) and
985# file (which may contain directories)
986sub get_full_filenames {
987 my ($base_dir, $file) = @_;
988
989 my $filename_full_path = $file;
990 # add on directory if present
991 $filename_full_path = &util::filename_cat ($base_dir, $file) if $base_dir =~ /\S/;
992
993 my $filename_no_path = $file;
994
995 # remove directory if present
996 $filename_no_path =~ s/^.*[\/\\]//;
997 return ($filename_full_path, $filename_no_path);
998}
999
1000# returns the path of a file without the filename -- ie. the directory the file is in
1001sub filename_head {
1002 my $filename = shift(@_);
1003
1004 if ($ENV{'GSDLOS'} =~ /^windows$/i) {
1005 $filename =~ s/[^\\\\]*$//;
1006 }
1007 else {
1008 $filename =~ s/[^\\\/]*$//;
1009 }
1010
1011 return $filename;
1012}
1013
1014
1015
1016# returns 1 if filename1 and filename2 point to the same
1017# file or directory
1018sub filenames_equal {
1019 my ($filename1, $filename2) = @_;
1020
1021 # use filename_cat to clean up trailing slashes and
1022 # multiple slashes
1023 $filename1 = filename_cat ($filename1);
1024 $filename2 = filename_cat ($filename2);
1025
1026 # filenames not case sensitive on windows
1027 if ($ENV{'GSDLOS'} =~ /^windows$/i) {
1028 $filename1 =~ tr/[A-Z]/[a-z]/;
1029 $filename2 =~ tr/[A-Z]/[a-z]/;
1030 }
1031 return 1 if $filename1 eq $filename2;
1032 return 0;
1033}
1034
1035
1036sub filename_within_directory
1037{
1038 my ($filename,$within_dir) = @_;
1039
1040 if ($within_dir !~ m/[\/\\]$/) {
1041 my $dirsep = &util::get_dirsep();
1042 $within_dir .= $dirsep;
1043 }
1044
1045 $within_dir =~ s/\\/\\\\/g; # escape DOS style file separator
1046
1047 if ($filename =~ m/^$within_dir(.*)$/) {
1048 $filename = $1;
1049 }
1050
1051 return $filename;
1052}
1053
1054sub filename_within_collection
1055{
1056 my ($filename) = @_;
1057
1058 my $collect_dir = $ENV{'GSDLCOLLECTDIR'};
1059
1060 if (defined $collect_dir) {
1061
1062 # if from within GSDLCOLLECTDIR, then remove directory prefix
1063 # so source_filename is realative to it. This is done to aid
1064 # portability, i.e. the collection can be moved to somewhere
1065 # else on the file system and the archives directory will still
1066 # work. This is needed, for example in the applet version of
1067 # GLI where GSDLHOME/collect on the server will be different to
1068 # the collect directory of the remove user. Of course,
1069 # GSDLCOLLECTDIR subsequently needs to be put back on to turn
1070 # it back into a full pathname.
1071
1072 $filename = filename_within_directory($filename,$collect_dir);
1073 }
1074
1075 return $filename;
1076}
1077
1078sub prettyprint_file
1079{
1080 my ($base_dir,$file,$gli) = @_;
1081
1082 my $filename_full_path = &util::filename_cat($base_dir,$file);
1083
1084 if ($ENV{'GSDLOS'} =~ m/^windows$/i) {
1085 require Win32;
1086
1087 # For some reason base_dir in the form c:/a/b/c
1088 # This leads to confusion later on, so turn it back into
1089 # the more usual Windows form
1090 $base_dir =~ s/\//\\/g;
1091 my $long_base_dir = Win32::GetLongPathName($base_dir);
1092 my $long_full_path = Win32::GetLongPathName($filename_full_path);
1093
1094 $file = filename_within_directory($long_full_path,$long_base_dir);
1095 $file = encode("utf8",$file) if ($gli);
1096 }
1097
1098 return $file;
1099}
1100
1101
1102sub upgrade_if_dos_filename
1103{
1104 my ($filename_full_path,$and_encode) = @_;
1105
1106 if ($ENV{'GSDLOS'} =~ m/^windows$/i) {
1107 # Ensure any DOS-like filename, such as test~1.txt, has been upgraded
1108 # to its long (Windows) version
1109 my $long_filename = Win32::GetLongPathName($filename_full_path);
1110 if (defined $long_filename) {
1111 $filename_full_path = $long_filename;
1112 }
1113 # Make sure initial drive letter is lower-case (to fit in with rest of Greenstone)
1114 $filename_full_path =~ s/^(.):/\u$1:/;
1115 if ((defined $and_encode) && ($and_encode)) {
1116 $filename_full_path = encode("utf8",$filename_full_path);
1117 }
1118 }
1119
1120 return $filename_full_path;
1121}
1122
1123
1124sub downgrade_if_dos_filename
1125{
1126 my ($filename_full_path) = @_;
1127
1128 if ($ENV{'GSDLOS'} =~ m/^windows$/i) {
1129 require Win32;
1130
1131 # Ensure the given long Windows filename is in a form that can
1132 # be opened by Perl => convert it to a short DOS-like filename
1133
1134 my $short_filename = Win32::GetShortPathName($filename_full_path);
1135 if (defined $short_filename) {
1136 $filename_full_path = $short_filename;
1137 }
1138 # Make sure initial drive letter is lower-case (to fit in
1139 # with rest of Greenstone)
1140 $filename_full_path =~ s/^(.):/\u$1:/;
1141 }
1142
1143 return $filename_full_path;
1144}
1145
1146sub block_filename
1147{
1148 my ($block_hash,$filename) = @_;
1149
1150 if ($ENV{'GSDLOS'} =~ m/^windows$/) {
1151
1152 # lower case the entire thing, eg for cover.jpg when its actually cover.JPG
1153 my $lower_filename = lc($filename);
1154 $block_hash->{'file_blocks'}->{$lower_filename} = 1;
1155# my $lower_drive = $filename;
1156# $lower_drive =~ s/^([A-Z]):/\l$1:/i;
1157
1158# my $upper_drive = $filename;
1159# $upper_drive =~ s/^([A-Z]):/\u$1:/i;
1160#
1161# $block_hash->{'file_blocks'}->{$lower_drive} = 1;
1162# $block_hash->{'file_blocks'}->{$upper_drive} = 1;
1163 }
1164 else {
1165 $block_hash->{'file_blocks'}->{$filename} = 1;
1166 }
1167}
1168
1169
1170sub filename_is_absolute
1171{
1172 my ($filename) = @_;
1173
1174 if ($ENV{'GSDLOS'} =~ /^windows$/i) {
1175 return ($filename =~ m/^(\w:)?\\/);
1176 }
1177 else {
1178 return ($filename =~ m/^\//);
1179 }
1180}
1181
1182
1183## @method make_absolute()
1184#
1185# Ensure the given file path is absolute in respect to the given base path.
1186#
1187# @param $base_dir A string denoting the base path the given dir must be
1188# absolute to.
1189# @param $dir The directory to be made absolute as a string. Note that the
1190# dir may already be absolute, in which case it will remain
1191# unchanged.
1192# @return The now absolute form of the directory as a string.
1193#
1194# @author John Thompson, DL Consulting Ltd.
1195# @copy 2006 DL Consulting Ltd.
1196#
1197#used in buildcol.pl, doesn't work for all cases --kjdon
1198sub make_absolute {
1199
1200 my ($base_dir, $dir) = @_;
1201### print STDERR "dir = $dir\n";
1202 $dir =~ s/[\\\/]+/\//g;
1203 $dir = $base_dir . "/$dir" unless ($dir =~ m|^(\w:)?/|);
1204 $dir =~ s|^/tmp_mnt||;
1205 1 while($dir =~ s|/[^/]*/\.\./|/|g);
1206 $dir =~ s|/[.][.]?/|/|g;
1207 $dir =~ tr|/|/|s;
1208### print STDERR "dir = $dir\n";
1209
1210 return $dir;
1211}
1212## make_absolute() ##
1213
1214sub get_dirsep {
1215
1216 if ($ENV{'GSDLOS'} =~ /^windows$/i) {
1217 return "\\";
1218 } else {
1219 return "\/";
1220 }
1221}
1222
1223sub get_os_dirsep {
1224
1225 if ($ENV{'GSDLOS'} =~ /^windows$/i) {
1226 return "\\\\";
1227 } else {
1228 return "\\\/";
1229 }
1230}
1231
1232sub get_re_dirsep {
1233
1234 return "\\\\|\\\/";
1235}
1236
1237
1238sub get_dirsep_tail {
1239 my ($filename) = @_;
1240
1241 # returns last part of directory or filename
1242 # On unix e.g. a/b.d => b.d
1243 # a/b/c => c
1244
1245 my $dirsep = get_re_dirsep();
1246 my @dirs = split (/$dirsep/, $filename);
1247 my $tail = pop @dirs;
1248
1249 # - caused problems under windows
1250 #my ($tail) = ($filename =~ m/^(?:.*?$dirsep)?(.*?)$/);
1251
1252 return $tail;
1253}
1254
1255
1256# if this is running on windows we want binaries to end in
1257# .exe, otherwise they don't have to end in any extension
1258sub get_os_exe {
1259 return ".exe" if $ENV{'GSDLOS'} =~ /^windows$/i;
1260 return "";
1261}
1262
1263
1264# test to see whether this is a big or little endian machine
1265sub is_little_endian
1266{
1267 # To determine the name of the operating system, the variable $^O is a cheap alternative to pulling it out of the Config module;
1268 # If it is a Macintosh machine (i.e. the Darwin operating system), regardless if it's running on the IBM power-pc cpu or the x86 Intel-based chip with a power-pc emulator running on top of it, it's big-endian
1269 # Otherwise, it's little endian
1270
1271 #return 0 if $^O =~ /^darwin$/i;
1272 #return 0 if $ENV{'GSDLOS'} =~ /^darwin$/i;
1273
1274 # Going back to stating exactly whether the machine is little endian
1275 # or big endian, without any special case for Macs. Since for rata it comes
1276 # back with little endian and for shuttle with bigendian.
1277 return (ord(substr(pack("s",1), 0, 1)) == 1);
1278}
1279
1280
1281# will return the collection name if successful, "" otherwise
1282sub use_collection {
1283 my ($collection, $collectdir) = @_;
1284
1285 if (!defined $collectdir || $collectdir eq "") {
1286 $collectdir = &filename_cat ($ENV{'GSDLHOME'}, "collect");
1287 }
1288
1289 # get and check the collection
1290 if (!defined($collection) || $collection eq "") {
1291 if (defined $ENV{'GSDLCOLLECTION'}) {
1292 $collection = $ENV{'GSDLCOLLECTION'};
1293 } else {
1294 print STDOUT "No collection specified\n";
1295 return "";
1296 }
1297 }
1298
1299 if ($collection eq "modelcol") {
1300 print STDOUT "You can't use modelcol.\n";
1301 return "";
1302 }
1303
1304 # make sure the environment variables GSDLCOLLECTION and GSDLCOLLECTDIR
1305 # are defined
1306 $ENV{'GSDLCOLLECTION'} = $collection;
1307 $ENV{'GSDLCOLLECTDIR'} = &filename_cat ($collectdir, $collection);
1308
1309 # make sure this collection exists
1310 if (!-e $ENV{'GSDLCOLLECTDIR'}) {
1311 print STDOUT "Invalid collection ($collection).\n";
1312 return "";
1313 }
1314
1315 # everything is ready to go
1316 return $collection;
1317}
1318
1319sub get_current_collection_name {
1320 return $ENV{'GSDLCOLLECTION'};
1321}
1322
1323
1324# will return the collection name if successful, "" otherwise.
1325# Like use_collection (above) but for greenstone 3 (taking account of site level)
1326
1327sub use_site_collection {
1328 my ($site, $collection, $collectdir) = @_;
1329
1330 if (!defined $collectdir || $collectdir eq "") {
1331 die "GSDL3HOME not set.\n" unless defined $ENV{'GSDL3HOME'};
1332 $collectdir = &filename_cat ($ENV{'GSDL3HOME'}, "sites", $site, "collect");
1333 }
1334
1335 # collectdir explicitly set by this point (using $site variable if required).
1336 # Can call "old" gsdl2 use_collection now.
1337
1338 return use_collection($collection,$collectdir);
1339}
1340
1341
1342
1343sub locate_config_file
1344{
1345 my ($file) = @_;
1346
1347 my $locations = locate_config_files($file);
1348
1349 return shift @$locations; # returns undef if 'locations' is empty
1350}
1351
1352
1353sub locate_config_files
1354{
1355 my ($file) = @_;
1356
1357 my @locations = ();
1358
1359 if (-e $file) {
1360 # Clearly specified (most likely full filename)
1361 # No need to hunt in 'etc' directories, return value unchanged
1362 push(@locations,$file);
1363 }
1364 else {
1365 # Check for collection specific one before looking in global GSDL 'etc'
1366 if (defined $ENV{'GSDLCOLLECTDIR'} && $ENV{'GSDLCOLLECTDIR'} ne "") {
1367 my $test_collect_etc_filename
1368 = &util::filename_cat($ENV{'GSDLCOLLECTDIR'},"etc", $file);
1369
1370 if (-e $test_collect_etc_filename) {
1371 push(@locations,$test_collect_etc_filename);
1372 }
1373 }
1374 my $test_main_etc_filename
1375 = &util::filename_cat($ENV{'GSDLHOME'},"etc", $file);
1376 if (-e $test_main_etc_filename) {
1377 push(@locations,$test_main_etc_filename);
1378 }
1379 }
1380
1381 return \@locations;
1382}
1383
1384
1385sub hyperlink_text
1386{
1387 my ($text) = @_;
1388
1389 $text =~ s/(http:\/\/[^\s]+)/<a href=\"$1\">$1<\/a>/mg;
1390 $text =~ s/(^|\s+)(www\.(\w|\.)+)/<a href=\"http:\/\/$2\">$2<\/a>/mg;
1391
1392 return $text;
1393}
1394
1395
1396# A method to check if a directory is empty (note that an empty directory still has non-zero size!!!)
1397# Code is from http://episteme.arstechnica.com/eve/forums/a/tpc/f/6330927813/m/436007700831
1398sub is_dir_empty
1399{
1400 my ($path) = @_;
1401 opendir DIR, $path;
1402 while(my $entry = readdir DIR) {
1403 next if($entry =~ /^\.\.?$/);
1404 closedir DIR;
1405 return 0;
1406 }
1407 closedir DIR;
1408 return 1;
1409}
1410
1411# Returns the given filename converted using either URL encoding or base64
1412# encoding, as specified by $rename_method. If the given filename has no suffix
1413# (if it is just the tailname), then $no_suffix should be some defined value.
1414# rename_method can be url, none, base64
1415sub rename_file {
1416 my ($filename, $rename_method, $no_suffix) = @_;
1417
1418 if(!$filename) { # undefined or empty string
1419 return $filename;
1420 }
1421
1422 if (!$rename_method) {
1423 print STDERR "WARNING: no file renaming method specified. Defaulting to using URL encoding...\n";
1424 # Debugging information
1425 # my ($cpackage,$cfilename,$cline,$csubr,$chas_args,$cwantarray) = caller(1);
1426 # print STDERR "Called from method: $cfilename:$cline $cpackage->$csubr\n";
1427 $rename_method = "url";
1428 } elsif($rename_method eq "none") {
1429 return $filename; # would have already been renamed
1430 }
1431
1432 # No longer replace spaces with underscores, since underscores mess with incremental rebuild
1433 ### Replace spaces with underscore. Do this first else it can go wrong below when getting tailname
1434 ###$filename =~ s/ /_/g;
1435
1436 my ($tailname,$dirname,$suffix);
1437 if($no_suffix) { # given a tailname, no suffix
1438 ($tailname,$dirname) = File::Basename::fileparse($filename);
1439 }
1440 else {
1441 ($tailname,$dirname,$suffix) = File::Basename::fileparse($filename, "\\.(?:[^\\.]+?)\$");
1442 }
1443 if (!$suffix) {
1444 $suffix = "";
1445 }
1446 else {
1447 $suffix = lc($suffix);
1448 }
1449
1450 if ($rename_method eq "url") {
1451 $tailname = &unicode::url_encode($tailname);
1452 }
1453 elsif ($rename_method eq "base64") {
1454 $tailname = &unicode::base64_encode($tailname);
1455 $tailname =~ s/\s*//sg; # for some reason it adds spaces not just at end but also in middle
1456 }
1457
1458 $filename = "$tailname$suffix";
1459 $filename = "$dirname$filename" if ($dirname ne "./" && $dirname ne ".\\");
1460
1461 return $filename;
1462}
1463
1464
1465# BACKWARDS COMPATIBILITY: Just in case there are old .ldb/.bdb files
1466sub rename_ldb_or_bdb_file {
1467 my ($filename_no_ext) = @_;
1468
1469 my $new_filename = "$filename_no_ext.gdb";
1470 return if (-f $new_filename); # if the file has the right extension, don't need to do anything
1471 # try ldb
1472 my $old_filename = "$filename_no_ext.ldb";
1473
1474 if (-f $old_filename) {
1475 print STDERR "Renaming $old_filename to $new_filename\n";
1476 rename ($old_filename, $new_filename)
1477 || print STDERR "Rename failed: $!\n";
1478 return;
1479 }
1480 # try bdb
1481 $old_filename = "$filename_no_ext.bdb";
1482 if (-f $old_filename) {
1483 print STDERR "Renaming $old_filename to $new_filename\n";
1484 rename ($old_filename, $new_filename)
1485 || print STDERR "Rename failed: $!\n";
1486 return;
1487 }
1488}
1489
1490
1491# Returns the greenstone URL prefix extracted from the appropriate GS2/GS3 config file.
1492# By default, /greenstone3 for GS3 or /greenstone for GS2.
1493sub get_greenstone_url_prefix() {
1494 # if already set on a previous occasion, just return that
1495 # (Don't want to keep repeating this: cost of re-opening and scanning files.)
1496 return $ENV{'GREENSTONE_URL_PREFIX'} if($ENV{'GREENSTONE_URL_PREFIX'});
1497
1498 my ($configfile, $urlprefix, $defaultUrlprefix);
1499 my @propertynames = ();
1500
1501 if($ENV{'GSDL3SRCHOME'}) {
1502 $defaultUrlprefix = "/greenstone3";
1503 $configfile = &util::filename_cat($ENV{'GSDL3SRCHOME'}, "packages", "tomcat", "conf", "Catalina", "localhost", "greenstone3.xml");
1504 push(@propertynames, qw/path\s*\=/);
1505 } else {
1506 $defaultUrlprefix = "/greenstone";
1507 $configfile = &util::filename_cat($ENV{'GSDLHOME'}, "cgi-bin", "gsdlsite.cfg");
1508 push(@propertynames, (qw/\nhttpprefix/, qw/\ngwcgi/)); # inspect one property then the other
1509 }
1510
1511 $urlprefix = &extract_propvalue_from_file($configfile, \@propertynames);
1512
1513 if(!$urlprefix) { # no values found for URL prefix, use default values
1514 $urlprefix = $defaultUrlprefix;
1515 } else {
1516 #gwcgi can contain more than the wanted prefix, we split on / to get the first "directory" level
1517 $urlprefix =~ s/^\///; # remove the starting slash
1518 my @dirs = split(/(\\|\/)/, $urlprefix);
1519 $urlprefix = shift(@dirs);
1520
1521 if($urlprefix !~ m/^\//) { # in all cases: ensure the required forward slash is at the front
1522 $urlprefix = "/$urlprefix";
1523 }
1524 }
1525
1526 # set for the future
1527 $ENV{'GREENSTONE_URL_PREFIX'} = $urlprefix;
1528# print STDERR "*** in get_greenstone_url_prefix(): $urlprefix\n\n";
1529 return $urlprefix;
1530}
1531
1532
1533# Given a config file (xml or java properties file) and a list/array of regular expressions
1534# that represent property names to match on, this function will return the value for the 1st
1535# matching property name. If the return value is undefined, no matching property was found.
1536sub extract_propvalue_from_file() {
1537 my ($configfile, $propertynames) = @_;
1538
1539 my $value;
1540 unless(open(FIN, "<$configfile")) {
1541 print STDERR "extract_propvalue_from_file(): Unable to open $configfile. $!\n";
1542 return $value; # not initialised
1543 }
1544
1545 # Read the entire file at once, as one single line, then close it
1546 my $filecontents;
1547 {
1548 local $/ = undef;
1549 $filecontents = <FIN>;
1550 }
1551 close(FIN);
1552
1553 foreach my $regex (@$propertynames) {
1554 ($value) = $filecontents=~ m/$regex\s*(\S*)/s; # read value of the property given by regex up to the 1st space
1555 if($value) {
1556 $value =~ s/^\"//; # remove any startquotes
1557 $value =~ s/\".*$//; # remove the 1st endquotes (if any) followed by any xml
1558 last; # found value for a matching property, break from loop
1559 }
1560 }
1561
1562 return $value;
1563}
1564
1565# Subroutine that sources setup.bash, given GSDLHOME and GSDLOS and
1566# given that perllib is in @INC in order to invoke this subroutine.
1567# Call as follows -- after setting up INC to include perllib and
1568# after setting up GSDLHOME and GSDLOS:
1569#
1570# require util;
1571# &util::setup_greenstone_env($ENV{'GSDLHOME'}, $ENV{'GSDLOS'});
1572#
1573sub setup_greenstone_env() {
1574 my ($GSDLHOME, $GSDLOS) = @_;
1575
1576 #my %env_map = ();
1577 # Get the localised ENV settings of running a localised source setup.bash
1578 # and put it into the ENV here. Need to clear GSDLHOME before running setup
1579 #my $perl_command = "(cd $GSDLHOME; export GSDLHOME=; . ./setup.bash > /dev/null; env)";
1580 my $perl_command = "(cd $GSDLHOME; /bin/bash -c \"export GSDLHOME=; source setup.bash > /dev/null; env\")";
1581 if($GSDLOS =~ m/windows/i) {
1582 #$perl_command = "cmd /C \"cd $GSDLHOME&& set GSDLHOME=&& setup.bat > nul&& set\"";
1583 $perl_command = "(cd $GSDLHOME&& set GSDLHOME=&& setup.bat > nul&& set)";
1584 }
1585 if (!open(PIN, "$perl_command |")) {
1586 print STDERR ("Unable to execute command: $perl_command. $!\n");
1587 }
1588
1589 while (defined (my $perl_output_line = <PIN>)) {
1590 my($key,$value) = ($perl_output_line =~ m/^([^=]*)[=](.*)$/);
1591 #$env_map{$key}=$value;
1592 $ENV{$key}=$value;
1593 }
1594
1595 # If any keys in $ENV don't occur in Greenstone's localised env
1596 # (stored in $env_map), delete those entries from $ENV
1597 #foreach $key (keys %ENV) {
1598 # if(!defined $env_map{$key}) {
1599 # print STDOUT "**** DELETING ENV KEY: $key\tVALUE: $ENV{'$key'}\n";
1600 # delete $ENV{$key}; # del $ENV(key, value) pair
1601 # }
1602 #}
1603 #undef %env_map;
1604}
1605
16061;
Note: See TracBrowser for help on using the repository browser.