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

Last change on this file since 29807 was 29807, checked in by ak19, 9 years ago

needed the 'use Unicode::Normalize' line on the Mac.

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