Index: gs2-extensions/tdb/trunk/perllib/DBDrivers/BaseDBDriver.pm
===================================================================
--- gs2-extensions/tdb/trunk/perllib/DBDrivers/BaseDBDriver.pm	(revision 30318)
+++ gs2-extensions/tdb/trunk/perllib/DBDrivers/BaseDBDriver.pm	(revision 30318)
@@ -0,0 +1,219 @@
+###############################################################################
+#
+# BaseDBDriver.pm -- base class for all the database drivers
+# A component of the Greenstone digital library software from the New Zealand
+# Digital Library Project at the University of Waikato, New Zealand.
+#
+# Copyright (C) 1999-2015 New Zealand Digital Library Project
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 2 of the License, or (at your option) any later
+# version.
+#
+# This program is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
+# more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# this program; if not, write to the Free Software Foundation, Inc., 675 Mass
+# Ave, Cambridge, MA 02139, USA.
+#
+###############################################################################
+
+package BaseDBDriver;
+
+# Pragma
+use strict;
+
+# Libaries
+use gsprintf 'gsprintf';
+
+###############################################################################
+## Private Functions
+###############################################################################
+
+
+## @function _convert_infodb_hash_to_string(hashmap)
+#
+sub _convert_infodb_hash_to_string
+{
+    my $infodb_map = shift(@_);
+    my $infodb_entry_value = "";
+    foreach my $infodb_value_key (keys(%$infodb_map)) {
+        foreach my $infodb_value (@{$infodb_map->{$infodb_value_key}}) {
+            $infodb_entry_value .= "<$infodb_value_key>" . $infodb_value . "\n";
+        }
+    }
+    return $infodb_entry_value;
+}
+## _convert_infodb_hash_to_string(hashmap) => string ##
+
+
+## @function _convert_infodb_string_to_hash(string)
+#
+sub _convert_infodb_string_to_hash
+{
+    my $infodb_entry_value = shift(@_);
+    my $infodb_map = ();
+
+    if (!defined $infodb_entry_value) {
+	print STDERR "Warning: No value to convert into a infodb hashtable\n";
+    }
+    else {
+        while ($infodb_entry_value =~ /^<(.*?)>(.*)$/mg) {
+            my $infodb_value_key = $1;
+            my $infodb_value = $2;
+
+            if (!defined($infodb_map->{$infodb_value_key})) {
+                $infodb_map->{$infodb_value_key} = [ $infodb_value ];
+            }
+            else {
+                push(@{$infodb_map->{$infodb_value_key}}, $infodb_value);
+            }
+	}
+    }
+
+    return $infodb_map;
+}
+## _convert_infodb_string_to_hash(string) => hashmap ##
+
+
+###############################################################################
+## Public Functions
+###############################################################################
+
+
+## @function supports_datestamp()
+#
+sub supports_datestamp
+{
+    return 0;
+}
+## supports_datestamp() => integer ##
+
+
+## @function supports_merge()
+#
+sub supports_merge
+{
+    return 0;
+}
+## supports_merge() => integer ##
+
+
+## @function supports_rss()
+#
+sub supports_rss
+{
+    return 0;
+}
+## supports_rss() => integer ##
+
+
+###############################################################################
+## Virtual Functions
+###############################################################################
+
+
+## @function close_infodb_write_handle
+#
+sub close_infodb_write_handle
+{
+    gsprintf(STDERR, (caller(0))[3] . " {common.must_be_implemented}\n");
+    die("\n");
+}
+## close_infodb_write_handle ##
+
+
+## @function delete_infodb_entry
+#
+sub delete_infodb_entry
+{
+    gsprintf(STDERR, (caller(0))[3] . " {common.must_be_implemented}\n");
+    die("\n");
+}
+## delete_infodb_entry ##
+
+
+## @function get_infodb_file_path
+#
+sub get_infodb_file_path
+{
+    gsprintf(STDERR, (caller(0))[3] . " {common.must_be_implemented}\n");
+    die("\n");
+}
+## get_infodb_file_path ##
+
+
+## @function merge_databases
+#
+sub merge_databases
+{
+    gsprintf(STDERR, (caller(0))[3] . " {common.must_be_implemented}\n");
+    die("\n");
+}
+## merge_databases ##
+
+
+## @function open_infodb_write_handle
+#
+sub open_infodb_write_handle
+{
+    gsprintf(STDERR, (caller(0))[3] . " {common.must_be_implemented}\n");
+    die("\n");
+}
+## open_infodb_write_handle ##
+
+
+## @function set_infodb_entry()
+#
+sub set_infodb_entry
+{
+    gsprintf(STDERR, (caller(0))[3] . " {common.must_be_implemented}\n");
+    die("\n");
+}
+## set_infodb_entry() => void ##
+
+
+## @function read_infodb_file
+#
+sub read_infodb_file
+{
+    gsprintf(STDERR, (caller(0))[3] . " {common.must_be_implemented}\n");
+    die("\n");
+}
+## read_infodb_file ##
+
+
+## @function read_infodb_keys
+#
+sub read_infodb_keys
+{
+    gsprintf(STDERR, (caller(0))[3] . " {common.must_be_implemented}\n");
+    die("\n");
+}
+## read_infodb_keys ##
+
+
+## @function write_infodb_entry
+#
+sub write_infodb_entry
+{
+    gsprintf(STDERR, (caller(0))[3] . " {common.must_be_implemented}\n");
+    die("\n");
+}
+## write_infodb_entry ##
+
+
+## @function write_infodb_rawentry
+#
+sub write_infodb_rawentry
+{
+    gsprintf(STDERR, (caller(0))[3] . " {common.must_be_implemented}\n");
+    die("\n");
+}
+## write_infodb_rawentry ##
+
+1;
Index: gs2-extensions/tdb/trunk/perllib/DBDrivers/GDBM.pm
===================================================================
--- gs2-extensions/tdb/trunk/perllib/DBDrivers/GDBM.pm	(revision 30318)
+++ gs2-extensions/tdb/trunk/perllib/DBDrivers/GDBM.pm	(revision 30318)
@@ -0,0 +1,272 @@
+###############################################################################
+#
+# GDBM.pm -- utility functions for writing to gdbm databases
+#
+# A component of the Greenstone digital library software from the New Zealand
+# Digital Library Project at the University of Waikato, New Zealand.
+#
+# Copyright (C) 1999-2015 New Zealand Digital Library Project
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 2 of the License, or (at your option) any later
+# version.
+#
+# This program is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
+# more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# this program; if not, write to the Free Software Foundation, Inc., 675 Mass
+# Ave, Cambridge, MA 02139, USA.
+#
+###############################################################################
+
+package DBDrivers::GDBM;
+
+# Pragma
+use strict;
+
+# Libraries
+use util;
+use FileUtils;
+use DBDrivers::BaseDBDriver;
+
+sub BEGIN
+{
+    @DBDrivers::GDBM::ISA = ( 'DBDrivers::BaseDBDriver' );
+}
+
+sub new
+{
+    my $class = shift(@_);
+    return bless ($self, $class);
+}
+
+# -----------------------------------------------------------------------------
+#   GDBM IMPLEMENTATION
+# -----------------------------------------------------------------------------
+
+
+## @function open_infodb_write_handle(string, string)
+#
+sub open_infodb_write_handle
+{
+    my $infodb_file_path = shift(@_);
+    my $opt_append = shift(@_);
+
+    my $txt2db_exe = &FileUtils::filenameConcatenate($ENV{'GSDLHOME'},"bin",$ENV{'GSDLOS'}, "txt2db" . &util::get_os_exe());
+    my $infodb_file_handle = undef;
+    my $cmd = "\"$txt2db_exe\"";
+    if ((defined $opt_append) && ($opt_append eq "append")) {
+        $cmd .= " -append";
+    }
+    $cmd .= " \"$infodb_file_path\"";
+
+    if (!-e "$txt2db_exe") {
+        print STDERR "Error: Unable to find $txt2db_exe\n";
+        return undef;
+    }
+
+    if(!open($infodb_file_handle, "| $cmd")) {
+        print STDERR "Error: Failed to open pipe to $cmd\n";
+        print STDERR "       $!\n";
+        return undef;
+    }
+
+    binmode($infodb_file_handle,":utf8");
+
+    return $infodb_file_handle;
+}
+## open_infodb_write_handle(string, string) => filehandle ##
+
+
+## @function close_infodb_write_handle(filehandle)
+#
+sub close_infodb_write_handle
+{
+    my $infodb_handle = shift(@_);
+    close($infodb_handle);
+}
+## close_infodb_write_handle(filehandle) => void ##
+
+
+## @function get_infodb_file_path()
+#
+sub get_infodb_file_path
+{
+    my $collection_name = shift(@_);
+    my $infodb_directory_path = shift(@_);
+    my $infodb_file_extension = ".gdb";
+    my $infodb_file_name = &util::get_dirsep_tail($collection_name) . $infodb_file_extension;
+    return &FileUtils::filenameConcatenate($infodb_directory_path, $infodb_file_name);
+}
+## get_infodb_file_path() => string ##
+
+
+## @function read_infodb_file(string, hashmap)
+#
+sub read_infodb_file
+{
+    my $infodb_file_path = shift(@_);
+    my $infodb_map = shift(@_);
+
+    open (PIPEIN, "db2txt \"$infodb_file_path\" |") || die "couldn't open pipe from db2txt \$infodb_file_path\"\n";
+
+    binmode(PIPEIN,":utf8");
+
+    my $infodb_line = "";
+    my $infodb_key = "";
+    my $infodb_value = "";
+    while (defined ($infodb_line = <PIPEIN>)) {
+        $infodb_line =~ s/(\r\n)+$//; # more general than chomp
+
+        if ($infodb_line =~ /^\[([^\]]+)\]$/) {
+            $infodb_key = $1;
+        }
+        elsif ($infodb_line =~ /^-{70}$/) {
+            $infodb_map->{$infodb_key} = $infodb_value;
+            $infodb_key = "";
+            $infodb_value = "";
+        }
+        else {
+            $infodb_value .= $infodb_line;
+        }
+    }
+  close (PIPEIN);
+}
+## read_infodb_file(string, hashmap) => void ##
+
+
+## @function read_infodb_keys(string, hashmap)
+#
+sub read_infodb_keys
+{
+    my $infodb_file_path = shift(@_);
+    my $infodb_map = shift(@_);
+
+    open (PIPEIN, "gdbmkeys \"$infodb_file_path\" |") || die "couldn't open pipe from gdbmkeys \$infodb_file_path\"\n";
+
+    binmode(PIPEIN,":utf8");
+
+    my $infodb_line = "";
+    my $infodb_key = "";
+    my $infodb_value = "";
+    while (defined ($infodb_line = <PIPEIN>)) {
+        # chomp $infodb_line; # remove end of line
+        $infodb_line =~ s/(\r\n)+$//; # more general than chomp
+
+        $infodb_map->{$infodb_line} = 1;
+    }
+
+  close (PIPEIN);
+}
+## read_infodb_keys(string, hashmap) => void ##
+
+
+## @function write_infodb_entry(filehandle, string, hashmap)
+#
+sub write_infodb_entry
+{
+    my $infodb_handle = shift(@_);
+    my $infodb_key = shift(@_);
+    my $infodb_map = shift(@_);
+
+    print $infodb_handle "[$infodb_key]\n";
+    foreach my $infodb_value_key (sort keys(%$infodb_map)) {
+        foreach my $infodb_value (@{$infodb_map->{$infodb_value_key}}) {
+            if ($infodb_value =~ /-{70,}/) {
+                # if value contains 70 or more hyphens in a row we need to escape them
+                # to prevent txt2db from treating them as a separator
+                $infodb_value =~ s/-/&\#045;/gi;
+            }
+            print $infodb_handle "<$infodb_value_key>" . $infodb_value . "\n";
+        }
+    }
+    print $infodb_handle '-' x 70, "\n";
+}
+## write_infodb_entry(filehandle, string, hashmap) => void ##
+
+
+## @function write_infodb_rawentry(filehandle, string, string)
+#
+sub write_infodb_rawentry
+{
+    my $infodb_handle = shift(@_);
+    my $infodb_key = shift(@_);
+    my $infodb_val = shift(@_);
+
+    print $infodb_handle "[$infodb_key]\n";
+    print $infodb_handle "$infodb_val\n";
+    print $infodb_handle '-' x 70, "\n";
+}
+## write_infodb_rawentry(filehandle, string, string) ##
+
+
+## @function set_infodb_entry(string, string, hashmap)
+#
+sub set_infodb_entry
+{
+    my $infodb_file_path = shift(@_);
+    my $infodb_key = shift(@_);
+    my $infodb_map = shift(@_);
+
+    # HTML escape anything that is not part of the "contains" metadata value
+    foreach my $k (keys %$infodb_map) {
+	  my @escaped_v = ();
+	  foreach my $v (@{$infodb_map->{$k}}) {
+	    if ($k eq "contains") {
+		  push(@escaped_v, $v);
+	    }
+	    else {
+		  my $ev = &ghtml::unescape_html($v);
+		  push(@escaped_v, $ev);
+	    }
+	  }
+	  $infodb_map->{$k} = \@escaped_v;
+	}
+
+    # Generate the record string
+    my $serialized_infodb_map = &dbutil::convert_infodb_hash_to_string($infodb_map);
+
+    # Store it into GDBM using 'txt2db -append' which despite its name
+    # actually replaces the record if it already exists
+    my $cmd = "txt2db -append \"$infodb_file_path\"";
+
+    my $status = undef;
+    if(!open(GOUT, "| $cmd")) {
+	print STDERR "Error: gdbm::set_infodb_entry() failed to open pipe to: $cmd\n";
+	print STDERR "       $!\n";
+	$status = -1;
+    }
+    else {
+	binmode(GOUT,":utf8");
+
+	print GOUT "[$infodb_key]\n";
+	print GOUT "$serialized_infodb_map\n";
+
+	close(GOUT);
+	$status = 0; # as in exit status of cmd OK
+    }
+    return $status;
+}
+## set_infodb_entry(string, string, hashmap) => integer ##
+
+
+## @function delete_infodb_entry(filehandle, string)
+#
+sub delete_infodb_entry
+{
+  my $infodb_handle = shift(@_);
+  my $infodb_key = shift(@_);
+
+  # A minus at the end of a key (after the ]) signifies 'delete'
+  print $infodb_handle "[$infodb_key]-\n";
+
+  # The 70 minus signs are also needed, to help make the parsing by db2txt simple
+  print $infodb_handle '-' x 70, "\n";
+}
+## delete_infodb_entry(filehandle, string) => void ##
+
+1;
Index: gs2-extensions/tdb/trunk/perllib/DBDrivers/GDBMTXTGZ.pm
===================================================================
--- gs2-extensions/tdb/trunk/perllib/DBDrivers/GDBMTXTGZ.pm	(revision 30318)
+++ gs2-extensions/tdb/trunk/perllib/DBDrivers/GDBMTXTGZ.pm	(revision 30318)
@@ -0,0 +1,178 @@
+###############################################################################
+#
+# GDBMTXTGZ.pm -- utility functions for writing to gdbm-txtgz databases
+#
+# A component of the Greenstone digital library software from the New Zealand
+# Digital Library Project at the University of Waikato, New Zealand.
+#
+# Copyright (C) 1999-2015 New Zealand Digital Library Project
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 2 of the License, or (at your option) any later
+# version.
+#
+# This program is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
+# more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# this program; if not, write to the Free Software Foundation, Inc., 675 Mass
+# Ave, Cambridge, MA 02139, USA.
+#
+###############################################################################
+
+package DBDrivers::GDBMTXTGZ;
+
+# Pragma
+use strict;
+
+# Libraries
+use util;
+use FileUtils;
+use DBDrivers::GDBM;
+
+sub BEGIN
+{
+    @DBDrivers::GDBMTXTGZ::ISA = ( 'DBDrivers::GDBM' );
+}
+
+sub new
+{
+    my $class = shift(@_);
+    return bless ($self, $class);
+}
+
+# -----------------------------------------------------------------------------
+#   GDBM TXT-GZ IMPLEMENTATION
+# -----------------------------------------------------------------------------
+
+# With infodb_handle already set up, these functions work the same as parent version
+# sub close_infodb_write_handle {}
+# sub delete_infodb_entry {}
+# sub write_infodb_entry {}
+# sub write_infodb_rawentry {}
+
+
+## @function open_infodb_write_handle(string)
+#
+# Keep infodb in GDBM neutral form => save data as compressed text file, read
+# for txt2db to be run on it later (i.e. by the runtime system, first time the
+# collection is ever accessed).  This makes it easier distribute pre-built
+# collections to various architectures.
+#
+# NB: even if two architectures are little endian (e.g. Intel and ARM procesors)
+# GDBM does *not* guarantee that the database generated on one will work on the
+# other
+#
+sub open_infodb_write_handle
+{
+    my $infodb_file_path = shift(@_);
+
+    # Greenstone ships with gzip for windows, on $PATH
+    my $infodb_file_handle = undef;
+    if (!open($infodb_file_handle, "| gzip - > \"$infodb_file_path\"")) {
+        print STDERR "Error: Failed to open pipe to gzip - > \"$infodb_file_path\"\n";
+        print STDERR "       $!\n";
+        return undef;
+    }
+    binmode($infodb_file_handle,":utf8");
+    return $infodb_file_handle;
+}
+## open_infodb_write_handle(string) => filehandle ##
+
+
+## @function get_infodb_file_path(string, string)
+#
+sub get_infodb_file_path
+{
+    my $collection_name = shift(@_);
+    my $infodb_directory_path = shift(@_);
+
+    my $infodb_file_name = &util::get_dirsep_tail($collection_name).".txt.gz";
+    return &util::filename_cat($infodb_directory_path, $infodb_file_name);
+}
+## get_infodb_file_path(string, string) => string ##
+
+
+## @function read_infodb_file(string, hashmap)
+#
+sub read_infodb_file
+{
+    my $infodb_file_path = shift(@_);
+    my $infodb_map = shift(@_);
+
+    my $cmd = "gzip --decompress --to-stdout \"$infodb_file_path\"";
+
+    open (PIPEIN, "$cmd |") || die "Error: Couldn't open pipe from gzip: $!\n  $cmd\n";
+
+    binmode(PIPEIN,":utf8");
+    my $infodb_line = "";
+    my $infodb_key = "";
+    my $infodb_value = "";
+    while (defined ($infodb_line = <PIPEIN>)) {
+        $infodb_line =~ s/(\r\n)+$//; # more general than chomp
+
+        if ($infodb_line =~ /^\[([^\]]+)\]$/) {
+            $infodb_key = $1;
+        }
+        elsif ($infodb_line =~ /^-{70}$/) {
+            $infodb_map->{$infodb_key} = $infodb_value;
+            $infodb_key = "";
+            $infodb_value = "";
+        }
+        else {
+            $infodb_value .= $infodb_line;
+        }
+    }
+
+    close (PIPEIN);
+}
+## read_infodb_file(string, hashmap) => void ##
+
+
+## @function read_infodb_keys(string, hashmap)
+#
+sub read_infodb_keys
+{
+    my $infodb_file_path = shift(@_);
+    my $infodb_map = shift(@_);
+
+    my $cmd = "gzip --decompress --to-stdout \"$infodb_file_path\"";
+
+    open (PIPEIN, "$cmd |") || die "Error: Couldn't open pipe from gzip: $!\n  $cmd\n";
+
+    binmode(PIPEIN,":utf8");
+    my $infodb_line = "";
+    my $infodb_key = "";
+    while (defined ($infodb_line = <PIPEIN>)) {
+        $infodb_line =~ s/(\r\n)+$//; # more general than chomp
+
+        if ($infodb_line =~ /^\[([^\]]+)\]$/) {
+            $infodb_key = $1;
+        }
+        elsif ($infodb_line =~ /^-{70}$/) {
+            $infodb_map->{$infodb_key} = 1;
+            $infodb_key = "";
+        }
+    }
+
+    close (PIPEIN);
+}
+## read_infodb_keys(string, hashmap) => void ##
+
+
+## @function set_infodb_entry(string, string, hashmap)
+#
+sub set_infodb_entry
+{
+    my $infodb_file_path = shift(@_);
+    my $infodb_key = shift(@_);
+    my $infodb_map = shift(@_);
+
+    print STDERR "***** gdbmtxtgz::set_infodb_entry() not implemented yet!\n";
+}
+## set_infodb_entry(string, string, hashmap) => void ##
+
+1;
Index: gs2-extensions/tdb/trunk/perllib/DBDrivers/JDBM.pm
===================================================================
--- gs2-extensions/tdb/trunk/perllib/DBDrivers/JDBM.pm	(revision 30318)
+++ gs2-extensions/tdb/trunk/perllib/DBDrivers/JDBM.pm	(revision 30318)
@@ -0,0 +1,335 @@
+###############################################################################
+#
+# DBDrivers/JDBM.pm -- utility functions for writing to jdbm databases
+#
+# A component of the Greenstone digital library software from the New Zealand
+# Digital Library Project at the University of Waikato, New Zealand.
+#
+# Copyright (C) 1999-2015 New Zealand Digital Library Project
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 2 of the License, or (at your option) any later
+# version.
+#
+# This program is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
+# more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# this program; if not, write to the Free Software Foundation, Inc., 675 Mass
+# Ave, Cambridge, MA 02139, USA.
+#
+###############################################################################
+
+package DBDrivers::JDBM;
+
+# Pragma
+use strict;
+
+# Libraries
+use util;
+use FileUtils;
+use DBDrivers::BaseDBDriver;
+
+sub BEGIN
+{
+    @DBDrivers::JDBM::ISA = ( 'DBDrivers::BaseDBDriver' );
+}
+
+sub new
+{
+    my $class = shift(@_);
+    return bless ($self, $class);
+}
+
+# -----------------------------------------------------------------------------
+#   JDBM IMPLEMENTATION
+# -----------------------------------------------------------------------------
+
+# When DBUtil::* is properly structured with inheritence, then
+# much of this code (along with GDBM and GDBM-TXT-GZ) can be grouped into
+# a shared base class.  Really it is only the the command that needs to
+# be constructed that changes between much of the code that is used
+
+sub open_infodb_write_handle
+{
+  my $infodb_file_path = shift(@_);
+  my $opt_append = shift(@_);
+
+  my $jdbmwrap_jar = &util::filename_cat($ENV{'GSDLHOME'},"bin","java", "JDBMWrapper.jar");
+  my $jdbm_jar = &util::filename_cat($ENV{'GSDLHOME'},"lib","java", "jdbm.jar");
+
+  my $classpath = &util::pathname_cat($jdbmwrap_jar,$jdbm_jar);
+
+  if ($^O eq "cygwin") {
+      # Away to run a java program, using a binary that is native to Windows, so need
+      # Windows directory and path separators
+
+      $classpath = `cygpath -wp "$classpath"`;
+      chomp($classpath);
+      $classpath =~ s%\\%\\\\%g;
+  }
+
+  my $infodb_file_handle = undef;
+  my $txt2jdb_cmd = "java -cp \"$classpath\" Txt2Jdb";
+
+  if ((defined $opt_append) && ($opt_append eq "append")) {
+      $txt2jdb_cmd .= " -append";
+      print STDERR "Append operation to $infodb_file_path\n";
+  }
+  else {
+      print STDERR "Create database $infodb_file_path\n";
+  }
+  
+  # Lop off file extension, as JDBM does not expect this to be present
+  $infodb_file_path =~ s/\.jdb$//;
+
+  if ($^O eq "cygwin") {
+      $infodb_file_path = `cygpath -w "$infodb_file_path"`;
+      chomp($infodb_file_path);
+      $infodb_file_path =~ s%\\%\\\\%g;
+  }
+
+  $txt2jdb_cmd .= " \"$infodb_file_path\"";
+
+  if (!open($infodb_file_handle, "| $txt2jdb_cmd"))
+  {
+      print STDERR "Error: Failed to open pipe to $txt2jdb_cmd";
+      print STDERR "       $!\n";
+      return undef;
+  }
+  
+  binmode($infodb_file_handle,":utf8");
+  return $infodb_file_handle;
+}
+
+
+
+sub close_infodb_write_handle
+{
+  my $infodb_handle = shift(@_);
+
+  close($infodb_handle);
+}
+
+
+sub get_infodb_file_path
+{
+  my $collection_name = shift(@_);
+  my $infodb_directory_path = shift(@_);
+
+  my $infodb_file_extension = ".jdb";
+  my $infodb_file_name = &util::get_dirsep_tail($collection_name) . $infodb_file_extension;
+  return &util::filename_cat($infodb_directory_path, $infodb_file_name);
+}
+
+
+sub read_infodb_file
+{
+  my $infodb_file_path = shift(@_);
+  my $infodb_map = shift(@_);
+
+  my $jdbmwrap_jar = &util::filename_cat($ENV{'GSDLHOME'},"bin","java", "JDBMWrapper.jar");
+  my $jdbm_jar = &util::filename_cat($ENV{'GSDLHOME'},"lib","java", "jdbm.jar");
+
+  my $classpath = &util::pathname_cat($jdbmwrap_jar,$jdbm_jar);
+
+  if ($^O eq "cygwin") {
+      # Away to run a java program, using a binary that is native to Windows, so need
+      # Windows directory and path separators
+      
+      $classpath = `cygpath -wp "$classpath"`;
+      chomp($classpath);
+      $classpath =~ s%\\%\\\\%g;
+
+      $infodb_file_path = `cygpath -w "$infodb_file_path"`;
+      chomp($infodb_file_path);
+      $infodb_file_path =~ s%\\%\\\\%g;
+  }
+
+  my $jdb2txt_cmd = "java -cp \"$classpath\" Jdb2Txt";
+
+  open (PIPEIN, "$jdb2txt_cmd \"$infodb_file_path\" |") || die "couldn't open pipe from db2txt \$infodb_file_path\"\n";
+  binmode(PIPEIN,":utf8");
+  my $infodb_line = "";
+  my $infodb_key = "";
+  my $infodb_value = "";
+  while (defined ($infodb_line = <PIPEIN>))
+  {
+    $infodb_line =~ s/(\r\n)+$//; # more general than chomp
+
+    if ($infodb_line =~ /^\[([^\]]+)\]$/)
+    {
+      $infodb_key = $1;
+    }
+    elsif ($infodb_line =~ /^-{70}$/)
+    {
+      $infodb_map->{$infodb_key} = $infodb_value;
+      $infodb_key = "";
+      $infodb_value = "";
+    }
+    else
+    {
+      $infodb_value .= $infodb_line;
+    }
+  }
+
+  close (PIPEIN);
+}
+
+sub read_infodb_keys
+{
+  my $infodb_file_path = shift(@_);
+  my $infodb_map = shift(@_);
+
+  my $jdbmwrap_jar = &util::filename_cat($ENV{'GSDLHOME'},"bin","java", "JDBMWrapper.jar");
+  my $jdbm_jar = &util::filename_cat($ENV{'GSDLHOME'},"lib","java", "jdbm.jar");
+
+  my $classpath = &util::pathname_cat($jdbmwrap_jar,$jdbm_jar);
+
+  my $jdbkeys_cmd = "java -cp \"$classpath\" JdbKeys";
+
+  open (PIPEIN, "$jdbkeys_cmd \"$infodb_file_path\" |") || die "couldn't open pipe from jdbmkeys \$infodb_file_path\"\n";
+  binmode(PIPEIN,":utf8");
+  my $infodb_line = "";
+  my $infodb_key = "";
+  my $infodb_value = "";
+  while (defined ($infodb_line = <PIPEIN>))
+  {
+      # chomp $infodb_line; # remove end of line 
+      $infodb_line =~ s/(\r\n)+$//; # more general than chomp
+
+      $infodb_map->{$infodb_line} = 1;
+  }
+
+  close (PIPEIN);
+}
+
+
+    
+sub write_infodb_entry
+{
+
+  my $infodb_handle = shift(@_);
+  my $infodb_key = shift(@_);
+  my $infodb_map = shift(@_);
+
+  print $infodb_handle "[$infodb_key]\n";
+  foreach my $infodb_value_key (keys(%$infodb_map))
+  {
+    foreach my $infodb_value (@{$infodb_map->{$infodb_value_key}})
+    {
+      if ($infodb_value =~ /-{70,}/)
+      {
+        # if value contains 70 or more hyphens in a row we need to escape them
+        # to prevent txt2db from treating them as a separator
+        $infodb_value =~ s/-/&\#045;/gi;
+      }
+      print $infodb_handle "<$infodb_value_key>" . $infodb_value . "\n";
+    }
+  }
+  print $infodb_handle '-' x 70, "\n";
+}
+
+
+sub write_infodb_rawentry
+{
+
+  my $infodb_handle = shift(@_);
+  my $infodb_key = shift(@_);
+  my $infodb_val = shift(@_);
+  
+  print $infodb_handle "[$infodb_key]\n";
+  print $infodb_handle "$infodb_val\n";
+  print $infodb_handle '-' x 70, "\n";
+}
+
+sub set_infodb_entry
+{
+    my $infodb_file_path = shift(@_);
+    my $infodb_key = shift(@_);
+    my $infodb_map = shift(@_);
+  
+    # HTML escape anything that is not part of the "contains" metadata value
+    foreach my $k (keys %$infodb_map) {
+	  my @escaped_v = ();
+	  foreach my $v (@{$infodb_map->{$k}}) {
+	    if ($k eq "contains") {
+		  push(@escaped_v, $v);
+	    }
+	    else {
+		  my $ev = &ghtml::unescape_html($v);
+		  push(@escaped_v, $ev);
+	    }
+	  }
+	  $infodb_map->{$k} = \@escaped_v;
+	}
+	
+    # Generate the record string
+    my $serialized_infodb_map = &dbutil::convert_infodb_hash_to_string($infodb_map);
+###    print STDERR "**** ser dr\n$serialized_infodb_map\n\n\n";
+
+    # Store it into JDBM using 'Txt2Jdb .... -append' which despite its name
+    # actually replaces the record if it already exists
+
+    my $jdbmwrap_jar = &util::filename_cat($ENV{'GSDLHOME'},"bin","java", "JDBMWrapper.jar");
+    my $jdbm_jar = &util::filename_cat($ENV{'GSDLHOME'},"lib","java", "jdbm.jar");
+    
+    my $classpath = &util::pathname_cat($jdbmwrap_jar,$jdbm_jar);
+
+    # Lop off file extension, as JDBM does not expect this to be present
+    $infodb_file_path =~ s/\.jdb$//;
+
+    if ($^O eq "cygwin") {
+ 	# Away to run a java program, using a binary that is native to Windows, so need
+	# Windows directory and path separators
+	
+      $classpath = `cygpath -wp "$classpath"`;
+      chomp($classpath);
+      $classpath =~ s%\\%\\\\%g;
+
+      $infodb_file_path = `cygpath -w "$infodb_file_path"`;
+      chomp($infodb_file_path);
+      $infodb_file_path =~ s%\\%\\\\%g;
+    }
+
+    my $cmd = "java -cp \"$classpath\" Txt2Jdb -append \"$infodb_file_path\"";
+
+    my $status = undef;
+    if(!open(GOUT, "| $cmd"))
+    {
+	print STDERR "Error: jdbm::set_infodb_entry() failed to open pipe to: $cmd\n";
+	print STDERR "       $!\n";
+	$status = -1;
+    }
+    else {
+	binmode(GOUT,":utf8");
+	
+	print GOUT "[$infodb_key]\n";
+	print GOUT "$serialized_infodb_map\n";
+
+	close(GOUT);
+	$status = 0; # as in exit status of cmd OK
+    }
+
+    return $status;  
+}
+
+
+
+
+sub delete_infodb_entry
+{
+  my $infodb_handle = shift(@_);
+  my $infodb_key = shift(@_);
+  
+  # A minus at the end of a key (after the ]) signifies 'delete'
+  print $infodb_handle "[$infodb_key]-\n"; 
+
+  # The 70 minus signs are also needed, to help make the parsing by db2txt simple
+  print $infodb_handle '-' x 70, "\n";
+}
+
+1;
Index: gs2-extensions/tdb/trunk/perllib/DBDrivers/MSSQL.pm
===================================================================
--- gs2-extensions/tdb/trunk/perllib/DBDrivers/MSSQL.pm	(revision 30318)
+++ gs2-extensions/tdb/trunk/perllib/DBDrivers/MSSQL.pm	(revision 30318)
@@ -0,0 +1,325 @@
+###############################################################################
+#
+# DBDrivers/MSSQL.pm -- utility functions for writing to mssql databases
+#
+# A component of the Greenstone digital library software from the New Zealand
+# Digital Library Project at the University of Waikato, New Zealand.
+#
+# Copyright (C) 1999-2015 New Zealand Digital Library Project
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 2 of the License, or (at your option) any later
+# version.
+#
+# This program is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
+# more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# this program; if not, write to the Free Software Foundation, Inc., 675 Mass
+# Ave, Cambridge, MA 02139, USA.
+#
+###############################################################################
+
+package DBDrivers::MSSQL;
+
+# Pragma
+use strict;
+
+# Libraries
+use Encode;
+use DBDrivers::BaseDBDriver;
+
+sub BEGIN
+{
+    @DBDrivers::MSSQL::ISA = ( 'DBDrivers::BaseDBDriver' );
+}
+
+sub new
+{
+    my $class = shift(@_);
+    if ($^O !~ /cygwin|MSWin32/) {
+        print STDERR "Warning! Non-Windows operating system detected... good luck getting this to work.\n";
+    }
+    return bless ($self, $class);
+}
+
+# -----------------------------------------------------------------------------
+#   MSSQL IMPLEMENTATION
+# -----------------------------------------------------------------------------
+
+# The hard coded server connection thingy which should be place in some
+# configuration file.
+# If you have problem connecting to your MS SQL server:
+# 1. Check if your MSSQL server has been started.
+# 2. Check if the TCP/IP connection has been enabled.
+# 3. Use telnet to the server
+# (don't forget to specify the port, which can be found in the configuration manager)
+# If none of the above helped, the you need to start googling then.
+my $host = "localhost,1660"; # Need to look up your SQL server and see what port is it using.
+my $user = "sa"; # Generally "sa" for default admin, but YMMV
+my $pwd = "[When installing the MSSQL, you will be asked to input a password for the sa user, use that password]";
+my $database = "[Create a database in MSSQL and use it here]";
+
+my $mssql_collection_name = "";
+my $mssql_data_table_name = "";
+my $mssql_document_metadata_table_name = "";
+
+
+sub open_infodb_write_handle
+{
+  my $infodb_file_path = shift(@_);
+
+  # You might have to install the DBD::ADO module from CPAN
+  use DBI;
+  use DBD::ADO;
+  Win32::OLE->Option(CP => Win32::OLE::CP_UTF8);
+
+  # Create the unique name for the table
+  # We do not want to change the database for the current running index
+  # Therefore we use timestamp and collection short name to create an unqiue name
+  my $cur_time = time();
+  my $unique_key = $mssql_collection_name . "_" . $cur_time;
+  $mssql_data_table_name = "data_" . $unique_key;
+  $mssql_document_metadata_table_name = "document_metadata_" . $unique_key;
+  print STDERR "MSSQL: Creating unique table name. Unique ID:[" . $unique_key . "]\n";
+      
+  # Store these information into the infodbfile  
+  open(FH, ">" . $infodb_file_path);
+  print FH "mss-host\t" . $host . "\n";
+  print FH "username\t" . $user . "\n";
+  print FH "password\t" . $pwd . "\n";
+  print FH "database\t" . $database . "\n";
+  print FH "tableid\t" . $unique_key . "\n";
+  close(FH);
+  print STDERR "MSSQL: Saving db info into :[" . $infodb_file_path . "]\n";
+
+  # Make the connection
+  my $dsn = "Provider=SQLNCLI;Server=$host;Database=$database";
+  my $infodb_handle = DBI->connect("dbi:ADO:$dsn", $user, $pwd, { RaiseError => 1, AutoCommit => 1}) || return undef;
+  print STDERR "MSSQL: Connect to MS SQL database. DSN:[" . $dsn . "]\n";
+
+  # Make sure the data table has been created.
+  my $data_table_checker_array = dbgetarray($infodb_handle, "SELECT name FROM sysobjects WHERE name = '" . $mssql_data_table_name . "' AND OBJECTPROPERTY(id,'IsUserTable') = 1");
+  if (scalar(@{$data_table_checker_array}) == 0)
+  {
+    dbquery($infodb_handle, "CREATE TABLE " . $mssql_data_table_name . " (one_key NVARCHAR(50) UNIQUE, one_value NVARCHAR(MAX))");
+  }
+  print STDERR "MSSQL: Making sure the data table(" . $mssql_data_table_name . ") exists\n";
+    
+  # Make sure the document_metadata table has been created.
+  my $document_metadata_table_checker_array = dbgetarray($infodb_handle, "SELECT name FROM sysobjects WHERE name = '" . $mssql_document_metadata_table_name . "' AND OBJECTPROPERTY(id,'IsUserTable') = 1");
+  if (scalar(@{$document_metadata_table_checker_array}) == 0)
+  {
+    dbquery($infodb_handle, "CREATE TABLE " . $mssql_document_metadata_table_name . " (id INTEGER IDENTITY(1,1) PRIMARY KEY, docOID NVARCHAR(50), element NVARCHAR(MAX), value NVARCHAR(MAX))");
+    dbquery($infodb_handle, "CREATE INDEX dmd ON " . $mssql_document_metadata_table_name . "(docOID)");
+  } 
+  print STDERR "MSSQL: Making sure the document_metadata table(" . $mssql_data_table_name . ") exists.\n";
+  
+  return $infodb_handle;
+}
+
+
+sub close_infodb_write_handle
+{
+  my $infodb_handle = shift(@_);    
+  
+  $infodb_handle->disconnect();
+}
+
+
+sub get_infodb_file_path
+{
+  my $collection_name = shift(@_);
+  my $infodb_directory_path = shift(@_);
+
+  my $infodb_file_extension = ".mssqldbinfo";
+  my $infodb_file_name = &util::get_dirsep_tail($collection_name) . $infodb_file_extension;
+  
+  # This will be used in the open_infodb_write_handle function
+  $mssql_collection_name =  $collection_name;
+
+  return &util::filename_cat($infodb_directory_path, $infodb_file_name);
+}
+
+
+sub read_infodb_file
+{
+  my $infodb_file_path = shift(@_);
+  my $infodb_map = shift(@_);
+
+  print STDERR "******* mssql::read_infodb_file() TO BE IMPLEMENTED!\n";
+  print STDERR "******* See sqlite.pm for comparable implementation that has been coded up!\n";
+}
+
+sub read_infodb_keys
+{
+  my $infodb_file_path = shift(@_);
+  my $infodb_map = shift(@_);
+
+  print STDERR "******* mssql::read_infodb_keys() TO BE IMPLEMENTED!\n";
+  print STDERR "******* See sqlite.pm for comparable implementation that has been coded up!\n";
+}
+
+
+sub write_infodb_entry
+{
+  my $infodb_handle = shift(@_);
+  my $infodb_key = shift(@_);
+  my $infodb_map = shift(@_);
+  
+  # Add the key -> value mapping into the "data" table
+  my $infodb_entry_value = "";
+  foreach my $infodb_value_key (keys(%$infodb_map))
+  {
+    foreach my $infodb_value (@{$infodb_map->{$infodb_value_key}})
+    {
+      $infodb_entry_value .= "<$infodb_value_key>" . &Encode::decode_utf8($infodb_value) . "\n";
+    }
+  }
+  
+  # Prepare the query
+  my $safe_infodb_key = &mssql_safe($infodb_key);
+  my $query = "INSERT INTO " . $mssql_data_table_name . " (one_key, one_value) VALUES (N'" . $safe_infodb_key . "', N'" . &mssql_safe($infodb_entry_value) . "')";
+  dbquery($infodb_handle, $query);
+  
+  # If this infodb entry is for a document, add all the interesting document metadata to the
+  # "document_metadata" table (for use by the dynamic classifiers)
+  if ($infodb_key !~ /\./ && $infodb_entry_value =~ /\<doctype\>doc\n/)
+  {
+    dbquery($infodb_handle, "DELETE FROM " . $mssql_document_metadata_table_name . " WHERE docOID=N'" . $safe_infodb_key . "'");
+    
+    foreach my $infodb_value_key (keys(%$infodb_map))
+    {            
+      # We're not interested in most of the automatically added document metadata
+      next if ($infodb_value_key eq "archivedir" ||
+               $infodb_value_key eq "assocfilepath" ||
+               $infodb_value_key eq "childtype" ||
+               $infodb_value_key eq "contains" ||
+               $infodb_value_key eq "docnum" ||
+               $infodb_value_key eq "doctype" ||
+               $infodb_value_key eq "Encoding" ||
+               $infodb_value_key eq "FileSize" ||
+               $infodb_value_key eq "hascover" ||
+               $infodb_value_key eq "hastxt" ||
+               $infodb_value_key eq "lastmodified" ||
+               $infodb_value_key eq "metadataset" ||
+               $infodb_value_key eq "thistype" ||
+               $infodb_value_key =~ /^metadatafreq\-/ ||
+               $infodb_value_key =~ /^metadatalist\-/);
+      foreach my $infodb_value (@{$infodb_map->{$infodb_value_key}})
+      {
+        $infodb_handle->{LongReadLen} = 65535; # Added for the encoding issue
+        my $query = "INSERT INTO " . $mssql_document_metadata_table_name . " (docOID, element, value) VALUES (N'" . $safe_infodb_key . "', N'" . &mssql_safe(&Encode::decode_utf8($infodb_value_key)) . "', N'" . &mssql_safe(&Encode::decode_utf8($infodb_value)) . "')";
+        dbquery($infodb_handle, $query);
+      }
+    }
+  }
+}
+
+
+sub write_infodb_rawentry
+{
+  my $infodb_handle = shift(@_);
+  my $infodb_key = shift(@_);
+  my $infodb_val = shift(@_);
+  
+  # Prepare the query
+  my $safe_infodb_key = &mssql_safe($infodb_key);
+  my $query = "INSERT INTO " . $mssql_data_table_name . " (one_key, one_value) VALUES (N'" . $safe_infodb_key . "', N'" . &mssql_safe($infodb_val) . "')";
+  dbquery($infodb_handle, $query);
+}
+
+
+ sub set_infodb_entry
+{
+  my $infodb_file_path = shift(@_);
+  my $infodb_key = shift(@_);
+  my $infodb_map = shift(@_);
+  
+  print STDERR "***** mssql::set_infodb_entry() not implemented yet!\n";
+}
+
+sub delete_infodb_entry
+{
+  my $infodb_handle = shift(@_);
+  my $infodb_key = shift(@_);
+  
+  # Delete the key from the "data" table
+
+  
+  # Prepare the query
+  my $safe_infodb_key = &mssql_safe($infodb_key);
+  my $query = "DELETE FROM " . $mssql_data_table_name . " WHERE one_key=N'" . $safe_infodb_key . "'";
+  dbquery($infodb_handle, $query);
+  
+  # If this infodb entry is for a document, add all the interesting document metadata to the
+  # "document_metadata" table (for use by the dynamic classifiers)
+  if ($infodb_key !~ /\./)
+  {
+      # Possible for there not to be a docOID matching this infodb_key
+      # (entries are only made when <doctype> == doc
+      # Attempt to delete it, and don't complain if one isn't found
+
+      dbquery($infodb_handle, "DELETE FROM " . $mssql_document_metadata_table_name . " WHERE docOID=N'" . $safe_infodb_key . "'");
+      
+  }
+}
+
+
+
+sub mssql_safe
+{
+  my $value = shift(@_);
+  
+  # Escape any single quotes in the value
+  $value =~ s/\'/\'\'/g;
+  
+  return $value;
+}
+
+
+sub dbquery
+{
+  my $infodb_handle = shift(@_);
+  my $sql_query = shift(@_);
+
+  # Execute the SQL statement
+  my $statement_handle = $infodb_handle->prepare($sql_query);
+  $statement_handle->execute();
+  if ($statement_handle->err) 
+  {
+    print STDERR "Error:" . $statement_handle->errstr . "\n";
+    return undef;
+  }
+  
+  return $statement_handle;
+}
+
+
+sub dbgetarray
+{
+  my $infodb_handle = shift(@_);
+  my $sql_query = shift(@_);
+  
+  my $statement_handle = dbquery($infodb_handle, $sql_query);
+  my $return_array = [];
+  
+  # Iterate through the results and push them into an array
+  if (!defined($statement_handle)) 
+  {
+    return [];
+  }
+  
+  while ((my $temp_hash = $statement_handle->fetchrow_hashref()))
+  {
+    push(@$return_array, $temp_hash);
+  }
+
+  return $return_array; 
+}
+
+
+1;
Index: gs2-extensions/tdb/trunk/perllib/DBDrivers/SQLite.pm
===================================================================
--- gs2-extensions/tdb/trunk/perllib/DBDrivers/SQLite.pm	(revision 30318)
+++ gs2-extensions/tdb/trunk/perllib/DBDrivers/SQLite.pm	(revision 30318)
@@ -0,0 +1,401 @@
+###############################################################################
+#
+# DBDrivers/SQLite.pm -- utility functions for writing to sqlite databases
+#
+# A component of the Greenstone digital library software from the New Zealand
+# Digital Library Project at the University of Waikato, New Zealand.
+#
+# Copyright (C) 2009-2010 DL Consulting Ltd.
+# Copyright (C) 2009-2015 New Zealand Digital Library Project
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 2 of the License, or (at your option) any later
+# version.
+#
+# This program is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
+# more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# this program; if not, write to the Free Software Foundation, Inc., 675 Mass
+# Ave, Cambridge, MA 02139, USA.
+#
+###############################################################################
+
+package DBDrivers::SQLite;
+
+# Pragma
+use strict;
+
+# Libraries
+use util;
+use DBDrivers::BaseDBDriver;
+
+sub BEGIN
+{
+    if (!defined $ENV{'GSDLHOME'} || !defined $ENV{'GSDLOS'}) {
+        die("Error! Environment must be prepared by sourcing setup.bash\n");
+    }
+    @DBDrivers::SQLite::ISA = ( 'DBDrivers::BaseDBDriver' );
+}
+
+sub new
+{
+    my $class = shift(@_);
+    return bless ($self, $class);
+}
+
+# -----------------------------------------------------------------------------
+#   SQLITE IMPLEMENTATION
+# -----------------------------------------------------------------------------
+
+# Please set $db_fast to 1 if you wish to enable faster I/O to the database by
+# using optimisations such as PRAGMA journal_mode (MEMORY instead of DELETE)
+# and synchronous (OFF instead of FULL)
+# Please be aware that in this case it will be less secure and the database
+# file may become corrupted if the if the operating system crashes or the
+# computer loses power before that data has been written to the disk surface.
+# But the speed gain is about 50x
+my $db_fast = 0;
+
+# Set to 1 to enable Write Ahead Logging - which is supposed to allow multiple
+# readers/writers on a SQLite database (incompatible with db_fast). From SQLite
+# 3.7 onwards, WAL offers limited parallel reader/writer support but is limited
+# to single computers (doesn't work over networked filesystems). For details
+# see: http://www.sqlite.org/draft/wal.html [jmt12]
+my $db_wal = 0;
+
+## Private Methods
+
+## @function _getExecutable
+#
+sub _getExecutable
+{
+    my $sqlite3_exe = &util::filename_cat($ENV{'GSDLHOME'}, 'bin', $ENV{'GSDLOS'}, 'sqlite3' . &util::get_os_exe());
+    if (!-e "$sqlite3_exe") {
+        die("Error! Unable to find SQLite3 executable: $sqlite3_exe\n");
+    }
+    return $sqlite3_exe;
+}
+## _getExecutable() => string ##
+
+
+sub sqlite_safe
+{
+    my $value = shift(@_);
+
+    # Escape any single quotes in the value
+    $value =~ s/\'/\'\'/g;
+
+    return $value;
+}
+
+
+sub open_infodb_write_handle
+{
+    my $infodb_file_path = shift(@_);
+    my $opt_append = shift(@_);
+
+    my $sqlite3_exe = &_getExecutable();
+    my $infodb_handle = undef;
+
+    # running sqlite3 with the pragma journal_mode=memory, causes sqlite to print out the
+    # word "memory". While this is not a problem usually, in our case, this ends up going out
+    # to the web page first, as part of the web page's headers, thus ruining the web page
+    # which causes an Internal Server Error (500). Therefore, we redirect sqlite's output to
+    # the nul device instead.
+    # using WAL mode (which also changes the journal) suffers a similar issue [jmt12]
+    my $nul_device="";
+    if($db_fast == 1 || $db_wal == 1) {
+        if($ENV{'GSDLOS'} =~ m/windows/) {
+            $nul_device=">NUL";
+	} else {
+            $nul_device=">/dev/null"; # linux, mac
+	}
+  }
+
+  if(!open($infodb_handle, "| \"$sqlite3_exe\" \"$infodb_file_path\"$nul_device"))
+  {
+      print STDERR "Error: Failed to open pipe to \"$sqlite3_exe\" \"$infodb_file_path\"\n";
+      print STDERR "       $!\n";
+      return undef;
+  }
+
+  binmode($infodb_handle,":utf8");
+  
+   # Add extra optimisations, less secure but with a massive gain in performance with large databases which are often uptaded
+   # They should be set before the transaction begins
+  if (defined $db_fast && $db_fast == 1) {
+	print $infodb_handle "PRAGMA synchronous=OFF;\n";
+	print $infodb_handle "PRAGMA journal_mode=MEMORY;\n";
+  }
+  # Allow parallel readers/writers by using a Write Ahead Logger
+  elsif ($db_wal)
+  {
+    print $infodb_handle "PRAGMA journal_mode=WAL;\n";
+  }
+
+  # This is very important for efficiency, otherwise each command will be actioned one at a time
+  print $infodb_handle "BEGIN TRANSACTION;\n";
+  
+
+
+  if (!(defined $opt_append) || ($opt_append ne "append")) {
+    print $infodb_handle "DROP TABLE IF EXISTS data;\n";
+	print $infodb_handle "DROP TABLE IF EXISTS document_metadata;\n";
+  }
+   
+  print $infodb_handle "CREATE TABLE IF NOT EXISTS data (key TEXT PRIMARY KEY, value TEXT);\n";
+  print $infodb_handle "CREATE TABLE IF NOT EXISTS document_metadata (id INTEGER PRIMARY KEY, docOID TEXT, element TEXT, value TEXT);\n";
+
+  # This is crucial for efficiency when importing large amounts of data
+  print $infodb_handle "CREATE INDEX IF NOT EXISTS dmd ON document_metadata(docOID);\n";
+
+  return $infodb_handle;
+}
+
+
+sub close_infodb_write_handle
+{
+  my $infodb_handle = shift(@_);
+
+  # This is crucial for efficient queries on the database!
+  print $infodb_handle "CREATE INDEX IF NOT EXISTS dme ON document_metadata(element);\n";
+  
+  # Close the transaction we began after opening the file
+  print $infodb_handle "END TRANSACTION;\n";
+
+  close($infodb_handle);
+}
+
+
+sub read_infodb_cmd
+{
+  my $infodb_file_path = shift(@_);
+  my $sqlcmd = shift(@_);
+
+  my $result = "";
+
+  my $sqlite3_exe = &_getExecutable();
+  my $infodb_handle = undef;
+  my $cmd = "\"$sqlite3_exe\" \"$infodb_file_path\" \"$sqlcmd\"";
+
+  if (!-e "$sqlite3_exe" || !open($infodb_handle, "$cmd |"))
+  {
+      print STDERR "Unable to execute: $cmd\n";
+      print STDERR "$!\n";
+  }
+  else {
+
+      binmode($infodb_handle, ":utf8");
+      my $line;
+      while (defined($line=<$infodb_handle>)) {
+	  $result .= $line;
+      }
+
+      close($infodb_handle);
+  }
+
+  return $result;
+}
+
+sub get_infodb_file_path
+{
+  my $collection_name = shift(@_);
+  my $infodb_directory_path = shift(@_);
+
+  my $infodb_file_extension = ".db";
+  my $infodb_file_name = &util::get_dirsep_tail($collection_name) . $infodb_file_extension;
+  return &util::filename_cat($infodb_directory_path, $infodb_file_name);
+}
+
+
+sub read_infodb_file
+{
+  my $infodb_file_path = shift(@_);
+  my $infodb_map = shift(@_);
+
+
+  my $keys_str = read_infodb_cmd($infodb_file_path,"SELECT key FROM data ORDER BY key;");
+
+  my @keys = split(/\n/,$keys_str);
+
+  foreach my $k (@keys) {
+      
+      my $k_safe = &sqlite_safe($k);
+      my $select_val_cmd = "SELECT value FROM data WHERE key='$k_safe';";
+
+      my $val_str = read_infodb_cmd($infodb_file_path,$select_val_cmd);
+
+      $infodb_map->{$k} = $val_str;
+  }
+
+}
+
+
+sub read_infodb_keys
+{
+  my $infodb_file_path = shift(@_);
+  my $infodb_map = shift(@_);
+
+
+  my $keys_str = read_infodb_cmd($infodb_file_path,"SELECT key FROM data;");
+
+  my @keys = split(/\n/,$keys_str);
+
+  foreach my $key (@keys)
+  {
+      $infodb_map->{$key} = 1;
+  }
+}
+
+sub read_infodb_rawentry
+{
+  my $infodb_file_path = shift(@_);
+  my $infodb_key = shift(@_);
+
+  
+  my $key_safe = &sqlite_safe($infodb_key);
+  my $select_val_cmd = "SELECT value FROM data WHERE key='$key_safe';";
+
+  my $val_str = read_infodb_cmd($infodb_file_path,$select_val_cmd);
+
+  return $val_str
+}
+
+sub read_infodb_entry
+{
+  my $infodb_file_path = shift(@_);
+  my $infodb_key = shift(@_);
+
+  my $val_str = read_infodb_rawentry($infodb_file_path,$infodb_key);
+  
+  my $rec_hash = &dbutil::convert_infodb_string_to_hash($val_str);
+
+  return $rec_hash;
+}
+
+
+sub write_infodb_entry
+{
+  my $infodb_handle = shift(@_);
+  my $infodb_key = shift(@_);
+  my $infodb_map = shift(@_);
+  
+
+  # Add the key -> value mapping into the "data" table
+  my $infodb_entry_value = "";
+  foreach my $infodb_value_key (keys(%$infodb_map))
+  {
+    foreach my $infodb_value (@{$infodb_map->{$infodb_value_key}})
+    {
+      $infodb_entry_value .= "<$infodb_value_key>" . $infodb_value . "\n";
+    }
+  }
+  
+  my $safe_infodb_key = &sqlite_safe($infodb_key);
+  print $infodb_handle "INSERT OR REPLACE INTO data (key, value) VALUES ('" . $safe_infodb_key . "', '" . &sqlite_safe($infodb_entry_value) . "');\n";
+
+  # If this infodb entry is for a document, add all the interesting document metadata to the
+  #   "document_metadata" table (for use by the dynamic classifiers)
+  if ($infodb_key !~ /\./ && $infodb_entry_value =~ /\<doctype\>doc\n/)
+  {
+	
+    print $infodb_handle "DELETE FROM document_metadata WHERE docOID='" . $safe_infodb_key . "';\n";
+	
+    foreach my $infodb_value_key (keys(%$infodb_map))
+    {
+      # We're not interested in most of the automatically added document metadata
+      next if ($infodb_value_key eq "archivedir" ||
+               $infodb_value_key eq "assocfilepath" ||
+               $infodb_value_key eq "childtype" ||
+               $infodb_value_key eq "contains" ||
+               $infodb_value_key eq "docnum" ||
+               $infodb_value_key eq "doctype" ||
+               $infodb_value_key eq "Encoding" ||
+               $infodb_value_key eq "FileSize" ||
+               $infodb_value_key eq "hascover" ||
+               $infodb_value_key eq "hastxt" ||
+               $infodb_value_key eq "lastmodified" ||
+               $infodb_value_key eq "metadataset" ||
+               $infodb_value_key eq "thistype" ||
+               $infodb_value_key =~ /^metadatafreq\-/ ||
+               $infodb_value_key =~ /^metadatalist\-/);
+
+      foreach my $infodb_value (@{$infodb_map->{$infodb_value_key}})
+      {
+		 print $infodb_handle "INSERT INTO document_metadata (docOID, element, value) VALUES ('" . $safe_infodb_key . "', '" . &sqlite_safe($infodb_value_key) . "', '" . &sqlite_safe($infodb_value) . "');\n";
+      }
+    }
+  }
+
+	 #### DEBUGGING
+	#my $new_file = "D:\\sql.txt";
+	#open(FOUT, ">>$new_file") or die "Unable to open $new_file for writing out sql statements...ERROR: $!\n";
+    #print FOUT "BEGIN;\n".$insertStatementsBuffer."\nEND;\n";
+    #close(FOUT);
+	#print STDERR $insertStatementsBuffer; 
+	 #### END DEBUGGING
+}
+
+sub write_infodb_rawentry
+{
+  my $infodb_handle = shift(@_);
+  my $infodb_key = shift(@_);
+  my $infodb_val = shift(@_);
+
+  my $safe_infodb_key = &sqlite_safe($infodb_key);
+  print $infodb_handle "INSERT OR REPLACE INTO data (key, value) VALUES ('" . $safe_infodb_key . "', '" . &sqlite_safe($infodb_val) . "');\n";
+}
+
+
+sub set_infodb_entry
+{
+  my $infodb_file_path = shift(@_);
+  my $infodb_key = shift(@_);
+  my $infodb_map = shift(@_);
+  my $infodb_handle = open_infodb_write_handle($infodb_file_path, "append");
+
+  if (!defined $infodb_handle) {
+      print STDERR "Error: Failed to open infodb write handle\n";
+	  return -1;
+  }
+  else {
+	  write_infodb_entry($infodb_handle,$infodb_key,$infodb_map);
+      close_infodb_write_handle($infodb_handle);
+  }
+  # Not currently checking for errors on write to DB
+  return 0;
+
+}
+
+
+
+sub delete_infodb_entry
+{
+  my $infodb_handle = shift(@_);
+  my $infodb_key = shift(@_);
+
+  # Delete the key from the "data" table
+
+  my $safe_infodb_key = &sqlite_safe($infodb_key);
+
+  print $infodb_handle "DELETE FROM data WHERE key='" . $safe_infodb_key . "';\n";
+
+  # If this infodb entry is for a document, delete the
+  #   "document_metadata" table entry also (for use by the dynamic classifiers)
+  if ($infodb_key !~ /\./)
+  {
+      # Possible for there not to be a docOID matching this infodb_key
+      # (entries are only made when <doctype> == doc
+      # Attempt to delete it, and don't complain if one isn't found
+
+      print $infodb_handle "DELETE FROM document_metadata WHERE docOID='" . $safe_infodb_key . "';\n";
+
+  }
+}
+
+
+1;
Index: gs2-extensions/tdb/trunk/perllib/DBDrivers/TDB.pm
===================================================================
--- gs2-extensions/tdb/trunk/perllib/DBDrivers/TDB.pm	(revision 30318)
+++ gs2-extensions/tdb/trunk/perllib/DBDrivers/TDB.pm	(revision 30318)
@@ -0,0 +1,249 @@
+###############################################################################
+#
+# DBDrivers/TDB.pm -- utility functions for writing to tdb databases. Should be
+#                     hauntingly similar to GDBM utility functions.
+#
+# A component of the Greenstone digital library software from the New Zealand
+# Digital Library Project at the University of Waikato, New Zealand.
+#
+# Copyright (C) 2011-2015 New Zealand Digital Library Project
+#
+# This program is free software; you can redistribute it and/or modify it under
+# the terms of the GNU General Public License as published by the Free Software
+# Foundation; either version 2 of the License, or (at your option) any later
+# version.
+#
+# This program is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
+# more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# this program; if not, write to the Free Software Foundation, Inc., 675 Mass
+# Ave, Cambridge, MA 02139, USA.
+#
+###############################################################################
+
+package DBDrivers::TDB;
+
+# Pragma
+use strict;
+
+# Libraries
+use Cwd;
+use ghtml;
+use util;
+use DBDrivers::GDBM;
+
+sub BEGIN
+{
+    if (!defined $ENV{'GSDLHOME'} || !defined $ENV{'GSDLOS'}) {
+        die("Error! Environment not prepared. Have you sourced setup.bash?\n");
+    }
+    if (!defined $ENV{'GEXTTDBEDIT_INSTALLED'}) {
+        die("Error! Path to TDB binaries not found. Have you sourced setup.bash?\n");
+    }
+    @DBDrivers::TDB::ISA = ( 'DBDrivers::GDBM' );
+}
+
+sub new
+{
+    my $class = shift(@_);
+    return bless ($self, $class);
+}
+
+# -----------------------------------------------------------------------------
+#   TDB IMPLEMENTATION
+# -----------------------------------------------------------------------------
+
+## Ask TDB executables to display debugging information?
+my $debug = 0; # 1 to enable
+
+## Should the TDB used a specific affinity?
+my $forced_affinity = -1; # zero upwards indicates the affinity
+
+## Default TDB file extension
+my $infodb_file_extension = '.tdb';
+
+## @function _get_tdb_executable(string)
+#
+sub _get_tdb_executable
+{
+    my $program = shift(@_);
+    if (!defined $ENV{GEXTTDBEDIT_INSTALLED} || !-d $ENV{GEXTTDBEDIT_INSTALLED})
+    {
+	die('Fatal Error! Path to TDB binaries not found. Have you sourced setup.bash?');
+    }
+    my $program_exe = &util::filename_cat($ENV{GEXTTDBEDIT_INSTALLED} . '/bin/' . $program . &util::get_os_exe());
+    if (!-x $program_exe)
+    {
+	die('Fatal Error! File doesn\'t exist or isn\'t executable: ' . $program_exe);
+    }
+    return $program_exe;
+}
+## get_tdb_executable(string) => string ##
+
+
+# With infodb_handle already set up, these functions work the same as parent version
+# sub close_infodb_write_handle {}
+# sub delete_infodb_entry {}
+# sub write_infodb_entry {}
+# sub write_infodb_rawentry {}
+
+
+## @function open_infodb_write_handle(string, string)
+#
+sub open_infodb_write_handle
+{
+    my $infodb_file_path = shift(@_);
+    my $opt_append = shift(@_);
+
+    my $txt2tdb_exe = &_get_tdb_executable('txt2tdb');
+
+    my $pool_key = $infodb_file_path;
+    my $cmd = '"' . $txt2tdb_exe . '"';
+    if ((defined $opt_append) && ($opt_append eq "append")) {
+        $cmd .= ' -append';
+    }
+    $cmd .= ' "' . $infodb_file_path . '"';
+    # Optional flags
+    if ($forced_affinity >= 0) {
+        $cmd = 'taskset -c 5 ' . $cmd;
+    }
+    if ($debug) {
+        $cmd .= ' -debug';
+    }
+
+    # we're going to pipe the key value pairs, in the appropriate format, from
+    # within the buildproc, so we create a piped handle here
+    my $infodb_file_handle = undef;
+    print STDERR "tdb::open_infodb_write_handle(" . $infodb_file_path . ")\n";
+    if(!open($infodb_file_handle, "| $cmd")) {
+        print STDERR "Error: Failed to open pipe to $cmd\n";
+        print STDERR "       $!\n";
+        return undef;
+    }
+    binmode($infodb_file_handle,":utf8");
+    return $infodb_file_handle;
+}
+## open_infodb_write_handle(string, string) => filehandle ##
+
+
+## @function get_infodb_file_path(string, string)
+#
+sub get_infodb_file_path
+{
+    my $collection_name = shift(@_);
+    my $infodb_directory_path = shift(@_);
+    my $infodb_file_name = &util::get_dirsep_tail($collection_name) . $infodb_file_extension;
+    return &util::filename_cat($infodb_directory_path, $infodb_file_name);
+}
+## get_infodb_file_path(string, string) => string ##
+
+
+## @function read_infodb_file
+#
+sub read_infodb_file
+{
+    my $infodb_file_path = shift(@_);
+    my $infodb_map = shift(@_);
+
+    my $tdb2txt_exe = &_get_tdb_executable('tdb2txt');
+
+    if (!open (PIPEIN, '"' . $tdb2txt_exe . '" "' . $infodb_file_path . '" |')) {
+        print STDERR 'Error: Failed to open pipe to ' . $tdb2txt_exe . "\n";
+        print STDERR "       $!\n";
+        return undef;
+    }
+
+    binmode(PIPEIN,":utf8");
+
+    my $infodb_line = "";
+    my $infodb_key = "";
+    my $infodb_value = "";
+    while (defined ($infodb_line = <PIPEIN>)) {
+        if ($infodb_line =~ /^\[([^\]]+)\]$/) {
+            $infodb_key = $1;
+        }
+        elsif ($infodb_line =~ /^-{70}$/) {
+            $infodb_map->{$infodb_key} = $infodb_value;
+            $infodb_key = "";
+            $infodb_value = "";
+        }
+        else {
+            $infodb_value .= $infodb_line;
+        }
+    }
+    close (PIPEIN);
+}
+## read_infodb_file(string, hashmap) => void ##
+
+
+## @function read_infodb_keys(string, hashmap)
+#
+sub read_infodb_keys
+{
+    my $infodb_file_path = shift(@_);
+    my $infodb_map = shift(@_);
+
+    my $tdbkeys_exe = &_get_tdb_executable('tdbkeys');
+
+    if (!open (PIPEIN, '"' . tdbkeys_exe . '" "' . $infodb_file_path . '" |')) {
+        die("Error! Couldn't open pipe from read_infodb_keys: $infodb_file_path\n$!\n");
+    }
+
+    binmode(PIPEIN,":utf8");
+
+    my $infodb_line = "";
+    my $infodb_key = "";
+    my $infodb_value = "";
+    while (defined ($infodb_line = <PIPEIN>)) {
+        # remove end of line
+        chomp $infodb_line;
+        $infodb_map->{$infodb_line} = 1;
+    }
+
+    close (PIPEIN);
+}
+## read_infodb_keys(string, hashmap) => void ##
+
+
+## @function set_infodb_entry(string, string, hashmap)
+#
+sub set_infodb_entry
+{
+    my $infodb_file_path = shift(@_);
+    my $infodb_key = shift(@_);
+    my $infodb_map = shift(@_);
+
+    # Protect metadata values that go inside quotes for tdbset
+    foreach my $k (keys %$infodb_map) {
+        my @escaped_v = ();
+        foreach my $v (@{$infodb_map->{$k}}) {
+            if ($k eq "contains") {
+                # protect quotes in ".2;".3 etc
+                $v =~ s/\"/\\\"/g;
+                push(@escaped_v, $v);
+            }
+            else {
+                my $ev = &ghtml::unescape_html($v);
+                $ev =~ s/\"/\\\"/g;
+                push(@escaped_v, $ev);
+            }
+        }
+        $infodb_map->{$k} = \@escaped_v;
+    }
+
+    # Generate the record string
+    my $serialized_infodb_map = &_convert_infodb_hash_to_string($infodb_map);
+
+    # Store it into GDBM
+    my $tdbset_exe = &_get_tdb_executable('tdbset');
+    my $cmd = '"' . $tdbset_exe . '" "' . $infodb_file_path . '" "' . $infodb_key . '" "' . $serialized_infodb_map . '"';
+    my $status = system($cmd);
+
+    return $status;
+}
+## set_infodb_entry(string, string, hashmap) => integer ##
+
+1;
