root/main/trunk/greenstone2/perllib/util.pm @ 31475

Revision 31475, 61.3 KB (checked in by kjdon, 4 years ago)

block_filename moved to EncodingUtil? plugin

  • Property svn:keywords set to Author Date Id Revision
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;
29use FileUtils;
30
31use Encode;
32use Unicode::Normalize 'normalize';
33
34use File::Copy;
35use File::Basename;
36# Config for getting the perlpath in the recommended way, though it uses paths that are
37# hard-coded into the Config file that's generated upon configuring and compiling perl.
38# $^X works better in some cases to return the path to perl used to launch the script,
39# but if launched with plain "perl" (no full-path), that will be just what it returns.
40use Config;
41# New module for file related utility functions - intended as a
42# placeholder for an extension that allows a variety of different
43# filesystems (FTP, HTTP, SAMBA, WEBDav, HDFS etc)
44use FileUtils;
45
46if ($ENV{'GSDLOS'} =~ /^windows$/i) {
47    require Win32; # for working out Windows Long Filenames from Win 8.3 short filenames
48}
49
50# removes files (but not directories)
51sub rm {
52  warnings::warnif("deprecated", "util::rm() is deprecated, using FileUtils::removeFiles() instead");
53  return &FileUtils::removeFiles(@_);
54}
55
56# recursive removal
57sub filtered_rm_r {
58  warnings::warnif("deprecated", "util::filtered_rm_r() is deprecated, using FileUtils::removeFilesFiltered() instead");
59  return &FileUtils::removeFilesFiltered(@_);
60}
61
62# recursive removal
63sub rm_r {
64  warnings::warnif("deprecated", "util::rm_r() is deprecated, using FileUtils::removeFilesRecursive() instead");
65  return &FileUtils::removeFilesRecursive(@_);
66}
67
68# moves a file or a group of files
69sub mv {
70  warnings::warnif("deprecated", "util::mv() is deprecated, using FileUtils::moveFiles() instead");
71  return &FileUtils::moveFiles(@_);
72}
73
74# Move the contents of source directory into target directory
75# (as opposed to merely replacing target dir with the src dir)
76# This can overwrite any files with duplicate names in the target
77# but other files and folders in the target will continue to exist
78sub mv_dir_contents {
79  warnings::warnif("deprecated", "util::mv_dir_contents() is deprecated, using FileUtils::moveDirectoryContents() instead");
80  return &FileUtils::moveDirectoryContents(@_);
81}
82
83# copies a file or a group of files
84sub cp {
85  warnings::warnif("deprecated", "util::cp() is deprecated, using FileUtils::copyFiles() instead");
86  return &FileUtils::copyFiles(@_);
87}
88
89# recursively copies a file or group of files
90# syntax: cp_r (sourcefiles, destination directory)
91# destination must be a directory - to copy one file to
92# another use cp instead
93sub cp_r {
94  warnings::warnif("deprecated", "util::cp_r() is deprecated, using FileUtils::copyFilesrecursive() instead");
95  return &FileUtils::copyFilesRecursive(@_);
96}
97
98# recursively copies a file or group of files
99# syntax: cp_r (sourcefiles, destination directory)
100# destination must be a directory - to copy one file to
101# another use cp instead
102sub cp_r_nosvn {
103  warnings::warnif("deprecated", "util::cp_r_nosvn() is deprecated, using FileUtils::copyFilesRecursiveNoSVN() instead");
104  return &FileUtils::copyFilesRecursiveNoSVN(@_);
105}
106
107# copies a directory and its contents, excluding subdirectories, into a new directory
108sub cp_r_toplevel {
109  warnings::warnif("deprecated", "util::cp_r_toplevel() is deprecated, using FileUtils::recursiveCopyTopLevel() instead");
110  return &FileUtils::recursiveCopyTopLevel(@_);
111}
112
113sub mk_dir {
114  warnings::warnif("deprecated", "util::mk_dir() is deprecated, using FileUtils::makeDirectory() instead");
115  return &FileUtils::makeDirectory(@_);
116}
117
118# in case anyone cares - I did some testing (using perls Benchmark module)
119# on this subroutine against File::Path::mkpath (). mk_all_dir() is apparently
120# slightly faster (surprisingly) - Stefan.
121sub mk_all_dir {
122  warnings::warnif("deprecated", "util::mk_all_dir() is deprecated, using FileUtils::makeAllDirectories() instead");
123  return &FileUtils::makeAllDirectories(@_);
124}
125
126# make hard link to file if supported by OS, otherwise copy the file
127sub hard_link {
128  warnings::warnif("deprecated", "util::hard_link() is deprecated, using FileUtils::hardLink() instead");
129  return &FileUtils::hardLink(@_);
130}
131
132# make soft link to file if supported by OS, otherwise copy file
133sub soft_link {
134  warnings::warnif("deprecated", "util::soft_link() is deprecated, using FileUtils::softLink() instead");
135  return &FileUtils::softLink(@_);
136}
137
138# Primarily for filenames generated by processing
139# content of HTML files (which are mapped to UTF-8 internally)
140#
141# To turn this into an octet string that really exists on the file
142# system:
143# 1. don't need to do anything special for Unix-based systems
144#   (as underlying file system is byte-code)
145# 2. need to map to short DOS filenames for Windows
146
147sub utf8_to_real_filename
148{
149    my ($utf8_filename) = @_;
150
151    my $real_filename;
152
153    if (($ENV{'GSDLOS'} =~ m/^windows$/i) && ($^O ne "cygwin")) {
154    require Win32;
155
156    my $unicode_filename = decode("utf8",$utf8_filename);
157    $real_filename = Win32::GetShortPathName($unicode_filename);
158    }
159    else {
160    $real_filename = $utf8_filename;
161    }
162
163    return $real_filename;
164}
165
166sub raw_filename_to_unicode
167{
168    my ($directory, $raw_file, $filename_encoding ) = @_;
169       
170    my $unicode_filename = $raw_file;
171    if (($ENV{'GSDLOS'} =~ m/^windows$/i) && ($^O ne "cygwin")) {
172        # Try turning a short version to the long version
173        # If there are "funny" characters in the file name, that can't be represented in the ANSI code, then we will have a short weird version, eg E74~1.txt
174        $unicode_filename = &util::get_dirsep_tail(&util::upgrade_if_dos_filename(&FileUtils::filenameConcatenate($directory, $raw_file), 0));
175       
176       
177        if ($unicode_filename eq $raw_file) {
178        # This means the original filename *was* able to be encoded in the local ANSI file encoding (eg windows_1252), so now we turn it back to perl's unicode
179       
180        $unicode_filename = &Encode::decode(locale_fs => $unicode_filename);
181        }
182        # else This means we did have one of the funny filenames. the getLongPathName (used in upgrade_if_dos_filename) will return unicode, so we don't need to do anything more.
183       
184                   
185    } else {
186        # we had a utf-8 string, turn it into perl internal unicode
187        $unicode_filename = &Encode::decode("utf-8", $unicode_filename);
188   
189       
190    }
191    #Does the filename have url encoded chars in it?
192    if (&unicode::is_url_encoded($unicode_filename)) {
193        $unicode_filename = &unicode::url_decode($unicode_filename);
194    }
195   
196    # Normalise the filename to canonical composition - on mac, filenames use decopmposed form for accented chars
197    if ($ENV{'GSDLOS'} =~ m/^darwin$/i) {
198        $unicode_filename = normalize('C', $unicode_filename); # Composed form 'C'
199    }
200    return $unicode_filename;
201
202}
203sub fd_exists {
204  warnings::warnif("deprecated", "util::fd_exists() is deprecated, using FileUtils::fileTest() instead");
205  return &FileUtils::fileTest(@_);
206}
207
208sub file_exists {
209  warnings::warnif("deprecated", "util::file_exists() is deprecated, using FileUtils::fileExists() instead");
210  return &FileUtils::fileExists(@_);
211}
212
213sub dir_exists {
214  warnings::warnif("deprecated", "util::dir_exists() is deprecated, using FileUtils::directoryExists() instead");
215  return &FileUtils::directoryExists(@_);
216}
217
218# updates a copy of a directory in some other part of the filesystem
219# verbosity settings are: 0=low, 1=normal, 2=high
220# both $fromdir and $todir should be absolute paths
221sub cachedir {
222  warnings::warnif("deprecated", "util::cachedir() is deprecated, using FileUtils::synchronizeDirectories() instead");
223  return &FileUtils::synchronizeDirectories(@_);
224}
225
226# this function returns -1 if either file is not found
227# assumes that $file1 and $file2 are absolute file names or
228# in the current directory
229# $file2 is allowed to be newer than $file1
230sub differentfiles {
231  warnings::warnif("deprecated", "util::differentfiles() is deprecated, using FileUtils::differentFiles() instead");
232  return &FileUtils::differentFiles(@_);
233}
234
235
236# works out the temporary directory, including in the case where Greenstone is not writable
237# In that case, gs3-setup.bat would already have set the GS_TMP_OUTPUT_DIR temp variable
238sub determine_tmp_dir
239{
240    my $try_collect_dir = shift(@_) || 0;
241
242    my $tmp_dirname;
243    if(defined $ENV{'GS_TMP_OUTPUT_DIR'}) {
244        $tmp_dirname = $ENV{'GS_TMP_OUTPUT_DIR'};
245    } elsif($try_collect_dir && defined $ENV{'GSDLCOLLECTDIR'}) {
246        $tmp_dirname = $ENV{'GSDLCOLLECTDIR'};
247    } elsif(defined $ENV{'GSDLHOME'}) {
248        $tmp_dirname = $ENV{'GSDLHOME'};
249    } else {
250        return undef;
251    }
252   
253    if(!defined $ENV{'GS_TMP_OUTPUT_DIR'}) {
254        # test the tmp_dirname folder is writable, by trying to write out a file
255        # Unfortunately, cound not get if(-w $dirname) to work on directories on Windows
256            ## http://alvinalexander.com/blog/post/perl/perl-file-test-operators-reference-cheat-sheet (test file/dir writable)
257            ## http://www.makelinux.net/alp/083 (real and effective user IDs)
258       
259        my $tmp_test_file = &FileUtils::filenameConcatenate($tmp_dirname, "writability_test.tmp");
260        if (open (FOUT, ">$tmp_test_file")) {
261            close(FOUT);
262            &FileUtils::removeFiles($tmp_test_file);
263        } else { # location not writable, use TMP location
264            $tmp_dirname = &FileUtils::filenameConcatenate($ENV{'TMP'}, "greenstone");
265            $ENV{'GS_TMP_OUTPUT_DIR'} = $tmp_dirname; # store for next time
266        }
267    }
268   
269    $tmp_dirname = &FileUtils::filenameConcatenate($tmp_dirname, "tmp");
270    &FileUtils::makeAllDirectories ($tmp_dirname) unless -e $tmp_dirname;
271
272    return $tmp_dirname;
273}
274
275sub get_tmp_filename
276{
277    my $file_ext = shift(@_) || undef;
278
279    my $opt_dot_file_ext = "";
280    if (defined $file_ext) {
281    if ($file_ext !~ m/\./) {
282        # no dot, so needs one added in at start
283        $opt_dot_file_ext = ".$file_ext"
284    }
285    else {
286        # allow for "extensions" such as _metadata.txt to be handled
287        # gracefully
288        $opt_dot_file_ext = $file_ext;
289    }
290    }
291
292    my $tmpdir = &util::determine_tmp_dir(0);
293
294    my $count = 1000;
295    my $rand = int(rand $count);
296    my $full_tmp_filename = &FileUtils::filenameConcatenate($tmpdir, "F$rand$opt_dot_file_ext");
297
298    while (-e $full_tmp_filename) {
299    $rand = int(rand $count);
300    $full_tmp_filename = &FileUtils::filenameConcatenate($tmpdir, "F$rand$opt_dot_file_ext");
301    $count++;
302    }
303   
304    return $full_tmp_filename;
305}
306
307# These 2 are "static" variables used by the get_timestamped_tmp_folder() subroutine below and
308# belong with that function. They help ensure the timestamped tmp folders generated are unique.
309my $previous_timestamp = undef;
310my $previous_timestamp_f = 0; # frequency
311
312sub get_timestamped_tmp_folder
313{
314    my $tmp_dirname = &util::determine_tmp_dir(1);
315   
316    # add the timestamp into the path otherwise we can run into problems
317    # if documents have the same name
318    my $timestamp = time;   
319   
320    if (!defined $previous_timestamp || ($timestamp > $previous_timestamp)) {
321        $previous_timestamp_f = 0;
322        $previous_timestamp = $timestamp;
323    } else {
324        $previous_timestamp_f++;
325    }
326   
327    my $time_tmp_dirname = &FileUtils::filenameConcatenate($tmp_dirname, $timestamp);
328    $tmp_dirname = $time_tmp_dirname;   
329    my $i = $previous_timestamp_f;
330   
331    if($previous_timestamp_f > 0) {
332        $tmp_dirname = $time_tmp_dirname."_".$i;
333        $i++;
334    }
335    while (-e $tmp_dirname) {
336    $tmp_dirname = $time_tmp_dirname."_".$i;
337    $i++;
338    }
339    &FileUtils::makeDirectory($tmp_dirname);
340
341    return $tmp_dirname;
342}
343
344sub get_parent_folder
345{
346    my ($path) = @_;
347    my ($tailname, $dirname, $suffix)
348    = &File::Basename::fileparse($path, "\\.[^\\.]+\$");
349
350    return &FileUtils::sanitizePath($dirname);
351}
352
353sub get_timestamped_tmp_filename_in_collection
354{
355
356    my ($input_filename, $output_ext) = @_;
357    # derive tmp filename from input filename
358    my ($tailname, $dirname, $suffix)
359    = &File::Basename::fileparse($input_filename, "\\.[^\\.]+\$");
360
361    # softlink to collection tmp dir
362    my $tmp_dirname = &util::get_timestamped_tmp_folder();
363    $tmp_dirname = $dirname unless defined $tmp_dirname;
364
365    # following two steps copied from ConvertBinaryFile
366    # do we need them?? can't use them as is, as they use plugin methods.
367
368    #$tailname = $self->SUPER::filepath_to_utf8($tailname) unless &unicode::check_is_utf8($tailname);
369
370    # URLEncode this since htmls with images where the html filename is utf8 don't seem
371    # to work on Windows (IE or Firefox), as browsers are looking for filesystem-encoded
372    # files on the filesystem.
373    #$tailname = &util::rename_file($tailname, $self->{'file_rename_method'}, "without_suffix");
374    if (defined $output_ext) {
375    $output_ext = ".$output_ext"; # add the dot
376    } else {
377    $output_ext = $suffix;
378    }
379    $output_ext= lc($output_ext);
380    my $tmp_filename = &FileUtils::filenameConcatenate($tmp_dirname, "$tailname$output_ext");
381   
382    return $tmp_filename;
383}
384
385sub get_toplevel_tmp_dir
386{
387    return &FileUtils::filenameConcatenate($ENV{'GSDLHOME'}, "tmp");
388}
389
390
391sub get_collectlevel_tmp_dir
392{
393    my $tmp_dirname = &FileUtils::filenameConcatenate($ENV{'GSDLCOLLECTDIR'}, "tmp");
394    &FileUtils::makeDirectory($tmp_dirname) if (!-e $tmp_dirname);
395
396    return $tmp_dirname;
397}
398
399
400sub filename_to_regex {
401    my $filename = shift (@_);
402
403    # need to make single backslashes double so that regex works
404    $filename =~ s/\\/\\\\/g; # if ($ENV{'GSDLOS'} =~ /^windows$/i);   
405   
406    # note that the first part of a substitution is a regex, so RE chars need to be escaped,
407    # the second part of a substitution is not a regex, so for e.g. full-stop can be specified literally
408    $filename =~ s/\./\\./g; # in case there are extensions/other full stops, escape them
409    $filename =~ s@\(@\\(@g; # escape brackets
410    $filename =~ s@\)@\\)@g; # escape brackets
411    $filename =~ s@\[@\\[@g; # escape brackets
412    $filename =~ s@\]@\\]@g; # escape brackets
413   
414    return $filename;
415}
416
417sub unregex_filename {
418    my $filename = shift (@_);
419
420    # need to put doubled backslashes for regex back to single
421    $filename =~ s/\\\./\./g; # remove RE syntax for .
422    $filename =~ s@\\\(@(@g; # remove RE syntax for ( => "\(" turns into "("
423    $filename =~ s@\\\)@)@g; # remove RE syntax for ) => "\)" turns into ")"
424    $filename =~ s@\\\[@[@g; # remove RE syntax for [ => "\[" turns into "["
425    $filename =~ s@\\\]@]@g; # remove RE syntax for ] => "\]" turns into "]"
426   
427    # \\ goes to \
428    # This is the last step in reverse mirroring the order of steps in filename_to_regex()
429    $filename =~ s/\\\\/\\/g; # remove RE syntax for \   
430    return $filename;
431}
432
433sub filename_cat {
434  # I've disabled this warning for now, as every Greenstone perl
435  # script seems to make use of this function and so you drown in a
436  # sea of deprecated warnings [jmt12]
437#  warnings::warnif("deprecated", "util::filename_cat() is deprecated, using FileUtils::filenameConcatenate() instead");
438  return &FileUtils::filenameConcatenate(@_);
439}
440
441
442sub _pathname_cat {
443    my $join_char  = shift(@_);
444    my $first_path = shift(@_);
445    my (@pathnames) = @_;
446
447    # If first_path is not null or empty, then add it back into the list
448    if (defined $first_path && $first_path =~ /\S/) {
449    unshift(@pathnames, $first_path);
450    }
451
452    my $pathname = join($join_char, @pathnames);
453
454    # remove duplicate slashes
455    if ($join_char eq ";") {
456    $pathname =~ s/[\\\/]+/\\/g;
457    if ($^O eq "cygwin") {
458        # Once we've collapsed muliple (potentialy > 2) slashes
459        # For cygwin, actually want things double-backslahed
460        $pathname =~ s/\\/\\\\/g;
461    }
462
463    } else {
464    $pathname =~ s/[\/]+/\//g;
465    # DB: want a pathname abc\de.html to remain like this
466    }
467
468    return $pathname;
469}
470
471
472sub pathname_cat {
473    my (@pathnames) = @_;
474
475    my $join_char;
476    if (($ENV{'GSDLOS'} =~ /^windows$/i) && ($^O ne "cygwin")) {
477    $join_char = ";";
478    } else {
479    $join_char = ":";
480    }
481    return _pathname_cat($join_char,@pathnames);
482}
483
484
485sub javapathname_cat {
486    my (@pathnames) = @_;
487
488    my $join_char;
489
490    # Unlike pathname_cat() above, not interested if running in a Cygwin environment
491    # This is because the java we run is actually a native Windows executable
492
493    if (($ENV{'GSDLOS'} =~ /^windows$/i)) {
494    $join_char = ";";
495    } else {
496    $join_char = ":";
497    }
498    return _pathname_cat($join_char,@pathnames);
499}
500
501
502sub makeFilenameJavaCygwinCompatible
503{
504    my ($java_filename) = @_;
505
506    if ($^O eq "cygwin") {
507    # To be used with a Java program, but under Cygwin
508    # Because the java binary that is native to Windows, need to
509    # convert the Cygwin paths (i.e. Unix style) to be Windows
510    # compatible
511   
512    $java_filename = `cygpath -wp "$java_filename"`;
513    chomp($java_filename);
514    $java_filename =~ s%\\%\\\\%g;
515    }
516
517    return $java_filename;
518}
519
520sub tidy_up_oid {
521    my ($OID) = @_;
522    if ($OID =~ /[\.\/\\]/) {
523    print STDERR "Warning, identifier $OID contains periods or slashes(.\\\/), replacing them with _\n";
524    $OID =~ s/[\.\\\/]/_/g; #remove any periods
525    }
526    if ($OID =~ /^\s.*\s$/) {
527    print STDERR "Warning, identifier $OID starts or ends with whitespace. Removing it\n";
528    # remove starting and trailing whitespace
529    $OID =~ s/^\s+//;
530    $OID =~ s/\s+$//;
531    }
532    if ($OID =~ /^[\d]*$/) {
533    print STDERR "Warning, identifier $OID contains only digits. Prepending 'D'.\n";
534    $OID = "D" . $OID;
535    }       
536   
537    return $OID;
538}
539
540sub envvar_prepend {
541    my ($var,$val) = @_;
542
543    # 64 bit linux can't handle ";" as path separator, so make sure to set this to the right one for the OS
544##    my $pathsep = (defined $ENV{'GSDLOS'} && $ENV{'GSDLOS'} !~ m/windows/) ? ":" : ";";
545
546    # Rewritten above to make ":" the default (Windows is the special
547    # case, anything else 'unusual' such as Solaris etc is Unix)
548    my $pathsep = (defined $ENV{'GSDLOS'} && (($ENV{'GSDLOS'} =~ m/windows/) && ($^O ne "cygwin"))) ? ";" : ":";
549
550    # do not prepend any value/path that's already in the environment variable
551   
552    my $escaped_val = &filename_to_regex($val); # escape any backslashes and brackets for upcoming regex
553    if (!defined($ENV{$var})) {
554    $ENV{$var} = "$val";
555    }
556    elsif($ENV{$var} !~ m/$escaped_val/) {
557    $ENV{$var} = "$val".$pathsep.$ENV{$var};
558    }
559}
560
561sub envvar_append {
562    my ($var,$val) = @_;
563
564    # 64 bit linux can't handle ";" as path separator, so make sure to set this to the right one for the OS
565    my $pathsep = (defined $ENV{'GSDLOS'} && $ENV{'GSDLOS'} !~ m/windows/) ? ":" : ";";
566   
567    # do not append any value/path that's already in the environment variable
568
569    my $escaped_val = &filename_to_regex($val); # escape any backslashes and brackets for upcoming regex
570    if (!defined($ENV{$var})) {
571    $ENV{$var} = "$val";
572    }
573    elsif($ENV{$var} !~ m/$escaped_val/) {
574    $ENV{$var} = $ENV{$var}.$pathsep."$val";
575    }
576}
577
578
579
580# splits a filename into a prefix and a tail extension using the tail_re, or
581# if that fails, splits on the file_extension . (dot)
582sub get_prefix_and_tail_by_regex {
583
584    my ($filename,$tail_re) = @_;
585   
586    my ($file_prefix,$file_ext) = ($filename =~ m/^(.*?)($tail_re)$/);
587    if ((!defined $file_prefix) || (!defined $file_ext)) {
588    ($file_prefix,$file_ext) = ($filename =~ m/^(.*)(\..*?)$/);
589    }
590
591    return ($file_prefix,$file_ext);
592}
593
594# get full path and file only path from a base_dir (which may be empty) and
595# file (which may contain directories)
596sub get_full_filenames {
597    my ($base_dir, $file) = @_;
598   
599#    my ($cpackage,$cfilename,$cline,$csubr,$chas_args,$cwantarray) = caller(0);
600#    my ($lcfilename) = ($cfilename =~ m/([^\\\/]*)$/);
601#    print STDERR "** Calling method: $lcfilename:$cline $cpackage->$csubr\n";
602
603
604    my $filename_full_path = $file;
605    # add on directory if present
606    $filename_full_path = &FileUtils::filenameConcatenate($base_dir, $file) if $base_dir =~ /\S/;
607   
608    my $filename_no_path = $file;
609
610    # remove directory if present
611    $filename_no_path =~ s/^.*[\/\\]//;
612    return ($filename_full_path, $filename_no_path);
613}
614
615# returns the path of a file without the filename -- ie. the directory the file is in
616sub filename_head {
617    my $filename = shift(@_);
618
619    if (($ENV{'GSDLOS'} =~ /^windows$/i) && ($^O ne "cygwin")) {
620    $filename =~ s/[^\\\\]*$//;
621    }
622    else {
623    $filename =~ s/[^\\\/]*$//;
624    }
625
626    return $filename;
627}
628
629
630
631# returns 1 if filename1 and filename2 point to the same
632# file or directory
633sub filenames_equal {
634    my ($filename1, $filename2) = @_;
635
636    # use filename_cat to clean up trailing slashes and
637    # multiple slashes
638    $filename1 = &FileUtils::filenameConcatenate($filename1);
639    $filename2 = &FileUtils::filenameConcatenate($filename2);
640
641    # filenames not case sensitive on windows
642    if ($ENV{'GSDLOS'} =~ /^windows$/i) {
643    $filename1 =~ tr/[A-Z]/[a-z]/;
644    $filename2 =~ tr/[A-Z]/[a-z]/;
645    }
646    return 1 if $filename1 eq $filename2;
647    return 0;
648}
649
650# If filename is relative to within_dir, returns the relative path of filename to that directory
651# with slashes in the filename returned as they were in the original (absolute) filename.
652sub filename_within_directory
653{
654    my ($filename,$within_dir) = @_;
655   
656    if ($within_dir !~ m/[\/\\]$/) {
657    my $dirsep = &util::get_dirsep();
658    $within_dir .= $dirsep;
659    }
660   
661    $within_dir = &filename_to_regex($within_dir); # escape DOS style file separator and brackets   
662    if ($filename =~ m/^$within_dir(.*)$/) {
663    $filename = $1;
664    }
665   
666    return $filename;
667}
668
669# If filename is relative to within_dir, returns the relative path of filename to that directory in URL format.
670# Filename and within_dir can be any type of slashes, but will be compared as URLs (i.e. unix-style slashes).
671# The subpath returned will also be a URL type filename.
672sub filename_within_directory_url_format
673{
674    my ($filename,$within_dir) = @_;
675   
676    # convert parameters only to / slashes if Windows
677   
678    my $filename_urlformat = &filepath_to_url_format($filename);
679    my $within_dir_urlformat = &filepath_to_url_format($within_dir);
680
681    #if ($within_dir_urlformat !~ m/\/$/) {
682        # make sure directory ends with a slash
683        #$within_dir_urlformat .= "/";
684    #}
685   
686    my $within_dir_urlformat_re = &filename_to_regex($within_dir_urlformat); # escape any special RE characters, such as brackets
687   
688    #print STDERR "@@@@@ $filename_urlformat =~ $within_dir_urlformat_re\n";
689   
690    # dir prefix may or may not end with a slash (this is discarded when extracting the sub-filepath)
691    if ($filename_urlformat =~ m/^$within_dir_urlformat_re(?:\/)*(.*)$/) {
692        $filename_urlformat = $1;
693    }
694   
695    return $filename_urlformat;
696}
697
698# Convert parameter to use / slashes if Windows (if on Linux leave any \ as is,
699# since on Linux it doesn't represent a file separator but an escape char).
700sub filepath_to_url_format
701{
702    my ($filepath) = @_;
703    if (($ENV{'GSDLOS'} =~ /^windows$/i) && ($^O ne "cygwin")) {
704        # Only need to worry about Windows, as Unix style directories already in url-format
705        # Convert Windows style \ => /
706        $filepath =~ s@\\@/@g;     
707    }
708    return $filepath;
709}
710
711# regex filepaths on windows may include \\ as path separator. Convert \\ to /
712sub filepath_regex_to_url_format
713{
714    my ($filepath) = @_;
715    if (($ENV{'GSDLOS'} =~ /^windows$/i) && ($^O ne "cygwin")) {
716    # Only need to worry about Windows, as Unix style directories already in url-format
717    # Convert Windows style \\ => /
718    $filepath =~ s@\\\\@/@g;       
719    }
720    return $filepath;
721   
722}
723
724# Like File::Basename::fileparse, but expects filepath in url format (ie only / slash for dirsep)
725# and ignores trailing /
726# returns (file, dirs) dirs will be empty if no subdirs
727sub url_fileparse
728{
729    my ($filepath) = @_;
730    # remove trailing /
731    $filepath =~ s@/$@@;
732    if ($filepath !~ m@/@) {
733    return ($filepath, "");
734    }
735    my ($dirs, $file) = $filepath =~ m@(.+/)([^/]+)@;
736    return ($file, $dirs);
737   
738}
739
740
741sub filename_within_collection
742{
743    my ($filename) = @_;
744
745    my $collect_dir = $ENV{'GSDLCOLLECTDIR'};
746   
747    if (defined $collect_dir) {
748
749    # if from within GSDLCOLLECTDIR, then remove directory prefix
750    # so source_filename is realative to it.  This is done to aid
751    # portability, i.e. the collection can be moved to somewhere
752    # else on the file system and the archives directory will still
753    # work.  This is needed, for example in the applet version of
754    # GLI where GSDLHOME/collect on the server will be different to
755    # the collect directory of the remove user.  Of course,
756    # GSDLCOLLECTDIR subsequently needs to be put back on to turn
757    # it back into a full pathname.
758
759    $filename = filename_within_directory($filename,$collect_dir);
760    }
761   
762    return $filename;
763}
764
765sub prettyprint_file
766{
767    my ($base_dir,$file,$gli) = @_;
768
769    my $filename_full_path = &FileUtils::filenameConcatenate($base_dir,$file);
770
771    if (($ENV{'GSDLOS'} =~ m/^windows$/i) && ($^O ne "cygwin")) {
772    require Win32;
773
774    # For some reason base_dir in the form c:/a/b/c
775    # This leads to confusion later on, so turn it back into
776    # the more usual Windows form
777    $base_dir =~ s/\//\\/g;
778    my $long_base_dir = Win32::GetLongPathName($base_dir);
779    my $long_full_path = Win32::GetLongPathName($filename_full_path);
780
781    $file = filename_within_directory($long_full_path,$long_base_dir);
782    $file = encode("utf8",$file) if ($gli);
783    }
784
785    return $file;
786}
787
788
789sub upgrade_if_dos_filename
790{
791    my ($filename_full_path,$and_encode) = @_;
792
793    if (($ENV{'GSDLOS'} =~ m/^windows$/i) && ($^O ne "cygwin")) {
794    # Ensure any DOS-like filename, such as test~1.txt, has been upgraded
795    # to its long (Windows) version
796    my $long_filename = Win32::GetLongPathName($filename_full_path);
797    if (defined $long_filename) {
798       
799        $filename_full_path = $long_filename;
800    }
801    # Make sure initial drive letter is lower-case (to fit in with rest of Greenstone)
802    $filename_full_path =~ s/^(.):/\u$1:/;
803   
804    if ((defined $and_encode) && ($and_encode)) {
805        $filename_full_path = encode("utf8",$filename_full_path);
806    }
807    }
808
809    return $filename_full_path;
810}
811
812
813sub downgrade_if_dos_filename
814{
815    my ($filename_full_path) = @_;
816
817    if (($ENV{'GSDLOS'} =~ m/^windows$/i) && ($^O ne "cygwin")) {
818    require Win32;
819
820    # Ensure the given long Windows filename is in a form that can
821    # be opened by Perl => convert it to a short DOS-like filename
822
823    my $short_filename = Win32::GetShortPathName($filename_full_path);
824    if (defined $short_filename) {
825        $filename_full_path = $short_filename;
826    }
827    # Make sure initial drive letter is lower-case (to fit in
828    # with rest of Greenstone)
829    $filename_full_path =~ s/^(.):/\u$1:/;
830    }
831
832    return $filename_full_path;
833}
834
835
836sub filename_is_absolute
837{
838  warnings::warnif("deprecated", "util::filename_is_absolute() is deprecated, using FileUtils::isFilenameAbsolute() instead");
839  return &FileUtils::isFilenameAbsolute(@_);
840}
841
842
843## @method make_absolute()
844#
845#  Ensure the given file path is absolute in respect to the given base path.
846#
847#  @param  $base_dir A string denoting the base path the given dir must be
848#                    absolute to.
849#  @param  $dir The directory to be made absolute as a string. Note that the
850#               dir may already be absolute, in which case it will remain
851#               unchanged.
852#  @return The now absolute form of the directory as a string.
853#
854#  @author John Thompson, DL Consulting Ltd.
855#  @copy 2006 DL Consulting Ltd.
856#
857#used in buildcol.pl, doesn't work for all cases --kjdon
858sub make_absolute {
859   
860    my ($base_dir, $dir) = @_;
861###    print STDERR "dir = $dir\n";
862    $dir =~ s/[\\\/]+/\//g;
863    $dir = $base_dir . "/$dir" unless ($dir =~ m|^(\w:)?/|);
864    $dir =~ s|^/tmp_mnt||;
865    1 while($dir =~ s|/[^/]*/\.\./|/|g);
866    $dir =~ s|/[.][.]?/|/|g;
867    $dir =~ tr|/|/|s;
868###    print STDERR "dir = $dir\n";
869   
870    return $dir;
871}
872## make_absolute() ##
873
874sub get_dirsep {
875
876    if (($ENV{'GSDLOS'} =~ /^windows$/i) && ($^O ne "cygwin")) {
877    return "\\";
878    } else {
879    return "\/";
880    }
881}
882
883sub get_os_dirsep {
884
885    if (($ENV{'GSDLOS'} =~ /^windows$/i) && ($^O ne "cygwin")) {
886    return "\\\\";
887    } else {
888    return "\\\/";
889    }
890}
891
892sub get_re_dirsep {
893
894    return "\\\\|\\\/";
895}
896
897
898sub get_dirsep_tail {
899    my ($filename) = @_;
900   
901    # returns last part of directory or filename
902    # On unix e.g. a/b.d => b.d
903    #              a/b/c => c
904
905    my $dirsep = get_re_dirsep();
906    my @dirs = split (/$dirsep/, $filename);
907    my $tail = pop @dirs;
908
909    # - caused problems under windows
910    #my ($tail) = ($filename =~ m/^(?:.*?$dirsep)?(.*?)$/);
911
912    return $tail;
913}
914
915
916# if this is running on windows we want binaries to end in
917# .exe, otherwise they don't have to end in any extension
918sub get_os_exe {
919    return ".exe" if (($ENV{'GSDLOS'} =~ /^windows$/i) && ($^O ne "cygwin"));
920    return "";
921}
922
923
924# test to see whether this is a big or little endian machine
925sub is_little_endian
926{
927    # To determine the name of the operating system, the variable $^O is a cheap alternative to pulling it out of the Config module;
928    # 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
929    # Otherwise, it's little endian
930
931    #return 0 if $^O =~ /^darwin$/i;
932    #return 0 if $ENV{'GSDLOS'} =~ /^darwin$/i;
933   
934    # Going back to stating exactly whether the machine is little endian
935    # or big endian, without any special case for Macs. Since for rata it comes
936    # back with little endian and for shuttle with bigendian.
937    return (ord(substr(pack("s",1), 0, 1)) == 1);
938}
939
940
941# will return the collection name if successful, "" otherwise
942sub use_collection {
943    my ($collection, $collectdir) = @_;
944
945    if (!defined $collectdir || $collectdir eq "") {
946    $collectdir = &FileUtils::filenameConcatenate($ENV{'GSDLHOME'}, "collect");
947    }
948
949    if (!defined $ENV{'GREENSTONEHOME'}) { # for GS3, would have been defined in use_site_collection, to GSDL3HOME
950     $ENV{'GREENSTONEHOME'} = $ENV{'GSDLHOME'};
951    }
952
953    # get and check the collection
954    if (!defined($collection) || $collection eq "") {
955    if (defined $ENV{'GSDLCOLLECTION'}) {
956        $collection = $ENV{'GSDLCOLLECTION'};
957    } else {
958        print STDOUT "No collection specified\n";
959        return "";
960    }
961    }
962   
963    if ($collection eq "modelcol") {
964    print STDOUT "You can't use modelcol.\n";
965    return "";
966    }
967
968    # make sure the environment variables GSDLCOLLECTION and GSDLCOLLECTDIR
969    # are defined
970    $ENV{'GSDLCOLLECTION'} = $collection;
971    $ENV{'GSDLCOLLECTHOME'} = $collectdir;
972    $ENV{'GSDLCOLLECTDIR'} = &FileUtils::filenameConcatenate($collectdir, $collection);
973
974    # make sure this collection exists
975    if (!-e $ENV{'GSDLCOLLECTDIR'}) {
976    print STDOUT "Invalid collection ($collection).\n";
977    return "";
978    }
979
980    # everything is ready to go
981    return $collection;
982}
983
984sub get_current_collection_name {
985    return $ENV{'GSDLCOLLECTION'};
986}
987
988
989# will return the collection name if successful, "" otherwise. 
990# Like use_collection (above) but for greenstone 3 (taking account of site level)
991
992sub use_site_collection {
993    my ($site, $collection, $collectdir) = @_;
994
995    if (!defined $collectdir || $collectdir eq "") {
996    die "GSDL3HOME not set.\n" unless defined $ENV{'GSDL3HOME'};
997    $collectdir = &FileUtils::filenameConcatenate($ENV{'GSDL3HOME'}, "sites", $site, "collect");
998    }
999
1000    if (defined $ENV{'GSDL3HOME'}) {
1001    $ENV{'GREENSTONEHOME'} = $ENV{'GSDL3HOME'};     
1002    $ENV{'SITEHOME'} = &FileUtils::filenameConcatenate($ENV{'GREENSTONEHOME'}, "sites", $site);
1003    } elsif (defined $ENV{'GSDL3SRCHOME'}) {
1004    $ENV{'GREENSTONEHOME'} = &FileUtils::filenameConcatenate($ENV{'GSDL3SRCHOME'}, "web"); 
1005    $ENV{'SITEHOME'} = &FileUtils::filenameConcatenate($ENV{'GREENSTONEHOME'}, "sites", $site);
1006    } else {
1007    print STDERR "*** util::use_site_collection(). Warning: Neither GSDL3HOME nor GSDL3SRCHOME set.\n";
1008    }
1009
1010    # collectdir explicitly set by this point (using $site variable if required).
1011    # Can call "old" gsdl2 use_collection now.
1012
1013    return use_collection($collection,$collectdir);
1014}
1015
1016
1017
1018sub locate_config_file
1019{
1020    my ($file) = @_;
1021
1022    my $locations = locate_config_files($file);
1023
1024    return shift @$locations; # returns undef if 'locations' is empty
1025}
1026
1027
1028sub locate_config_files
1029{
1030    my ($file) = @_;
1031
1032    my @locations = ();
1033
1034    if (-e $file) {
1035    # Clearly specified (most likely full filename)
1036    # No need to hunt in 'etc' directories, return value unchanged
1037    push(@locations,$file);
1038    }
1039    else {
1040    # Check for collection specific one before looking in global GSDL 'etc'
1041    if (defined $ENV{'GSDLCOLLECTDIR'} && $ENV{'GSDLCOLLECTDIR'} ne "") {
1042        my $test_collect_etc_filename
1043        = &FileUtils::filenameConcatenate($ENV{'GSDLCOLLECTDIR'},"etc", $file);
1044       
1045        if (-e $test_collect_etc_filename) {
1046        push(@locations,$test_collect_etc_filename);
1047        }
1048    }
1049    my $test_main_etc_filename
1050        = &FileUtils::filenameConcatenate($ENV{'GSDLHOME'},"etc", $file);
1051    if (-e $test_main_etc_filename) {
1052        push(@locations,$test_main_etc_filename);
1053    }
1054    }
1055
1056    return \@locations;
1057}
1058
1059
1060sub hyperlink_text
1061{
1062    my ($text) = @_;
1063   
1064    $text =~ s/(http:\/\/[^\s]+)/<a href=\"$1\">$1<\/a>/mg;
1065    $text =~ s/(^|\s+)(www\.(\w|\.)+)/<a href=\"http:\/\/$2\">$2<\/a>/mg;
1066
1067    return $text;
1068}
1069
1070
1071# A method to check if a directory is empty (note that an empty directory still has non-zero size!!!)
1072# Code is from http://episteme.arstechnica.com/eve/forums/a/tpc/f/6330927813/m/436007700831
1073sub is_dir_empty {
1074  warnings::warnif("deprecated", "util::is_dir_empty() is deprecated, using FileUtils::isDirectoryEmpty() instead");
1075  return &FileUtils::isDirectoryEmpty(@_);
1076}
1077
1078# Returns the given filename converted using either URL encoding or base64
1079# encoding, as specified by $rename_method. If the given filename has no suffix
1080# (if it is just the tailname), then $no_suffix should be some defined value.
1081# rename_method can be url, none, base64
1082sub rename_file {
1083    my ($filename, $rename_method, $no_suffix)  = @_;
1084
1085    if(!$filename) { # undefined or empty string
1086    return $filename;
1087    }
1088
1089    if (!$rename_method) {
1090    print STDERR "WARNING: no file renaming method specified. Defaulting to using URL encoding...\n";
1091    # Debugging information
1092    # my ($cpackage,$cfilename,$cline,$csubr,$chas_args,$cwantarray) = caller(1);
1093    # print STDERR "Called from method: $cfilename:$cline $cpackage->$csubr\n";
1094    $rename_method = "url";
1095    } elsif($rename_method eq "none") {
1096    return $filename; # would have already been renamed
1097    }
1098
1099    # No longer replace spaces with underscores, since underscores mess with incremental rebuild
1100    ### Replace spaces with underscore. Do this first else it can go wrong below when getting tailname
1101    ###$filename =~ s/ /_/g;
1102
1103    my ($tailname,$dirname,$suffix);
1104    if($no_suffix) { # given a tailname, no suffix
1105    ($tailname,$dirname) = File::Basename::fileparse($filename);
1106    }
1107    else {
1108    ($tailname,$dirname,$suffix) = File::Basename::fileparse($filename, "\\.(?:[^\\.]+?)\$");
1109    }
1110    if (!$suffix) {
1111    $suffix = "";
1112    }
1113    # This breaks GLI matching extracted metadata to files in Enrich panel, as
1114    # original is eg .JPG while gsdlsourcefilename ends up .jpg
1115    # Not sure why it was done in first place...
1116    #else {
1117    #$suffix = lc($suffix);
1118    #}
1119
1120    if ($rename_method eq "url") {
1121    $tailname = &unicode::url_encode($tailname);
1122    }
1123    elsif ($rename_method eq "base64") {
1124    $tailname = &unicode::base64_encode($tailname);
1125    $tailname =~ s/\s*//sg;      # for some reason it adds spaces not just at end but also in middle
1126    }
1127
1128    $filename = "$tailname$suffix";
1129    $filename = "$dirname$filename" if ($dirname ne "./" && $dirname ne ".\\");
1130
1131    return $filename;
1132}
1133
1134
1135# BACKWARDS COMPATIBILITY: Just in case there are old .ldb/.bdb files
1136sub rename_ldb_or_bdb_file {
1137    my ($filename_no_ext) = @_;
1138
1139    my $new_filename = "$filename_no_ext.gdb";
1140    return if (-f $new_filename); # if the file has the right extension, don't need to do anything
1141    # try ldb
1142    my $old_filename = "$filename_no_ext.ldb";
1143   
1144    if (-f $old_filename) {
1145    print STDERR "Renaming $old_filename to $new_filename\n";
1146    rename ($old_filename, $new_filename)
1147        || print STDERR "Rename failed: $!\n";
1148    return;
1149    }
1150    # try bdb
1151    $old_filename = "$filename_no_ext.bdb";
1152    if (-f $old_filename) {
1153    print STDERR "Renaming $old_filename to $new_filename\n";   
1154    rename ($old_filename, $new_filename)
1155        || print STDERR "Rename failed: $!\n";
1156    return;
1157    }
1158}
1159
1160sub os_dir() {
1161   
1162    my $gsdlarch = "";
1163    if(defined $ENV{'GSDLARCH'}) {
1164    $gsdlarch = $ENV{'GSDLARCH'};
1165    }
1166    return $ENV{'GSDLOS'}.$gsdlarch;
1167}
1168
1169# returns 1 if this (GS server) is a GS3 installation, returns 0 if it's GS2.
1170sub is_gs3() {
1171    if($ENV{'GSDL3SRCHOME'}) {
1172    return 1;
1173    } else {
1174    return 0;
1175    }
1176}
1177
1178# Returns the greenstone URL prefix extracted from the appropriate GS2/GS3 config file.
1179# By default, /greenstone3 for GS3 or /greenstone for GS2.
1180sub get_greenstone_url_prefix() {
1181    # if already set on a previous occasion, just return that
1182    # (Don't want to keep repeating this: cost of re-opening and scanning files.)
1183    return $ENV{'GREENSTONE_URL_PREFIX'} if($ENV{'GREENSTONE_URL_PREFIX'});
1184
1185    my ($configfile, $urlprefix, $defaultUrlprefix);
1186    my @propertynames = ();
1187
1188    if($ENV{'GSDL3SRCHOME'}) {
1189    $defaultUrlprefix = "/greenstone3";
1190    $configfile = &FileUtils::filenameConcatenate($ENV{'GSDL3SRCHOME'}, "packages", "tomcat", "conf", "Catalina", "localhost", "greenstone3.xml");
1191    push(@propertynames, qw/path\s*\=/);
1192    } else {
1193    $defaultUrlprefix = "/greenstone";
1194    $configfile = &FileUtils::filenameConcatenate($ENV{'GSDLHOME'}, "cgi-bin", &os_dir(), "gsdlsite.cfg");
1195    push(@propertynames, (qw/\nhttpprefix/, qw/\ngwcgi/)); # inspect one property then the other
1196    }
1197
1198    $urlprefix = &extract_propvalue_from_file($configfile, \@propertynames);
1199
1200    if(!$urlprefix) { # no values found for URL prefix, use default values
1201    $urlprefix = $defaultUrlprefix;
1202    } else {
1203    #gwcgi can contain more than the wanted prefix, we split on / to get the first "directory" level
1204    $urlprefix =~ s/^\///; # remove the starting slash
1205    my @dirs = split(/(\\|\/)/, $urlprefix);
1206    $urlprefix = shift(@dirs);
1207
1208    if($urlprefix !~ m/^\//) { # in all cases: ensure the required forward slash is at the front
1209        $urlprefix = "/$urlprefix";
1210    }
1211    }
1212
1213    # set for the future
1214    $ENV{'GREENSTONE_URL_PREFIX'} = $urlprefix;
1215#    print STDERR "*** in get_greenstone_url_prefix(): $urlprefix\n\n";
1216    return $urlprefix;
1217}
1218
1219
1220
1221#
1222# The following comes from activate.pl
1223#
1224# Designed to work with a server included with GS.
1225#  - For GS3, we ask ant for the library URL.
1226#  - For GS2, we derive the URL from the llssite.cfg file.
1227
1228sub get_full_greenstone_url_prefix
1229{   
1230    # if already set on a previous occasion, just return that
1231    # (Don't want to keep repeating this: cost of re-opening and scanning files.)
1232    return $ENV{'GREENSTONE_URL_PREFIX'} if($ENV{'GREENSTONE_URL_PREFIX'});
1233
1234    my $gs_mode = ($ENV{'GSDL3SRCHOME'}) ? "gs3" : "gs2";
1235   
1236    my $url = undef;   
1237   
1238    if($gs_mode eq "gs2") {     
1239    my $llssite_cfg = &FileUtils::filenameConcatenate($ENV{'GSDLHOME'}, "llssite.cfg");
1240   
1241    if(-f $llssite_cfg) {
1242        # check llssite.cfg for line with url property
1243        # for server.exe also need to use portnumber and enterlib properties           
1244       
1245        # Read in the entire contents of the file in one hit
1246        if (!open (FIN, $llssite_cfg)) {
1247        print STDERR "util::get_library_URL() failed to open $llssite_cfg ($!)\n";
1248        return undef;
1249        }
1250       
1251        my $contents;
1252        sysread(FIN, $contents, -s FIN);           
1253        close(FIN);
1254       
1255        my @lines = split(/[\n\r]+/, $contents); # split on carriage-returns and/or linefeeds
1256        my $enterlib = "";
1257        my $portnumber = "8282"; # will remain empty (implicit port 80) unless it's specifically been assigned
1258       
1259        foreach my $line (@lines) {             
1260        if($line =~ m/^url=(.*)$/) {
1261            $url = $1;                 
1262        } elsif($line =~ m/^enterlib=(.*)$/) {
1263            $enterlib = $1;                 
1264        } elsif($line =~ m/^portnumber=(.*)$/) {
1265            $portnumber = $1;                   
1266        }   
1267        }
1268       
1269        if(!$url) {
1270        return undef;
1271        }
1272        elsif($url eq "URL_pending") { # library is not running
1273        # do not process url=URL_pending in the file, since for server.exe
1274        # this just means the Enter Library button hasn't been pressed yet             
1275        $url = undef;
1276        }
1277        else {
1278        # In the case of server.exe, need to do extra work to get the proper URL
1279        # But first, need to know whether we're indeed dealing with server.exe:
1280       
1281        # compare the URL's domain to the full URL
1282        # E.g. for http://localhost:8383/greenstone3/cgi-bin, the domain is localhost:8383
1283        my $uri = URI->new( $url );
1284        my $host = $uri->host;
1285        #print STDERR "@@@@@ host: $host\n";
1286        if($url =~ m/http:\/\/$host(\/)?$/) {
1287            #if($url !~ m/http:\/\/$host:$portnumber(\/)?/ || $url =~ m/http:\/\/$host(\/)?$/) {
1288            # (if the URL does not contain the portnumber, OR if the port is implicitly 80 and)                 
1289            # If the domain with http:// prefix is completely the same as the URL, assume server.exe
1290            # then the actual URL is the result of suffixing the port and enterlib properties in llssite.cfg
1291            $url = $url.":".$portnumber.$enterlib;         
1292        } # else, apache web server         
1293       
1294        }           
1295    }
1296    } elsif($gs_mode eq "gs3") {
1297    # Either check build.properties for tomcat.server, tomcat.port and app.name (and default servlet name).
1298    # app.name is stored in app.path by build.xml. Need to move app.name in build.properties from build.xml
1299   
1300    # Or, run the new target get-default-servlet-url
1301    # the output can look like:
1302    #
1303    # Buildfile: build.xml
1304    #   [echo] os.name: Windows Vista
1305    #
1306    # get-default-servlet-url:
1307    #   [echo] http://localhost:8383/greenstone3/library
1308    # BUILD SUCCESSFUL
1309    # Total time: 0 seconds
1310   
1311    #my $output = qx/ant get-default-servlet-url/; # backtick operator, to get STDOUT (else 2>&1)
1312    # - see http://stackoverflow.com/questions/799968/whats-the-difference-between-perls-backticks-system-and-exec
1313   
1314    # The get-default-servlet-url ant target can be run from anywhere by specifying the
1315    # location of GS3's ant build.xml buildfile. Activate.pl can be run from anywhere for GS3
1316    # GSDL3SRCHOME will be set for GS3 by gs3-setup.sh, a step that would have been necessary
1317    # to run the activate.pl script in the first place
1318   
1319    my $full_build_xml = &FileUtils::javaFilenameConcatenate($ENV{'GSDL3SRCHOME'},"build.xml");
1320
1321    my $perl_command = "ant -buildfile \"$full_build_xml\" get-default-servlet-url";
1322   
1323    if (open(PIN, "$perl_command |")) {
1324        while (defined (my $perl_output_line = <PIN>)) {
1325
1326        if($perl_output_line =~ m@http:\/\/(\S*)@) { # grab all the non-whitespace chars
1327            $url="http://".$1;
1328        }
1329        }
1330        close(PIN);
1331    } else {
1332        print STDERR "util::get_library_URL() failed to run $perl_command to work out library URL for $gs_mode\n";
1333    }       
1334    }
1335   
1336    # either the url is still undef or it is now set
1337    #print STDERR "\n@@@@@ final URL:|$url|\n" if $url;     
1338    #print STDERR "\n@@@@@ URL still undef\n" if !$url;
1339
1340    $ENV{'FULL_GREENSTONE_URL_PREFIX'} = $url;
1341
1342    return $url;
1343}
1344
1345
1346# Given a config file (xml or java properties file) and a list/array of regular expressions
1347# that represent property names to match on, this function will return the value for the 1st
1348# matching property name. If the return value is undefined, no matching property was found.
1349sub extract_propvalue_from_file() {
1350    my ($configfile, $propertynames) = @_;
1351
1352    my $value;
1353    unless(open(FIN, "<$configfile")) {
1354    print STDERR "extract_propvalue_from_file(): Unable to open $configfile. $!\n";
1355    return $value; # not initialised
1356    }
1357
1358    # Read the entire file at once, as one single line, then close it
1359    my $filecontents;
1360    {
1361    local $/ = undef;       
1362    $filecontents = <FIN>;
1363    }
1364    close(FIN);
1365
1366    foreach my $regex (@$propertynames) {
1367        ($value) = $filecontents=~ m/$regex\s*(\S*)/s; # read value of the property given by regex up to the 1st space
1368    if($value) {
1369            $value =~ s/^\"//;     # remove any startquotes
1370        $value =~ s/\".*$//;   # remove the 1st endquotes (if any) followed by any xml
1371        last;              # found value for a matching property, break from loop
1372    }
1373    }
1374
1375    return $value;
1376}
1377
1378# Subroutine that sources setup.bash, given GSDLHOME and GSDLOS and
1379# given that perllib is in @INC in order to invoke this subroutine.
1380# Call as follows -- after setting up INC to include perllib and
1381# after setting up GSDLHOME and GSDLOS:
1382#
1383# require util;
1384# &util::setup_greenstone_env($ENV{'GSDLHOME'}, $ENV{'GSDLOS'});
1385#
1386sub setup_greenstone_env() {
1387    my ($GSDLHOME, $GSDLOS) = @_;
1388
1389    #my %env_map = ();
1390    # Get the localised ENV settings of running a localised source setup.bash
1391    # and put it into the ENV here. Need to clear GSDLHOME before running setup
1392    #my $perl_command = "(cd $GSDLHOME; export GSDLHOME=; . ./setup.bash > /dev/null; env)";
1393    my $perl_command = "(cd $GSDLHOME; /bin/bash -c \"export GSDLHOME=; source setup.bash > /dev/null; env\")";     
1394    if (($GSDLOS =~ m/windows/i) && ($^O ne "cygwin"))  {
1395        #$perl_command = "cmd /C \"cd $GSDLHOME&& set GSDLHOME=&& setup.bat > nul&& set\"";
1396        $perl_command = "(cd $GSDLHOME&& set GSDLHOME=&& setup.bat > nul&& set)";
1397    }
1398    if (!open(PIN, "$perl_command |")) {
1399        print STDERR ("Unable to execute command: $perl_command. $!\n");
1400    }
1401
1402    my $lastkey;
1403    while (defined (my $perl_output_line = <PIN>)) {
1404        my($key,$value) = ($perl_output_line =~ m/^([^=]*)[=](.*)$/);
1405        if(defined $key) {
1406            #$env_map{$key}=$value;     
1407            $ENV{$key}=$value;
1408            $lastkey = $key;
1409        } elsif($lastkey && $perl_output_line !~ m/^\s*$/) {
1410            # there was no equals sign in $perl_output_line, so this
1411            # $perl_output_line may be a spillover from the previous
1412            $ENV{$lastkey} = $ENV{$lastkey}."\n".$perl_output_line;
1413        }
1414    }
1415    close (PIN);
1416
1417    # If any keys in $ENV don't occur in Greenstone's localised env
1418    # (stored in $env_map), delete those entries from $ENV
1419    #foreach $key (keys %ENV) {
1420    #   if(!defined $env_map{$key}) {
1421    #       print STDOUT "**** DELETING ENV KEY: $key\tVALUE: $ENV{$key}\n";
1422    #       delete $ENV{$key}; # del $ENV(key, value) pair
1423    #   }
1424    #}
1425    #undef %env_map;
1426}
1427
1428sub get_perl_exec() {   
1429    my $perl_exec = $^X; # may return just "perl"
1430   
1431    if($ENV{'PERLPATH'}) {
1432        # OR: # $perl_exec = &FileUtils::filenameConcatenate($ENV{'PERLPATH'},"perl");
1433        if (($ENV{'GSDLOS'} =~ m/windows/) && ($^O ne "cygwin")) {
1434            $perl_exec = "$ENV{'PERLPATH'}\\Perl.exe";
1435        } else {
1436            $perl_exec = "$ENV{'PERLPATH'}/perl";
1437        }
1438    } else { # no PERLPATH, use Config{perlpath} else $^X: special variables
1439        # containing the full path to the current perl executable we're using
1440        $perl_exec = $Config{perlpath}; # configured path for perl
1441        if (!-e $perl_exec) { # may not point to location on this machine
1442            $perl_exec = $^X; # may return just "perl"
1443            if($perl_exec =~ m/^perl/i) { # warn if just perl or Perl.exe
1444                print STDERR "**** WARNING: Perl exec found contains no path: $perl_exec";             
1445            }
1446        }
1447    }
1448   
1449    return $perl_exec;
1450}
1451
1452# returns the path to the java command in the JRE included with GS (if any),
1453# quoted to safeguard any spaces in this path, otherwise a simple java
1454# command is returned which assumes and will try for a system java.
1455sub get_java_command {
1456    my $java = "java";
1457    if(defined $ENV{'GSDLHOME'}) { # should be, as this script would be launched from the cmd line
1458                               # after running setup.bat or from GLI which also runs setup.bat
1459    my $java_bin = &FileUtils::filenameConcatenate($ENV{'GSDLHOME'},"packages","jre","bin");
1460    if(-d $java_bin) {
1461        $java = &FileUtils::filenameConcatenate($java_bin,"java");
1462        $java = "\"".$java."\""; # quoted to preserve spaces in path
1463    }
1464    }
1465    return $java;
1466}
1467
1468
1469# Given the qualified collection name (colgroup/collection),
1470# returns the collection and colgroup parts
1471sub get_collection_parts {
1472    # http://perldoc.perl.org/File/Basename.html
1473    # my($filename, $directories, $suffix) = fileparse($path);
1474    # "$directories contains everything up to and including the last directory separator in the $path
1475    # including the volume (if applicable). The remainder of the $path is the $filename."
1476    #my ($collection, $colgroup) = &File::Basename::fileparse($qualified_collection);   
1477
1478    my $qualified_collection = shift(@_);
1479
1480    # Since activate.pl can be launched from the command-line, including by a user,
1481    # best not to assume colgroup uses URL-style slashes as would be the case with GLI
1482    # Also allow for the accidental inclusion of multiple slashes
1483    my ($colgroup, $collection) = split(/[\/\\]+/, $qualified_collection); #split('/', $qualified_collection);
1484   
1485    if(!defined $collection) {
1486        $collection = $colgroup;
1487        $colgroup = "";
1488    }
1489    return ($collection, $colgroup);
1490}
1491
1492# work out the "collectdir/collection" location
1493sub resolve_collection_dir {
1494    my ($collect_dir, $qualified_collection, $site) = @_; #, $gs_mode
1495   
1496    if (defined $ENV{'GSDLCOLLECTDIR'}) { # a predefined collection dir exists
1497        return $ENV{'GSDLCOLLECTDIR'};
1498    }
1499
1500    my ($colgroup, $collection) = &util::get_collection_parts($qualified_collection);   
1501   
1502    if (!defined $collect_dir || !$collect_dir) { # if undefined or empty string
1503        $collect_dir = &util::get_working_collect_dir($site);
1504    }
1505
1506    return &FileUtils::filenameConcatenate($collect_dir,$colgroup,$collection);
1507}
1508
1509# work out the full path to "collect" of this greenstone 2/3 installation
1510sub get_working_collect_dir {
1511    my ($site) = @_;   
1512
1513    if (defined $ENV{'GSDLCOLLECTHOME'}) { # a predefined collect dir exists
1514    return $ENV{'GSDLCOLLECTHOME'};
1515    }
1516
1517    if (defined $site && $site) { # site non-empty, so get default collect dir for GS3
1518   
1519    if (defined $ENV{'GSDL3HOME'}) {
1520        return &FileUtils::filenameConcatenate($ENV{'GSDL3HOME'},"sites",$site,"collect"); # web folder
1521    }
1522    elsif (defined $ENV{'GSDL3SRCHOME'}) {
1523        return &FileUtils::filenameConcatenate($ENV{'GSDL3SRCHOME'},"web","sites",$site,"collect");
1524    }
1525    }
1526
1527    elsif (defined $ENV{'SITEHOME'}) {
1528    return &FileUtils::filenameConcatenate($ENV{'SITEHOME'},"collect");
1529    }
1530   
1531    else { # get default collect dir for GS2
1532    return &FileUtils::filenameConcatenate($ENV{'GSDLHOME'},"collect");
1533    }
1534}
1535
1536sub is_abs_path_any_os {
1537    my ($path) = @_;
1538
1539    # We can have filenames in our DBs that were produced on other OS, so this method exists
1540    # to help identify absolute paths in such cases.
1541
1542    return 1 if($path =~ m@^/@); # full paths begin with forward slash on linux/mac
1543    return 1 if($path =~ m@^([a-zA-Z]\:|\\)@); # full paths begin with drive letter colon for Win or \ for volume, http://stackoverflow.com/questions/13011013/get-only-volume-name-from-filepath
1544
1545    return 0;
1546}
1547
1548
1549# This subroutine is for improving portability of Greenstone collections from one OS to another,
1550# to be used to convert absolute paths going into db files into paths with placeholders instead.
1551# This sub works with util::get_common_gs_paths and takes a path to a greenstone file and, if it's
1552# an absolute path, then it will replace the longest matching greenstone-path prefix of the given
1553# path with a placeholder to match.
1554# The Greenstone-path prefixes that can be matched are the following common Greenstone paths:
1555# the path to the current (specific) collection, the path to the general GS collect directory,
1556# the path to the site directory if GS3, else the path to the GSDLHOME/GSDL3HOME folder.
1557# The longest matching prefix will be replaced with the equivalent placeholder:
1558# @THISCOLLECTPATH@, else @COLLECTHOME@, else @SITEHOME@, else @GSDLHOME@.
1559sub abspath_to_placeholders {
1560    my $path = shift(@_); # path to convert from absolute to one with placeholders
1561    my $opt_long_or_short_winfilenames = shift(@_) || "short"; # whether we want to force use of long file names even on windows, default uses short
1562
1563    return $path unless is_abs_path_any_os($path); # path is relative
1564
1565    if ($opt_long_or_short_winfilenames eq "long") {
1566    $path = &util::upgrade_if_dos_filename($path); # will only do something on windows
1567    }
1568   
1569    # now we know we're dealing with absolute paths and have to replace gs prefixes with placeholders
1570    my @gs_paths = ($ENV{'GSDLCOLLECTDIR'}, $ENV{'GSDLCOLLECTHOME'}, $ENV{'SITEHOME'}, $ENV{'GREENSTONEHOME'}); # list in this order: from longest to shortest path
1571
1572    my %placeholder_map = ($ENV{'GREENSTONEHOME'} => '@GSDLHOME@', # can't use double-quotes around at-sign, else perl tries to evaluate it as referring to an array
1573               $ENV{'GSDLCOLLECTHOME'} => '@COLLECTHOME@',
1574               $ENV{'GSDLCOLLECTDIR'} => '@THISCOLLECTPATH@'
1575    );
1576    $placeholder_map{$ENV{'SITEHOME'}} = '@SITEHOME@' if defined $ENV{'SITEHOME'};
1577
1578    $path = &util::_abspath_to_placeholders($path, \@gs_paths, \%placeholder_map);
1579
1580    if ($ENV{'GSDLOS'} =~ /^windows$/i && $opt_long_or_short_winfilenames eq "short") {
1581    # for windows need to look for matches on short file names too
1582    # matched paths are again to be replaced with the usual placeholders
1583
1584    my $gsdlcollectdir = &util::downgrade_if_dos_filename($ENV{'GSDLCOLLECTDIR'});
1585    my $gsdlcollecthome = &util::downgrade_if_dos_filename($ENV{'GSDLCOLLECTHOME'});
1586    my $sitehome = (defined $ENV{'SITEHOME'}) ? &util::downgrade_if_dos_filename($ENV{'SITEHOME'}) : undef;
1587    my $greenstonehome =  &util::downgrade_if_dos_filename($ENV{'GREENSTONEHOME'});
1588
1589    @gs_paths = ($gsdlcollectdir, $gsdlcollecthome, $sitehome, $greenstonehome); # order matters
1590
1591    %placeholder_map = ($greenstonehome => '@GSDLHOME@', # can't use double-quotes around at-sign, else perl tries to evaluate it as referring to an array
1592                $gsdlcollecthome => '@COLLECTHOME@',
1593                $gsdlcollectdir => '@THISCOLLECTPATH@'
1594        );
1595    $placeholder_map{$sitehome} = '@SITEHOME@' if defined $sitehome;
1596
1597    $path = &util::_abspath_to_placeholders($path, \@gs_paths, \%placeholder_map);
1598    }
1599
1600    return $path;
1601}
1602
1603sub _abspath_to_placeholders {
1604    my ($path, $gs_paths_ref, $placeholder_map_ref) = @_;
1605
1606    # The sequence of elements in @gs_paths matters   
1607    # Need to loop starting from the *longest* matching path (the path to the specific collection)
1608    # to the shortest matching path (the path to gsdlhome/gsdl3home folder):
1609
1610    foreach my $gs_path (@$gs_paths_ref) {
1611    next if(!defined $gs_path); # site undefined for GS2
1612
1613    my $re_path =  &util::filename_to_regex($gs_path); # escape for regex
1614
1615    if($path =~ m/^$re_path/i) { # case sensitive or not for OS?
1616
1617        my $placeholder = $placeholder_map_ref->{$gs_path}; # get the placeholder to replace the matched path with
1618
1619        $path =~ s/^$re_path/$placeholder/; #case sensitive or not?
1620        #$path =~ s/^[\\\/]//; # remove gs_path's trailing separator left behind at the start of the path
1621        # lowercase file extension, This is needed when shortfilenames are used, as case affects alphetical ordering, which affects diffcol     
1622        $path =~ s/\.([A-Z]+)$/".".lc($1)/e;
1623        last; # done
1624    }
1625    }
1626   
1627    return $path;
1628}
1629
1630# Function that does the reverse of the util::abspath_to_placeholders subroutine
1631# Once again, call this with the values returned from util::get_common_gs_paths
1632sub placeholders_to_abspath {
1633    my $path = shift(@_); # path that can contain placeholders to convert to resolved absolute path
1634    my $opt_long_or_short_winfilenames = shift(@_) || "short"; # whether we want to force use of long file names even on windows, default uses short
1635
1636    return $path if($path !~ m/@/); # path contains no placeholders
1637   
1638    # replace placeholders with gs prefixes
1639    my @placeholders = ('@THISCOLLECTPATH@', '@COLLECTHOME@', '@SITEHOME@', '@GSDLHOME@'); # order of paths not crucial in this case,
1640                       # but listed here from longest to shortest once placeholders are have been resolved
1641
1642    # can't use double-quotes around at-sign, else perl tries to evaluate it as referring to an array
1643    my %placeholder_to_gspath_map;
1644    if ($ENV{'GSDLOS'} =~ /^windows$/i && $opt_long_or_short_winfilenames eq "short") {
1645    # always replace placeholders with short file names of the absolute paths on windows?
1646    %placeholder_to_gspath_map = ('@GSDLHOME@' => &util::downgrade_if_dos_filename($ENV{'GREENSTONEHOME'}),
1647                     '@COLLECTHOME@' => &util::downgrade_if_dos_filename($ENV{'GSDLCOLLECTHOME'}),
1648                     '@THISCOLLECTPATH@' => &util::downgrade_if_dos_filename($ENV{'GSDLCOLLECTDIR'})
1649    );
1650    $placeholder_to_gspath_map{'@SITEHOME@'} =  &util::downgrade_if_dos_filename($ENV{'SITEHOME'}) if defined $ENV{'SITEHOME'};
1651    } else {
1652    %placeholder_to_gspath_map = ('@GSDLHOME@' => $ENV{'GREENSTONEHOME'},
1653                      '@SITEHOME@' => $ENV{'SITEHOME'}, # can be undef
1654                      '@COLLECTHOME@' => $ENV{'GSDLCOLLECTHOME'},
1655                      '@THISCOLLECTPATH@' => $ENV{'GSDLCOLLECTDIR'}
1656        ); # $placeholder_to_gspath_map{'@SITEHOME@'} = $ENV{'SITEHOME'} if defined $ENV{'SITEHOME'};
1657    }
1658
1659    foreach my $placeholder (@placeholders) {
1660    my $gs_path = $placeholder_to_gspath_map{$placeholder};
1661
1662    next if(!defined $gs_path); # sitehome for GS2 is undefined
1663
1664    if($path =~ m/^$placeholder/) {
1665        $path =~ s/^$placeholder/$gs_path/;
1666        last; # done
1667    }
1668    }
1669   
1670    return $path;
1671}
1672
1673# Used by pdfpstoimg.pl and PDFBoxConverter to create a .item file from
1674# a directory containing sequentially numbered images.
1675sub create_itemfile
1676{
1677    my ($output_dir, $convert_basename, $convert_to) = @_;
1678    my $page_num = "";
1679
1680    opendir(DIR, $output_dir) || die "can't opendir $output_dir: $!";
1681    my @dir_files = grep {-f "$output_dir/$_"} readdir(DIR);
1682    closedir DIR;
1683
1684    # Sort files in the directory by page_num
1685    sub page_number {
1686    my ($dir) = @_;
1687    my ($pagenum) =($dir =~ m/^.*?[-\.]?(\d+)(\.(jpg|gif|png))?$/i);
1688#   my ($pagenum) =($dir =~ m/(\d+)(\.(jpg|gif|png))?$/i); # this works but is not as safe/strict about input filepatterns as the above
1689
1690    $pagenum = 1 unless defined $pagenum;
1691    return $pagenum;
1692    }
1693
1694    # sort the files in the directory in the order of page_num rather than lexically.
1695    @dir_files = sort { page_number($a) <=> page_number($b) } @dir_files;
1696
1697    # work out if the numbering of the now sorted image files starts at 0 or not
1698    # by checking the number of the first _image_ file (skipping item files)
1699    my $starts_at_0 = 0;
1700    my $firstfile = ($dir_files[0] !~ /\.item$/i) ? $dir_files[0] : $dir_files[1];
1701    if(page_number($firstfile) == 0) { # 00 will evaluate to 0 too in this condition
1702    $starts_at_0 = 1;
1703    }
1704
1705    my $item_file = &FileUtils::filenameConcatenate($output_dir, $convert_basename.".item");
1706    my $item_fh;
1707    &FileUtils::openFileHandle($item_file, 'w', \$item_fh);
1708    print $item_fh "<PagedDocument>\n";
1709
1710    foreach my $file (@dir_files){
1711    if ($file !~ /\.item/i){
1712        $page_num = page_number($file);
1713        $page_num++ if $starts_at_0; # image numbers start at 0, so add 1
1714        print $item_fh "   <Page pagenum=\"$page_num\" imgfile=\"$file\" txtfile=\"\"/>\n";
1715    }
1716    }
1717
1718    print $item_fh "</PagedDocument>\n";
1719    &FileUtils::closeFileHandle($item_file, \$item_fh);
1720    return $item_file;
1721}
1722
1723# Sets the gnomelib_env. Based on the logic in wvware.pl which can perhaps be replaced with a call to this function in future
1724sub set_gnomelib_env
1725{
1726    ## SET THE ENVIRONMENT AS DONE IN SETUP.BASH/BAT OF GNOME-LIB
1727    # Though this is only needed for darwin Lion at this point (and android, though that is untested)
1728
1729    my $libext = "so";
1730    if ($ENV{'GSDLOS'} =~ m/^windows$/i) {
1731    return;
1732    } elsif ($ENV{'GSDLOS'} =~ m/^darwin$/i) {
1733    $libext = "dylib";
1734    }
1735
1736    if (!defined $ENV{'GEXTGNOME'}) {
1737        ##print STDERR "@@@ Setting GEXTGNOME env\n";
1738
1739    my $gnome_dir = &FileUtils::filenameConcatenate($ENV{'GSDLHOME'},"ext","gnome-lib-minimal");
1740
1741    if(! -d $gnome_dir) {
1742        $gnome_dir = &FileUtils::filenameConcatenate($ENV{'GSDLHOME'},"ext","gnome-lib");
1743
1744        if(! -d $gnome_dir) {
1745        $gnome_dir = "";
1746        }
1747    }
1748   
1749    # now set other the related env vars,
1750    # IF we've found the gnome-lib dir installed in the ext folder 
1751
1752    if ($gnome_dir ne "" && -f &FileUtils::filenameConcatenate($gnome_dir, $ENV{'GSDLOS'}, "lib", "libiconv.$libext")) {
1753        $ENV{'GEXTGNOME'} = $gnome_dir;
1754        $ENV{'GEXTGNOME_INSTALLED'}=&FileUtils::filenameConcatenate($ENV{'GEXTGNOME'}, $ENV{'GSDLOS'});
1755       
1756        my $gnomelib_bin = &FileUtils::filenameConcatenate($ENV{'GEXTGNOME_INSTALLED'}, "bin");
1757        if(-d $gnomelib_bin) { # no bin subfolder in GS binary's cutdown gnome-lib-minimal folder
1758        &util::envvar_prepend("PATH", $gnomelib_bin);
1759        }
1760
1761        # util's prepend will create LD/DYLD_LIB_PATH if it doesn't exist yet
1762        my $gextlib = &FileUtils::filenameConcatenate($ENV{'GEXTGNOME_INSTALLED'}, "lib");
1763
1764        if($ENV{'GSDLOS'} eq "linux") {
1765        &util::envvar_prepend("LD_LIBRARY_PATH", $gextlib);
1766        }
1767        elsif ($ENV{'GSDLOS'} eq "darwin") {
1768        #&util::envvar_prepend("DYLD_LIBRARY_PATH", $gextlib);
1769        &util::envvar_prepend("DYLD_FALLBACK_LIBRARY_PATH", $gextlib);
1770        }
1771    }
1772   
1773    # Above largely mimics the setup.bash of the gnome-lib-minimal.
1774    # Not doing the devel-srcpack that gnome-lib-minimal's setup.bash used to set
1775    # Not exporting GSDLEXTS variable either
1776    }
1777
1778#    print STDERR "@@@@@ GEXTGNOME: ".$ENV{'GEXTGNOME'}."\n\tINSTALL".$ENV{'GEXTGNOME_INSTALLED'}."\n";
1779#    print STDERR "\tPATH".$ENV{'PATH'}."\n";
1780#    print STDERR "\tLD_LIB_PATH".$ENV{'LD_LIBRARY_PATH'}."\n" if $ENV{'LD_LIBRARY_PATH};
1781#    print STDERR "\tDYLD_FALLBACK_LIB_PATH".$ENV{'DYLD_FALLBACK_LIBRARY_PATH'}."\n" if $ENV{'DYLD_FALLBACK_LIBRARY_PATH};
1782
1783    # if no GEXTGNOME, maybe users didn't need gnome-lib to run gnomelib/libiconv dependent binaries like hashfile, suffix, wget
1784    # (wvware is launched in a gnomelib env from its own script, but could possibly go through this script in future)
1785}
1786
1787
1788
1789## @function augmentINC()
1790#
1791#  Prepend a path (if it exists) onto INC but only if it isn't already in INC
1792#  @param $new_path The path to add
1793#  @author jmt12
1794#
1795sub augmentINC
1796{
1797  my ($new_path) = @_;
1798  my $did_add_path = 0;
1799  # might need to be replaced with FileUtils::directoryExists() call eventually
1800  if (-d $new_path)
1801  {
1802    my $did_find_path = 0;
1803    foreach my $existing_path (@INC)
1804    {
1805      if ($existing_path eq $new_path)
1806      {
1807        $did_find_path = 1;
1808        last;
1809      }
1810    }
1811    if (!$did_find_path)
1812    {
1813      unshift(@INC, $new_path);
1814      $did_add_path = 1;
1815    }
1816  }
1817  return $did_add_path;
1818}
1819## augmentINC()
1820
1821
18221;
Note: See TracBrowser for help on using the browser.