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

Last change on this file since 21425 was 21425, checked in by davidb, 14 years ago

Fixed typo in variable declaration

  • Property svn:keywords set to Author Date Id Revision
File size: 29.7 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
28use File::Copy;
[619]29use File::Basename;
[4]30
[14926]31use strict;
[14365]32
[14926]33
[4]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
61
[10211]62
[4]63# recursive removal
[10211]64sub filtered_rm_r {
65 my ($files,$file_accept_re,$file_reject_re) = @_;
[4]66
[10211]67 my @files_array = (ref $files eq "ARRAY") ? @$files : ($files);
68
[4]69 # recursively remove the files
[10211]70 foreach my $file (@files_array) {
[4]71 $file =~ s/[\/\\]+$//; # remove trailing slashes
72
73 if (!-e $file) {
[10211]74 print STDERR "util::filtered_rm_r $file does not exist\n";
[4]75
[721]76 } elsif ((-d $file) && (!-l $file)) { # don't recurse down symbolic link
[4]77 # get the contents of this directory
78 if (!opendir (INDIR, $file)) {
[10211]79 print STDERR "util::filtered_rm_r could not open directory $file\n";
[4]80 } else {
81 my @filedir = grep (!/^\.\.?$/, readdir (INDIR));
82 closedir (INDIR);
[10211]83
[4]84 # remove all the files in this directory
[10211]85 map {$_="$file/$_";} @filedir;
86 &filtered_rm_r (\@filedir,$file_accept_re,$file_reject_re);
[4]87
[10211]88 if (!defined $file_accept_re && !defined $file_reject_re) {
89 # remove this directory
90 if (!rmdir $file) {
91 print STDERR "util::filtered_rm_r couldn't remove directory $file\n";
92 }
[4]93 }
94 }
[10211]95 } else {
96 next if (defined $file_reject_re && ($file =~ m/$file_reject_re/));
[4]97
[10211]98 if ((!defined $file_accept_re) || ($file =~ m/$file_accept_re/)) {
99 # remove this file
100 &rm ($file);
101 }
[4]102 }
103 }
104}
105
[10211]106
107# recursive removal
108sub rm_r {
109 my (@files) = @_;
110
111 # use the more general (but reterospectively written function
112 # filtered_rm_r function()
113
114 filtered_rm_r(\@files,undef,undef); # no accept or reject expressions
115}
116
117
118
119
[721]120# moves a file or a group of files
121sub mv {
122 my $dest = pop (@_);
123 my (@srcfiles) = @_;
[4]124
[721]125 # remove trailing slashes from source and destination files
126 $dest =~ s/[\\\/]+$//;
127 map {$_ =~ s/[\\\/]+$//;} @srcfiles;
128
129 # a few sanity checks
130 if (scalar (@srcfiles) == 0) {
131 print STDERR "util::mv no destination directory given\n";
132 return;
133 } elsif ((scalar (@srcfiles) > 1) && (!-d $dest)) {
134 print STDERR "util::mv if multiple source files are given the ".
135 "destination must be a directory\n";
136 return;
137 }
138
139 # move the files
[8716]140 foreach my $file (@srcfiles) {
[721]141 my $tempdest = $dest;
142 if (-d $tempdest) {
143 my ($filename) = $file =~ /([^\\\/]+)$/;
144 $tempdest .= "/$filename";
145 }
146 if (!-e $file) {
147 print STDERR "util::mv $file does not exist\n";
148 } else {
149 rename ($file, $tempdest);
150 }
151 }
152}
153
154
[4]155# copies a file or a group of files
156sub cp {
157 my $dest = pop (@_);
158 my (@srcfiles) = @_;
159
160 # remove trailing slashes from source and destination files
161 $dest =~ s/[\\\/]+$//;
162 map {$_ =~ s/[\\\/]+$//;} @srcfiles;
163
164 # a few sanity checks
165 if (scalar (@srcfiles) == 0) {
166 print STDERR "util::cp no destination directory given\n";
167 return;
168 } elsif ((scalar (@srcfiles) > 1) && (!-d $dest)) {
169 print STDERR "util::cp if multiple source files are given the ".
170 "destination must be a directory\n";
171 return;
172 }
173
174 # copy the files
[8716]175 foreach my $file (@srcfiles) {
[4]176 my $tempdest = $dest;
177 if (-d $tempdest) {
178 my ($filename) = $file =~ /([^\\\/]+)$/;
179 $tempdest .= "/$filename";
180 }
181 if (!-e $file) {
182 print STDERR "util::cp $file does not exist\n";
183 } elsif (!-f $file) {
184 print STDERR "util::cp $file is not a plain file\n";
185 } else {
186 &File::Copy::copy ($file, $tempdest);
187 }
188 }
189}
190
191
[721]192
[4]193# recursively copies a file or group of files
[1454]194# syntax: cp_r (sourcefiles, destination directory)
195# destination must be a directory - to copy one file to
196# another use cp instead
[4]197sub cp_r {
198 my $dest = pop (@_);
199 my (@srcfiles) = @_;
200
201 # a few sanity checks
202 if (scalar (@srcfiles) == 0) {
[1454]203 print STDERR "util::cp_r no destination directory given\n";
[4]204 return;
[1454]205 } elsif (-f $dest) {
206 print STDERR "util::cp_r destination must be a directory\n";
[4]207 return;
208 }
209
[1454]210 # create destination directory if it doesn't exist already
211 if (! -d $dest) {
212 my $store_umask = umask(0002);
213 mkdir ($dest, 0777);
214 umask($store_umask);
215 }
216
[4]217 # copy the files
[8716]218 foreach my $file (@srcfiles) {
[4]219
220 if (!-e $file) {
[1454]221 print STDERR "util::cp_r $file does not exist\n";
[4]222
223 } elsif (-d $file) {
[1586]224 # make the new directory
225 my ($filename) = $file =~ /([^\\\/]*)$/;
226 $dest = &util::filename_cat ($dest, $filename);
227 my $store_umask = umask(0002);
228 mkdir ($dest, 0777);
229 umask($store_umask);
[836]230
[4]231 # get the contents of this directory
232 if (!opendir (INDIR, $file)) {
233 print STDERR "util::cp_r could not open directory $file\n";
234 } else {
[1454]235 my @filedir = readdir (INDIR);
[4]236 closedir (INDIR);
[8716]237 foreach my $f (@filedir) {
[1454]238 next if $f =~ /^\.\.?$/;
239 # copy all the files in this directory
240 my $ff = &util::filename_cat ($file, $f);
241 &cp_r ($ff, $dest);
242 }
[4]243 }
244
245 } else {
[1454]246 &cp($file, $dest);
[4]247 }
248 }
249}
250
[11179]251# copies a directory and its contents, excluding subdirectories, into a new directory
252sub cp_r_toplevel {
253 my $dest = pop (@_);
254 my (@srcfiles) = @_;
[4]255
[11179]256 # a few sanity checks
257 if (scalar (@srcfiles) == 0) {
258 print STDERR "util::cp_r no destination directory given\n";
259 return;
260 } elsif (-f $dest) {
261 print STDERR "util::cp_r destination must be a directory\n";
262 return;
263 }
264
265 # create destination directory if it doesn't exist already
266 if (! -d $dest) {
267 my $store_umask = umask(0002);
268 mkdir ($dest, 0777);
269 umask($store_umask);
270 }
271
272 # copy the files
273 foreach my $file (@srcfiles) {
274
275 if (!-e $file) {
276 print STDERR "util::cp_r $file does not exist\n";
277
278 } elsif (-d $file) {
279 # make the new directory
280 my ($filename) = $file =~ /([^\\\/]*)$/;
281 $dest = &util::filename_cat ($dest, $filename);
282 my $store_umask = umask(0002);
283 mkdir ($dest, 0777);
284 umask($store_umask);
285
286 # get the contents of this directory
287 if (!opendir (INDIR, $file)) {
288 print STDERR "util::cp_r could not open directory $file\n";
289 } else {
290 my @filedir = readdir (INDIR);
291 closedir (INDIR);
292 foreach my $f (@filedir) {
293 next if $f =~ /^\.\.?$/;
294
295 # copy all the files in this directory, but not directories
296 my $ff = &util::filename_cat ($file, $f);
297 if (-f $ff) {
298 &cp($ff, $dest);
299 #&cp_r ($ff, $dest);
300 }
301 }
302 }
303
304 } else {
305 &cp($file, $dest);
306 }
307 }
308}
309
[721]310sub mk_dir {
311 my ($dir) = @_;
312
[836]313 my $store_umask = umask(0002);
314 my $mkdir_ok = mkdir ($dir, 0777);
315 umask($store_umask);
316
317 if (!$mkdir_ok)
318 {
[721]319 print STDERR "util::mk_dir could not create directory $dir\n";
320 return;
321 }
322}
323
[1046]324# in case anyone cares - I did some testing (using perls Benchmark module)
325# on this subroutine against File::Path::mkpath (). mk_all_dir() is apparently
326# slightly faster (surprisingly) - Stefan.
[4]327sub mk_all_dir {
328 my ($dir) = @_;
329
330 # use / for the directory separator, remove duplicate and
331 # trailing slashes
332 $dir=~s/[\\\/]+/\//g;
333 $dir=~s/[\\\/]+$//;
334
335 # make sure the cache directory exists
336 my $dirsofar = "";
337 my $first = 1;
[8716]338 foreach my $dirname (split ("/", $dir)) {
[4]339 $dirsofar .= "/" unless $first;
340 $first = 0;
341
342 $dirsofar .= $dirname;
343
344 next if $dirname =~ /^(|[a-z]:)$/i;
[836]345 if (!-e $dirsofar)
346 {
347 my $store_umask = umask(0002);
348 my $mkdir_ok = mkdir ($dirsofar, 0777);
349 umask($store_umask);
350 if (!$mkdir_ok)
351 {
352 print STDERR "util::mk_all_dir could not create directory $dirsofar\n";
353 return;
354 }
355 }
[4]356 }
357}
358
[619]359# make hard link to file if supported by OS, otherwise copy the file
360sub hard_link {
[18463]361 my ($src, $dest, $verbosity) = @_;
[4]362
[619]363 # remove trailing slashes from source and destination files
364 $src =~ s/[\\\/]+$//;
365 $dest =~ s/[\\\/]+$//;
366
367 # a few sanity checks
[812]368 if (-e $dest) {
369 # destination file already exists
370 return;
371 }
372 elsif (!-e $src) {
[619]373 print STDERR "util::hard_link source file $src does not exist\n";
[3628]374 return 1;
[619]375 }
376 elsif (-d $src) {
377 print STDERR "util::hard_link source $src is a directory\n";
[3628]378 return 1;
[619]379 }
380
381 my $dest_dir = &File::Basename::dirname($dest);
382 mk_all_dir($dest_dir) if (!-e $dest_dir);
383
[5494]384 # link not supported on windows 9x
385 if (($ENV{'GSDLOS'} =~ /^windows$/i) && (Win32::FsType() !~ /^ntfs$/i)) {
[14365]386 &File::Copy::copy ($src, $dest);
387
388 } elsif (!link($src, $dest)) {
[18463]389 if ((!defined $verbosity) || ($verbosity>2)) {
390 print STDERR "util::hard_link: unable to create hard link. ";
391 print STDERR " Copying file: $src -> $dest\n";
392 }
[14365]393 &File::Copy::copy ($src, $dest);
[619]394 }
[3628]395 return 0;
[619]396}
397
[2193]398# make soft link to file if supported by OS, otherwise copy file
[721]399sub soft_link {
[15165]400 my ($src, $dest, $ensure_paths_absolute) = @_;
[619]401
[721]402 # remove trailing slashes from source and destination files
403 $src =~ s/[\\\/]+$//;
404 $dest =~ s/[\\\/]+$//;
[619]405
[15165]406 # Ensure file paths are absolute IF requested to do so
407 # Soft_linking didn't work for relative paths
408 if(defined $ensure_paths_absolute && $ensure_paths_absolute) {
409 # We need to ensure that the src file is the absolute path
410 # See http://perldoc.perl.org/File/Spec.html
411 if(!File::Spec->file_name_is_absolute( $src )) { # it's relative
412 $src = File::Spec->rel2abs($src); # make absolute
413 }
414 # Might as well ensure that the destination file's absolute path is used
415 if(!File::Spec->file_name_is_absolute( $dest )) {
416 $dest = File::Spec->rel2abs($dest); # make absolute
417 }
418 }
419
[721]420 # a few sanity checks
421 if (!-e $src) {
422 print STDERR "util::soft_link source file $src does not exist\n";
423 return 0;
424 }
[619]425
[721]426 my $dest_dir = &File::Basename::dirname($dest);
427 mk_all_dir($dest_dir) if (!-e $dest_dir);
[14365]428
[2193]429 if ($ENV{'GSDLOS'} =~ /^windows$/i) {
[14365]430 # symlink not supported on windows
431 &File::Copy::copy ($src, $dest);
[2193]432
433 } elsif (!eval {symlink($src, $dest)}) {
[2974]434 print STDERR "util::soft_link: unable to create soft link.\n";
[721]435 return 0;
436 }
437
438 return 1;
439}
440
441
442
443
[4]444# updates a copy of a directory in some other part of the filesystem
445# verbosity settings are: 0=low, 1=normal, 2=high
446# both $fromdir and $todir should be absolute paths
447sub cachedir {
448 my ($fromdir, $todir, $verbosity) = @_;
449 $verbosity = 1 unless defined $verbosity;
450
451 # use / for the directory separator, remove duplicate and
452 # trailing slashes
453 $fromdir=~s/[\\\/]+/\//g;
454 $fromdir=~s/[\\\/]+$//;
455 $todir=~s/[\\\/]+/\//g;
456 $todir=~s/[\\\/]+$//;
457
458 &mk_all_dir ($todir);
459
460 # get the directories in ascending order
461 if (!opendir (FROMDIR, $fromdir)) {
462 print STDERR "util::cachedir could not read directory $fromdir\n";
463 return;
464 }
465 my @fromdir = grep (!/^\.\.?$/, sort(readdir (FROMDIR)));
466 closedir (FROMDIR);
467
468 if (!opendir (TODIR, $todir)) {
469 print STDERR "util::cacedir could not read directory $todir\n";
470 return;
471 }
472 my @todir = grep (!/^\.\.?$/, sort(readdir (TODIR)));
473 closedir (TODIR);
474
475 my $fromi = 0;
476 my $toi = 0;
477
478 while ($fromi < scalar(@fromdir) || $toi < scalar(@todir)) {
479# print "fromi: $fromi toi: $toi\n";
480
481 # see if we should delete a file/directory
482 # this should happen if the file/directory
483 # is not in the from list or if its a different
484 # size, or has an older timestamp
485 if ($toi < scalar(@todir)) {
486 if (($fromi >= scalar(@fromdir)) ||
487 ($todir[$toi] lt $fromdir[$fromi] ||
488 ($todir[$toi] eq $fromdir[$fromi] &&
489 &differentfiles("$fromdir/$fromdir[$fromi]","$todir/$todir[$toi]",
490 $verbosity)))) {
491
492 # the files are different
493 &rm_r("$todir/$todir[$toi]");
494 splice(@todir, $toi, 1); # $toi stays the same
495
496 } elsif ($todir[$toi] eq $fromdir[$fromi]) {
497 # the files are the same
498 # if it is a directory, check its contents
499 if (-d "$todir/$todir[$toi]") {
500 &cachedir ("$fromdir/$fromdir[$fromi]",
501 "$todir/$todir[$toi]", $verbosity);
502 }
503
504 $toi++;
505 $fromi++;
506 next;
507 }
508 }
509
510 # see if we should insert a file/directory
511 # we should insert a file/directory if there
512 # is no tofiles left or if the tofile does not exist
513 if ($fromi < scalar(@fromdir) && ($toi >= scalar(@todir) ||
514 $todir[$toi] gt $fromdir[$fromi])) {
515 &cp_r ("$fromdir/$fromdir[$fromi]", "$todir/$fromdir[$fromi]");
516 splice (@todir, $toi, 0, $fromdir[$fromi]);
517
518 $toi++;
519 $fromi++;
520 }
521 }
522}
523
524# this function returns -1 if either file is not found
525# assumes that $file1 and $file2 are absolute file names or
526# in the current directory
527# $file2 is allowed to be newer than $file1
528sub differentfiles {
529 my ($file1, $file2, $verbosity) = @_;
530 $verbosity = 1 unless defined $verbosity;
531
532 $file1 =~ s/\/+$//;
533 $file2 =~ s/\/+$//;
534
535 my ($file1name) = $file1 =~ /\/([^\/]*)$/;
536 my ($file2name) = $file2 =~ /\/([^\/]*)$/;
537
538 return -1 unless (-e $file1 && -e $file2);
539 if ($file1name ne $file2name) {
540 print STDERR "filenames are not the same\n" if ($verbosity >= 2);
541 return 1;
542 }
543
[8716]544 my @file1stat = stat ($file1);
545 my @file2stat = stat ($file2);
[4]546
547 if (-d $file1) {
548 if (! -d $file2) {
549 print STDERR "one file is a directory\n" if ($verbosity >= 2);
550 return 1;
551 }
552 return 0;
553 }
554
555 # both must be regular files
556 unless (-f $file1 && -f $file2) {
557 print STDERR "one file is not a regular file\n" if ($verbosity >= 2);
558 return 1;
559 }
560
561 # the size of the files must be the same
562 if ($file1stat[7] != $file2stat[7]) {
563 print STDERR "different sized files\n" if ($verbosity >= 2);
564 return 1;
565 }
566
567 # the second file cannot be older than the first
568 if ($file1stat[9] > $file2stat[9]) {
569 print STDERR "file is older\n" if ($verbosity >= 2);
570 return 1;
571 }
572
573 return 0;
574}
575
576
[16266]577sub get_tmp_filename
578{
579 my $file_ext = shift(@_) || undef;
580
581 my $opt_dot_file_ext = (defined $file_ext) ? ".$file_ext" : "";
582
[2795]583 my $tmpdir = filename_cat($ENV{'GSDLHOME'}, "tmp");
[4]584 &mk_all_dir ($tmpdir) unless -e $tmpdir;
585
586 my $count = 1000;
587 my $rand = int(rand $count);
[16266]588 my $full_tmp_filename = &filename_cat($tmpdir, "F$rand$opt_dot_file_ext");
589
590 while (-e $full_tmp_filename) {
[4]591 $rand = int(rand $count);
[16266]592 $full_tmp_filename = &filename_cat($tmpdir, "F$rand$opt_dot_file_ext");
[4]593 $count++;
594 }
[16266]595
596 return $full_tmp_filename;
[4]597}
598
[21218]599sub get_toplevel_tmp_dir
600{
601 return filename_cat($ENV{'GSDLHOME'}, "tmp");
602}
603
604
[17512]605sub filename_to_regex {
606 my $filename = shift (@_);
[4]607
[17512]608 # need to put single backslash back to double so that regex works
609 if ($ENV{'GSDLOS'} =~ /^windows$/i) {
610 $filename =~ s/\\/\\\\/g;
611 }
612 return $filename;
613}
614
[4]615sub filename_cat {
[7507]616 my $first_file = shift(@_);
[4]617 my (@filenames) = @_;
[10146]618
[16266]619# Useful for debugging
620# -- might make sense to call caller(0) rather than (1)??
621# my ($cpackage,$cfilename,$cline,$csubr,$chas_args,$cwantarray) = caller(1);
[15113]622# print STDERR "Calling method; $cfilename:$cline $cpackage->$csubr\n";
[18913]623
624 # If first_file is not null or empty, then add it back into the list
625 if (defined $first_file && $first_file =~ /\S/) {
[7507]626 unshift(@filenames, $first_file);
627 }
628
[4]629 my $filename = join("/", @filenames);
630
631 # remove duplicate slashes and remove the last slash
[488]632 if ($ENV{'GSDLOS'} =~ /^windows$/i) {
633 $filename =~ s/[\\\/]+/\\/g;
634 } else {
[836]635 $filename =~ s/[\/]+/\//g;
636 # DB: want a filename abc\de.html to remain like this
[488]637 }
638 $filename =~ s/[\\\/]$//;
[4]639
640 return $filename;
641}
642
[21413]643
644sub pathname_cat {
645 my $first_path = shift(@_);
646 my (@pathnames) = @_;
647
648 # If first_path is not null or empty, then add it back into the list
649 if (defined $first_path && $first_path =~ /\S/) {
650 unshift(@pathnames, $first_path);
651 }
652
[21425]653 my $join_char;
[21413]654 if ($ENV{'GSDLOS'} =~ /^windows$/i) {
655 $join_char = ";";
656 } else {
657 $join_char = ":";
658 }
659
660 my $pathname = join($join_char, @pathnames);
661
662 # remove duplicate slashes
663 if ($ENV{'GSDLOS'} =~ /^windows$/i) {
664 $pathname =~ s/[\\\/]+/\\/g;
665 } else {
666 $pathname =~ s/[\/]+/\//g;
667 # DB: want a pathname abc\de.html to remain like this
668 }
669
670 return $pathname;
671}
672
673
[19616]674sub tidy_up_oid {
675 my ($OID) = @_;
676 if ($OID =~ /\./) {
677 print STDERR "Warning, identifier $OID contains periods (.), removing them\n";
678 $OID =~ s/\.//g; #remove any periods
679 }
680 if ($OID =~ /^\s.*\s$/) {
681 print STDERR "Warning, identifier $OID starts or ends with whitespace. Removing it\n";
682 # remove starting and trailing whitespace
683 $OID =~ s/^\s+//;
684 $OID =~ s/\s+$//;
685 }
686 if ($OID =~ /^[\d]*$/) {
687 print STDERR "Warning, identifier $OID contains only digits. Prepending 'D'.\n";
688 $OID = "D" . $OID;
689 }
690
691 return $OID;
692}
[10212]693sub envvar_prepend {
694 my ($var,$val) = @_;
695
[16404]696 # do not prepend any value/path that's already in the environment variable
[16442]697 if ($ENV{'GSDLOS'} =~ /^windows$/i)
698 {
699 my $escaped_val = $val;
700 $escaped_val =~ s/\\/\\\\/g; # escape any Windows backslashes for upcoming regex
701 if($ENV{$var} !~ m/$escaped_val/) {
702 $ENV{$var} = "$val;".$ENV{$var};
[16404]703 }
[16442]704 }
705 else {
706 if($ENV{$var} !~ m/$val/) {
707 $ENV{$var} = "$val:".$ENV{$var};
[16404]708 }
[10212]709 }
710}
711
712sub envvar_append {
713 my ($var,$val) = @_;
714
[16404]715 # do not append any value/path that's already in the environment variable
[16442]716 if ($ENV{'GSDLOS'} =~ /^windows$/i)
717 {
718 my $escaped_val = $val;
719 $escaped_val =~ s/\\/\\\\/g; # escape any Windows backslashes for upcoming regex
720 if($ENV{$var} !~ m/$escaped_val/) {
[16404]721 $ENV{$var} .= ";$val";
722 }
[16442]723 }
724 else {
725 if($ENV{$var} !~ m/$val/) {
[16404]726 $ENV{$var} .= ":$val";
727 }
[16442]728 }
[10212]729}
730
[16442]731
[16380]732# splits a filename into a prefix and a tail extension using the tail_re, or
733# if that fails, splits on the file_extension . (dot)
734sub get_prefix_and_tail_by_regex {
[10212]735
[16380]736 my ($filename,$tail_re) = @_;
737
738 my ($file_prefix,$file_ext) = ($filename =~ m/^(.*?)($tail_re)$/);
739 if ((!defined $file_prefix) || (!defined $file_ext)) {
740 ($file_prefix,$file_ext) = ($filename =~ m/^(.*)(\..*?)$/);
741 }
742
743 return ($file_prefix,$file_ext);
744}
745
746# get full path and file only path from a base_dir (which may be empty) and
747# file (which may contain directories)
748sub get_full_filenames {
749 my ($base_dir, $file) = @_;
750
751 my $filename_full_path = $file;
752 # add on directory if present
753 $filename_full_path = &util::filename_cat ($base_dir, $file) if $base_dir =~ /\S/;
754
755 my $filename_no_path = $file;
756
757 # remove directory if present
758 $filename_no_path =~ s/^.*[\/\\]//;
759 return ($filename_full_path, $filename_no_path);
760}
761
[8682]762# returns the path of a file without the filename -- ie. the directory the file is in
763sub filename_head {
764 my $filename = shift(@_);
765
766 if ($ENV{'GSDLOS'} =~ /^windows$/i) {
767 $filename =~ s/[^\\\\]*$//;
768 }
769 else {
770 $filename =~ s/[^\\\/]*$//;
771 }
772
773 return $filename;
774}
775
776
[1454]777# returns 1 if filename1 and filename2 point to the same
778# file or directory
779sub filenames_equal {
780 my ($filename1, $filename2) = @_;
781
782 # use filename_cat to clean up trailing slashes and
783 # multiple slashes
784 $filename1 = filename_cat ($filename1);
[2516]785 $filename2 = filename_cat ($filename2);
[1454]786
787 # filenames not case sensitive on windows
788 if ($ENV{'GSDLOS'} =~ /^windows$/i) {
789 $filename1 =~ tr/[A-Z]/[a-z]/;
790 $filename2 =~ tr/[A-Z]/[a-z]/;
791 }
792 return 1 if $filename1 eq $filename2;
793 return 0;
794}
795
[10281]796sub filename_within_collection
797{
798 my ($filename) = @_;
799
800 my $collect_dir = $ENV{'GSDLCOLLECTDIR'};
801
802 if (defined $collect_dir) {
803 my $dirsep = &util::get_dirsep();
804 if ($collect_dir !~ m/$dirsep$/) {
805 $collect_dir .= $dirsep;
806 }
807
808 $collect_dir =~ s/\\/\\\\/g; # escape DOS style file separator
809
[15875]810 # if from within GSDLCOLLECTDIR, then remove directory prefix
811 # so source_filename is realative to it. This is done to aid
812 # portability, i.e. the collection can be moved to somewhere
813 # else on the file system and the archives directory will still
814 # work. This is needed, for example in the applet version of
815 # GLI where GSDLHOME/collect on the server will be different to
816 # the collect directory of the remove user. Of course,
817 # GSDLCOLLECTDIR subsequently needs to be put back on to turn
818 # it back into a full pathname.
819
[10281]820 if ($filename =~ /^$collect_dir(.*)$/) {
821 $filename = $1;
822 }
823 }
824
825 return $filename;
826}
827
[18441]828sub filename_is_absolute
829{
830 my ($filename) = @_;
831
832 if ($ENV{'GSDLOS'} =~ /^windows$/i) {
833 return ($filename =~ m/^(\w:)?\\/);
834 }
835 else {
836 return ($filename =~ m/^\//);
837 }
838}
839
840
[17572]841## @method make_absolute()
842#
843# Ensure the given file path is absolute in respect to the given base path.
844#
845# @param $base_dir A string denoting the base path the given dir must be
846# absolute to.
847# @param $dir The directory to be made absolute as a string. Note that the
848# dir may already be absolute, in which case it will remain
849# unchanged.
850# @return The now absolute form of the directory as a string.
851#
852# @author John Thompson, DL Consulting Ltd.
853# @copy 2006 DL Consulting Ltd.
854#
855#used in buildcol.pl, doesn't work for all cases --kjdon
856sub make_absolute {
857
858 my ($base_dir, $dir) = @_;
[18441]859### print STDERR "dir = $dir\n";
[17572]860 $dir =~ s/[\\\/]+/\//g;
861 $dir = $base_dir . "/$dir" unless ($dir =~ m|^(\w:)?/|);
862 $dir =~ s|^/tmp_mnt||;
863 1 while($dir =~ s|/[^/]*/\.\./|/|g);
864 $dir =~ s|/[.][.]?/|/|g;
865 $dir =~ tr|/|/|s;
[18441]866### print STDERR "dir = $dir\n";
[17572]867
868 return $dir;
869}
870## make_absolute() ##
[10281]871
[7929]872sub get_dirsep {
873
874 if ($ENV{'GSDLOS'} =~ /^windows$/i) {
875 return "\\";
876 } else {
877 return "\/";
878 }
879}
880
[619]881sub get_os_dirsep {
[4]882
[619]883 if ($ENV{'GSDLOS'} =~ /^windows$/i) {
884 return "\\\\";
885 } else {
886 return "\\\/";
887 }
888}
889
890sub get_re_dirsep {
891
892 return "\\\\|\\\/";
893}
894
895
[15003]896sub get_dirsep_tail {
897 my ($filename) = @_;
898
899 # returns last part of directory or filename
900 # On unix e.g. a/b.d => b.d
901 # a/b/c => c
902
[15088]903 my $dirsep = get_re_dirsep();
904 my @dirs = split (/$dirsep/, $filename);
905 my $tail = pop @dirs;
[15003]906
[15088]907 # - caused problems under windows
908 #my ($tail) = ($filename =~ m/^(?:.*?$dirsep)?(.*?)$/);
909
[15003]910 return $tail;
911}
912
913
[4]914# if this is running on windows we want binaries to end in
915# .exe, otherwise they don't have to end in any extension
916sub get_os_exe {
917 return ".exe" if $ENV{'GSDLOS'} =~ /^windows$/i;
918 return "";
919}
920
921
[86]922# test to see whether this is a big or little endian machine
[15713]923sub is_little_endian
924{
925 # To determine the name of the operating system, the variable $^O is a cheap alternative to pulling it out of the Config module;
926 # 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
927 # Otherwise, it's little endian
928
929 #return 0 if $^O =~ /^darwin$/i;
[17714]930 #return 0 if $ENV{'GSDLOS'} =~ /^darwin$/i;
931
932 # Going back to stating exactly whether the machine is little endian
933 # or big endian, without any special case for Macs. Since for rata it comes
934 # back with little endian and for shuttle with bigendian.
[15713]935 return (ord(substr(pack("s",1), 0, 1)) == 1);
[86]936}
[4]937
[86]938
[135]939# will return the collection name if successful, "" otherwise
940sub use_collection {
[1454]941 my ($collection, $collectdir) = @_;
[135]942
[1454]943 if (!defined $collectdir || $collectdir eq "") {
944 $collectdir = &filename_cat ($ENV{'GSDLHOME'}, "collect");
945 }
946
[135]947 # get and check the collection
948 if (!defined($collection) || $collection eq "") {
949 if (defined $ENV{'GSDLCOLLECTION'}) {
950 $collection = $ENV{'GSDLCOLLECTION'};
951 } else {
[2359]952 print STDOUT "No collection specified\n";
[135]953 return "";
954 }
955 }
956
957 if ($collection eq "modelcol") {
[2359]958 print STDOUT "You can't use modelcol.\n";
[135]959 return "";
960 }
961
962 # make sure the environment variables GSDLCOLLECTION and GSDLCOLLECTDIR
963 # are defined
[17204]964 $ENV{'GSDLCOLLECTION'} = $collection;
[1454]965 $ENV{'GSDLCOLLECTDIR'} = &filename_cat ($collectdir, $collection);
[135]966
967 # make sure this collection exists
968 if (!-e $ENV{'GSDLCOLLECTDIR'}) {
[2359]969 print STDOUT "Invalid collection ($collection).\n";
[135]970 return "";
971 }
972
973 # everything is ready to go
974 return $collection;
975}
976
[21207]977sub get_current_collection_name {
978 return $ENV{'GSDLCOLLECTION'};
979}
[14926]980
981
982# will return the collection name if successful, "" otherwise.
983# Like use_collection (above) but for greenstone 3 (taking account of site level)
984
985sub use_site_collection {
986 my ($site, $collection, $collectdir) = @_;
987
988 if (!defined $collectdir || $collectdir eq "") {
989 die "GSDL3HOME not set.\n" unless defined $ENV{'GSDL3HOME'};
990 $collectdir = &filename_cat ($ENV{'GSDL3HOME'}, "sites", $site, "collect");
991 }
992
993 # collectdir explicitly set by this point (using $site variable if required).
994 # Can call "old" gsdl2 use_collection now.
995
996 return use_collection($collection,$collectdir);
997}
998
999
1000
[15018]1001sub locate_config_file
1002{
1003 my ($file) = @_;
1004
1005 my $locations = locate_config_files($file);
1006
1007 return shift @$locations; # returns undef if 'locations' is empty
1008}
1009
1010
1011sub locate_config_files
1012{
1013 my ($file) = @_;
1014
1015 my @locations = ();
1016
1017 if (-e $file) {
1018 # Clearly specified (most likely full filename)
1019 # No need to hunt in 'etc' directories, return value unchanged
1020 push(@locations,$file);
1021 }
1022 else {
1023 # Check for collection specific one before looking in global GSDL 'etc'
[16969]1024 if (defined $ENV{'GSDLCOLLECTDIR'} && $ENV{'GSDLCOLLECTDIR'} ne "") {
1025 my $test_collect_etc_filename
1026 = &util::filename_cat($ENV{'GSDLCOLLECTDIR'},"etc", $file);
1027
1028 if (-e $test_collect_etc_filename) {
1029 push(@locations,$test_collect_etc_filename);
1030 }
[15018]1031 }
1032 my $test_main_etc_filename
1033 = &util::filename_cat($ENV{'GSDLHOME'},"etc", $file);
1034 if (-e $test_main_etc_filename) {
1035 push(@locations,$test_main_etc_filename);
1036 }
1037 }
1038
1039 return \@locations;
1040}
1041
1042
[9955]1043sub hyperlink_text
1044{
1045 my ($text) = @_;
1046
1047 $text =~ s/(http:\/\/[^\s]+)/<a href=\"$1\">$1<\/a>/mg;
1048 $text =~ s/(^|\s+)(www\.(\w|\.)+)/<a href=\"http:\/\/$2\">$2<\/a>/mg;
1049
1050 return $text;
1051}
1052
1053
[16436]1054# A method to check if a directory is empty (note that an empty directory still has non-zero size!!!)
1055# Code is from http://episteme.arstechnica.com/eve/forums/a/tpc/f/6330927813/m/436007700831
1056sub is_dir_empty
1057{
1058 my ($path) = @_;
1059 opendir DIR, $path;
1060 while(my $entry = readdir DIR) {
1061 next if($entry =~ /^\.\.?$/);
1062 closedir DIR;
1063 return 0;
1064 }
1065 closedir DIR;
1066 return 1;
1067}
1068
[18337]1069# Returns the given filename converted using either URL encoding or base64
1070# encoding, as specified by $rename_method. If the given filename has no suffix
[20413]1071# (if it is just the tailname), then $no_suffix should be some defined value.
1072# rename_method can be url, none, base64
[18319]1073sub rename_file {
[18337]1074 my ($filename, $rename_method, $no_suffix) = @_;
[18329]1075
[18337]1076 if(!$filename) { # undefined or empty string
[18329]1077 return $filename;
1078 }
[18319]1079
[20413]1080 if (!$rename_method) {
1081 print STDERR "WARNING: no file renaming method specified. Defaulting to using URL encoding...\n";
1082 # Debugging information
1083 my ($cpackage,$cfilename,$cline,$csubr,$chas_args,$cwantarray) = caller(1);
1084 print STDERR "Called from method: $cfilename:$cline $cpackage->$csubr\n";
1085 $rename_method = "url";
1086 } elsif($rename_method eq "none") {
1087 return $filename; # would have already been renamed
1088 }
1089
[19762]1090 # No longer replace spaces with underscores, since underscores mess with incremental rebuild
1091 ### Replace spaces with underscore. Do this first else it can go wrong below when getting tailname
1092 ###$filename =~ s/ /_/g;
[18337]1093
1094 my ($tailname,$dirname,$suffix);
1095 if($no_suffix) { # given a tailname, no suffix
1096 ($tailname,$dirname) = File::Basename::fileparse($filename);
1097 }
1098 else {
1099 ($tailname,$dirname,$suffix) = File::Basename::fileparse($filename, "\\.(?:[^\\.]+?)\$");
1100 }
[18400]1101 $suffix = "" if !$suffix;
[18337]1102
[20413]1103 if ($rename_method eq "url") {
[18319]1104 $tailname = &unicode::url_encode($tailname);
1105 }
1106 elsif ($rename_method eq "base64") {
[18341]1107 $tailname = &unicode::base64_encode($tailname);
[18319]1108 $tailname =~ s/\s*//sg; # for some reason it adds spaces not just at end but also in middle
1109 }
[18326]1110
[18319]1111 $filename = "$tailname$suffix";
[18326]1112 $filename = "$dirname$filename" if ($dirname ne "./" && $dirname ne ".\\");
[18319]1113
1114 return $filename;
1115}
1116
[18657]1117# makes sure that the file has a gdb extension
1118sub rename_gdbm_file {
1119 my ($filename_no_ext) = @_;
1120
1121 my $new_filename = "$filename_no_ext.gdb";
1122 return if (-f $new_filename); # if gdb file exists, don't need to do anything
1123 # try ldb
1124 my $old_filename = "$filename_no_ext.ldb";
1125
1126 if (-f $old_filename) {
[19056]1127 print STDERR "Renaming $old_filename to $new_filename\n";
1128 rename ($old_filename, $new_filename)
1129 || print STDERR "Rename failed: $!\n";
[18657]1130 return;
1131 }
1132 # try bdb
1133 $old_filename = "$filename_no_ext.bdb";
1134 if (-f $old_filename) {
[19056]1135 print STDERR "Renaming $old_filename to $new_filename\n";
1136 rename ($old_filename, $new_filename)
1137 || print STDERR "Rename failed: $!\n";
[18657]1138 return;
1139 }
1140}
1141
1142
1143
[4]11441;
Note: See TracBrowser for help on using the repository browser.