root/main/trunk/greenstone2/perllib/cgiactions/metadataaction.pm @ 27366

Revision 27366, 115.9 KB (checked in by ak19, 7 years ago)

1. Handling quotes and colons in user comments: since these are sent and retrieved from metadata-server.pl as JSON strings, the quotes and colons in user-added meta needs to be protected since JSON uses these characters for packaging up data. 2. Cosmetic changes to baseaction: clarified some comments.

Line 
1###########################################################################
2#
3# metadataaction.pm --
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) 2009 New Zealand Digital Library Project
9#
10# This program is free software; you can redistr   te it and/or modify
11# it under the terms of the GNU General Public License as published by
12# the Free Software Foundation; either version 2 of the License, or
13# (at your option) any later version.
14#
15# This program is distributed in the hope that it will be useful,
16# but WITHOUT ANY WARRANTY; without even the implied warranty of
17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18# GNU General Public License for more details.
19#
20# You should have received a copy of the GNU General Public License
21# along with this program; if not, write to the Free Software
22# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23#
24###########################################################################
25
26package metadataaction;
27
28use strict;
29
30use cgiactions::baseaction;
31
32use dbutil;
33use ghtml;
34
35use JSON;
36
37
38BEGIN {
39#    unshift (@INC, "$ENV{'GSDLHOME'}/perllib/cpan/perl-5.8");
40    require XML::Rules;
41}
42
43@metadataaction::ISA = ('baseaction');
44
45my $action_table =
46{
47    #GET METHODS
48    "get-import-metadata" => {
49        'compulsory-args' => [ "d", "metaname" ],
50        'optional-args'   => [ "metapos" ] },
51
52    "get-archives-metadata" => {
53        'compulsory-args' => [ "d", "metaname" ],
54        'optional-args'   => [ "metapos" ] },
55   
56    "get-index-metadata" => {
57        'compulsory-args' => [ "d", "metaname" ],
58        'optional-args'   => [ "metapos" ] },
59
60    "get-metadata" => { # alias for get-index-metadata
61        'compulsory-args' => [ "d", "metaname" ],
62        'optional-args'   => [ "metapos" ] },
63
64    "get-live-metadata" => {
65        'compulsory-args' => [ "d", "metaname" ],
66        'optional-args'   => [ ] },
67
68    "get-metadata-array" => { # where param can be ONE of: index (default), import, archives, live
69        'compulsory-args' => [ "json" ],
70        'optional-args'   => [ "where" ],
71        'help-string' => [
72        'metadata-server.pl?a=get-metadata-array&c=demo&where=index&json=[{"docid":"HASHc5bce2d6d3e5b04e470ec9","metatable":[{"metaname":"username","metapos":"all"},{"metaname":"usertimestamp","metapos":"all"}, {"metaname":"usercomment","metapos":"all"}]}]'
73        ]},
74
75    #SET METHODS
76    "set-live-metadata" => {
77        'compulsory-args' => [ "d", "metaname", "metavalue" ],
78        'optional-args'   => [ ] },
79
80    "set-metadata" => { # generic set-meta function. The 'where' param can be set to any combination of index|archives|import|live. docid d is still compulsory for setting index, archives and live meta
81        'compulsory-args' => [ "metaname", "metavalue" ],
82        'optional-args'   => [ "where", "metapos", "metamode", "prevmetavalue", "d", "f" ] },
83
84    "set-index-metadata" => {
85        'compulsory-args' => [ "d", "metaname", "metavalue" ],
86        'optional-args'   => [ "metapos", "metamode" ] },
87
88    "set-archives-metadata" => {
89        'compulsory-args' => [ "d", "metaname", "metavalue" ],
90        'optional-args'   => [ "metapos", "metamode", "prevmetavalue" ] }, # metamode can be "accumulate", "override",
91   
92    "set-import-metadata" => {
93        'compulsory-args' => [ "metaname", "metavalue" ],
94        'optional-args'   => [ "d", "f", "metamode", "metapos", "prevmetavalue" ] }, # metamode can be "accumulate", "override", or "unique-id". Also need to add the ability to specify a previous metadata value to overwrite (because we can't use metapos). Metapos now supported, but assumes you are working with a Simple (instead of Complex) collection
95                 
96    #SET METHODS (ARRAY)
97    "set-metadata-array" => {
98        'compulsory-args' => [ "where", "json" ],
99        'optional-args'   => [ ],
100        'help-string' => [
101        'A simple example: metadata-server.pl?a=set-metadata-array&where=archives|index|import&c=demo&json=[{"docid":"HASHc5bce2d6d3e5b04e470ec9","metaname":"Title","metavalue":"Tralalala","metamode":"accumulate"},{"docid":"HASHbe483fa4df4e096335d1c8","metaname":"Title","metavalue":"Lala was here","metapos":0, "metamode":"override"}]',
102       
103        'A more complex example: metadata-server.pl?a=set-metadata-array&where=archives|index&c=demo&json=[{"docid":"HASHc5bce2d6d3e5b04e470ec9.1","metatable":[{"metaname":"Title","metavals":["Transformers","Robots in disguise","Autobots"]}],"metamode":"override"},{"docid":"HASHbe483fa4df4e096335d1c8.2","metaname":"Title","metavalue":"Pinky was here","metamode":"accumulate"}]' ] },
104
105# The same examples rewritten for when running the metadata-server.pl script from the commandline:
106
107# the simple example: metadata-server.pl a="set-metadata-array" where="archives|index|import" c="demo" json="[{\"docid\":\"HASHc5bce2d6d3e5b04e470ec9\",\"metaname\":\"Title\",\"metavalue\":\"Tralalala\",\"metamode\":\"accumulate\"},{\"docid\":\"HASHbe483fa4df4e096335d1c8\",\"metaname\":\"Title\",\"metavalue\":\"Lala was here\",\"metapos\":0, \"metamode\":\"override\"}]",
108       
109# the more complex example: metadata-server.pl a="set-metadata-array" where="archives|index" c="demo" json="[{\"docid\":\"HASHc5bce2d6d3e5b04e470ec9.1\",\"metatable\":[{\"metaname\":\"Title\",\"metavals\":[\"Transformers\",\"Robots in disguise\",\"Autobots\"]}],\"metamode\":\"override\"},{\"docid\":\"HASHbe483fa4df4e096335d1c8.2\",\"metaname\":\"Title\",\"metavalue\":\"Pinky was here\",\"metamode\":\"accumulate\"}]"
110                     
111    "set-archives-metadata-array" => {
112        'compulsory-args' => [ "json" ],
113        'optional-args'   => [ ] },
114       
115    "set-import-metadata-array" => {
116        'compulsory-args' => [ "json" ],
117        'optional-args'   => [ ] },
118
119    "set-index-metadata-array" => {
120        'compulsory-args' => [ "json" ],
121        'optional-args'   => [ ] },
122   
123    "set-live-metadata-array" => {
124        'compulsory-args' => [ "json" ],
125        'optional-args'   => [ ] },
126       
127    #REMOVE METHODS
128    "remove-import-metadata" => {
129        'compulsory-args' => [ "d", "metaname", "metavalue" ], #TODO: add f argument
130        'optional-args'   => [ "metapos" ] }, # only provide metapos arg for SIMPLE collections
131                     
132    "remove-archives-metadata" => {
133        'compulsory-args' => [ "d", "metaname" ], #TODO: add f argument
134        'optional-args'   => [ "metapos", "metavalue" ] },
135
136    "remove-live-metadata" => {
137        'compulsory-args' => [ "d", "metaname" ],
138        'optional-args'   => [ ] },
139
140    "remove-index-metadata" => {
141        'compulsory-args' => [ "d", "metaname" ],
142        'optional-args'   => [ "metapos", "metavalue" ] },
143
144    "remove-metadata" => { # generic remove-meta function. The 'where' param can be set to any combination of index|archives|import|live. docid d is still compulsory for setting index, archives and live meta
145        'compulsory-args' => [ "d", "metaname" ],
146        'optional-args'   => [ "where", "metapos", "metavalue" ] },
147
148    #INSERT METHODS
149    "insert-metadata" => {
150        'compulsory-args' => [ "d", "metaname", "metavalue" ],
151        'optional-args'   => [ ] }
152};
153
154
155sub new
156{
157    my $class = shift (@_);
158    my ($gsdl_cgi,$iis6_mode) = @_;
159
160    # Treat metavalue specially.  To transmit this through a GET request
161    # the Javascript side has url-encoded it, so here we need to decode
162    # it before proceeding
163
164    my $url_encoded_metavalue = $gsdl_cgi->param("metavalue");
165    my $url_decoded_metavalue = &unicode::url_decode($url_encoded_metavalue,1);
166    my $unicode_array = &unicode::utf82unicode($url_decoded_metavalue);
167
168    $url_decoded_metavalue = join("",map(chr($_),@$unicode_array));
169    $gsdl_cgi->param("metavalue",$url_decoded_metavalue);
170
171    my $self = new baseaction($action_table,$gsdl_cgi,$iis6_mode);
172
173    return bless $self, $class;
174}
175
176
177sub get_live_metadata
178{
179    my $self = shift @_;
180
181    my $username  = $self->{'username'};
182    my $collect   = $self->{'collect'};
183    my $gsdl_cgi  = $self->{'gsdl_cgi'};
184    my $gsdlhome  = $self->{'gsdlhome'};
185    my $infodbtype = $self->{'infodbtype'};
186   
187    # live metadata gets/saves value scoped (prefixed) by the current usename
188    # so (for now) let's not bother to enforce authentication
189
190    # Obtain the collect dir
191    my $site = $self->{'site'};
192    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
193    ## my $collect_dir = &util::filename_cat($gsdlhome, "collect");
194
195    # No locking collection when getting metadata, only when setting it
196#    $self->lock_collection($username, $collect); # Make sure the collection isn't locked by someone else
197
198    # look up additional args
199    my $docid  = $self->{'d'};
200    if ((!defined $docid) || ($docid =~ m/^\s*$/)) {
201       $gsdl_cgi->generate_error("No docid (d=...) specified.");
202    }
203
204    # Generate the dbkey
205    my $metaname  = $self->{'metaname'};
206    my $dbkey = "$docid.$metaname";
207
208    # To people who know $collect_tail please add some comments
209    # Obtain path to the database
210    my $collect_tail = $collect;
211    $collect_tail =~ s/^.*[\/|\\]//;
212    my $index_text_directory = &util::filename_cat($collect_dir,$collect,"index","text");
213    my $infodb_file_path = &dbutil::get_infodb_file_path($infodbtype, "live-$collect_tail", $index_text_directory);
214   
215    # Obtain the content of the key
216    my $cmd = "gdbmget $infodb_file_path $dbkey";
217    if (open(GIN,"$cmd |") == 0) {
218        # Catch error if gdbmget failed
219    my $mess = "Failed to get metadata key: $metaname\n";
220    $mess .= "$!\n";
221
222    $gsdl_cgi->generate_error($mess);
223    }
224    else {
225    binmode(GIN,":utf8");
226        # Read everything in and concatenate them into $metavalue
227    my $metavalue = "";
228    my $line;
229    while (defined ($line=<GIN>)) {
230        $metavalue .= $line;
231    }
232    close(GIN);
233    chomp($metavalue); # Get rid off the tailing newlines
234    $gsdl_cgi->generate_ok_message("$metavalue");
235    }
236
237    # Release the lock once it is done
238#    $self->unlock_collection($username, $collect);
239}
240
241# just calls the index version
242sub get_metadata
243{
244    my $self = shift @_;
245    $self->get_index_metadata(@_);
246}
247
248# JSON version that will get the requested metadata values
249# from the requested source (index, import, archives or live)
250# One of the params is a JSON string and the return value is JSON too
251# http://forums.asp.net/t/1844684.aspx/1 - Web api method return json in string
252sub get_metadata_array
253{
254    my $self = shift @_;
255
256    my $where = $self->{'where'};
257    if (!$where) { 
258    $where = "index"; # default behaviour is to get the values from index
259    }
260
261    # Only when setting metadata do we perform authentication and do we lock the collection,
262    # not when getting metadata
263
264    # for get_meta_array, the where param can only be ONE of import, archives, index, live
265    if($where =~ m/index/) {
266    $self->_get_index_metadata_array(@_);
267    }
268    elsif($where =~ m/archives/) {
269    $self->_get_archives_metadata_array(@_);
270    }
271    elsif($where =~ m/import/) {
272    $self->_get_import_metadata_array(@_);
273    }
274    elsif($where =~ m/live/) {
275        $self->_get_live_metadata_array(@_);
276    }
277}
278
279# Unused at present. Added for completion. Tested.
280sub _get_import_metadata_array {
281   
282    my $self = shift @_;
283
284    my $collect   = $self->{'collect'};
285    my $gsdl_cgi  = $self->{'gsdl_cgi'};
286    my $site = $self->{'site'};
287    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
288   
289    # look up additional args
290    my $infodbtype = $self->{'infodbtype'};
291   
292    my $archive_dir = &util::filename_cat($collect_dir, $collect, "archives");
293    my $arcinfo_doc_filename = &dbutil::get_infodb_file_path($infodbtype, "archiveinf-doc", $archive_dir);
294    my $json_str      = $self->{'json'};
295    my $doc_array = decode_json $json_str;
296
297    my $json_result_str = "[";
298    my $first_doc_rec = 1;
299    foreach my $doc_array_rec ( @$doc_array ) {
300   
301    my $docid = $doc_array_rec->{'docid'}; # no subsection metadata support in metadata.xml, only toplevel meta
302   
303    if($first_doc_rec) {
304        $first_doc_rec = 0;
305    } else {
306        $json_result_str .= ",";
307    }
308    $json_result_str = $json_result_str . "{\"docid\":\"" . $docid . "\""; 
309
310    my $metatable = $doc_array_rec->{'metatable'}; # a subarray, or need to generate an error saying JSON structure is wrong
311    $json_result_str = $json_result_str . ",\"metatable\":[";
312
313    my $first_rec = 1;
314    foreach my $metatable_rec ( @$metatable ) { # the subarray metatable is an array of hashmaps       
315
316        # Read the docid entry     
317        my $doc_rec = &dbutil::read_infodb_entry($infodbtype, $arcinfo_doc_filename, $docid);
318        # This now stores the full pathname
319        my $import_filename = $doc_rec->{'src-file'}->[0];
320
321        # figure out correct metadata.xml file [?]
322        # Assuming the metadata.xml file is next to the source file
323        # Note: This will not work if it is using the inherited metadata from the parent folder
324        my ($import_tailname, $import_dirname) = File::Basename::fileparse($import_filename);
325        my $metadata_xml_filename = &util::filename_cat($import_dirname, "metadata.xml");
326
327
328        if($first_rec) {
329        $first_rec = 0;
330        } else {
331        $json_result_str .= ",";       
332        }
333       
334        my $metaname  = $metatable_rec->{'metaname'};
335        $json_result_str .= "{\"metaname\":\"$metaname\",\"metavals\":[";
336
337        my $metapos   = $metatable_rec->{'metapos'}; # 0... 1|all|undefined
338        if(!defined $metapos) {
339        $metapos = 0;
340        }
341
342        # Obtain the specified metadata value(s)
343        my $metavalue;
344
345        if($metapos ne "all") { # get the value at a single metapos
346        $metavalue = $self->get_metadata_from_metadata_xml($gsdl_cgi, $metadata_xml_filename, $metaname, $metapos, $import_tailname);
347
348        #print STDERR "**** Metafilename, metaname, metapos, sec_num: $metadata_xml_filename, $metaname, $metapos, $import_tailname\n";
349       
350        $json_result_str .= "{\"metapos\":\"$metapos\",\"metavalue\":\"$metavalue\"}";
351
352        } else {
353        my $first_metaval = 1;
354        $metapos = 0;
355        $metavalue = $self->get_metadata_from_metadata_xml($gsdl_cgi, $metadata_xml_filename, $metaname, $metapos, $import_tailname);
356
357        while (defined $metavalue && $metavalue ne "") {
358            if($first_metaval) {       
359            $first_metaval = 0;
360            } else {
361            $json_result_str .= ",";
362            }
363       
364            $json_result_str .= "{\"metapos\":\"$metapos\",\"metavalue\":\"$metavalue\"}";
365
366            $metapos++;
367            $metavalue = $self->get_metadata_from_metadata_xml($gsdl_cgi, $metadata_xml_filename, $metaname, $metapos, $import_tailname);
368        }
369        }
370
371        $json_result_str .= "]}"; # close metavals array and metatable record
372    }
373   
374    $json_result_str .= "]}"; # close metatable array and docid record
375    }
376
377    $json_result_str .= "]"; # close array of docids
378    $gsdl_cgi->generate_ok_message($json_result_str."\n");
379}
380
381# Unused method, but included for completion. Tested, works. Takes a JSON string and returns a JSON string.
382# For more information on the format of the output, see _get_index_metadata_array, which is in use.
383sub _get_archives_metadata_array {
384
385    my $self = shift @_;
386
387    my $collect   = $self->{'collect'};
388    my $gsdl_cgi  = $self->{'gsdl_cgi'};
389    my $site = $self->{'site'};
390    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
391
392    # look up additional args   
393    my $infodbtype = $self->{'infodbtype'};
394
395    my $archive_dir = &util::filename_cat($collect_dir, $collect, "archives");
396    my $arcinfo_doc_filename = &dbutil::get_infodb_file_path($infodbtype, "archiveinf-doc", $archive_dir);
397
398    my $json_str      = $self->{'json'};
399    my $doc_array = decode_json $json_str;
400
401    my $json_result_str = "[";
402    my $first_doc_rec = 1;
403    foreach my $doc_array_rec ( @$doc_array ) {
404   
405    my $docid     = $doc_array_rec->{'docid'};
406   
407    if($first_doc_rec) {
408        $first_doc_rec = 0;
409    } else {
410        $json_result_str .= ",";
411    }
412    $json_result_str = $json_result_str . "{\"docid\":\"" . $docid . "\""; 
413
414    my $metatable = $doc_array_rec->{'metatable'}; # a subarray, or need to generate an error saying JSON structure is wrong
415    $json_result_str = $json_result_str . ",\"metatable\":[";
416
417    my $first_rec = 1;
418    foreach my $metatable_rec ( @$metatable ) { # the subarray metatable is an array of hashmaps       
419
420        my ($docid, $docid_secnum) = ($doc_array_rec->{'docid'} =~ m/^(.*?)(\..*)?$/);
421        $docid_secnum = "" if (!defined $docid_secnum);
422
423        # Read the docid entry     
424        my $doc_rec = &dbutil::read_infodb_entry($infodbtype, $arcinfo_doc_filename, $docid);
425        # This now stores the full pathname
426        my $doc_filename = $doc_rec->{'doc-file'}->[0];
427        $doc_filename = &util::filename_cat($archive_dir, $doc_filename);
428
429        if($first_rec) {
430        $first_rec = 0;
431        } else {
432        $json_result_str .= ",";       
433        }
434       
435        my $metaname  = $metatable_rec->{'metaname'};
436        $json_result_str .= "{\"metaname\":\"$metaname\",\"metavals\":[";
437
438        my $metapos   = $metatable_rec->{'metapos'}; # 0... 1|all|undefined
439        if(!defined $metapos) {
440        $metapos = 0;
441        }
442
443
444        # Obtain the specified metadata value(s)
445        my $metavalue;
446
447        if($metapos ne "all") { # get the value at a single metapos
448
449        $metavalue = $self->get_metadata_from_archive_xml($gsdl_cgi, $doc_filename, $metaname, $metapos, $docid_secnum);
450        #print STDERR "**** Docname, metaname, metapos, sec_num: $doc_filename, $metaname, $metapos, $docid_secnum\n";
451       
452        $json_result_str .= "{\"metapos\":\"$metapos\",\"metavalue\":\"$metavalue\"}";
453
454        } else {
455        my $first_metaval = 1;
456        $metapos = 0;
457        $metavalue = $self->get_metadata_from_archive_xml($gsdl_cgi, $doc_filename, $metaname, $metapos, $docid_secnum);
458
459        while (defined $metavalue && $metavalue ne "") {
460            if($first_metaval) {       
461            $first_metaval = 0;
462            } else {
463            $json_result_str .= ",";
464            }
465       
466            $json_result_str .= "{\"metapos\":\"$metapos\",\"metavalue\":\"$metavalue\"}";
467
468            $metapos++;
469            $metavalue = $self->get_metadata_from_archive_xml($gsdl_cgi, $doc_filename, $metaname, $metapos, $docid_secnum);
470        }
471        }
472
473        $json_result_str .= "]}"; # close metavals array and metatable record
474    }
475   
476    $json_result_str .= "]}"; # close metatable array and docid record
477    }
478
479    $json_result_str .= "]"; # close array of docids
480    $gsdl_cgi->generate_ok_message($json_result_str."\n");
481}
482
483
484# Unused at present. Added for completion. Tested, but not sure if it retrieves metadata in the manner it's expected to.
485sub _get_live_metadata_array
486{
487    my $self = shift @_;
488
489    my $collect   = $self->{'collect'};
490    my $gsdl_cgi  = $self->{'gsdl_cgi'};
491    my $site = $self->{'site'};
492    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
493
494    # look up additional args   
495    my $infodbtype = $self->{'infodbtype'};
496   
497    # To people who know $collect_tail please add some comments
498    # Obtain the path to the database
499    my $collect_tail = $collect;
500    $collect_tail =~ s/^.*[\/|\\]//;
501    my $index_text_directory = &util::filename_cat($collect_dir,$collect,"index","text");
502    my $infodb_file_path = &dbutil::get_infodb_file_path($infodbtype, "live-$collect_tail", $index_text_directory);
503
504    my $json_str      = $self->{'json'};
505    my $doc_array = decode_json $json_str;
506
507    my $json_result_str = "[";
508    my $first_doc_rec = 1;
509
510    foreach my $doc_array_rec ( @$doc_array ) {
511   
512    my $docid     = $doc_array_rec->{'docid'};
513   
514    if($first_doc_rec) {
515        $first_doc_rec = 0;
516    } else {
517        $json_result_str .= ",";
518    }
519    $json_result_str = $json_result_str . "{\"docid\":\"" . $docid . "\""; 
520   
521    my $metatable = $doc_array_rec->{'metatable'}; # a subarray, or need to generate an error saying JSON structure is wrong
522    $json_result_str = $json_result_str . ",\"metatable\":[";
523   
524    my $first_rec = 1;
525    foreach my $metatable_rec ( @$metatable ) { # the subarray metatable is an array of hashmaps       
526        if($first_rec) {
527        $first_rec = 0;
528        } else {
529        $json_result_str .= ",";       
530        }
531       
532        my $metaname  = $metatable_rec->{'metaname'};
533        $json_result_str .= "{\"metaname\":\"$metaname\",\"metavals\":[";
534       
535        # Generate the dbkey
536        my $dbkey = "$docid.$metaname";
537       
538        # metapos for get_live_metadata is always assumed to be "all".
539        # It's always going to get all the lines of metavalues associated with a metaname
540        # (It's the metaname itself that should contain an increment number, if there are to be multiple values).
541        #my $metapos = "all";
542        my $metapos = $metatable_rec->{'metapos'} || 0; # Can be 0... 1|all|undefined. Defaults to 0 if undefined/false
543        my $metavalue = "";
544       
545        # Obtain the content of the key
546        my $cmd = "gdbmget $infodb_file_path $dbkey";
547        if (open(GIN,"$cmd |") != 0) { # Success.
548       
549        binmode(GIN,":utf8");
550        # Read everything in and concatenate them into $metavalue       
551        my $line;
552        my $first_metaval = 1;
553        my $pos = 0;
554        while (defined ($line=<GIN>)) {
555            chomp($line); # Get rid off the tailing newlines
556           
557            if($metapos eq "all") {
558            if($first_metaval) {       
559                $first_metaval = 0;
560            } else {
561                $json_result_str .= ",";
562            }           
563            $metavalue = $line;
564            $json_result_str .= "{\"metapos\":\"$pos\",\"metavalue\":\"$metavalue\"}";
565            } elsif($metapos == $pos) {
566            $metavalue = $line;
567            $json_result_str .= "{\"metapos\":\"$metapos\",\"metavalue\":\"$metavalue\"}";
568            last;
569            } # else, the current $pos is not the required $metapos
570            $pos += 1;
571        }
572        close(GIN);
573        } # else open cmd == 0 (failed) and metavals array will be empty [] for this metaname
574       
575        $json_result_str .= "]}"; # close metavals array and metatable record
576    }
577   
578    $json_result_str .= "]}"; # close metatable array and docid record
579    }
580
581    $json_result_str .= "]"; # close array of docids
582   
583    $gsdl_cgi->generate_ok_message($json_result_str."\n");   
584}
585
586
587# Takes a JSON string and returns a JSON string
588# Request string is of the form:
589# http://localhost:8283/greenstone/cgi-bin/metadata-server.pl?a=get-metadata-array&c=demo&where=index&json=[{"docid":"HASHc5bce2d6d3e5b04e470ec9","metatable":[{"metaname":"username","metapos":"all"},{"metaname":"usertimestamp","metapos":"all"}, {"metaname":"usercomment","metapos":"all"}]}]
590# Resulting string is of the form:
591# [{"docid":"HASHc5bce2d6d3e5b04e470ec9","metatable":[{"metaname":"username","metavals":[{"metapos":"0","metavalue":"me"},{"metapos":"1","metavalue":"admin"}]},{"metaname":"usertimestamp","metavals":[{"metapos":"0","metavalue":"1367900586888"},{"metapos":"1","metavalue":"1367900616574"}]},{"metaname":"usercomment","metavals":[{"metapos":"0","metavalue":"Hi"},{"metapos":"1","metavalue":"Hello"}]}]}]
592sub _get_index_metadata_array
593{
594    my $self = shift @_;
595
596    my $collect   = $self->{'collect'};
597    my $gsdl_cgi  = $self->{'gsdl_cgi'};
598    my $site = $self->{'site'};
599    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
600
601    # look up additional args   
602    my $infodbtype = $self->{'infodbtype'};
603   
604    # To people who know $collect_tail please add some comments
605    # Obtain the path to the database
606    my $collect_tail = $collect;
607    $collect_tail =~ s/^.*[\/|\\]//;
608    my $index_text_directory = &util::filename_cat($collect_dir,$collect,"index","text");
609    my $infodb_file_path = &dbutil::get_infodb_file_path($infodbtype, $collect_tail, $index_text_directory);
610
611    my $json_str      = $self->{'json'};
612    my $doc_array = decode_json $json_str;
613
614    my $json_result_str = "[";
615    my $first_doc_rec = 1;
616
617    foreach my $doc_array_rec ( @$doc_array ) {
618   
619    my $docid     = $doc_array_rec->{'docid'};
620   
621    if($first_doc_rec) {
622        $first_doc_rec = 0;
623    } else {
624        $json_result_str .= ",";
625    }
626    $json_result_str = $json_result_str . "{\"docid\":\"" . $docid . "\""; 
627
628    my $metatable = $doc_array_rec->{'metatable'}; # a subarray, or need to generate an error saying JSON structure is wrong
629    $json_result_str = $json_result_str . ",\"metatable\":[";
630
631    my $first_rec = 1;
632    foreach my $metatable_rec ( @$metatable ) { # the subarray metatable is an array of hashmaps       
633        if($first_rec) {
634        $first_rec = 0;
635        } else {
636        $json_result_str .= ",";       
637        }
638       
639        my $metaname  = $metatable_rec->{'metaname'};
640        $json_result_str .= "{\"metaname\":\"$metaname\",\"metavals\":[";
641
642        my $metapos   = $metatable_rec->{'metapos'}; # 0... 1|all|undefined
643        if(!defined $metapos) {
644        $metapos = 0;
645        }
646
647         # Read the docid entry
648        my $doc_rec = &dbutil::read_infodb_entry($infodbtype, $infodb_file_path, $docid);
649 
650        # Basically loop through and unescape_html the values
651        foreach my $k (keys %$doc_rec) {
652        my @escaped_v = ();
653        foreach my $v (@{$doc_rec->{$k}}) {
654            my $ev = &ghtml::unescape_html($v);
655            push(@escaped_v, $ev);
656        }
657        $doc_rec->{$k} = \@escaped_v;
658        }
659
660        # Obtain the specified metadata value(s)
661        my $metavalue;
662
663        if($metapos ne "all") { # get the value at a single metapos
664
665        $metavalue = $doc_rec->{$metaname}->[$metapos];
666
667        # protect any double quotes and colons in the metavalue before putting it into JSON
668        $metavalue =~ s/\"/&quot;/g if defined $metavalue;
669        $metavalue =~ s/\:/&58;/g if defined $metavalue;
670
671        $json_result_str .= "{\"metapos\":\"$metapos\",\"metavalue\":\"$metavalue\"}";
672
673        } else {
674        my $first_metaval = 1;
675        $metapos = 0;
676        $metavalue = $doc_rec->{$metaname}->[$metapos];
677
678        while (defined $metavalue) {
679
680            # protect any double quotes and colons in the metavalue before putting it into JSON
681            $metavalue =~ s/\"/&quot;/g;
682            $metavalue =~ s/\:/&58;/g;
683
684            if($first_metaval) {       
685            $first_metaval = 0;
686            } else {
687            $json_result_str .= ",";
688            }
689       
690            $json_result_str .= "{\"metapos\":\"$metapos\",\"metavalue\":\"$metavalue\"}";
691
692            $metapos++;
693            $metavalue = $doc_rec->{$metaname}->[$metapos];
694        }
695        }
696
697        $json_result_str .= "]}"; # close metavals array and metatable record
698    }
699   
700    $json_result_str .= "]}"; # close metatable array and docid record
701    }
702
703    $json_result_str .= "]"; # close array of docids
704
705    $gsdl_cgi->generate_ok_message($json_result_str."\n");   
706}
707
708
709sub get_index_metadata
710{
711    my $self = shift @_;
712
713    my $username  = $self->{'username'};
714    my $collect   = $self->{'collect'};
715    my $gsdl_cgi  = $self->{'gsdl_cgi'};
716    my $gsdlhome  = $self->{'gsdlhome'};
717
718    # Obtain the collect dir
719    my $site = $self->{'site'};
720    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
721    ##my $collect_dir = &util::filename_cat($gsdlhome, "collect");
722
723    # look up additional args
724    my $docid     = $self->{'d'};
725    my $metaname  = $self->{'metaname'};
726    my $metapos   = $self->{'metapos'};
727    my $infodbtype = $self->{'infodbtype'};
728
729    # To people who know $collect_tail please add some comments
730    # Obtain path to the database
731    my $collect_tail = $collect;
732    $collect_tail =~ s/^.*[\/|\\]//;
733    my $index_text_directory = &util::filename_cat($collect_dir,$collect,"index","text");
734    my $infodb_file_path = &dbutil::get_infodb_file_path($infodbtype, $collect_tail, $index_text_directory);
735
736    # Read the docid entry
737    my $doc_rec = &dbutil::read_infodb_entry($infodbtype, $infodb_file_path, $docid);
738 
739    # Basically loop through and unescape_html the values
740    foreach my $k (keys %$doc_rec) {
741    my @escaped_v = ();
742    foreach my $v (@{$doc_rec->{$k}}) {
743        my $ev = &ghtml::unescape_html($v);
744        push(@escaped_v, $ev);
745    }
746    $doc_rec->{$k} = \@escaped_v;
747    }
748
749    # Obtain the specified metadata value
750    $metapos = 0 if (!defined $metapos);
751    my $metavalue = $doc_rec->{$metaname}->[$metapos];
752    $gsdl_cgi->generate_ok_message("$metavalue");
753   
754}
755
756
757sub get_import_metadata
758{
759    my $self = shift @_;
760
761    my $username  = $self->{'username'};
762    my $collect   = $self->{'collect'};
763    my $gsdl_cgi  = $self->{'gsdl_cgi'};
764    my $gsdlhome  = $self->{'gsdlhome'};
765
766    # Obtain the collect dir
767    my $site = $self->{'site'};
768    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
769    ##my $collect_dir = &util::filename_cat($gsdlhome, "collect");
770
771    # look up additional args
772    my $docid     = $self->{'d'};
773    my $metaname  = $self->{'metaname'};
774    my $metapos = $self->{'metapos'};
775    $metapos = 0 if (!defined $metapos); # gets the first value by default since metapos defaults to 0
776
777    my $infodbtype = $self->{'infodbtype'};
778    if (!defined $docid)
779    {
780        $gsdl_cgi->generate_error("No docid (d=...) specified.\n");
781    }
782
783    # Obtain where the metadata.xml is from the archiveinfo-doc.gdb file
784    # If the doc oid is not specified, we assume the metadata.xml is next to the specified "f"
785    my $metadata_xml_file;
786    my $import_filename = undef;
787   
788
789    my $archive_dir = &util::filename_cat($collect_dir, $collect, "archives");
790    my $arcinfo_doc_filename = &dbutil::get_infodb_file_path($infodbtype, "archiveinf-doc", $archive_dir);
791    my $doc_rec = &dbutil::read_infodb_entry($infodbtype, $arcinfo_doc_filename, $docid);
792
793    # This now stores the full pathname
794    $import_filename = $doc_rec->{'src-file'}->[0];
795
796    # figure out correct metadata.xml file [?]
797    # Assuming the metadata.xml file is next to the source file
798    # Note: This will not work if it is using the inherited metadata from the parent folder
799    my ($import_tailname, $import_dirname) = File::Basename::fileparse($import_filename);
800    my $metadata_xml_filename = &util::filename_cat($import_dirname, "metadata.xml");
801
802    $gsdl_cgi->generate_ok_message($self->get_metadata_from_metadata_xml($gsdl_cgi, $metadata_xml_filename, $metaname, $metapos, $import_tailname));
803
804}
805
806sub get_metadata_from_metadata_xml
807{
808    my $self = shift @_;
809    my ($gsdl_cgi, $metadata_xml_filename, $metaname, $metapos, $src_file) = @_;
810   
811    my @rules =
812    (
813        _default => 'raw',
814        'Metadata' => \&gfmxml_metadata,
815        'FileName' => \&mxml_filename
816    );
817       
818    my $parser = XML::Rules->new
819    (
820        rules => \@rules,
821        output_encoding => 'utf8'
822    );
823   
824    my $xml_in = "";
825    if (!open(MIN,"<$metadata_xml_filename"))
826    {
827        $gsdl_cgi->generate_error("Unable to read in $metadata_xml_filename: $!");
828    }
829    else
830    {
831        # Read them in
832        my $line;
833        while (defined ($line=<MIN>)) {
834            $xml_in .= $line;
835        }
836        close(MIN);
837
838        $parser->parse($xml_in, {metaname => $metaname, metapos => $metapos, src_file => $src_file});
839       
840        if(defined $parser->{'pad'}->{'metavalue'})
841        {
842            return $parser->{'pad'}->{'metavalue'};
843        }
844        else
845        {
846            return "";
847        }
848    }
849}
850
851sub gfmxml_metadata
852{
853    my ($tagname, $attrHash, $contextArray, $parentDataArray, $parser) = @_;
854
855    # no subsection support yet in metadata.xml
856
857    if (($parser->{'parameters'}->{'src_file'} eq $parser->{'parameters'}->{'current_file'}) && $parser->{'parameters'}->{'metaname'} eq $attrHash->{'name'})
858    {
859        if (!defined $parser->{'parameters'}->{'poscount'})
860        {
861            $parser->{'parameters'}->{'poscount'} = 0;
862        }
863        else
864        {
865            $parser->{'parameters'}->{'poscount'}++;
866        }
867   
868        # gets the first value by default, since metapos defaults to 0
869        if (($parser->{'parameters'}->{'poscount'} == $parser->{'parameters'}->{'metapos'}))
870        {
871            if($parser->{'parameters'}->{'metapos'} > 0) {
872            print STDERR "@@@@ WARNING: non-zero metapos.\n";
873            print STDERR "@@@@ Assuming SIMPLE collection and proceeding to retrieve the import meta at position: ".$parser->{'parameters'}->{'metapos'}.".\n";
874            }
875            $parser->{'pad'}->{'metavalue'} = $attrHash->{'_content'};
876        }
877    }
878}
879
880sub get_archives_metadata
881{
882    my $self = shift @_;
883
884    my $username  = $self->{'username'};
885    my $collect   = $self->{'collect'};
886    my $gsdl_cgi  = $self->{'gsdl_cgi'};
887#   my $gsdlhome  = $self->{'gsdlhome'};
888    my $infodbtype = $self->{'infodbtype'};
889
890    # Obtain the collect dir
891    my $site = $self->{'site'};
892    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
893   
894    my $archive_dir = &util::filename_cat($collect_dir, $collect, "archives");
895
896    # look up additional args
897    my ($docid, $docid_secnum) = ($self->{'d'} =~ m/^(.*?)(\..*)?$/);
898    $docid_secnum = "" if (!defined $docid_secnum);
899   
900    my $metaname = $self->{'metaname'};
901    my $metapos = $self->{'metapos'};
902    $metapos = 0 if (!defined $metapos);
903   
904    my $arcinfo_doc_filename = &dbutil::get_infodb_file_path($infodbtype, "archiveinf-doc", $archive_dir);
905    my $doc_rec = &dbutil::read_infodb_entry($infodbtype, $arcinfo_doc_filename, $docid);
906
907    # This now stores the full pathname
908    my $doc_filename = $doc_rec->{'doc-file'}->[0];
909
910    $gsdl_cgi->generate_ok_message($self->get_metadata_from_archive_xml($gsdl_cgi, &util::filename_cat($archive_dir, $doc_filename), $metaname, $metapos, $docid_secnum));
911
912}
913
914sub get_metadata_from_archive_xml
915{
916    my $self = shift @_;
917    my ($gsdl_cgi, $doc_xml_filename, $metaname, $metapos, $secid) = @_;
918   
919    my @start_rules = ('Section' => \&dxml_start_section);
920   
921    my @rules =
922    (
923        _default => 'raw',
924        'Metadata' => \&gfdxml_metadata
925    );
926       
927    my $parser = XML::Rules->new
928    (
929        start_rules => \@start_rules,
930        rules => \@rules,
931        output_encoding => 'utf8'
932    );
933   
934    my $xml_in = "";
935    if (!open(MIN,"<$doc_xml_filename"))
936    {
937        $gsdl_cgi->generate_error("Unable to read in $doc_xml_filename: $!");
938    }
939    else
940    {
941        # Read them in
942        my $line;
943        while (defined ($line=<MIN>)) {
944            $xml_in .= $line;
945        }
946        close(MIN);
947
948        $parser->parse($xml_in, {metaname => $metaname, metapos => $metapos, secid => $secid});
949       
950        if(defined $parser->{'pad'}->{'metavalue'})
951        {
952            return $parser->{'pad'}->{'metavalue'};
953        }
954        else
955        {
956            return "";
957        }
958    }
959}
960
961sub gfdxml_metadata
962{
963    my ($tagname, $attrHash, $contextArray, $parentDataArray, $parser) = @_;
964   
965    if(!($parser->{'parameters'}->{'secid'} eq $parser->{'parameters'}->{'curr_section_num'}))
966    {
967        return;
968    }
969
970    if ($parser->{'parameters'}->{'metaname'} eq $attrHash->{'name'})
971    {
972        if (!defined $parser->{'parameters'}->{'poscount'})
973        {
974            $parser->{'parameters'}->{'poscount'} = 0;
975        }
976        else
977        {
978            $parser->{'parameters'}->{'poscount'}++;
979        }
980    }
981
982    if (($parser->{'parameters'}->{'metaname'} eq $attrHash->{'name'}) && ($parser->{'parameters'}->{'poscount'} == $parser->{'parameters'}->{'metapos'}))
983    {   
984        $parser->{'pad'}->{'metavalue'} = $attrHash->{'_content'};
985    }
986}
987
988sub _set_live_metadata
989{
990    my $self = shift @_;
991
992    my $collect   = $self->{'collect'};
993    my $gsdl_cgi  = $self->{'gsdl_cgi'};
994    #my $gsdlhome  = $self->{'gsdlhome'};
995    my $infodbtype = $self->{'infodbtype'};
996
997    # Obtain the collect dir
998    my $site = $self->{'site'};
999    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
1000    ##my $collect_dir = &util::filename_cat($gsdlhome, "collect");
1001
1002
1003    # look up additional args
1004    my $docid     = $self->{'d'};
1005    if ((!defined $docid) || ($docid =~ m/^\s*$/)) {
1006      $gsdl_cgi->generate_error("No docid (d=...) specified."); # generates error and dies
1007    }
1008    my $metavalue = $self->{'metavalue'};
1009
1010    # Generate the dbkey   
1011    my $metaname  = $self->{'metaname'};
1012    my $dbkey = "$docid.$metaname";
1013
1014    # To people who know $collect_tail please add some comments
1015    # Obtain path to the database
1016    my $collect_tail = $collect;
1017    $collect_tail =~ s/^.*[\/|\\]//;
1018    my $index_text_directory = &util::filename_cat($collect_dir,$collect,"index","text");
1019    my $infodb_file_path = &dbutil::get_infodb_file_path($infodbtype, "live-$collect_tail", $index_text_directory);
1020
1021    # Set the new value
1022    my $cmd = "gdbmset \"$infodb_file_path\" \"$dbkey\" \"$metavalue\"";
1023    my $status = system($cmd);
1024    if ($status != 0) {
1025        # Catch error if gdbmget failed
1026    my $mess = "Failed to set metadata key: $dbkey\n";
1027
1028    $mess .= "PATH: $ENV{'PATH'}\n";
1029    $mess .= "cmd = $cmd\n";
1030    $mess .= "Exit status: $status\n";
1031    $mess .= "System Error Message: $!\n";
1032
1033    $gsdl_cgi->generate_error($mess);
1034    }
1035    else {
1036    $gsdl_cgi->generate_ok_message("set-live-metadata successful: Key[$metaname]=$metavalue");
1037    }
1038
1039    #return $status; # in case calling functions have any further use for this
1040}
1041
1042sub set_live_metadata
1043{
1044    my $self = shift @_;
1045
1046    my $username  = $self->{'username'};
1047    my $collect   = $self->{'collect'};
1048    my $gsdl_cgi  = $self->{'gsdl_cgi'};
1049 
1050    if ($baseaction::authentication_enabled) {
1051    # Ensure the user is allowed to edit this collection   
1052    $self->authenticate_user($username, $collect); #&authenticate_user($gsdl_cgi, $username, $collect);
1053    }
1054
1055    # Make sure the collection isn't locked by someone else
1056    $self->lock_collection($username, $collect);
1057
1058    $self->_set_live_metadata(@_);
1059
1060    # Release the lock once it is done
1061    $self->unlock_collection($username, $collect);
1062}
1063
1064sub set_index_metadata_entry
1065{
1066    my $self = shift @_;
1067    my ($collect_dir,$collect,$infodbtype,$docid,$metaname,$metapos,$metavalue,$metamode) = @_;
1068   
1069    # To people who know $collect_tail please add some comments
1070    # Obtain path to the database
1071    my $collect_tail = $collect;
1072    $collect_tail =~ s/^.*[\/|\\]//;
1073    my $index_text_directory = &util::filename_cat($collect_dir,$collect,"index","text");
1074    my $infodb_file_path = &dbutil::get_infodb_file_path($infodbtype, $collect_tail, $index_text_directory);
1075   
1076#   print STDERR "**** infodb file path = $infodb_file_path\n";
1077#   print STDERR "***** infodb type = $infodbtype\n";
1078   
1079    # Read the docid entry
1080    my $doc_rec = &dbutil::read_infodb_entry($infodbtype, $infodb_file_path, $docid);
1081   
1082    # Set the metadata value
1083    if (defined $metapos) {
1084    # if metamode=accumulate AND metapos, warn user and then use metapos
1085    if (defined $metamode && $metamode eq "accumulate") {
1086        print STDERR "**** Warning: metamode is set to accumulate yet metapos is also provided for $docid\n";
1087        print STDERR "**** Proceeding by using metapos\n";
1088    }
1089    $doc_rec->{$metaname}->[$metapos] = $metavalue;
1090    }
1091    elsif (defined $metamode && $metamode eq "override") {
1092    $doc_rec->{$metaname} = [ $metavalue ];
1093    }
1094    else { # default for index was to override, but because accumulate is less destructive,
1095    # and because accumulate is the default for archives and import, that's the new default for index too
1096    if(defined $doc_rec->{$metaname}) {
1097        push(@{$doc_rec->{$metaname}}, $metavalue); # accumulate the value for that metaname
1098    } else {
1099        $doc_rec->{$metaname} = [ $metavalue ];
1100    }
1101    }
1102 
1103    my $status = &dbutil::set_infodb_entry($infodbtype, $infodb_file_path,$docid,$doc_rec);
1104   
1105    return $status;
1106   
1107}
1108
1109sub _set_import_metadata
1110{
1111    my $self = shift @_;
1112
1113    my $collect   = $self->{'collect'};
1114    my $gsdl_cgi  = $self->{'gsdl_cgi'};
1115    my $infodbtype = $self->{'infodbtype'};
1116#    my $gsdlhome  = $self->{'gsdlhome'};
1117     
1118    # Obtain the collect and archive dir   
1119    my $site = $self->{'site'};
1120    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
1121    ## my $collect_dir = &util::filename_cat($gsdlhome, "collect");
1122    my $archive_dir = &util::filename_cat($collect_dir,$collect,"archives");
1123   
1124    # look up additional args
1125    # want either d= or f=
1126    my $docid  = $self->{'d'};
1127    my ($docid_root,$docid_secnum);
1128    if(defined $docid) {   
1129    ($docid_root,$docid_secnum) = ($docid =~ m/^(.*?)(\..*)?$/);   
1130    # as yet no support for setting subsection metadata in metadata.xml
1131    if ((defined $docid_secnum) && ($docid_secnum !~ m/^\s*$/)) {
1132        $gsdl_cgi->generate_message("*** No support yet for setting import metadata at subsections level.\n");
1133        return;
1134    }
1135    }
1136
1137    my $import_file  = $self->{'f'};
1138    if ((!defined $docid) && (!defined $import_file)) {
1139    $gsdl_cgi->generate_error("No docid (d=...) or import file (f=) specified.");
1140    }
1141
1142    # Get the parameters and set default mode to "accumulate"
1143    my $metaname   = $self->{'metaname'};
1144    my $metavalue  = $self->{'metavalue'};
1145##    $metavalue =~ s/&amp;lt;(.*?)&amp;gt;/<$1>/g;
1146    $metavalue =~ s/&lt;(.*?)&gt;/<$1>/g;
1147   
1148    my $metamode   = $self->{'metamode'};
1149    if ((!defined $metamode) || ($metamode =~ m/^\s*$/)) {
1150    # make "accumulate" the default (less destructive, as won't actually
1151    # delete any existing values)
1152    $metamode = "accumulate";
1153    }
1154
1155    # adding metapos and prevmetavalue support to import_metadata subroutines
1156    my $metapos   = $self->{'metapos'}; # don't force undef to 0. Undef has meaning when metamode=override
1157    my $prevmetavalue = $self->{'prevmetavalue'};
1158
1159    my $arcinfo_doc_filename = &dbutil::get_infodb_file_path($infodbtype, "archiveinf-doc", $archive_dir);
1160    my $metadata_xml_filename = $self->set_import_metadata_entry($gsdl_cgi, $arcinfo_doc_filename, $infodbtype, $docid_root, $metaname, $metapos,$metavalue, $metamode,$prevmetavalue, $collect, $collect_dir); # at this point, docid_root = docid
1161
1162    my $mess = "set-import-metadata successful: Key[$docid] -> $metadata_xml_filename\n";
1163    $mess .= "  $metaname";
1164    $mess .= " = $metavalue";
1165    $mess .= " ($metamode)\n";
1166
1167    $gsdl_cgi->generate_ok_message($mess);
1168
1169    #return $status; # in case calling functions have any further use for this
1170}
1171
1172# the version of set_index_meta that doesn't do authentication
1173sub _set_archives_metadata
1174{
1175    my $self = shift @_;
1176
1177    my $collect   = $self->{'collect'};
1178    my $gsdl_cgi  = $self->{'gsdl_cgi'};
1179    my $infodbtype = $self->{'infodbtype'};
1180   
1181    # Obtain the collect and archive dir   
1182    my $site = $self->{'site'};
1183    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
1184    my $archive_dir = &util::filename_cat($collect_dir,$collect,"archives");
1185
1186    # look up additional args
1187    my $docid  = $self->{'d'};
1188    my $metaname   = $self->{'metaname'};
1189    my $metavalue  = $self->{'metavalue'};
1190    my $prevmetavalue = $self->{'prevmetavalue'};
1191   
1192    my $metapos    = $self->{'metapos'}; # don't force undef to 0. Undef has meaning when metamode=override
1193                                  # Don't append "|| undef", since if metapos=0 it will then be set to undef
1194
1195    my $metamode   = $self->{'metamode'};
1196    if ((!defined $metamode) || ($metamode =~ m/^\s*$/)) {
1197    # make "accumulate" the default (less destructive, as won't actually
1198    # delete any existing values)
1199    $metamode = "accumulate";
1200    }
1201
1202    my $status = $self->set_archives_metadata_entry($gsdl_cgi,$archive_dir, $collect_dir,$collect, $infodbtype,$docid,
1203                $metaname,$metapos,$metavalue,$metamode,$prevmetavalue);
1204   
1205    if ($status == 0) {
1206    my $mess = "set-archives-metadata successful: Key[$docid]\n";
1207    $mess .= "  $metaname";
1208    $mess .= "->[$metapos]" if (defined $metapos);
1209    $mess .= " = $metavalue";
1210    $mess .= " ($metamode)\n";
1211   
1212    $gsdl_cgi->generate_ok_message($mess); 
1213    }
1214    else {
1215    my $mess .= "Failed to set archives metadata key: $docid\n";
1216    $mess .= "Exit status: $status\n";
1217    if(defined $self->{'error_msg'}) {
1218        $mess .= "Error Message: $self->{'error_msg'}\n";
1219    } else {
1220        $mess .= "System Error Message: $!\n";
1221    }
1222    $mess .= "-" x 20 . "\n";
1223   
1224    $gsdl_cgi->generate_error($mess);
1225    }
1226
1227    #return $status; # in case calling functions have any further use for this
1228}
1229
1230
1231# the version of set_index_meta that doesn't do authentication
1232sub _set_index_metadata
1233{
1234    my $self = shift @_;
1235
1236    my $collect   = $self->{'collect'};
1237    my $gsdl_cgi  = $self->{'gsdl_cgi'};
1238
1239    my $site = $self->{'site'};
1240    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
1241
1242    # look up additional args
1243    my $docid     = $self->{'d'};
1244    my $metaname  = $self->{'metaname'};
1245    my $metapos   = $self->{'metapos'}; # undef has meaning
1246    my $metavalue = $self->{'metavalue'};
1247    my $infodbtype = $self->{'infodbtype'};
1248    my $metamode  = $self->{'metamode'};   
1249
1250    my $status = $self->set_index_metadata_entry($collect_dir,$collect,$infodbtype,$docid,$metaname,$metapos,$metavalue,$metamode);
1251   
1252    if ($status != 0) {
1253        # Catch error if set infodb entry failed
1254    my $mess = "Failed to set metadata key: $docid\n";
1255   
1256    $mess .= "PATH: $ENV{'PATH'}\n";
1257    $mess .= "Exit status: $status\n";
1258    $mess .= "System Error Message: $!\n";
1259   
1260    $gsdl_cgi->generate_error($mess);
1261    }
1262    else {
1263    my $mess = "set-index-metadata successful: Key[$docid]\n";
1264    $mess .= "  $metaname";
1265    $mess .= "->[$metapos]" if (defined $metapos);
1266    $mess .= " = $metavalue\n";
1267   
1268    $gsdl_cgi->generate_ok_message($mess);
1269    }
1270
1271    #return $status; # in case calling functions have any further use for this
1272}
1273
1274sub set_index_metadata
1275{
1276    my $self = shift @_;
1277
1278    my $username  = $self->{'username'};
1279    my $collect   = $self->{'collect'};
1280    my $gsdl_cgi  = $self->{'gsdl_cgi'};
1281    #my $gsdlhome  = $self->{'gsdlhome'};
1282
1283    if ($baseaction::authentication_enabled) {
1284    # Ensure the user is allowed to edit this collection   
1285    $self->authenticate_user($username, $collect); #&authenticate_user($gsdl_cgi, $username, $collect);
1286    }
1287
1288    my $site = $self->{'site'};
1289    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
1290   
1291    $gsdl_cgi->checked_chdir($collect_dir);
1292
1293    # Obtain the collect dir
1294    ## my $collect_dir = &util::filename_cat($gsdlhome, "collect");
1295
1296    # Make sure the collection isn't locked by someone else
1297    $self->lock_collection($username, $collect);
1298
1299    $self->_set_index_metadata(@_);
1300   
1301    # Release the lock once it is done
1302    $self->unlock_collection($username, $collect);
1303}
1304
1305# call this to set the metadata for a combination of dirs archives, import or index, or live
1306# if none specified, defaults to index which was the original behaviour of set_metadata.
1307sub set_metadata
1308{
1309    my $self = shift @_;
1310
1311    # Testing that not defining a variable, setting it to "" or to "  " all return false
1312    # >perl -e 'my $whichdirs=""; if($whichdirs) {print "$whichdirs\n"};'
1313
1314    my $where = $self->{'where'};
1315    if(!$where) {   
1316    $self->set_index_metadata(@_); # call the full version of set_index_meta for the default behaviour
1317    return;
1318    }
1319
1320    # authenticate and lock collection once, even if processing multiple dirs
1321    my $username  = $self->{'username'};
1322    my $collect   = $self->{'collect'};
1323    my $gsdl_cgi  = $self->{'gsdl_cgi'};
1324   
1325    if ($baseaction::authentication_enabled) {
1326    # Ensure the user is allowed to edit this collection   
1327    $self->authenticate_user($username, $collect); #&authenticate_user($gsdl_cgi, $username, $collect);
1328    }
1329   
1330    if($where =~ m/index/) {
1331    my $site = $self->{'site'};
1332    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
1333    $gsdl_cgi->checked_chdir($collect_dir);
1334    }
1335
1336    # Make sure the collection isn't locked by someone else
1337    $self->lock_collection($username, $collect);
1338
1339
1340    # now at last can set the metadata. $where can specify multiple
1341    # $where is of the form: import|archives|index, or a subset thereof
1342
1343    #my @whichdirs = split('\|', $where);
1344
1345    # just check whether $where contains import/archives/index/live in turn, and
1346    # for each case, process it accordingly
1347    if($where =~ m/import/) {
1348    $self->_set_import_metadata(@_);       
1349    }
1350
1351    if($where =~ m/archives/) {
1352
1353    # look up docID arg which is optional to set_metadata because it's optional
1354    # to set_import, but which is compulsory to set_archives_metadata
1355    my $docid     = $self->{'d'};
1356    if ((!defined $docid) || ($docid =~ m/^\s*$/)) {
1357        $gsdl_cgi->generate_error("No docid (d=...) specified."); # generates error and dies
1358    }
1359    # we have a docid, so can set archives meta
1360    $self->_set_archives_metadata(@_); 
1361    }
1362
1363    if($where =~ m/index/) {
1364   
1365    # look up docID arg which is optional to set_metadata because it's optional
1366    # to set_import, but which is compulsory to set_archives_metadata
1367    my $docid     = $self->{'d'};
1368    if ((!defined $docid) || ($docid =~ m/^\s*$/)) {
1369        $gsdl_cgi->generate_error("No docid (d=...) specified.");
1370    }
1371    # we have a docid, so can set index meta
1372    $self->_set_index_metadata(@_);
1373    }   
1374
1375    if($where =~ m/live/) {
1376    $self->_set_live_metadata(@_); # docid param, d, is compulsory, but is checked for in subroutine
1377    }
1378
1379    # Release the lock once it is done
1380    $self->unlock_collection($username, $collect);
1381}
1382
1383sub set_metadata_array
1384{
1385    my $self = shift @_;
1386
1387    my $where = $self->{'where'};
1388    if(!$where) {   
1389    $self->set_index_metadata_array(@_); # default behaviour is the full version of set_index_meta_array
1390    return;
1391    }
1392
1393    my $username  = $self->{'username'};
1394    my $collect   = $self->{'collect'};
1395    my $gsdl_cgi  = $self->{'gsdl_cgi'};
1396
1397    if ($baseaction::authentication_enabled) {
1398    # Ensure the user is allowed to edit this collection
1399    $self->authenticate_user($username, $collect); #&authenticate_user($gsdl_cgi, $username, $collect);
1400    }
1401
1402    # Not sure if the checked_chdir is necessary, since lock_collection also does a chdir
1403    # But including the stmt during this code reorganisation to preserve as-is what used to happen
1404    my $site = $self->{'site'};
1405    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
1406    $gsdl_cgi->checked_chdir($collect_dir);
1407
1408    # Make sure the collection isn't locked by someone else
1409    $self->lock_collection($username, $collect);
1410
1411    if($where =~ m/import/) {
1412    $self->_set_import_metadata_array(@_);
1413    }
1414    if($where =~ m/archives/) {
1415    $self->_set_archives_metadata_array(@_);
1416    }
1417    if($where =~ m/index/) {
1418    $self->_set_index_metadata_array(@_);
1419    }
1420    if($where =~ m/live/) {
1421        $self->_set_live_metadata_array(@_);
1422    }
1423
1424    # Release the lock once it is done
1425    $self->unlock_collection($username, $collect);
1426}
1427
1428sub _set_index_metadata_array
1429{
1430    my $self = shift @_;
1431
1432    my $collect   = $self->{'collect'};
1433    my $gsdl_cgi  = $self->{'gsdl_cgi'};
1434    my $site = $self->{'site'};
1435    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
1436
1437   
1438    # look up additional args
1439   
1440    my $infodbtype = $self->{'infodbtype'};
1441   
1442    my $json_str      = $self->{'json'};
1443    my $doc_array = decode_json $json_str;
1444   
1445   
1446    my $global_status = 0;
1447    my $global_mess = "";
1448   
1449    my @all_docids = ();
1450   
1451    foreach my $doc_array_rec ( @$doc_array ) {
1452   
1453    my $status = -1;
1454    my $docid     = $doc_array_rec->{'docid'};
1455   
1456    push(@all_docids,$docid);
1457
1458    my $metaname  = $doc_array_rec->{'metaname'};
1459    if(defined $metaname) {
1460        my $metapos   = $doc_array_rec->{'metapos'}; # can legitimately be undef
1461        my $metavalue = $doc_array_rec->{'metavalue'};
1462        my $metamode = $doc_array_rec->{'metamode'} || $self->{'metamode'};
1463
1464        $status = $self->set_index_metadata_entry($collect_dir,$collect,$infodbtype,$docid,$metaname,$metapos,$metavalue,$metamode);
1465    } elsif (defined $doc_array_rec->{'metatable'}) { # if no metaname, we expect a metatable
1466        my $metatable = $doc_array_rec->{'metatable'}; # a subarray, or need to generate an error saying JSON structure is wrong
1467       
1468        foreach my $metatable_rec ( @$metatable ) { # the subarray metatable is an array of hashmaps
1469        $metaname  = $metatable_rec->{'metaname'};
1470        my $metamode  = $metatable_rec->{'metamode'} || $doc_array_rec->{'metamode'} || $self->{'metamode'};
1471        my $metapos = undef;
1472        my $metavals = $metatable_rec->{'metavals'}; # a sub-subarray
1473
1474        foreach my $metavalue ( @$metavals ) { # metavals is an array
1475            $status = $self->set_index_metadata_entry($collect_dir,$collect,$infodbtype,$docid,$metaname,$metapos,$metavalue,$metamode); # how do we use metamode in set_meta_entry?
1476            if($metamode eq "override") { # now, having overridden the metavalue for the first,
1477            # need to accumulate subsequent metavals for this metaname, else the just-assigned
1478            # metavalue for this metaname will be lost
1479            $metamode = "accumulate";
1480            }
1481        }           
1482        }
1483    }
1484   
1485    if ($status != 0) {
1486        # Catch error if set infodb entry failed
1487        $global_status = $status;
1488        $global_mess .= "Failed to set metadata key: $docid\n";
1489        $global_mess .= "Exit status: $status\n";
1490        $global_mess .= "System Error Message: $!\n";
1491        $global_mess .= "-" x 20;
1492    }
1493    }
1494   
1495    if ($global_status != 0) {
1496    $global_mess .= "PATH: $ENV{'PATH'}\n";
1497    $gsdl_cgi->generate_error($global_mess);
1498    }
1499    else {
1500    my $mess = "set-metadata-array successful: Keys[ ".join(", ",@all_docids)."]\n";
1501    $gsdl_cgi->generate_ok_message($mess);
1502    }
1503}
1504
1505sub set_index_metadata_array
1506{
1507    my $self = shift @_;
1508
1509    my $username  = $self->{'username'};
1510    my $collect   = $self->{'collect'};
1511    my $gsdl_cgi  = $self->{'gsdl_cgi'};
1512#    my $gsdlhome  = $self->{'gsdlhome'};
1513
1514    if ($baseaction::authentication_enabled) {
1515    # Ensure the user is allowed to edit this collection   
1516    $self->authenticate_user($username, $collect); #&authenticate_user($gsdl_cgi, $username, $collect);
1517    }
1518
1519    my $site = $self->{'site'};
1520    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
1521   
1522    $gsdl_cgi->checked_chdir($collect_dir);
1523
1524    # Obtain the collect dir
1525    ## my $collect_dir = &util::filename_cat($gsdlhome, "collect");
1526
1527    # Make sure the collection isn't locked by someone else
1528    $self->lock_collection($username, $collect);
1529
1530    $self->_set_index_metadata_array(@_);
1531
1532    # Release the lock once it is done
1533    $self->unlock_collection($username, $collect);
1534}
1535
1536# experimental, newly added in and untested
1537sub _set_live_metadata_array
1538{
1539    my $self = shift @_;
1540
1541    my $collect   = $self->{'collect'};
1542    my $gsdl_cgi  = $self->{'gsdl_cgi'};
1543
1544    my $site = $self->{'site'};
1545    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
1546
1547   
1548    # look up additional args
1549    my $infodbtype = $self->{'infodbtype'};
1550    # To people who know $collect_tail please add some comments
1551    # Obtain path to the database
1552    my $collect_tail = $collect;
1553    $collect_tail =~ s/^.*[\/|\\]//;
1554    my $index_text_directory = &util::filename_cat($collect_dir,$collect,"index","text");
1555    my $infodb_file_path = &dbutil::get_infodb_file_path($infodbtype, "live-$collect_tail", $index_text_directory);
1556
1557   
1558    my $json_str      = $self->{'json'};
1559    my $doc_array = decode_json $json_str;
1560   
1561   
1562    my $global_status = 0;
1563    my $global_mess = "";
1564   
1565    my @all_docids = ();
1566
1567
1568    foreach my $doc_array_rec ( @$doc_array ) {
1569   
1570    my $status = -1;
1571    my $docid     = $doc_array_rec->{'docid'};
1572
1573    push(@all_docids,$docid);
1574
1575    my $metaname  = $doc_array_rec->{'metaname'};
1576    if(defined $metaname) {
1577        my $dbkey = "$docid.$metaname";
1578        my $metavalue = $doc_array_rec->{'metavalue'};
1579
1580        # Set the new value
1581        my $cmd = "gdbmset \"$infodb_file_path\" \"$dbkey\" \"$metavalue\"";
1582        $status = system($cmd);
1583
1584    } elsif (defined $doc_array_rec->{'metatable'}) { # if no metaname, we expect a metatable
1585        my $metatable = $doc_array_rec->{'metatable'}; # a subarray, or need to generate an error saying JSON structure is wrong
1586        foreach my $metatable_rec ( @$metatable ) {
1587        $metaname  = $metatable_rec->{'metaname'};
1588        my $dbkey = "$docid.$metaname";
1589
1590        my $metavals = $metatable_rec->{'metavals'}; # a sub-subarray
1591        foreach my $metavalue ( @$metavals ) {
1592             my $cmd = "gdbmset \"$infodb_file_path\" \"$dbkey\" \"$metavalue\"";
1593             $status = system($cmd);
1594        }
1595        }
1596       
1597    }
1598
1599    if ($status != 0) {
1600        # Catch error if gdbmget failed
1601        $global_status = $status;
1602        $global_mess .= "Failed to set metadata key: $docid\n"; # $dbkey
1603        $global_mess .= "Exit status: $status\n";
1604        $global_mess .= "System Error Message: $!\n";
1605        $global_mess .= "-" x 20;
1606    }
1607    }
1608   
1609    if ($global_status != 0) {
1610    $global_mess .= "PATH: $ENV{'PATH'}\n";
1611    $gsdl_cgi->generate_error($global_mess);
1612    }
1613    else {
1614    my $mess = "set-live-metadata-array successful: Keys[ ".join(", ",@all_docids)."]\n";
1615    $gsdl_cgi->generate_ok_message($mess);
1616    }
1617}
1618
1619sub set_live_metadata_array
1620{
1621    my $self = shift @_;
1622
1623    my $username  = $self->{'username'};
1624    my $collect   = $self->{'collect'};
1625    my $gsdl_cgi  = $self->{'gsdl_cgi'};
1626
1627    if ($baseaction::authentication_enabled) {
1628    # Ensure the user is allowed to edit this collection   
1629    $self->authenticate_user($username, $collect); #&authenticate_user($gsdl_cgi, $username, $collect);
1630    }
1631
1632    my $site = $self->{'site'};
1633    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
1634   
1635    $gsdl_cgi->checked_chdir($collect_dir);
1636
1637    # Make sure the collection isn't locked by someone else
1638    $self->lock_collection($username, $collect);
1639
1640    $self->_set_live_metadata_array(@_);
1641
1642    # Release the lock once it is done
1643    $self->unlock_collection($username, $collect);
1644}
1645
1646
1647sub dxml_metadata
1648{
1649    my ($tagname, $attrHash, $contextArray, $parentDataArray, $parser) = @_;
1650    my $metaname = $parser->{'parameters'}->{'metaname'};
1651    my $metamode = $parser->{'parameters'}->{'metamode'};
1652   
1653    print STDERR "**** Processing closing </Metadata> tag\n";
1654   
1655    my $opt_doc_secnum = $parser->{'parameters'}->{'secnum'};
1656   
1657    # Find the right metadata tag and checks if we are going to
1658    # override it
1659    #
1660    # Note: This over writes the first metadata block it
1661    # encountered. If there are multiple Sections in the doc.xml, it
1662    # might not behave as you would expect
1663
1664    my $curr_secnum = $parser->{'parameters'}->{'curr_section_num'};
1665##    print STDERR "**** checking $opt_doc_secnum <=> $curr_secnum\n";
1666##    print STDERR "**** metamode = $metamode\n";
1667   
1668    if ((!defined $opt_doc_secnum) || ($opt_doc_secnum eq $curr_secnum))
1669    {
1670        my $name_attr = $attrHash->{'name'};
1671        if (($name_attr eq $metaname) && ($metamode eq "override"))
1672        {
1673            if (!defined $parser->{'parameters'}->{'poscount'})
1674            {
1675                $parser->{'parameters'}->{'poscount'} = 0;
1676            }
1677            else
1678            {
1679                $parser->{'parameters'}->{'poscount'}++;
1680            }
1681           
1682            if(defined $parser->{'parameters'}->{'metapos'} && $parser->{'parameters'}->{'poscount'} == $parser->{'parameters'}->{'metapos'})
1683            {
1684                ##print STDERR "#### got match!!\n";
1685                # Get the value and override the current value
1686                my $metavalue = $parser->{'parameters'}->{'metavalue'};
1687                $attrHash->{'_content'} = $metavalue;
1688               
1689                # Don't want it to wipe out any other pieces of metadata
1690                $parser->{'parameters'}->{'metamode'} = "done";
1691            }
1692            elsif(defined $parser->{'parameters'}->{'prevmetavalue'} && $parser->{'parameters'}->{'prevmetavalue'} eq $attrHash->{'_content'})
1693            {
1694                my $metavalue = $parser->{'parameters'}->{'metavalue'};
1695                $attrHash->{'_content'} = $metavalue;
1696                $parser->{'parameters'}->{'metamode'} = "done";
1697            }
1698        }
1699    }
1700
1701    # RAW is [$tagname => $attrHash] not $tagname => $attrHash!!
1702    return [$tagname => $attrHash];
1703}
1704
1705# This method exists purely for catching invalid section numbers that the client
1706# requested to edit. Once the parser has reached the end (the final </Archive> tag),
1707# we've seen all the Sections in the doc.xml, and none of their section nums matched
1708# if the metamode has not been set to 'done' by then.
1709sub dxml_archive
1710{
1711    my ($tagname, $attrHash, $contextArray, $parentDataArray, $parser) = @_;
1712    my $metamode = $parser->{'parameters'}->{'metamode'};
1713   
1714    my $curr_secnum = $parser->{'parameters'}->{'curr_section_num'};
1715    my $opt_doc_secnum = $parser->{'parameters'}->{'secnum'};
1716   
1717#    print STDERR "@@@ $tagname Processing a closing </Archive> tag [$curr_secnum|$opt_doc_secnum]\n";
1718   
1719    if ($metamode ne "done" && $curr_secnum ne $opt_doc_secnum) {
1720    print STDERR "@@@ $tagname Finished processing FINAL Section.\n";
1721
1722    my $metaname = $parser->{'parameters'}->{'metaname'};
1723    my $metavalue = $parser->{'parameters'}->{'metavalue'};
1724   
1725    print STDERR "@@@ Requested section number $opt_doc_secnum not found.\n";
1726    print STDERR "\t(last seen section number in document was $curr_secnum)\n";
1727    print STDERR "\tDiscarded metadata value '$metavalue' for meta '$metaname'\n";
1728    print STDERR "\tin section $opt_doc_secnum.\n";
1729    $parser->{'custom_err_msg'} = "Requested section number $opt_doc_secnum not found.";
1730    }
1731   
1732    # RAW is [$tagname => $attrHash] not $tagname => $attrHash!!
1733    return [$tagname => $attrHash];
1734}
1735
1736sub dxml_description
1737{
1738    my ($tagname, $attrHash, $contextArray, $parentDataArray, $parser) = @_;
1739    my $metamode = $parser->{'parameters'}->{'metamode'};
1740
1741    my $curr_secnum = $parser->{'parameters'}->{'curr_section_num'};
1742    my $opt_doc_secnum = $parser->{'parameters'}->{'secnum'} || "";
1743   
1744    print STDERR "**** Processing a closing </Description> tag \n";
1745#   print STDERR "@@@ $tagname Processing a closing </Description> tag [$curr_secnum|$opt_doc_secnum]\n";
1746   
1747    # Accumulate the metadata
1748
1749    # We'll be accumulating metadata at this point if we haven't found and therefore
1750    # haven't processed the metadata yet.
1751    # For subsections, this means that if we're at a matching subsection, but haven't
1752    # found the correct metaname to override in that subsection, we accumulate it as new
1753    # meta in the subsection by adding it to the current description.
1754    # If there's no subsection info for the metadata, it will accumulate at the top level
1755    # section description if we hadn't found a matching metaname to override at this point.
1756
1757    # Both curr_secnum and opt_doc_secnum can be "". In the former case, it means we're now
1758    # at the toplevel section. In the latter case, it means we want to process meta in the
1759    # toplevel section. So the eq check between the values below will work in all cases.
1760   
1761    # The only time this won't work is if an opt_doc_secnum beyond the section numbers of
1762    # this document has been provided. In that case, the metadata for that opt_doc_secnum
1763    # won't get attached/accumulated to any part of the doc, not even its top-level section.
1764
1765    if ($curr_secnum eq $opt_doc_secnum
1766        && ($metamode eq "accumulate" || $metamode eq "override")) {
1767        if ($metamode eq "override") {
1768        print "No metadata value to override.  Switching 'metamode' to accumulate\n";
1769        }
1770
1771        # If we get to here and metamode is override, this means there
1772        # was no existing value to overide => treat as an append operation
1773       
1774        # Tack a new metadata tag on to the end of the <Metadata>+ block
1775        my $metaname = $parser->{'parameters'}->{'metaname'};
1776        my $metavalue = $parser->{'parameters'}->{'metavalue'};
1777       
1778        my $metadata_attr = {
1779        '_content' => $metavalue,
1780        'name' => $metaname,
1781        'mode' => "accumulate"
1782        };
1783       
1784        my $append_metadata = [ "Metadata" => $metadata_attr ];
1785        my $description_content = $attrHash->{'_content'};
1786       
1787        print "Appending metadata to doc.xml\n";
1788       
1789        if (ref($description_content)) {
1790        # got some existing interesting nested content
1791        push(@$description_content, "    ", $append_metadata ,"\n        ");
1792        }
1793        else {
1794        #description_content is most likely a string such as "\n"
1795        $attrHash->{'_content'} = [$description_content, "    ", $append_metadata ,"\n" ];
1796        }
1797       
1798        $parser->{'parameters'}->{'metamode'} = "done";
1799    }       
1800    else {
1801        # metamode most likely "done" signifying that it has already found a position to add the metadata to.
1802##      print STDERR "**** NOT ACCUMULATE?!? \n";
1803    }
1804
1805    # RAW is [$tagname => $attrHash] not $tagname => $attrHash!!
1806    return [$tagname => $attrHash];
1807}
1808
1809
1810sub dxml_start_section
1811{
1812    my ($tagname, $attrHash, $contextArray, $parentDataArray, $parser) = @_;
1813
1814    my $new_depth = scalar(@$contextArray);
1815
1816#   print STDERR "**** START SECTION \n";
1817   
1818    if ($new_depth == 1) {
1819    $parser->{'parameters'}->{'curr_section_depth'} = 1;
1820    $parser->{'parameters'}->{'curr_section_num'}   = "";
1821    }
1822
1823    my $old_depth  = $parser->{'parameters'}->{'curr_section_depth'};
1824    my $old_secnum = $parser->{'parameters'}->{'curr_section_num'};
1825
1826    my $new_secnum;
1827
1828    if ($new_depth > $old_depth) {
1829    # child subsection
1830    $new_secnum = "$old_secnum.1";
1831    }
1832    elsif ($new_depth == $old_depth) {
1833    # sibling section => increase it's value by 1
1834    my ($tail_num) = ($old_secnum =~ m/\.(\d+)$/);
1835    $tail_num++;
1836    $new_secnum = $old_secnum;
1837    $new_secnum =~ s/\.(\d+)$/\.$tail_num/;
1838    }
1839    else {
1840    # back up to parent section => lopp off tail
1841    $new_secnum = $old_secnum;
1842    $new_secnum =~ s/\.\d+$//;
1843    }
1844
1845    $parser->{'parameters'}->{'curr_section_depth'} = $new_depth;
1846    $parser->{'parameters'}->{'curr_section_num'}   = $new_secnum;
1847   
1848    1;
1849}
1850
1851sub edit_xml_file
1852{
1853    my $self = shift @_;
1854    my ($gsdl_cgi, $filename, $start_rules, $rules, $options) = @_;
1855
1856    # use XML::Rules to add it in (read in and out again)
1857    my $parser = XML::Rules->new(start_rules     => $start_rules,
1858                 rules           => $rules,
1859                 style           => 'filter',
1860                                 output_encoding => 'utf8' );
1861
1862    my $xml_in = "";
1863    if (!open(MIN,"<$filename")) {
1864    $gsdl_cgi->generate_error("Unable to read in $filename: $!");
1865    }
1866    else {
1867        # Read all the text in
1868    my $line;
1869    while (defined ($line=<MIN>)) {
1870        $xml_in .= $line;
1871    }
1872    close(MIN);
1873   
1874    my $MOUT;   
1875    if (!open($MOUT,">$filename")) {
1876        $gsdl_cgi->generate_error("Unable to write out to $filename: $!");
1877    }
1878    else {
1879        # Matched lines will get handled by the call backs
1880##      my $xml_out = "";
1881
1882        binmode($MOUT,":utf8");
1883        $parser->filter($xml_in,$MOUT, $options);
1884
1885#       binmode(MOUT,":utf8");
1886#       print MOUT $xml_out;
1887        close($MOUT);       
1888    }
1889    }
1890
1891    # copy across any custom error information that was stored during parsing
1892    $self->{'error_msg'} = $parser->{'custom_err_msg'} if(defined $parser->{'custom_err_msg'});   
1893}
1894
1895sub edit_doc_xml
1896{
1897    my $self = shift @_;
1898    my ($gsdl_cgi, $doc_xml_filename, $metaname, $metavalue, $metapos, $metamode, $opt_secnum, $prevmetavalue) = @_;
1899
1900    my $info_mess = <<RAWEND;
1901****************************
1902  edit_doc_xml()
1903****************************
1904doc_xml_filename = $doc_xml_filename
1905metaname = $metaname
1906metavalue = $metavalue
1907metapos = $metapos
1908metamode = $metamode
1909opt_secnum = $opt_secnum
1910prevmetavalue = $prevmetavalue
1911****************************
1912RAWEND
1913
1914    $gsdl_cgi->generate_message($info_mess);
1915   
1916    # To monitor which section/subsection number we are in
1917    my @start_rules =
1918    ( 'Section'    => \&dxml_start_section );
1919
1920    # use XML::Rules to add it in (read in and out again)
1921    # Set the call back functions
1922    my @rules =
1923    ( _default => 'raw',
1924      'Metadata'    => \&dxml_metadata,
1925      'Description' => \&dxml_description,
1926      'Archive'     => \&dxml_archive); # just for catching errors at end
1927     
1928    # Sets the parameters
1929    my $options = { 'metaname'  => $metaname,
1930            'metapos'   => $metapos,
1931            'metavalue' => $metavalue,
1932            'metamode'  => $metamode,
1933            'prevmetavalue' => $prevmetavalue };
1934           
1935    if (defined $opt_secnum) {
1936    $options->{'secnum'} = $opt_secnum;
1937    }
1938
1939    $self->edit_xml_file($gsdl_cgi,$doc_xml_filename,\@start_rules,\@rules,$options);
1940}
1941
1942sub set_archives_metadata_entry
1943{
1944    my $self = shift @_;
1945    my ($gsdl_cgi, $archive_dir, $collect_dir, $collect, $infodbtype, $docid, $metaname, $metapos, $metavalue, $metamode, $prevmetavalue) = @_;
1946   
1947    my $info_mess = <<RAWEND;
1948****************************
1949  set_archives_metadata_entry()
1950****************************
1951archive_dir = $archive_dir
1952collect_dir = $collect_dir
1953collect = $collect
1954infodbtype = $infodbtype
1955docid = $docid
1956metaname = $metaname
1957metapos = $metapos
1958metavalue = $metavalue
1959metamode = $metamode
1960prevmetavalue = $prevmetavalue
1961****************************
1962RAWEND
1963
1964    $gsdl_cgi->generate_message($info_mess);
1965   
1966    # Obtain the doc.xml path for the specified docID
1967    my ($docid_root,$docid_secnum) = ($docid =~ m/^(.*?)(\..*)?$/);
1968
1969    my $arcinfo_doc_filename = &dbutil::get_infodb_file_path($infodbtype, "archiveinf-doc", $archive_dir);
1970    my $doc_rec = &dbutil::read_infodb_entry($infodbtype, $arcinfo_doc_filename, $docid_root);
1971    my $doc_xml_file = $doc_rec->{'doc-file'}->[0];
1972   
1973    # The $doc_xml_file is relative to the archives, and now let's get the full path
1974    my $archives_dir = &util::filename_cat($collect_dir,$collect,"archives");   
1975    my $doc_xml_filename = &util::filename_cat($archives_dir,$doc_xml_file);
1976
1977    # If we're overriding everything, then $metamode=override combined with $metapos=undefined
1978    # in which case, we need to remove all metavalues for the metaname at the given (sub)section
1979    # Thereafter, we will finally be setting the overriding metavalue for this metaname
1980    if(!defined $metapos && $metamode eq "override") {
1981    $self->remove_from_doc_xml($gsdl_cgi, &util::filename_cat($archive_dir, $doc_xml_file), $metaname, $metapos, undef, $docid_secnum, $metamode);
1982    }
1983
1984    # Edit the doc.xml file with the specified metadata name, value and position.
1985    # TODO: there is a potential problem here as this edit_doc_xml function
1986    # is assuming the simple doc.xml situation where there is only one Section and no SubSections.
1987    # Running import.pl -groupsize will cause this to have multiple sections in one doc.xml
1988   
1989    # dxml_metadata method ignores metapos if metamode anything other than override
1990    $self->edit_doc_xml($gsdl_cgi,$doc_xml_filename,
1991            $metaname,$metavalue,$metapos,$metamode,$docid_secnum,$prevmetavalue);
1992
1993    # return 0; # return 0 for now to indicate no error
1994    return (defined $self->{'error_msg'}) ? 1 : 0;
1995}
1996
1997
1998sub set_archives_metadata
1999{
2000    my $self = shift @_;
2001
2002    my $username  = $self->{'username'};
2003    my $collect   = $self->{'collect'};
2004    my $gsdl_cgi  = $self->{'gsdl_cgi'};
2005   
2006    if ($baseaction::authentication_enabled) {
2007    # Ensure the user is allowed to edit this collection
2008    $self->authenticate_user($username, $collect);
2009    }
2010
2011    # Make sure the collection isn't locked by someone else
2012    $self->lock_collection($username, $collect);
2013
2014    $self->_set_archives_metadata(@_);
2015
2016    # Release the lock once it is done
2017    $self->unlock_collection($username, $collect);
2018}
2019
2020sub _set_archives_metadata_array
2021{
2022    my $self = shift @_;
2023   
2024    my $collect   = $self->{'collect'};
2025    my $gsdl_cgi  = $self->{'gsdl_cgi'};
2026    my $site = $self->{'site'};
2027    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
2028
2029    # look up additional args
2030   
2031    my $infodbtype = $self->{'infodbtype'};
2032   
2033    my $archive_dir = &util::filename_cat($collect_dir,$collect,"archives");
2034   
2035    my $json_str      = $self->{'json'};
2036    my $doc_array = decode_json $json_str;
2037   
2038   
2039    my $global_status = 0;
2040    my $global_mess = "";
2041   
2042    my @all_docids = ();
2043   
2044    foreach my $doc_array_rec ( @$doc_array ) {
2045    my $status    = -1;
2046    my $docid     = $doc_array_rec->{'docid'};
2047
2048    push(@all_docids,$docid);
2049   
2050    my $metaname  = $doc_array_rec->{'metaname'};
2051    if(defined $metaname) {
2052       
2053        my $metapos   = $doc_array_rec->{'metapos'}; # don't force undef to 0. Undef has meaning when metamode=override
2054
2055        my $metamode  = $doc_array_rec->{'metamode'} || $self->{'metamode'};
2056        my $metavalue = $doc_array_rec->{'metavalue'};
2057        my $prevmetavalue = $self->{'prevmetavalue'}; # to make this sub behave as _set_archives_metadata
2058       
2059       
2060        if ((!defined $metamode) || ($metamode =~ m/^\s*$/)) {
2061        # make "accumulate" the default (less destructive, as it won't actually
2062        # delete any existing values)
2063        $metamode = "accumulate";
2064        }       
2065       
2066        $status = $self->set_archives_metadata_entry($gsdl_cgi,$archive_dir, $collect_dir,$collect, $infodbtype,$docid,
2067                $metaname,$metapos,$metavalue,$metamode,$prevmetavalue);
2068    } elsif (defined $doc_array_rec->{'metatable'}) { # if no metaname, we expect a metatable
2069        my $metatable = $doc_array_rec->{'metatable'}; # a subarray, or need to generate an error saying JSON structure is wrong
2070       
2071        foreach my $metatable_rec ( @$metatable ) {
2072        $metaname  = $metatable_rec->{'metaname'};
2073        my $metamode  = $metatable_rec->{'metamode'} || $doc_array_rec->{'metamode'} || $self->{'metamode'};
2074        my $metapos = undef;
2075        my $prevmetavalue = undef;
2076        my $metavals = $metatable_rec->{'metavals'}; # a sub-subarray
2077       
2078        foreach my $metavalue ( @$metavals ) {
2079            $status = $self->set_archives_metadata_entry($gsdl_cgi,$archive_dir, $collect_dir,$collect,$infodbtype,
2080                                 $docid,$metaname,$metapos,$metavalue,$metamode,$prevmetavalue);
2081           
2082            if($metamode eq "override") { # now, having overridden the metavalue for the first,
2083            # need to accumulate subsequent metavals for this metaname, else the just-assigned
2084            # metavalue for this metaname will be lost
2085            $metamode = "accumulate";
2086            }
2087        }           
2088        }       
2089    }
2090       
2091    if ($status != 0) {
2092        # Catch error if set infodb entry failed
2093        $global_status = $status;
2094        $global_mess .= "Failed to set metadata key: $docid\n";
2095        $global_mess .= "Exit status: $status\n";
2096        $global_mess .= "System Error Message: $!\n";
2097        $global_mess .= "-" x 20 . "\n";
2098    }
2099    }
2100   
2101    if ($global_status != 0) {
2102    $global_mess .= "PATH: $ENV{'PATH'}\n";
2103    $gsdl_cgi->generate_error($global_mess);
2104    }
2105    else {
2106    my $mess = "set-archives-metadata-array successful: Keys[ ".join(", ",@all_docids)."]\n";
2107    $gsdl_cgi->generate_ok_message($mess);
2108    }
2109}
2110
2111sub set_archives_metadata_array
2112{
2113    my $self = shift @_;
2114
2115    my $username  = $self->{'username'};
2116    my $collect   = $self->{'collect'};
2117    my $gsdl_cgi  = $self->{'gsdl_cgi'};
2118#    my $gsdlhome  = $self->{'gsdlhome'};
2119
2120    if ($baseaction::authentication_enabled) {
2121    # Ensure the user is allowed to edit this collection   
2122    $self->authenticate_user($username, $collect); #&authenticate_user($gsdl_cgi, $username, $collect);
2123    }
2124
2125    my $site = $self->{'site'};
2126    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
2127   
2128    $gsdl_cgi->checked_chdir($collect_dir);
2129
2130    # Obtain the collect dir
2131    ## my $collect_dir = &util::filename_cat($gsdlhome, "collect");
2132
2133    # Make sure the collection isn't locked by someone else
2134    $self->lock_collection($username, $collect);
2135
2136    $self->_set_archives_metadata_array(@_);
2137   
2138    # Release the lock once it is done
2139    $self->unlock_collection($username, $collect);
2140}
2141
2142sub _remove_archives_metadata
2143{
2144    my $self = shift @_;
2145
2146    my $collect   = $self->{'collect'};
2147    my $gsdl_cgi  = $self->{'gsdl_cgi'};
2148#   my $gsdlhome  = $self->{'gsdlhome'};
2149    my $infodbtype = $self->{'infodbtype'};
2150   
2151    my $site = $self->{'site'};
2152       
2153    # Obtain the collect and archive dir   
2154    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
2155   
2156    my $archive_dir = &util::filename_cat($collect_dir,$collect,"archives");
2157
2158    # look up additional args
2159    my ($docid, $docid_secnum) = ($self->{'d'} =~ m/^(.*?)(\..*)?$/);
2160   
2161    my $metaname = $self->{'metaname'};
2162    my $metapos = $self->{'metapos'};
2163
2164    my $metavalue = $self->{'metavalue'} || undef; # necessary to force fallback to undef here
2165
2166    # if the user hasn't told us what to delete, not having given a metavalue or metapos,
2167    # default to deleting the first metavalue for the given metaname
2168    # Beware that if both metapos AND metavalue are defined, both matches (if any)
2169    # seem to get deleted in one single remove_archives_meta action invocation.
2170    # Similarly, if 2 identical metavalues for a metaname exist and that metavalue is being
2171    # deleted, both get deleted.
2172    if(!defined $metapos && !defined $metavalue) {
2173        $metapos = 0;
2174    }
2175
2176    my $metamode = $self->{'metamode'} || undef;
2177
2178    my $arcinfo_doc_filename = &dbutil::get_infodb_file_path($infodbtype, "archiveinf-doc", $archive_dir);
2179    my $doc_rec = &dbutil::read_infodb_entry($infodbtype, $arcinfo_doc_filename, $docid);
2180
2181    # This now stores the full pathname
2182    my $doc_filename = $doc_rec->{'doc-file'}->[0];
2183
2184    my $status = $self->remove_from_doc_xml($gsdl_cgi, &util::filename_cat($archive_dir, $doc_filename), $metaname, $metapos, $metavalue, $docid_secnum, $metamode);
2185#   my $status = $self->remove_from_doc_xml($gsdl_cgi, &util::filename_cat($archive_dir, $doc_filename), $metaname, $metapos, undef, $docid_secnum);
2186   
2187    if ($status == 0)
2188    {
2189        my $mess = "remove-archives-metadata successful: Key[$docid]\n";
2190        $mess .= "  $metaname";
2191        $mess .= "->[$metapos]" if (defined $metapos);
2192
2193        $gsdl_cgi->generate_ok_message($mess); 
2194    }
2195    else
2196    {
2197        my $mess .= "Failed to remove archives metadata key: $docid\n";
2198        $mess .= "Exit status: $status\n";
2199        $mess .= "System Error Message: $!\n";
2200        $mess .= "-" x 20 . "\n";
2201       
2202        $gsdl_cgi->generate_error($mess);
2203    }
2204   
2205    #return $status; # in case calling functions have a use for this
2206}
2207
2208sub remove_archives_metadata
2209{
2210    my $self = shift @_;
2211
2212    my $username  = $self->{'username'};
2213    my $collect   = $self->{'collect'};
2214    my $gsdl_cgi  = $self->{'gsdl_cgi'};
2215   
2216    if ($baseaction::authentication_enabled)
2217    {
2218        # Ensure the user is allowed to edit this collection       
2219        $self->authenticate_user($username, $collect); #&authenticate_user($gsdl_cgi, $username, $collect);
2220    }
2221
2222    # Make sure the collection isn't locked by someone else
2223    $self->lock_collection($username, $collect);
2224
2225    $self->_remove_archives_metadata(@_);
2226
2227    # Release the lock once it is done
2228    $self->unlock_collection($username, $collect);
2229}
2230
2231sub remove_from_doc_xml
2232{
2233    my $self = shift @_;
2234    my ($gsdl_cgi, $doc_xml_filename, $metaname, $metapos, $metavalue, $secid, $metamode) = @_;
2235   
2236    my @start_rules = ('Section' => \&dxml_start_section);
2237   
2238    # Set the call-back functions for the metadata tags
2239    my @rules =
2240    (
2241        _default => 'raw',
2242        'Metadata' => \&rfdxml_metadata
2243    );
2244       
2245    my $parser = XML::Rules->new
2246    (
2247        start_rules => \@start_rules,
2248        rules => \@rules,
2249        style => 'filter',
2250        output_encoding => 'utf8',
2251#    normalisespaces => 1, # http://search.cpan.org/~jenda/XML-Rules-1.16/lib/XML/Rules.pm
2252        stripspaces => 2|0|0 # ineffectual
2253    );
2254   
2255    my $status = 0;
2256    my $xml_in = "";
2257    if (!open(MIN,"<$doc_xml_filename"))
2258    {
2259        $gsdl_cgi->generate_error("Unable to read in $doc_xml_filename: $!");
2260        $status = 1;
2261    }
2262    else
2263    {
2264        # Read them in
2265        my $line;
2266        while (defined ($line=<MIN>)) {
2267            $xml_in .= $line;
2268        }
2269        close(MIN);
2270
2271        # Filter with the call-back functions
2272        my $xml_out = "";
2273
2274        my $MOUT;
2275        if (!open($MOUT,">$doc_xml_filename")) {
2276            $gsdl_cgi->generate_error("Unable to write out to $doc_xml_filename: $!");
2277            $status = 1;
2278        }
2279        else {
2280            binmode($MOUT,":utf8");
2281            $parser->filter($xml_in, $MOUT, {metaname => $metaname, metapos => $metapos, metavalue => $metavalue, secid => $secid, metamode => $metamode});
2282            close($MOUT);       
2283        }
2284    }
2285    return $status;
2286}
2287
2288sub rfdxml_metadata
2289{
2290    my ($tagname, $attrHash, $contextArray, $parentDataArray, $parser) = @_;
2291
2292    # For comparisons, toplevel section is indicated by ""
2293    my $curr_sec_num = $parser->{'parameters'}->{'curr_section_num'} || "";
2294    my $secid = $parser->{'parameters'}->{'secid'} || "";
2295
2296    if (!($secid eq $curr_sec_num))
2297    {
2298        # RAW is [$tagname => $attrHash] not $tagname => $attrHash!!
2299        return [$tagname => $attrHash];
2300    }
2301
2302    if ($parser->{'parameters'}->{'metaname'} eq $attrHash->{'name'})
2303    {
2304        if (!defined $parser->{'parameters'}->{'poscount'})
2305        {
2306            $parser->{'parameters'}->{'poscount'} = 0;
2307        }
2308        else
2309        {
2310            $parser->{'parameters'}->{'poscount'}++;
2311        }
2312       
2313        # if overriding (for set-meta) but no metapos, then clear all the meta for this metaname
2314        if ((defined $parser->{'parameters'}->{'metamode'}) && ($parser->{'parameters'}->{'metamode'} eq "override") && (!defined $parser->{'parameters'}->{'metapos'})) {         
2315            return [];
2316        }
2317    }
2318
2319    if ((defined $parser->{'parameters'}->{'metapos'}) && ($parser->{'parameters'}->{'metaname'} eq $attrHash->{'name'}) && ($parser->{'parameters'}->{'poscount'} == $parser->{'parameters'}->{'metapos'}))
2320    {   
2321        return [];
2322    }
2323
2324    if ((defined $parser->{'parameters'}->{'metavalue'}) && ($parser->{'parameters'}->{'metaname'} eq $attrHash->{'name'}) && ($parser->{'parameters'}->{'metavalue'} eq $attrHash->{'_content'}))
2325    {   
2326        return [];
2327    }
2328   
2329    # RAW is [$tagname => $attrHash] not $tagname => $attrHash!!
2330    return [$tagname => $attrHash];
2331}
2332
2333sub mxml_metadata
2334{
2335    my ($tagname, $attrHash, $contextArray, $parentDataArray, $parser) = @_;
2336    my $metaname = $parser->{'parameters'}->{'metaname'};
2337    my $metamode = $parser->{'parameters'}->{'metamode'};
2338
2339    # Report error if we don't see FileName tag before this
2340    die "Fatal Error: Unexpected metadata.xml structure. Undefined current_file, possibly encountered Description before FileName" if (!defined($parser->{'parameters'}->{'current_file'}));
2341   
2342    # Don't do anything if we are not in the right FileSet
2343    my $file_regexp = $parser->{'parameters'}->{'current_file'};
2344    if ($file_regexp =~ /\.\*/) {
2345    # Only interested in a file_regexp if it specifies precisely one
2346    # file. 
2347    # So, skip anything with a .* in it as it is too general
2348##  print STDERR "@@@@ Skipping entry in metadata.xml where FileName=.* as it is too general\n";
2349    return [$tagname => $attrHash];
2350    }
2351    my $src_file = $parser->{'parameters'}->{'src_file'};
2352    if (!($src_file =~ /$file_regexp/)) {
2353    return [$tagname => $attrHash];
2354    }
2355##    print STDERR "*** mxl metamode = $metamode\n";
2356
2357    # Find the right metadata tag and checks if we are going to override it
2358    my $name_attr = $attrHash->{'name'};
2359    if (($name_attr eq $metaname) && ($metamode eq "override")) {
2360
2361    # now metadata.xml functions need to keep track of metapos
2362    if (!defined $parser->{'parameters'}->{'poscount'})
2363    {
2364        $parser->{'parameters'}->{'poscount'} = 0;
2365    }
2366    else
2367    {
2368        $parser->{'parameters'}->{'poscount'}++;
2369    }
2370
2371    # If either the metapos or prevmetavalue is set,
2372        # get the value and override the current value
2373    my $metavalue = $parser->{'parameters'}->{'metavalue'};
2374
2375    if(defined $parser->{'parameters'}->{'prevmetavalue'} && $parser->{'parameters'}->{'prevmetavalue'} eq $attrHash->{'_content'})
2376    {
2377        $attrHash->{'_content'} = $metavalue;
2378
2379        ##  print STDERR "**** overriding metadata.xml\n";
2380       
2381        # Don't want it to wipe out any other pieces of metadata
2382        $parser->{'parameters'}->{'metamode'} = "done";
2383    }
2384    elsif(defined $parser->{'parameters'}->{'metapos'} && $parser->{'parameters'}->{'poscount'} == $parser->{'parameters'}->{'metapos'})
2385    {
2386        $attrHash->{'_content'} = $metavalue;
2387        $parser->{'parameters'}->{'metamode'} = "done";
2388    }
2389    }
2390
2391    # mxml_description will process the metadata if metadata is accumulate,
2392    # or if we haven't found the metadata to override
2393
2394    # RAW is [$tagname => $attrHash] not $tagname => $attrHash!!
2395    return [$tagname => $attrHash];
2396}
2397
2398
2399sub mxml_description
2400{
2401    my ($tagname, $attrHash, $contextArray, $parentDataArray, $parser) = @_;
2402    my $metamode = $parser->{'parameters'}->{'metamode'};   
2403
2404    # Failed... Report error if we don't see FileName tag before this
2405    die "Fatal Error: Unexpected metadata.xml structure. Undefind current_file, possiblely encountered Description before FileName" if (!defined($parser->{'parameters'}->{'current_file'}));
2406
2407    # Don't do anything if we are not in the right FileSet
2408    my $file_regexp = $parser->{'parameters'}->{'current_file'};
2409    if ($file_regexp =~ m/\.\*/) {
2410    # Only interested in a file_regexp if it specifies precisely one
2411    # file. 
2412    # So, skip anything with a .* in it as it is too general
2413    return [$tagname => $attrHash];
2414    }
2415    my $src_file = $parser->{'parameters'}->{'src_file'};
2416   
2417    if (!($src_file =~ m/$file_regexp/)) {
2418    return [$tagname => $attrHash];
2419    }
2420
2421    # Accumulate the metadata block to the end of the description block
2422    # Note: This adds metadata block to all description blocks, so if there are
2423    # multiple FileSets, it will add to all of them
2424    if (($metamode eq "accumulate") || ($metamode eq "override")) {
2425
2426    # if metamode was "override" but get to here then it failed to
2427    # find an item to override, in which case it should append its
2428    # value to the end, just like the "accumulate" mode
2429
2430    if ($metamode eq "override") {
2431        print "No metadata value to override.  Switching 'metamode' to accumulate\n";
2432    }
2433
2434    # tack a new metadata tag on to the end of the <Metadata>+ block
2435    my $metaname = $parser->{'parameters'}->{'metaname'};
2436    my $metavalue = $parser->{'parameters'}->{'metavalue'};
2437   
2438    my $metadata_attr = { '_content' => $metavalue,
2439                  'name'     => $metaname,
2440                  'mode'     => "accumulate" };
2441
2442    my $append_metadata = [ "Metadata" => $metadata_attr ];
2443    my $description_content = $attrHash->{'_content'};
2444   
2445##  print STDERR "*** appending to metadata.xml\n";
2446
2447    # append the new metadata element to the end of the current
2448    # content contained inside this tag
2449    if (ref($description_content) eq "") {
2450        # => string or numeric literal
2451        # this is caused by a <Description> block has no <Metadata> child elements
2452        # => set up an empty array in '_content'
2453        $attrHash->{'_content'} = [ "\n" ];
2454        $description_content = $attrHash->{'_content'};
2455    }
2456
2457    push(@$description_content,"    ", $append_metadata ,"\n        ");
2458    $parser->{'parameters'}->{'metamode'} = "done";
2459    }
2460
2461    # RAW is [$tagname => $attrHash] not $tagname => $attrHash!!
2462    return [$tagname => $attrHash];
2463}
2464
2465
2466sub mxml_filename
2467{
2468    my ($tagname, $attrHash, $contextArray, $parentDataArray, $parser) = @_;
2469
2470    # Store the filename of the Current Fileset
2471    # Note: According to http://greenstone.org/dtd/DirectoryMetadata/1.0/DirectoryMetadata.dtd
2472    # FileName tag must come before Description tag
2473    $parser->{'parameters'}->{'current_file'} = $attrHash->{'_content'};
2474
2475    # RAW is [$tagname => $attrHash] not $tagname => $attrHash!!
2476    return [$tagname => $attrHash];
2477}
2478
2479
2480sub mxml_fileset
2481{
2482    my ($tagname, $attrHash, $contextArray, $parentDataArray, $parser) = @_;
2483
2484    # Initilise the current_file
2485    # Note: According to http://greenstone.org/dtd/DirectoryMetadata/1.0/DirectoryMetadata.dtd
2486    # FileName tag must come before Description tag
2487    $parser->{'parameters'}->{'current_file'} = "";
2488
2489    # RAW is [$tagname => $attrHash] not $tagname => $attrHash!!
2490    return [$tagname => $attrHash];
2491}
2492
2493sub mxml_directorymetadata
2494{
2495    my ($tagname, $attrHash, $contextArray, $parentDataArray, $parser) = @_;
2496
2497    # if we haven't processed the metadata when we reach the end of metadata.xml
2498    # it's because there's no particular FileSet element whose FileName matched
2499    # In which case, add a new FileSet for this FileName
2500    my $metamode = $parser->{'parameters'}->{'metamode'};
2501    if($metamode ne "done") {
2502   
2503    if ($metamode eq "override") {
2504        print "No metadata value to override.  Switching 'metamode' to accumulate\n";
2505    }
2506
2507    # If we get to here and metamode is override, this means there
2508    # was no existing value to overide => treat as an append operation
2509   
2510    # Create a new FileSet element and append to DirectoryMetadata
2511    # <FileSet>
2512    # <FileName>src_file</FileName>
2513    # <Description>
2514    # <Metadata mode="" name="">metavalue</Metadata>
2515    # </Description>
2516    # </FileSet>
2517    my $src_file = $parser->{'parameters'}->{'src_file'};
2518    my $metaname = $parser->{'parameters'}->{'metaname'};
2519    my $metavalue = $parser->{'parameters'}->{'metavalue'};
2520    my $metadata_attr = {
2521        '_content' => $metavalue,
2522        'name' => $metaname,
2523        'mode' => "accumulate"
2524    };
2525    my $append_metadata = [ "Metadata" => $metadata_attr ];
2526    my $description_attr->{'_content'} = [ "\n\t\t   ", $append_metadata, "\n\t\t"];
2527    my $description_element = [ "Description" => $description_attr ];
2528
2529    #_content is not an attribute, it's special and holds the children of this element
2530    # including the textnode value embedded in this element if any.
2531    my $filename_attr = {'_content' => $src_file};
2532    my $filename_element = [ "FileName" => $filename_attr ];
2533
2534    my $fileset_attr = {};
2535    $fileset_attr->{'_content'} = [ "\n\t\t", $filename_element,"\n\t\t",$description_element ,"\n\t" ];
2536    my $fileset = [ "FileSet" => $fileset_attr ]; #my $fileset = [ "FileSet" => {} ];
2537   
2538   
2539    # get children of dirmeta, and push the new FileSet element onto it
2540    print "Appending metadata to metadata.xml\n";
2541    my $dirmeta_content = $attrHash->{'_content'};
2542    if (ref($dirmeta_content)) {
2543        # got some existing interesting nested content
2544        #push(@$dirmeta_content, "    ", $fileset ,"\n        ");
2545        push(@$dirmeta_content, "\t", $fileset ,"\n");
2546    }
2547    else {
2548        #description_content is most likely a string such as "\n"
2549        #$attrHash->{'_content'} = [$dirmeta_content, "    ", $fileset ,"\n" ];
2550        $attrHash->{'_content'} = [$dirmeta_content, "\t", $fileset ,"\n" ];
2551    }   
2552
2553    $parser->{'parameters'}->{'metamode'} = "done";
2554    }
2555    # RAW is [$tagname => $attrHash] not $tagname => $attrHash!!
2556    return [$tagname => $attrHash];
2557}
2558
2559
2560sub edit_metadata_xml
2561{
2562    my $self = shift @_;
2563    my ($gsdl_cgi, $metadata_xml_filename, $metaname, $metapos, $metavalue, $metamode, $src_file, $prevmetavalue) = @_;
2564
2565    # Set the call-back functions for the metadata tags
2566    my @rules =
2567    ( _default => 'raw',
2568          'FileName' => \&mxml_filename,
2569      'Metadata' => \&mxml_metadata,
2570      'Description' => \&mxml_description,
2571          'FileSet' => \&mxml_fileset,
2572      'DirectoryMetadata' => \&mxml_directorymetadata);
2573
2574    # use XML::Rules to add it in (read in and out again)
2575    my $parser = XML::Rules->new(rules => \@rules,
2576                 style => 'filter',
2577                                 output_encoding => 'utf8',
2578                 stripspaces => 2|0|0); # http://search.cpan.org/~jenda/XML-Rules-1.16/lib/XML/Rules.pm
2579
2580    if (!-e $metadata_xml_filename) {
2581   
2582        if (open(MOUT,">$metadata_xml_filename")) {
2583           
2584            my $src_file_re = &util::filename_to_regex($src_file);
2585            # shouldn't the following also be in the above utility routine??
2586            # $src_file_re =~ s/\./\\./g;
2587       
2588            print MOUT "<?xml version=\"1.0\"?>\n";
2589            print MOUT "<DirectoryMetadata>\n";
2590            print MOUT " <FileSet>\n";
2591            print MOUT "  <FileName>$src_file_re</FileName>\n";
2592            print MOUT "  <Description>\n";
2593            print MOUT "  </Description>\n";
2594            print MOUT " </FileSet>\n";
2595            print MOUT "</DirectoryMetadata>\n";
2596
2597            close(MOUT);
2598        }
2599        else {
2600            $gsdl_cgi->generate_error("Unable to create $metadata_xml_filename: $!");
2601        }
2602    }
2603   
2604   
2605    my $xml_in = "";
2606    if (!open(MIN,"<$metadata_xml_filename")) {
2607        $gsdl_cgi->generate_error("Unable to read in $metadata_xml_filename: $!");
2608    }
2609    else {
2610        # Read them in
2611        my $line;
2612        while (defined ($line=<MIN>)) {
2613            $xml_in .= $line;
2614        }
2615        close(MIN);
2616
2617        # Filter with the call-back functions
2618        my $xml_out = "";
2619
2620        my $MOUT;
2621        if (!open($MOUT,">$metadata_xml_filename")) {
2622            $gsdl_cgi->generate_error("Unable to write out to $metadata_xml_filename: $!");
2623        }
2624        else {
2625            binmode($MOUT,":utf8");
2626
2627            # Some wise person please find out how to keep the DTD and encode lines in after it gets filtered by this XML::Rules
2628            # At the moment, I will just hack it!
2629            #my $header_with_utf8_dtd = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
2630            #$header_with_utf8_dtd .= "<!DOCTYPE DirectoryMetadata SYSTEM \"http://greenstone.org/dtd/DirectoryMetadata/1.0/DirectoryMetadata.dtd\">";
2631            #$xml_out =~ s/\<\?xml\sversion\=\"1.0\"\?\>/$header_with_utf8_dtd/;
2632            #print MOUT $xml_out;
2633
2634            $parser->filter($xml_in, $MOUT, { metaname => $metaname,
2635                              metapos => $metapos,
2636                      metavalue => $metavalue,
2637                      metamode => $metamode,
2638                      src_file => $src_file,
2639                      prevmetavalue => $prevmetavalue,
2640                      current_file => undef} );
2641            close($MOUT);       
2642        }
2643   }
2644}
2645
2646
2647sub set_import_metadata
2648{
2649    my $self = shift @_;
2650   
2651    my $username  = $self->{'username'};
2652    my $collect   = $self->{'collect'};
2653    my $gsdl_cgi  = $self->{'gsdl_cgi'};
2654   
2655    if ($baseaction::authentication_enabled) {
2656    # Ensure the user is allowed to edit this collection
2657    $self->authenticate_user($username, $collect);
2658    }
2659
2660    # Make sure the collection isn't locked by someone else
2661    $self->lock_collection($username, $collect);
2662 
2663    $self->_set_import_metadata(@_);
2664
2665    # Release the lock once it is done
2666    $self->unlock_collection($username, $collect);
2667   
2668}
2669
2670sub set_import_metadata_array
2671{
2672    my $self = shift @_;
2673
2674    my $username  = $self->{'username'};
2675    my $collect   = $self->{'collect'};
2676    my $gsdl_cgi  = $self->{'gsdl_cgi'};
2677#    my $gsdlhome  = $self->{'gsdlhome'};
2678
2679    if ($baseaction::authentication_enabled) {
2680    # Ensure the user is allowed to edit this collection   
2681    $self->authenticate_user($username, $collect); #&authenticate_user($gsdl_cgi, $username, $collect);
2682    }
2683
2684    my $site = $self->{'site'};
2685    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
2686   
2687    $gsdl_cgi->checked_chdir($collect_dir);
2688
2689    # Make sure the collection isn't locked by someone else
2690    $self->lock_collection($username, $collect);
2691
2692    $self->_set_import_metadata_array(@_);
2693
2694    # Release the lock once it is done
2695    $self->unlock_collection($username, $collect);
2696
2697}
2698
2699
2700sub _set_import_metadata_array
2701{
2702    my $self = shift @_;
2703
2704    my $collect   = $self->{'collect'};
2705    my $gsdl_cgi  = $self->{'gsdl_cgi'};
2706
2707    my $site = $self->{'site'};
2708    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
2709   
2710    # look up additional args
2711   
2712    my $infodbtype = $self->{'infodbtype'};
2713   
2714    my $archive_dir = &util::filename_cat($collect_dir,$collect,"archives");   
2715    my $arcinfo_doc_filename = &dbutil::get_infodb_file_path($infodbtype, "archiveinf-doc", $archive_dir);
2716   
2717    my $json_str = $self->{'json'};
2718    my $doc_array = decode_json $json_str;
2719   
2720    my $global_status = 0;
2721    my $global_mess = "";
2722   
2723    my @all_docids = ();
2724   
2725    foreach my $doc_array_rec ( @$doc_array )
2726    {
2727    my $status = -1;
2728    my $docid = $doc_array_rec->{'docid'};
2729   
2730    my ($docid_root,$docid_secnum);
2731    if(defined $docid) {   
2732        ($docid_root,$docid_secnum) = ($docid =~ m/^(.*?)(\..*)?$/);   
2733        # as yet no support for setting subsection metadata in metadata.xml
2734        if ((defined $docid_secnum) && ($docid_secnum !~ m/^\s*$/)) {
2735        $gsdl_cgi->generate_message("*** docid: $docid. No support yet for setting import metadata at subsections level.\n");
2736        next; # skip this docid in for loop
2737        }
2738    }
2739
2740    push(@all_docids,$docid); # docid_root rather
2741   
2742    my $metaname = $doc_array_rec->{'metaname'};
2743    if (defined $metaname) {
2744        my $metamode = $doc_array_rec->{'metamode'} || $self->{'metamode'};
2745        my $metavalue = $doc_array_rec->{'metavalue'};
2746        $metavalue =~ s/&lt;(.*?)&gt;/<$1>/g;
2747
2748        if ((!defined $metamode) || ($metamode =~ m/^\s*$/)) {
2749        # make "accumulate" the default (less destructive, as won't actually
2750        # delete any existing values)
2751        $metamode = "accumulate";
2752        }
2753
2754        # adding metapos and prevmetavalue support to import_metadata subroutines
2755        my $metapos   = $doc_array_rec->{'metapos'}; # don't force undef to 0. Undef has meaning when metamode=override
2756        my $prevmetavalue = $self->{'prevmetavalue'};
2757
2758        $self->set_import_metadata_entry($gsdl_cgi, $arcinfo_doc_filename, $infodbtype, $docid_root, $metaname, $metapos, $metavalue, $metamode, $prevmetavalue, $collect, $collect_dir); # at this point, docid_root = docid
2759       
2760    } elsif (defined $doc_array_rec->{'metatable'}) { # if no metaname, we expect a metatable
2761        my $metatable = $doc_array_rec->{'metatable'}; # a subarray, or need to generate an error saying JSON structure is wrong
2762       
2763        foreach my $metatable_rec ( @$metatable ) {
2764        $metaname  = $metatable_rec->{'metaname'};
2765        my $metamode  = $metatable_rec->{'metamode'} || $doc_array_rec->{'metamode'} || $self->{'metamode'};
2766        if ((!defined $metamode) || ($metamode =~ m/^\s*$/)) {
2767            # make "accumulate" the default (less destructive, as won't actually
2768            # delete any existing values)
2769            $metamode = "accumulate";
2770        }
2771
2772        # No support for metapos and prevmetavalue in the JSON metatable substructure
2773        my $metapos = undef;
2774        my $prevmetavalue = undef;
2775        my $metavals = $metatable_rec->{'metavals'}; # a sub-subarray
2776       
2777        foreach my $metavalue ( @$metavals ) {
2778            $metavalue =~ s/&lt;(.*?)&gt;/<$1>/g;
2779
2780            $self->set_import_metadata_entry($gsdl_cgi, $arcinfo_doc_filename, $infodbtype, $docid_root, $metaname, $metapos, $metavalue, $metamode, $prevmetavalue, $collect, $collect_dir); # at this point, docid_root = docid
2781            if($metamode eq "override") { # now, having overridden the first metavalue of the metaname,
2782            # need to accumulate subsequent metavals for this metaname, else the just-assigned
2783            # metavalue for this metaname will be lost
2784            $metamode = "accumulate";
2785            }
2786        }
2787        }
2788    }       
2789    }
2790
2791    # always a success message
2792    my $mess = "set-archives-metadata-array successful: Keys[ ".join(", ",@all_docids)."]\n";
2793    $gsdl_cgi->generate_ok_message($mess);
2794}
2795
2796# always returns true (1)
2797sub set_import_metadata_entry
2798{
2799    my $self = shift @_;
2800    my ($gsdl_cgi, $arcinfo_doc_filename, $infodbtype, $docid, $metaname, $metapos, $metavalue, $metamode, $prevmetavalue, $collect, $collect_dir) = @_;
2801
2802    my $info_mess = <<RAWEND;
2803****************************
2804  set_import_metadata_entry()
2805****************************
2806collect = $collect
2807collect_dir = $collect_dir
2808infodbtype = $infodbtype
2809arcinfo_doc_filename = $arcinfo_doc_filename
2810docid = $docid
2811metaname = $metaname
2812metapos = $metapos
2813metavalue = $metavalue
2814metamode = $metamode
2815prevmetavalue = $prevmetavalue
2816****************************
2817RAWEND
2818
2819    $gsdl_cgi->generate_message($info_mess);
2820
2821    # import works with metadata.xml which can have inherited metadata
2822    # so setting or removing at a metapos can have unintended effects for a COMPLEX collection
2823    # (a collection that has or can have inherited metadata). Metapos has expected behaviour for
2824    # a SIMPLE collection, which is one that doesn't have inherited metadata. Assume caller knows
2825    # what they're doing if they provide a metapos.
2826    if(defined $metapos) {
2827    print STDERR "@@@@ WARNING: metapos defined.\n";
2828    print STDERR "@@@@ Assuming SIMPLE collection and proceeding to modify the import meta at $metapos.\n";
2829    }
2830
2831    # Obtain where the metadata.xml is from the archiveinfo-doc.gdb file
2832    # If the doc oid is not specified, we assume the metadata.xml is next to the specified "f"
2833    my $metadata_xml_file;
2834    my $import_filename = undef;
2835   
2836    if (defined $docid) {
2837    # my $arcinfo_doc_filename = &dbutil::get_infodb_file_path($infodbtype, "archiveinf-doc", $archive_dir);
2838    my $doc_rec = &dbutil::read_infodb_entry($infodbtype, $arcinfo_doc_filename, $docid);
2839
2840    # This now stores the full pathname
2841    $import_filename = $doc_rec->{'src-file'}->[0];
2842    } else { # only for set_import_meta, not the case when calling method is set_import_metadata_array
2843         # as the array version of the method doesn't support the -f parameter yet
2844    my $import_file  = $self->{'f'};
2845    $import_filename = &util::filename_cat($collect_dir,$collect,$import_file);
2846    }
2847   
2848    # figure out correct metadata.xml file [?]
2849    # Assuming the metadata.xml file is next to the source file
2850    # Note: This will not work if it is using the inherited metadata from the parent folder
2851    my ($import_tailname, $import_dirname) = File::Basename::fileparse($import_filename);
2852    my $metadata_xml_filename = &util::filename_cat($import_dirname,"metadata.xml");
2853   
2854    # If we're overriding everything, then $metamode=override combined with $metapos=undefined
2855    # in which case, we need to remove all metavalues for the metaname at the given (sub)section
2856    # Thereafter, we will finally be able to set the overriding metavalue for this metaname
2857    if(!defined $metapos && $metamode eq "override") {
2858##  print STDERR "@@@ REMOVING all import metadata for $metaname\n";
2859    $self->remove_from_metadata_xml($gsdl_cgi, $metadata_xml_filename, $metaname, $metapos, undef, $import_tailname, $metamode); # we're removing all values, so metavalue=undef
2860
2861    }
2862
2863    # Edit the metadata.xml
2864    # Modified by Jeffrey from DL Consulting
2865    # Handle the case where there is one metadata.xml file for multiple FileSets
2866    # The XML filter needs to know whether it is in the right FileSet
2867    # TODO: This doesn't fix the problem where the metadata.xml is not next to the src file.
2868    # TODO: This doesn't handle the common metadata (where FileName doesn't point to a single file)
2869    $self->edit_metadata_xml($gsdl_cgi, $metadata_xml_filename, $metaname,
2870                 $metapos, $metavalue, $metamode, $import_tailname, $prevmetavalue);
2871    #return 0;
2872    return $metadata_xml_filename;
2873}
2874
2875sub _remove_import_metadata
2876{
2877    my $self = shift @_;
2878
2879    my $collect   = $self->{'collect'};
2880    my $gsdl_cgi  = $self->{'gsdl_cgi'};
2881#   my $gsdlhome  = $self->{'gsdlhome'};
2882    my $infodbtype = $self->{'infodbtype'};
2883   
2884    # Obtain the collect dir
2885    ## my $collect_dir = &util::filename_cat($gsdlhome, "collect");
2886    my $site = $self->{'site'};
2887    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
2888   
2889    ## my $collect_dir = &util::filename_cat($gsdlhome, "collect");
2890    my $archive_dir = &util::filename_cat($collect_dir,$collect,"archives");
2891
2892    # look up additional args
2893    my $docid = $self->{'d'};
2894    if ((!defined $docid) || ($docid =~ m/^\s*$/))
2895    {
2896        $gsdl_cgi->generate_error("No docid (d=...) specified.\n");
2897    }
2898   
2899    my $metaname = $self->{'metaname'};
2900    my $metapos = $self->{'metapos'};
2901    my $metavalue = $self->{'metavalue'};
2902    if(defined $metavalue) {
2903        $metavalue =~ s/&lt;(.*?)&gt;/<$1>/g;
2904    } elsif (!defined $metapos) { # if given no metavalue or metapos to delete, default to deleting the 1st
2905        $metapos = 0;
2906    }
2907    my $metamode = $self->{'metamode'} || undef;
2908
2909    # import works with metadata.xml which can have inherited metadata
2910    # so setting or removing at a metapos can have unintended effects for a COMPLEX collection
2911    # (a collection that has or can have inherited metadata). Metapos has expected behaviour for
2912    # a SIMPLE collection, which is one that doesn't have inherited metadata. Assume caller knows
2913    # what they're doing if they provide a metapos.
2914    if(defined $metapos) {
2915        print STDERR "@@@@ WARNING: metapos defined.\n";
2916        print STDERR "@@@@ Assuming SIMPLE collection and proceeding to modify the import meta at $metapos.\n";
2917    }
2918   
2919    # Obtain where the metadata.xml is from the archiveinfo-doc.gdb file
2920    # If the doc oid is not specified, we assume the metadata.xml is next to the specified "f"
2921    my $metadata_xml_file;
2922    my $import_filename = undef;
2923    if (defined $docid)
2924    {
2925        my $arcinfo_doc_filename = &dbutil::get_infodb_file_path($infodbtype, "archiveinf-doc", $archive_dir);
2926        my $doc_rec = &dbutil::read_infodb_entry($infodbtype, $arcinfo_doc_filename, $docid);
2927
2928        # This now stores the full pathname
2929        $import_filename = $doc_rec->{'src-file'}->[0];
2930    }
2931
2932    if((!defined $import_filename) || ($import_filename =~ m/^\s*$/))
2933    {
2934        $gsdl_cgi->generate_error("There is no metadata\n");
2935    }
2936   
2937    # figure out correct metadata.xml file [?]
2938    # Assuming the metadata.xml file is next to the source file
2939    # Note: This will not work if it is using the inherited metadata from the parent folder
2940    my ($import_tailname, $import_dirname) = File::Basename::fileparse($import_filename);
2941    my $metadata_xml_filename = &util::filename_cat($import_dirname,"metadata.xml");
2942   
2943    $self->remove_from_metadata_xml($gsdl_cgi, $metadata_xml_filename, $metaname, $metapos, $metavalue, $import_tailname, $metamode); # metamode has no meaning for removing meta, but is used by set_meta when overriding All
2944   
2945    my $mess = "remove-import-metadata successful: Key[$docid] -> $metadata_xml_filename\n";
2946    $mess .= "  $metaname";
2947    $mess .= " = $metavalue\n";
2948   
2949    $gsdl_cgi->generate_ok_message($mess);
2950
2951    #return $status; # in case calling functions have a use for this
2952}
2953
2954sub remove_import_metadata
2955{
2956    my $self = shift @_;
2957   
2958    my $username = $self->{'username'};
2959    my $collect   = $self->{'collect'};
2960    my $gsdl_cgi  = $self->{'gsdl_cgi'};
2961   
2962    if ($baseaction::authentication_enabled) {
2963        # Ensure the user is allowed to edit this collection       
2964        $self->authenticate_user($username, $collect); #&authenticate_user($gsdl_cgi, $username, $collect);
2965    }
2966
2967    # Make sure the collection isn't locked by someone else
2968    $self->lock_collection($username, $collect);
2969   
2970    $self->_remove_import_metadata(@_);
2971
2972    # Release the lock once it is done
2973    $self->unlock_collection($username, $collect);
2974
2975}
2976
2977sub remove_from_metadata_xml
2978{
2979    my $self = shift @_;
2980    my ($gsdl_cgi, $metadata_xml_filename, $metaname, $metapos, $metavalue, $src_file, $metamode) = @_;
2981    # metamode generally has no meaning for removing meta, but is used by set_meta
2982    # when overriding all metavals for a metaname, in which case remove_meta is called with metamode
2983
2984    # Set the call-back functions for the metadata tags
2985    my @rules =
2986    (
2987        _default => 'raw',
2988        'Metadata' => \&rfmxml_metadata,
2989        'FileName' => \&mxml_filename
2990    );
2991       
2992    my $parser = XML::Rules->new
2993    (
2994        rules => \@rules,
2995        style => 'filter',
2996        output_encoding => 'utf8',
2997     #normalisespaces => 1,
2998            stripspaces => 2|0|0 # ineffectual
2999    );
3000   
3001    my $xml_in = "";
3002    if (!open(MIN,"<$metadata_xml_filename"))
3003    {
3004        $gsdl_cgi->generate_error("Unable to read in $metadata_xml_filename: $!");
3005    }
3006    else
3007    {
3008        # Read them in
3009        my $line;
3010        while (defined ($line=<MIN>)) {
3011            $xml_in .= $line;
3012        }
3013        close(MIN);
3014
3015        # Filter with the call-back functions
3016        my $xml_out = "";
3017
3018        my $MOUT;
3019        if (!open($MOUT,">$metadata_xml_filename")) {
3020            $gsdl_cgi->generate_error("Unable to write out to $metadata_xml_filename: $!");
3021        }
3022        else {
3023            binmode($MOUT,":utf8");
3024            $parser->filter($xml_in, $MOUT, {metaname => $metaname, metapos => $metapos, metavalue => $metavalue, src_file => $src_file, metamode => $metamode, current_file => undef});
3025            close($MOUT);       
3026        }
3027    }
3028}
3029
3030sub rfmxml_metadata
3031{
3032    my ($tagname, $attrHash, $contextArray, $parentDataArray, $parser) = @_;
3033
3034    # metadata.xml does not handle subsections
3035
3036    # since metadata.xml now has to deal with metapos, we keep track of the metadata position
3037    if (($parser->{'parameters'}->{'src_file'} eq $parser->{'parameters'}->{'current_file'})
3038        && $parser->{'parameters'}->{'metaname'} eq $attrHash->{'name'})
3039    {
3040        if (!defined $parser->{'parameters'}->{'poscount'})
3041        {
3042            $parser->{'parameters'}->{'poscount'} = 0;
3043        }
3044        else
3045        {
3046            $parser->{'parameters'}->{'poscount'}++;
3047        }
3048
3049        # if overriding but no metapos, then clear all the meta for this metaname
3050        if ((defined $parser->{'parameters'}->{'metamode'}) && ($parser->{'parameters'}->{'metamode'} eq "override") && (!defined $parser->{'parameters'}->{'metapos'})) {
3051            return [];
3052        }
3053   
3054        if ((defined $parser->{'parameters'}->{'metapos'}) && ($parser->{'parameters'}->{'poscount'} == $parser->{'parameters'}->{'metapos'}))
3055        {
3056            return [];
3057        }
3058
3059        if ((defined $parser->{'parameters'}->{'metavalue'}) && ($attrHash->{'_content'} eq $parser->{'parameters'}->{'metavalue'}))
3060        {
3061            return [];
3062        }       
3063    }
3064
3065    # RAW is [$tagname => $attrHash] not $tagname => $attrHash!!
3066    return [$tagname => $attrHash];
3067}
3068
3069sub _remove_live_metadata
3070{
3071    my $self = shift @_;
3072
3073    my $collect   = $self->{'collect'};
3074    my $gsdl_cgi  = $self->{'gsdl_cgi'};
3075#    my $gsdlhome  = $self->{'gsdlhome'};
3076    my $infodbtype = $self->{'infodbtype'};
3077
3078    # Obtain the collect dir
3079    ## my $collect_dir = &util::filename_cat($gsdlhome, "collect");
3080    my $site = $self->{'site'};
3081    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
3082
3083   
3084    # look up additional args
3085    my $docid     = $self->{'d'};
3086    if ((!defined $docid) || ($docid =~ m/^\s*$/)) {
3087      $gsdl_cgi->generate_error("No docid (d=...) specified.");
3088    }
3089   
3090    # Generate the dbkey
3091    my $metaname  = $self->{'metaname'};
3092    my $dbkey = "$docid.$metaname";
3093
3094    # To people who know $collect_tail please add some comments
3095    # Obtain the live gdbm_db path
3096    my $collect_tail = $collect;
3097    $collect_tail =~ s/^.*[\/|\\]//;
3098    my $index_text_directory = &util::filename_cat($collect_dir,$collect,"index","text");
3099    my $infodb_file_path = &dbutil::get_infodb_file_path($infodbtype, "live-$collect_tail", $index_text_directory);
3100
3101    # Remove the key
3102    my $cmd = "gdbmdel \"$infodb_file_path\" \"$dbkey\"";
3103    my $status = system($cmd);
3104    if ($status != 0) {
3105        # Catch error if gdbmdel failed
3106    my $mess = "Failed to set metadata key: $dbkey\n";
3107   
3108    $mess .= "PATH: $ENV{'PATH'}\n";
3109    $mess .= "cmd = $cmd\n";
3110    $mess .= "Exit status: $status\n";
3111    $mess .= "System Error Message: $!\n";
3112
3113    $gsdl_cgi->generate_error($mess);
3114    }
3115    else {
3116    $gsdl_cgi->generate_ok_message("DB remove successful: Key[$metaname]");
3117    }
3118
3119}
3120
3121sub remove_live_metadata
3122{
3123    my $self = shift @_;
3124
3125    my $username  = $self->{'username'};
3126    my $collect   = $self->{'collect'};
3127    my $gsdl_cgi  = $self->{'gsdl_cgi'};
3128    my $gsdlhome  = $self->{'gsdlhome'};
3129   
3130    if ($baseaction::authentication_enabled) {
3131    # Ensure the user is allowed to edit this collection   
3132    $self->authenticate_user($username, $collect); #&authenticate_user($gsdl_cgi, $username, $collect);
3133    }
3134
3135    # Make sure the collection isn't locked by someone else
3136    $self->lock_collection($username, $collect);
3137
3138    $self->_remove_live_metadata(@_);
3139
3140    $self->unlock_collection($username, $collect);
3141}
3142
3143sub remove_metadata
3144{
3145    my $self = shift @_;
3146
3147    my $where = $self->{'where'};
3148    if(!$where) {
3149    $self->remove_index_metadata(@_); # call the full version of set_index_meta for the default behaviour
3150    return;
3151    }
3152
3153    my $username  = $self->{'username'};
3154    my $collect   = $self->{'collect'};
3155    my $gsdl_cgi  = $self->{'gsdl_cgi'};
3156
3157    if ($baseaction::authentication_enabled) {
3158    # Ensure the user is allowed to edit this collection   
3159    $self->authenticate_user($username, $collect); #&authenticate_user($gsdl_cgi, $username, $collect);
3160    }
3161
3162    # Make sure the collection isn't locked by someone else
3163    $self->lock_collection($username, $collect);
3164
3165    # check which directories need to be processed, specified in $where as
3166    # any combination of import|archives|index|live
3167    if($where =~ m/import/) {
3168    $self->_remove_import_metadata(@_);     
3169    }
3170    if($where =~ m/archives/) {
3171    $self->_remove_archives_metadata(@_);       
3172   }
3173    if($where =~ m/index/) {
3174    $self->_remove_index_metadata(@_);     
3175    }
3176
3177    # Release the lock once it is done
3178    $self->unlock_collection($username, $collect);
3179}
3180
3181# the internal version, without authentication
3182sub _remove_index_metadata
3183{   
3184    my $self = shift @_;
3185
3186    my $collect   = $self->{'collect'};
3187    my $gsdl_cgi  = $self->{'gsdl_cgi'};
3188#    my $gsdlhome  = $self->{'gsdlhome'};
3189    my $infodbtype = $self->{'infodbtype'};
3190   
3191    # Obtain the collect dir
3192    my $site = $self->{'site'};
3193    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
3194    ## my $collect_dir = &util::filename_cat($gsdlhome, "collect");
3195
3196        # look up additional args
3197    my $docid     = $self->{'d'};
3198    if ((!defined $docid) || ($docid =~ m/^\s*$/)) {
3199      $gsdl_cgi->generate_error("No docid (d=...) specified.");
3200    }
3201    my $metaname  = $self->{'metaname'};
3202    my $metapos   = $self->{'metapos'};
3203    my $metavalue = $self->{'metavalue'} || undef; # necessary to force fallback to undef here
3204
3205    # To people who know $collect_tail please add some comments
3206    # Obtain the path to the database
3207    my $collect_tail = $collect;
3208    $collect_tail =~ s/^.*[\/|\\]//;
3209    my $index_text_directory = &util::filename_cat($collect_dir,$collect,"index","text");
3210    my $infodb_file_path = &dbutil::get_infodb_file_path($infodbtype, $collect_tail, $index_text_directory);
3211
3212    # Read the docid entry
3213    my $doc_rec = &dbutil::read_infodb_entry($infodbtype, $infodb_file_path, $docid);
3214
3215    # Check to make sure the key does exist
3216    if (!defined ($doc_rec->{$metaname})) {
3217        $gsdl_cgi->generate_error("No metadata field \"" . $metaname . "\" in the specified document: [" . $docid . "]");
3218    }
3219
3220    # Obtain the specified metadata pos
3221    # if no metavalue or metapos to delete, default to deleting the 1st value for the metaname
3222    if(!defined $metapos && !defined $metavalue) {
3223        $metapos = 0;
3224    }
3225   
3226
3227    # consider check key is defined before deleting?
3228    # Loop through the metadata array and ignore the specified position
3229    my $filtered_metadata = [];
3230    my $num_metadata_vals = scalar(@{$doc_rec->{$metaname}});   
3231    for (my $i=0; $i<$num_metadata_vals; $i++) {
3232    my $metaval = shift(@{$doc_rec->{$metaname}});
3233
3234    if (!defined $metavalue && $i != $metapos) {
3235        push(@$filtered_metadata,$metaval);
3236    }
3237   
3238    if(defined $metavalue && !($metavalue eq $metaval))
3239    {
3240        push(@$filtered_metadata,$metaval);
3241    }
3242    }
3243    $doc_rec->{$metaname} = $filtered_metadata;
3244
3245    ## Use the dbutil set_entry method instead of assuming the database is gdbm
3246    my $status = &dbutil::set_infodb_entry($infodbtype, $infodb_file_path, $docid, $doc_rec);
3247
3248    if ($status != 0) {
3249    my $mess = "Failed to set metadata key: $docid\n";
3250   
3251    $mess .= "PATH: $ENV{'PATH'}\n";
3252    $mess .= "Exit status: $status\n";
3253    $mess .= "System Error Message: $!\n";
3254
3255    $gsdl_cgi->generate_error($mess);
3256    }
3257    else {
3258    my $mess = "DB set (with item deleted) successful: Key[$docid]\n";
3259    $mess .= "  $metaname";
3260    $mess .= "->[$metapos]" if (defined $metapos);
3261
3262    $gsdl_cgi->generate_ok_message($mess);
3263    }
3264
3265    #return $status; # in case calling functions have a use for this
3266}
3267
3268sub remove_index_metadata
3269{
3270    my $self = shift @_;
3271
3272    my $username  = $self->{'username'};
3273    my $collect   = $self->{'collect'};
3274    my $gsdl_cgi  = $self->{'gsdl_cgi'};
3275#    my $gsdlhome  = $self->{'gsdlhome'};
3276   
3277    if ($baseaction::authentication_enabled) {
3278    # Ensure the user is allowed to edit this collection   
3279    $self->authenticate_user($username, $collect); #&authenticate_user($gsdl_cgi, $username, $collect);
3280    }
3281
3282    # Obtain the collect dir
3283    my $site = $self->{'site'};
3284    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
3285    ## my $collect_dir = &util::filename_cat($gsdlhome, "collect");
3286
3287    # Make sure the collection isn't locked by someone else
3288    $self->lock_collection($username, $collect);
3289
3290    $self->_remove_index_metadata(@_);
3291
3292    # Release the lock once it is done
3293    $self->unlock_collection($username, $collect);
3294}
3295
3296
3297# Was trying to reused the codes, but the functions need to be broken
3298# down more before they can be reused, otherwise there will be too
3299# much overhead and duplicate process...
3300sub insert_metadata
3301{
3302    my $self = shift @_;
3303   
3304    my $username  = $self->{'username'};
3305    my $collect   = $self->{'collect'};
3306    my $gsdl_cgi  = $self->{'gsdl_cgi'};
3307    my $gsdlhome  = $self->{'gsdlhome'};
3308    my $infodbtype = $self->{'infodbtype'};
3309   
3310    # If the import metadata and gdbm database have been updated, we
3311    # need to insert some notification to warn user that the the text
3312    # they see at the moment is not indexed and require a rebuild.
3313    my $rebuild_pending_macro = "_rebuildpendingmessage_";
3314
3315    if ($baseaction::authentication_enabled) {
3316    # Ensure the user is allowed to edit this collection
3317    $self->authenticate_user($username, $collect);
3318    }
3319
3320    # Obtain the collect and archive dir   
3321    my $site = $self->{'site'};
3322    my $collect_dir = $gsdl_cgi->get_collection_dir($site);
3323    ##my $collect_dir = &util::filename_cat($gsdlhome, "collect");
3324    my $archive_dir = &util::filename_cat($collect_dir,$collect,"archives");
3325
3326    # Make sure the collection isn't locked by someone else
3327    $self->lock_collection($username, $collect);
3328   
3329    # Check additional args
3330    my $docid = $self->{'d'};
3331    if (!defined($docid)) {
3332    $gsdl_cgi->generate_error("No document id is specified: d=...");
3333    }
3334    my $metaname = $self->{'metaname'};
3335    if (!defined($metaname)) {
3336    $gsdl_cgi->generate_error("No metaname is specified: metadataname=...");
3337    }
3338    my $metavalue = $self->{'metavalue'};
3339    if (!defined($metavalue) || $metavalue eq "") {
3340    $gsdl_cgi->generate_error("No metavalue or empty metavalue is specified: metadataname=...");
3341    }
3342    # make "accumulate" the default (less destructive, as won't actually
3343    # delete any existing values)
3344    my $metamode = "accumulate";
3345
3346    # metapos/prevmetavalue were never before used in this subroutine, so set them to undefined
3347    my $metapos   = undef;
3348    my $prevmetavalue = undef;
3349
3350    #=======================================================================#
3351    # set_import_metadata [START]
3352    #=======================================================================#
3353    # Obtain where the metadata.xml is from the archiveinfo-doc.gdb file
3354    # If the doc oid is not specified, we assume the metadata.xml is next to the specified "f"
3355    my $metadata_xml_file;
3356    my $arcinfo_doc_filename = &dbutil::get_infodb_file_path($infodbtype, "archiveinf-doc", $archive_dir);
3357    my $archive_doc_rec = &dbutil::read_infodb_entry($infodbtype, $arcinfo_doc_filename, $docid);
3358   
3359    # This now stores the full pathname
3360    my $import_filename = $archive_doc_rec->{'src-file'}->[0];
3361   
3362    # figure out correct metadata.xml file [?]
3363    # Assuming the metadata.xml file is next to the source file
3364    # Note: This will not work if it is using the inherited metadata from the parent folder
3365    my ($import_tailname, $import_dirname)
3366    = File::Basename::fileparse($import_filename);
3367    my $metadata_xml_filename = &util::filename_cat($import_dirname,"metadata.xml");
3368
3369    # Shane's escape characters
3370    $metavalue = pack "U0C*", unpack "C*", $metavalue;
3371    $metavalue =~ s/\,/&#44;/g;
3372    $metavalue =~ s/\:/&#58;/g;
3373    $metavalue =~ s/\|/&#124;/g;
3374    $metavalue =~ s/\(/&#40;/g;
3375    $metavalue =~ s/\)/&#41;/g;
3376    $metavalue =~ s/\[/&#91;/g;
3377    $metavalue =~ s/\\/&#92;/g;
3378    $metavalue =~ s/\]/&#93;/g;
3379    $metavalue =~ s/\{/&#123;/g;
3380    $metavalue =~ s/\}/&#125;/g;
3381    $metavalue =~ s/\"/&#34;/g;
3382    $metavalue =~ s/\`/&#96;/g;
3383    $metavalue =~ s/\n/_newline_/g;
3384
3385    # Edit the metadata.xml
3386    # Modified by Jeffrey from DL Consulting
3387    # Handle the case where there is one metadata.xml file for multiple FileSets
3388    # The XML filter needs to know whether it is in the right FileSet
3389    # TODO: This doesn't fix the problem where the metadata.xml is not next to the src file.
3390    # TODO: This doesn't handle the common metadata (where FileName doesn't point to a single file)
3391    $self->edit_metadata_xml($gsdl_cgi, $metadata_xml_filename, $metaname,
3392                 $metapos, $metavalue, $metamode, $import_tailname, $prevmetavalue);
3393    #=======================================================================#
3394    # set_import_metadata [END]
3395    #=======================================================================#
3396
3397
3398    #=======================================================================#
3399    # set_metadata (accumulate version) [START]
3400    #=======================================================================#
3401    # To people who know $collect_tail please add some comments
3402    # Obtain path to the database
3403    my $collect_tail = $collect;
3404    $collect_tail =~ s/^.*[\/|\\]//;
3405    my $index_text_directory = &util::filename_cat($collect_dir,$collect,"index","text");
3406    my $infodb_file_path = &dbutil::get_infodb_file_path($infodbtype, $collect_tail, $index_text_directory);
3407
3408    # Read the docid entry
3409    my $doc_rec = &dbutil::read_infodb_entry($infodbtype, $infodb_file_path, $docid);
3410
3411    # Protect the quotes
3412    $metavalue =~ s/\"/\\\"/g;
3413
3414    # Adds the pending macro
3415    my $macro_metavalue = $rebuild_pending_macro . $metavalue;
3416
3417    # If the metadata doesn't exist, create a new one
3418    if (!defined($doc_rec->{$metaname})){   
3419    $doc_rec->{$metaname} = [ $macro_metavalue ];
3420    }
3421    # Else, let's acculumate the values
3422    else {
3423        push(@{$doc_rec->{$metaname}},$macro_metavalue);
3424    }
3425
3426    ## Use the dbutil set_entry method instead of assuming the database is gdbm
3427    my $status = &dbutil::set_infodb_entry($infodbtype, $infodb_file_path, $docid, $doc_rec);
3428
3429    if ($status != 0) {
3430        # Catch error if gdbmget failed
3431    my $mess = "Failed to set metadata key: $docid\n";
3432   
3433    $mess .= "PATH: $ENV{'PATH'}\n";
3434    $mess .= "Exit status: $status\n";
3435    $mess .= "System Error Message: $!\n";
3436
3437    $gsdl_cgi->generate_error($mess);
3438    }
3439    else {
3440    my $mess = "insert-metadata successful: Key[$docid]\n";
3441    $mess .= "  [In metadata.xml] $metaname";
3442    $mess .= " = $metavalue\n";
3443    $mess .= "  [In database] $metaname";
3444    $mess .= " = $macro_metavalue\n";
3445    $mess .= "  The new text has not been indexed, rebuilding collection is required\n";
3446        $gsdl_cgi->generate_ok_message($mess);
3447    }   
3448    #=======================================================================#
3449    # set_metadata (accumulate version) [END]
3450    #=======================================================================#
3451
3452    # Release the lock once it is done
3453    $self->unlock_collection($username, $collect);
3454}
3455
34561;
Note: See TracBrowser for help on using the browser.