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

Last change on this file since 23484 was 23484, checked in by ak19, 13 years ago

Further improvements by Dr Bainbridge to pretty-printing.

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