Project

General

Profile

1 1929 brooke
#!/usr/bin/perl
2
#
3
#  '$RCSfile$'
4
#  Copyright: 2000 Regents of the University of California
5
#
6
#   '$Author$'
7
#     '$Date$'
8
# '$Revision$'
9
#
10
# This program is free software; you can redistribute it and/or modify
11
# it under the terms of the GNU General Public License as published by
12
# the Free Software Foundation; either version 2 of the License, or
13
# (at your option) any later version.
14
#
15
# This program is distributed in the hope that it will be useful,
16
# but WITHOUT ANY WARRANTY; without even the implied warranty of
17
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
# GNU General Public License for more details.
19
#
20
# You should have received a copy of the GNU General Public License
21
# along with this program; if not, write to the Free Software
22
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23
#
24
25
#
26
# This is a CGI application for inserting metadata documents into
27
# the Metacat database.  It utilizes the Metacat.pm module for most work.
28
# In this script, we process the form fields passed in from a POST, insert a
29
# metadata document and an ACL document.
30
31
use Metacat;
32
use AppConfig qw(:expand :argcount);
33
use XML::LibXML;
34
use XML::LibXSLT;
35
use Template;
36
use Net::SMTP;
37
use CGI qw/:standard :html3/;
38
use strict;
39
40
# Global configuration paramters
41
#my $cfgdir = "@install-dir@";
42
#my $cfgdir = "/usr/local/devtools/tomcat/webapps/knb/style/skins";
43
my $cfgdir = "@install-dir@@style-skins-relpath@";
44
my $tmpdir = "@temp-dir@";
45
my $templatesdir = "@install-dir@@style-common-relpath@/templates";
46
my $now = time;
47
my $xslConvDir = "$cfgdir/lib/style/";
48
49
# Import all of the HTML form fields as variables
50
import_names('FORM');
51
52
# Set up the hash for returning data to the HTML templates
53
my $templateVars = { 'status' => 'success' };
54
my $error = 0;
55
my @errorMessages;
56
57
# create a new AppConfig object and load our config parameters
58
# note that this requires the form submission to have a "cfg" paramter
59
# to determine which config file to load
60
my $config = AppConfig->new({
61
    GLOBAL => { ARGCOUNT => ARGCOUNT_ONE, } });
62
63
$config->define("metacatUrl");
64
$config->define("username");
65
$config->define("password");
66
$config->define("ldapUrl");
67
$config->define("defaultScope");
68
$config->define("organization");
69
$config->define("orgabbrev");
70
$config->define("orgurl");
71
$config->define("accesspubid");
72
$config->define("accesssysid");
73
$config->define("datasetpubid");
74
$config->define("datasetsysid");
75 2138 sgarg
$config->define("hasKeyword", { DEFAULT => 'true'} );
76 2148 sgarg
$config->define("hasTemporal", { DEFAULT => 'true'} );
77
$config->define("hasSpatial", { DEFAULT => 'true'} );
78
$config->define("hasTaxonomic", { DEFAULT => 'true'} );
79
$config->define("hasMethod", { DEFAULT => 'true'} );
80
$config->define("temporalRequired", { DEFAULT => 'true'} );
81
$config->define("spatialRequired", { DEFAULT => 'true'} );
82 1929 brooke
$config->define("mailhost");
83
$config->define("sender");
84
$config->define("recipient");
85
$config->define("adminname");
86 1973 jones
if ($FORM::cfg eq 'nceas') {
87
    $config->define("nceas_db");
88
    $config->define("nceas_db_user");
89
    $config->define("nceas_db_password");
90
}
91 1929 brooke
$config->define("responseTemplate", { DEFAULT => 'crap.tmpl'} );
92
$config->define("entryFormTemplate", { DEFAULT => 'crap.tmpl'} );
93
$config->define("guideTemplate", { DEFAULT => 'crap.tmpl'} );
94
$config->define("confirmDataTemplate", { DEFAULT => 'crap.tmpl'} );
95
$config->define("deleteDataTemplate", { DEFAULT => 'crap.tmpl'} );
96 1955 jones
$config->define("debug", { DEFAULT => '0'} );
97 1929 brooke
$config->define("lat", { ARGCOUNT => ARGCOUNT_HASH} );
98
$config->define("lon", { ARGCOUNT => ARGCOUNT_HASH} );
99
100
if (! hasContent($FORM::cfg)) {
101
    $error = "Application misconfigured.  Please contact the administrator.";
102
    push(@errorMessages, $error);
103
} else {
104
    my $cfgfile = $cfgdir . "/" . $FORM::cfg . "/" . $FORM::cfg . ".cfg";
105
    $config->file($cfgfile);
106
}
107
108
my $metacatUrl = $config->metacatUrl();
109
my $username = $config->username();
110
my $password = $config->password();
111
my $ldapUrl = $config->ldapUrl();
112
my $defaultScope = $config->defaultScope();
113
my $organization = $config->organization();
114
my $orgabbrev = $config->orgabbrev();
115
my $orgurl = $config->orgurl();
116
my $orgfilter = $organization;
117 2138 sgarg
      $orgfilter =~ s/ /%20/g;
118 1929 brooke
my $responseTemplate = $config->responseTemplate();
119
my $entryFormTemplate = $config->entryFormTemplate();
120
my $deleteDataTemplate = $config->deleteDataTemplate();
121
my $guideTemplate = $config->guideTemplate();
122
my $confirmDataTemplate = $config->confirmDataTemplate();
123
my $accesspubid = $config->accesspubid();
124
my $accesssysid = $config->accesssysid();
125
my $datasetpubid = $config->datasetpubid();
126
my $datasetsysid = $config->datasetsysid();
127 2138 sgarg
my $hasKeyword = $config->hasKeyword();
128 2148 sgarg
my $hasTemporal = $config->hasTemporal();
129
my $hasSpatial = $config->hasSpatial();
130
my $hasTaxonomic = $config->hasTaxonomic();
131
my $hasMethod = $config->hasMethod();
132
my $temporalRequired = $config->temporalRequired();
133
my $spatialRequired = $config->spatialRequired();
134 1929 brooke
my $mailhost = $config->mailhost();
135
my $sender = $config->sender();
136
my $recipient = $config->recipient();
137
my $adminname = $config->adminname();
138 1973 jones
my $nceas_db;
139
my $nceas_db_user;
140
my $nceas_db_password;
141
if ($FORM::cfg eq 'nceas') {
142
    $nceas_db = $config->nceas_db();
143
    $nceas_db_user = $config->nceas_db_user();
144
    $nceas_db_password = $config->nceas_db_password();
145
}
146 1955 jones
my $debug = $config->debug();
147 1929 brooke
my $lat = $config->get('lat');
148
my $lon = $config->get('lon');
149
150
# Convert the lat and lon configs into usable data structures
151
my @sitelist;
152
my %siteLatDMS;
153
my %siteLongDMS;
154
foreach my $newsite (keys %$lat) {
155
    my ($latd, $latm, $lats, $latdir) = split(':', $lat->{$newsite});
156
    my ($lond, $lonm, $lons, $londir) = split(':', $lon->{$newsite});
157
    push(@sitelist, $newsite);
158
    $siteLatDMS{$newsite} = [ $latd, $latm, $lats, $latdir ];
159
    $siteLongDMS{$newsite} = [ $lond, $lonm, $lons, $londir ];
160
}
161
162
# set some configuration options for the template object
163
my $ttConfig = {
164
             INCLUDE_PATH => $templatesdir,
165
             INTERPOLATE  => 0,
166
             POST_CHOMP   => 1,
167
             };
168
169
# create an instance of the template processor
170
my $template = Template->new($ttConfig) || die $Template::ERROR, "\n";
171
172
print "Content-type: text/html\n\n";
173
174
# Set up the template information that is common to all forms
175
$$templateVars{'cfg'} = $FORM::cfg;
176
$$templateVars{'recipient'} = $recipient;
177
$$templateVars{'adminname'} = $adminname;
178
$$templateVars{'organization'} = $organization;
179
$$templateVars{'orgabbrev'} = $orgabbrev;
180
$$templateVars{'orgurl'} = $orgurl;
181
$$templateVars{'orgfilter'} = $orgfilter;
182
183 1983 jones
debug("Registry: Initialized");
184 1929 brooke
# Process the form based on stage parameter.
185
if ($FORM::stage =~ "guide") {
186
    # Send back the information on how to fill the form
187
    $$templateVars{'section'} = "Guide on How to Complete Registry Entries";
188
    $template->process( $guideTemplate, $templateVars);
189
    exit(0);
190
191
} elsif ($FORM::stage =~ "insert") {
192
    # The user has entered the data. Do data validation and send back data
193
    # to confirm the data that has been entered.
194
    toConfirmData();
195
    exit(0);
196
197 2015 sgarg
}elsif ($FORM::dataWrong =~ "No, go back to editing" && $FORM::stage =~ "confirmed") {
198 1929 brooke
    # The user wants to correct the data that he has entered.
199
    # Hence show the data again in entryData form.
200
    confirmDataToReEntryData();
201
    exit(0);
202
203
}elsif ($FORM::stage =~ "modify") {
204
    # Modification of a file has been requested.
205
    # Show the form will all the values filled in.
206
    my @sortedSites;
207
    foreach my $site (sort @sitelist) {
208
        push(@sortedSites, $site);
209
    }
210
    $$templateVars{'siteList'} = \@sortedSites;
211
    $$templateVars{'section'} = "Modification Form";
212
    $$templateVars{'docid'} = $FORM::docid;
213
    modifyData();
214
    exit(0);
215
216
}elsif ($FORM::stage =~ "delete_confirm") {
217
218
    # Result from deleteData form.
219
    if($FORM::deleteData =~ "Delete data"){
220 1977 jones
    # delete Data
221
    deleteData(1);
222
    exit(0);
223 1929 brooke
    } else {
224 1977 jones
    # go back to search page.
225
    exit(0);
226 1929 brooke
    }
227
228
}elsif ($FORM::stage =~ "delete") {
229
    # Deletion of a file has been requested.
230
    # Ask for username and password using deleteDataForm
231
    $$templateVars{'docid'} = $FORM::docid;
232
    $template->process( $deleteDataTemplate, $templateVars);
233
    exit(0);
234
235
}elsif ($FORM::stage !~ "confirmed") {
236
    # None of the stages have been reached and data is not being confirmed.
237
    # Hence, send back entry form for entry of data.
238 1983 jones
    debug("Registry: Sending form");
239 1929 brooke
    my @sortedSites;
240
    foreach my $site (sort @sitelist) {
241
        push(@sortedSites, $site);
242
    }
243 1973 jones
244
    if ($FORM::cfg eq 'nceas') {
245
        my $projects = getProjectList();
246 1974 jones
        $$templateVars{'projects'} = $projects;
247
        $$templateVars{'wg'} = \@FORM::wg;
248 1973 jones
    }
249 1974 jones
250 2138 sgarg
    $$templateVars{'hasKeyword'} = $hasKeyword;
251 2148 sgarg
    $$templateVars{'hasTemporal'} = $hasTemporal;
252
    $$templateVars{'hasSpatial'} = $hasSpatial;
253
    $$templateVars{'hasTaxonomic'} = $hasTaxonomic;
254
    $$templateVars{'hasMethod'} = $hasMethod;
255
    $$templateVars{'temporalRequired'} = $temporalRequired;
256
    $$templateVars{'spatialRequired'} = $spatialRequired;
257 2138 sgarg
258 1929 brooke
    $$templateVars{'siteList'} = \@sortedSites;
259
    $$templateVars{'section'} = "Entry Form";
260
    $$templateVars{'docid'} = "";
261 1983 jones
    debug("Registry: Sending form: ready to process template");
262 1929 brooke
    $template->process( $entryFormTemplate, $templateVars);
263 1983 jones
    debug("Registry: Sending form: template processed");
264 1929 brooke
    exit(0);
265
}
266
267
# Confirm stage has been reached. Enter the data into metacat.
268
269
# Initialize some global vars
270
my $latDeg1 = "";
271
my $latMin1 = "";
272
my $latSec1 = "";
273
my $hemisphLat1 = "";
274
my $longDeg1 = "";
275
my $longMin1 = "";
276
my $longSec1 = "";
277
my $hemisphLong1 = "";
278
my $latDeg2 = "";
279
my $latMin2 = "";
280
my $latSec2 = "";
281
my $hemisphLat2 = "";
282
my $longDeg2 = "";
283
my $longMin2 = "";
284
my $longSec2 = "";
285
my $hemisphLong2 = "";
286
287
# validate the input form parameters
288
my $invalidParams;
289
290
if (! $error) {
291
    $invalidParams = validateParameters(1);
292
    if (scalar(@$invalidParams)) {
293
        $$templateVars{'status'} = 'failure';
294
        $$templateVars{'invalidParams'} = $invalidParams;
295
        $error = 1;
296
    }
297
}
298
299
300
my $metacat;
301
my $docid;
302
if (! $error) {
303
    # Parameters have been validated and Create the XML document
304
305
    my $xmldoc = createXMLDocument();
306
307
    # Write out the XML file for debugging purposes
308
    #my $testFile = $tmpdir . "/test.xml";
309
310
    # Create a  metacat object
311
    $metacat = Metacat->new();
312
    if ($metacat) {
313
        $metacat->set_options( metacatUrl => $metacatUrl );
314
    } else {
315
        #die "failed during metacat creation\n";
316
        push(@errorMessages, "Failed during metacat creation.");
317
    }
318
319
    # Login to metacat
320
    my $userDN = $FORM::username;
321
    my $userOrg = $FORM::organization;
322
    my $userPass = $FORM::password;
323
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
324
325 2057 sgarg
    my $xmldocWithDocID = $xmldoc;
326
327 1929 brooke
    my $errorMessage = "";
328
    my $response = $metacat->login($dname, $userPass);
329
    if (! $response) {
330
        push(@errorMessages, $metacat->getMessage());
331
        push(@errorMessages, "Failed during login.\n");
332
    }
333
334 1982 jones
    debug( "Registry: A");
335 1955 jones
    if ($FORM::docid eq "") {
336
        debug( "Registry: B1");
337 1977 jones
        # document is being inserted
338
        my $notunique = "NOT_UNIQUE";
339
        while ($notunique eq "NOT_UNIQUE") {
340
            $docid = newAccessionNumber($defaultScope);
341
342 2057 sgarg
	    $xmldocWithDocID = $xmldoc;
343
            $xmldocWithDocID =~ s/docid/$docid/;
344
345 2138 sgarg
	    # Code for testing the xml file being inserted####
346 1992 jones
            #my $testFile = "/tmp/test.xml";
347
            #open (TFILE,">$testFile") || die ("Cant open xml file...\n");
348
            #print TFILE $xmldoc;
349
            #close(TFILE);
350 2138 sgarg
	    ####
351 1929 brooke
352 2057 sgarg
            $notunique = insertMetadata($xmldocWithDocID, $docid);
353 1977 jones
            #  if (!$notunique) {
354
            # Write out the XML file for debugging purposes
355
            #my $testFile = $tmpdir . "/test-new.xml";
356
            #open (TFILE,">$testFile") || die ("Cant open xml file...\n");
357
            #print TFILE $newdoc;
358
            #close(TFILE);
359
            #   }
360 1955 jones
361
            # The id wasn't unique, so update our lastid file
362 1977 jones
            if ($notunique eq "NOT_UNIQUE") {
363 1989 jones
                debug( "Registry: Updating lastid (B1.1)");
364 1955 jones
                updateLastId($defaultScope);
365
            }
366 1977 jones
        }
367 1955 jones
        debug("Registry: B2");
368 1977 jones
        if ($notunique ne "SUCCESS") {
369 1955 jones
            debug("Registry: NO SUCCESS");
370
            debug("Message is: $notunique");
371 1929 brooke
            push(@errorMessages, $notunique);
372 1977 jones
        }
373 2056 sgarg
374 1955 jones
        debug("Registry: B3");
375 1929 brooke
    } else {
376 1977 jones
        # document is being modified
377
        $docid = $FORM::docid;
378
379
        my $x;
380
        my $y;
381
        my $z;
382 1929 brooke
383 1977 jones
        ($x, $y, $z) = split(/\./, $docid);
384
        $z++;
385
        $docid = "$x.$y.$z";
386
387
        $xmldoc =~ s/docid/$docid/;
388 1929 brooke
389 1977 jones
        my $response = $metacat->update($docid, $xmldoc);
390 1929 brooke
391 1977 jones
        if (! $response) {
392
            push(@errorMessages, $metacat->getMessage());
393
            push(@errorMessages, "Failed while updating.\n");
394
        }
395 1929 brooke
396 1977 jones
        if (scalar(@errorMessages)) {
397 1955 jones
            debug("Registry: ErrorMessages defined in modify.");
398 2024 sgarg
399
	    $$templateVars{'docid'} = $FORM::docid;
400 2136 sgarg
	    copyFormToTemplateVars();
401 1977 jones
            $$templateVars{'status'} = 'failure';
402
            $$templateVars{'errorMessages'} = \@errorMessages;
403
            $error = 1;
404 2136 sgarg
        } else {
405
	    $$templateVars{'docid'} = $docid;
406
	    $$templateVars{'cfg'} = $FORM::cfg;
407
	}
408 1929 brooke
409 1955 jones
        #if (! $error) {
410
            #sendNotification($docid, $mailhost, $sender, $recipient);
411
        #}
412 1977 jones
413 1929 brooke
        # Create our HTML response and send it back
414 1977 jones
        $$templateVars{'function'} = "modified";
415
        $$templateVars{'section'} = "Modification Status";
416
        $template->process( $responseTemplate, $templateVars);
417 1929 brooke
418 1977 jones
        exit(0);
419 1929 brooke
    }
420
}
421
422 1955 jones
debug("Registry: C");
423 1929 brooke
424
if (scalar(@errorMessages)) {
425 1955 jones
    debug("Registry: ErrorMessages defined.");
426 2024 sgarg
    $$templateVars{'docid'} = $FORM::docid;
427 2136 sgarg
    copyFormToTemplateVars();
428 1929 brooke
    $$templateVars{'status'} = 'failure';
429
    $$templateVars{'errorMessages'} = \@errorMessages;
430
    $error = 1;
431 2056 sgarg
} else {
432
    $$templateVars{'docid'} = $docid;
433
    $$templateVars{'cfg'} = $FORM::cfg;
434 1929 brooke
}
435
436 1936 jones
#if (! $error) {
437
#sendNotification($docid, $mailhost, $sender, $recipient);
438
#}
439 1929 brooke
440
# Create our HTML response and send it back
441
$$templateVars{'function'} = "submitted";
442
$$templateVars{'section'} = "Submission Status";
443 2056 sgarg
444 1929 brooke
$template->process( $responseTemplate, $templateVars);
445
446
exit(0);
447
448
449
################################################################################
450
#
451 1955 jones
# Subroutine for updating a metacat id for a given scope to the highest value
452
#
453
################################################################################
454
sub updateLastId {
455
  my $scope = shift;
456
457
  my $errormsg = 0;
458
  my $docid = $metacat->getLastId($scope);
459
460
  if ($docid =~ /null/) {
461
      # No docids with this scope present, so do nothing
462
  } elsif ($docid) {
463
      # Update the lastid file for this scope
464
      (my $foundScope, my $id, my $rev) = split(/\./, $docid);
465
      debug("Docid is: $docid\n");
466
      debug("Lastid is: $id");
467
      my $scopeFile = $cfgdir . "/" . $FORM::cfg . "/" . $scope . ".lastid";
468
      open(LASTID, ">$scopeFile") or
469
          die "Failed to open lastid file for writing!";
470
      print LASTID $id, "\n";
471
      close(LASTID);
472
  } else {
473
    $errormsg = $metacat->getMessage();
474
    debug("Error in getLastId: $errormsg");
475
  }
476
}
477
478
################################################################################
479
#
480 1929 brooke
# Subroutine for inserting a document to metacat
481
#
482
################################################################################
483
sub insertMetadata {
484
  my $xmldoc = shift;
485
  my $docid = shift;
486
487
  my $notunique = "SUCCESS";
488 1989 jones
  debug("Registry: Starting insert (D1)");
489 1929 brooke
  my $response = $metacat->insert($docid, $xmldoc);
490
  if (! $response) {
491 1989 jones
    debug("Registry: Response gotten (D2)");
492 1929 brooke
    my $errormsg = $metacat->getMessage();
493 1989 jones
    debug("Registry: Error is (D3): ".$errormsg);
494 1929 brooke
    if ($errormsg =~ /is already in use/) {
495
      $notunique = "NOT_UNIQUE";
496
      #print "Accession number already used: $docid\n";
497
    } elsif ($errormsg =~ /<login>/) {
498
      $notunique = "SUCCESS";
499
    } else {
500
      #print "<p>Dumping error on failure...</p>\n";
501
      #print "<p>", $errormsg, "</p>\n";
502
      #die "Failed during insert\n";
503
      #print "<p>Failed during insert</p>\n";
504
      $notunique = $errormsg;
505
    }
506
  }
507 1989 jones
  debug("Registry: Ending insert (D4)");
508 1929 brooke
509
  return $notunique;
510
}
511
512
################################################################################
513
#
514
# Subroutine for generating a new accession number
515
#  Note: this is not threadsafe, assumes only one running process at a time
516
#  Also: need to check metacat for max id # used in this scope already
517
################################################################################
518
sub newAccessionNumber {
519
  my $scope = shift;
520
521
  my $docrev = 1;
522
  my $lastid = 1;
523
524
  my $scopeFile = $cfgdir . "/" . $FORM::cfg . "/" . $scope . ".lastid";
525
  if (-e $scopeFile) {
526
    open(LASTID, "<$scopeFile") or die "Failed to generate accession number!";
527
    $lastid = <LASTID>;
528
    chomp($lastid);
529
    $lastid++;
530
    close(LASTID);
531
  }
532
  open(LASTID, ">$scopeFile") or die "Failed to open lastid file for writing!";
533
  print LASTID $lastid, "\n";
534
  close(LASTID);
535
536
  my $docroot = "$scope.$lastid.";
537
  my $docid = $docroot . $docrev;
538
  return $docid;
539
}
540
541
################################################################################
542
#
543
# Validate the parameters to make sure that required params are provided
544
#
545
################################################################################
546
sub validateParameters {
547
    my $chkUser = shift;
548
    my @invalidParams;
549
550
    push(@invalidParams, "Provider's first name is missing.")
551
        unless hasContent($FORM::providerGivenName);
552
    push(@invalidParams, "Provider's last name is missing.")
553
        unless hasContent($FORM::providerSurName);
554
    push(@invalidParams, "Name of site is missing.")
555 1974 jones
        unless (hasContent($FORM::site) || $FORM::site =~ /elect/ ||
556
                $FORM::cfg eq "nceas");
557 1929 brooke
    push(@invalidParams, "Data set title is missing.")
558
        unless hasContent($FORM::title);
559
    push(@invalidParams, "Originator's first name is missing.")
560
        unless hasContent($FORM::origNamefirst0);
561
    push(@invalidParams, "Originator's last name is missing.")
562
        unless hasContent($FORM::origNamelast0);
563
    push(@invalidParams, "Abstract is missing.")
564
        unless hasContent($FORM::abstract);
565 2149 sgarg
    if($FORM::hasTemporal eq 'true'){
566
	push(@invalidParams, "Beginning year of data set is missing.")
567
	    unless (hasContent($FORM::beginningYear) || $FORM::temporalRequired ne 'true');
568
	push(@invalidParams, "Ending year has been specified but beginning year of data set is missing.")
569
	    if ((!hasContent($FORM::beginningYear)) && hasContent($FORM::endingYear));
570
    }
571 1983 jones
    push(@invalidParams, "Geographic description is missing.")
572 2148 sgarg
        unless (hasContent($FORM::geogdesc) || $FORM::spatialRequired ne 'true');
573 1929 brooke
574 2149 sgarg
    if($FORM::beginningMonth eq "00"){
575
	if (hasContent($FORM::beginningYear)){
576
	    $FORM::beginningMonth = "01";
577
	} else {
578
	    $FORM::beginningMonth = "";
579
	}
580
    }
581
    if($FORM::beginningDay eq "00"){
582
	if (hasContent($FORM::beginningYear)){
583
	    $FORM::beginningDay = "01";
584
	} else {
585
	    $FORM::beginningDay = "";
586
	}
587
    }
588
    if($FORM::endingMonth eq "00"){
589
	if (hasContent($FORM::endingYear)){
590
	    $FORM::endingMonth = "01";
591
	} else {
592
	    $FORM::endingMonth = "";
593
	}
594
    }
595
    if($FORM::endingDay eq "00"){
596
	if (hasContent($FORM::endingYear)){
597
	    $FORM::endingDay = "01";
598
	} else {
599
	    $FORM::endingDay = "";
600
	}
601
    }
602
603 1929 brooke
    # If the "use site" coord. box is checked and if the site is in
604
    # the longitude hash ...  && ($siteLatDMS{$FORM::site})
605 2149 sgarg
606 2148 sgarg
    if($FORM::hasSpatial eq 'true'){
607
	if (($FORM::useSiteCoord) && ($siteLatDMS{$FORM::site}) ) {
608 1929 brooke
609 2148 sgarg
	    $latDeg1 = $siteLatDMS{$FORM::site}[0];
610
	    $latMin1 = $siteLatDMS{$FORM::site}[1];
611
	    $latSec1 = $siteLatDMS{$FORM::site}[2];
612
	    $hemisphLat1 = $siteLatDMS{$FORM::site}[3];
613
	    $longDeg1 = $siteLongDMS{$FORM::site}[0];
614
	    $longMin1 = $siteLongDMS{$FORM::site}[1];
615
	    $longSec1 = $siteLongDMS{$FORM::site}[2];
616
	    $hemisphLong1 = $siteLongDMS{$FORM::site}[3];
617
618
	}  else {
619
620
	    $latDeg1 = $FORM::latDeg1;
621
	    $latMin1 = $FORM::latMin1;
622
	    $latSec1 = $FORM::latSec1;
623
	    $hemisphLat1 = $FORM::hemisphLat1;
624
	    $longDeg1 = $FORM::longDeg1;
625
	    $longMin1 = $FORM::longMin1;
626
	    $longSec1 = $FORM::longSec1;
627
	    $hemisphLong1 = $FORM::hemisphLong1;
628
	}
629 1929 brooke
    }
630
631
    # Check if latDeg1 and longDeg1 has values if useSiteCoord is used.
632
    # This check is required because some of the sites dont have lat
633
    # and long mentioned in the config file.
634
635 2148 sgarg
636
    if($FORM::hasSpatial eq 'true'){
637
	if ($FORM::useSiteCoord ) {
638
	    push(@invalidParams, "The Data Registry doesn't have latitude and longitude information for the site that you chose. Please go back and enter the spatial information.")
639
		unless(hasContent($latDeg1) && hasContent($longDeg1));
640
	}else{
641
	    push(@invalidParams, "Latitude degrees are missing.")
642 2149 sgarg
		unless (hasContent($latDeg1) || $FORM::spatialRequired ne 'true');
643 2148 sgarg
	    push(@invalidParams, "Longitude degrees are missing.")
644 2149 sgarg
		unless (hasContent($longDeg1) || $FORM::spatialRequired ne 'true');
645 2148 sgarg
	}
646 2149 sgarg
	push(@invalidParams,
647
	     "You must provide a geographic description if you provide latitude and longitude information.")
648
	    if ((hasContent($latDeg1) || (hasContent($longDeg1))) && (!hasContent($FORM::geogdesc)));
649 1929 brooke
    }
650
651 2148 sgarg
    if($FORM::hasMethod eq 'true'){
652
	push(@invalidParams,
653
	     "You must provide a method description if you provide a method title.")
654
	    if (hasContent($FORM::methodTitle) && ( !(scalar(@FORM::methodPara) > 0)
655
						    || (! hasContent($FORM::methodPara[0]))));
656
	push(@invalidParams,
657
	     "You must provide a method description if you provide a study extent description.")
658
	    if (hasContent($FORM::studyExtentDescription) && (!(scalar(@FORM::methodPara) > 0)
659
							      || (! hasContent($FORM::methodPara[0]))));
660
	push(@invalidParams,
661
	     "You must provide both a study extent description and a sampling description, or neither.")
662
	    if (
663 1997 jones
                (hasContent($FORM::studyExtentDescription) && !hasContent($FORM::samplingDescription)) ||
664
                (!hasContent($FORM::studyExtentDescription) && hasContent($FORM::samplingDescription))
665 2148 sgarg
		);
666
    }
667 1989 jones
668 1929 brooke
    push(@invalidParams, "Contact first name is missing.")
669 1977 jones
    unless (hasContent($FORM::origNamefirstContact) ||
670
        $FORM::useOrigAddress);
671 1929 brooke
    push(@invalidParams, "Contact last name is missing.")
672 1977 jones
    unless (hasContent($FORM::origNamelastContact) ||
673
        $FORM::useOrigAddress);
674 1929 brooke
    push(@invalidParams, "Data medium is missing.")
675 1977 jones
    unless (hasContent($FORM::dataMedium) || $FORM::dataMedium =~ /elect/);
676 1929 brooke
677
    return \@invalidParams;
678
}
679
680
################################################################################
681
#
682
# utility function to determine if a paramter is defined and not an empty string
683
#
684
################################################################################
685
sub hasContent {
686
    my $param = shift;
687
688
    my $paramHasContent;
689
    if (!defined($param) || $param eq '') {
690
        $paramHasContent = 0;
691
    } else {
692
        $paramHasContent = 1;
693
    }
694
    return $paramHasContent;
695
}
696
697 2032 sgarg
################################################################################
698
#
699
# Subroutine for replacing characters not recognizable by XML and otherwise.
700
#
701
################################################################################
702
sub normalize{
703
    my $val = shift;
704 1929 brooke
705 2032 sgarg
    $val =~ s/&/&amp;/g;
706
707
    $val =~ s/</&lt;/g;
708
    $val =~ s/>/&gt;/g;
709
    $val =~ s/\"/&quot;/g;
710
711
    my $returnVal = "";
712
713
    foreach (split(//,$val)){
714
	my $var = unpack "C*", $_;
715
716
	if($var<128 && $var>31){
717
	    $returnVal=$returnVal.$_;
718
	} elsif ($var<32){
719
	    if($var == 10){
720
		$returnVal=$returnVal.$_;
721
	    }
722
	    if($var == 13){
723
		$returnVal=$returnVal.$_;
724
	    }
725
	    if($var == 9){
726
		$returnVal=$returnVal.$_;
727
	    }
728
	} else {
729
	    $returnVal=$returnVal."&#".$var.";";
730
	}
731
    }
732
733
    $returnVal =~ s/&/%26/g;
734
    return $returnVal;
735
}
736
737 2037 sgarg
738 1929 brooke
################################################################################
739 2037 sgarg
#
740
# Subroutine for replacing characters that might create problem in HTML.
741
# Specifically written for " being used in any text field. This create a
742
# problem in confirmData template, when you specify input name value pair
743
# with value having a " in it.
744
#
745
################################################################################
746
sub normalizeCD{
747
    my $val = shift;
748
749
    $val =~ s/\"/&quot;/g;
750
751
    return $val;
752
}
753
754
755
################################################################################
756 1929 brooke
#
757
# Create the XML document from the HTML form input
758
# returns the XML document as a string
759
#
760
################################################################################
761
sub createXMLDocument {
762
763
    my $orig  = "";
764
    my $role  = "associatedParty";
765
    my $creat = "";
766
    my $metaP = "";
767
    my $apart = "";
768
    my $cont  = "";
769
    my $publ  = "";
770
    my $dso   = "";
771
    my $gmt = gmtime($now);
772 2032 sgarg
773
774 1929 brooke
    my $doc =  "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
775
776 2032 sgarg
    $doc .= "<eml:eml\n
777 1929 brooke
                     \t packageId=\"docid\" system=\"knb\"\n
778
                     \t xmlns:eml=\"eml://ecoinformatics.org/eml-2.0.0\"\n
779
                     \t xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n
780
                     \t xmlns:ds=\"eml://ecoinformatics.org/dataset-2.0.0\"\n
781
                     \t xmlns:stmml=\"http://www.xml-cml.org/schema/stmml\"\n
782
                     \t xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.0.0 eml.xsd\">\n";
783
784
    $doc .= "<!-- Person who filled in the catalog entry form: ";
785 2032 sgarg
    $doc .= normalize($FORM::providerGivenName)." ".normalize($FORM::providerSurName)." -->\n";
786 1929 brooke
    $doc .= "<!-- Form filled out at $gmt GMT -->\n";
787
    $doc .= "<dataset>\n";
788
789
    if (hasContent($FORM::identifier)) {
790
        $doc .= "<alternateIdentifier system=\"$FORM::site\">";
791 2032 sgarg
        $doc .= normalize($FORM::identifier) . "</alternateIdentifier>\n";
792 1929 brooke
    }
793
794
    if (hasContent($FORM::title)) {
795 2032 sgarg
        $doc .= "<title>".normalize($FORM::title)."</title>\n";
796 1929 brooke
    }
797
798
    if (hasContent($FORM::origNamelast0)) {
799 1977 jones
    $role = "creator";
800 1929 brooke
        $orig .= "<individualName>\n";
801 2032 sgarg
        $orig .= "<givenName>".normalize($FORM::origNamefirst0)."</givenName>\n";
802
        $orig .= "<surName>".normalize($FORM::origNamelast0)."</surName>\n";
803 1929 brooke
        $orig .= "</individualName>\n";
804
    }
805
806
    if (hasContent($FORM::origNameOrg)) {
807 2032 sgarg
        $orig .= "<organizationName>".normalize($FORM::origNameOrg)."</organizationName>\n";
808 1929 brooke
    }
809
810
    if (hasContent($FORM::origDelivery) || hasContent($FORM::origCity) ||
811
        (hasContent($FORM::origState   ) &&
812
        ($FORM::origState !~ "Select state here.")) ||
813
        hasContent($FORM::origStateOther) ||
814
        hasContent($FORM::origZIP ) || hasContent($FORM::origCountry)) {
815
        $orig .= "<address>\n";
816
817
        if (hasContent($FORM::origDelivery)) {
818 2032 sgarg
            $orig .= "<deliveryPoint>".normalize($FORM::origDelivery)."</deliveryPoint>\n";
819 1929 brooke
        }
820
        if (hasContent($FORM::origCity)) {
821 2032 sgarg
            $orig .= "<city>".normalize($FORM::origCity)."</city>\n";
822 1929 brooke
        }
823
824 1977 jones
    if (hasContent($FORM::origState) &&
825 1929 brooke
            ($FORM::origState !~ "Select state here.")) {
826 2032 sgarg
            $orig .= "<administrativeArea>".normalize($FORM::origState);
827 1929 brooke
            $orig .= "</administrativeArea>\n";
828
        } elsif (hasContent($FORM::origStateOther)) {
829 2032 sgarg
            $orig .= "<administrativeArea>".normalize($FORM::origStateOther);
830 1929 brooke
            $orig .= "</administrativeArea>\n";
831
        }
832
        if (hasContent($FORM::origZIP)) {
833 2032 sgarg
            $orig .= "<postalCode>".normalize($FORM::origZIP)."</postalCode>\n";
834 1929 brooke
        }
835
        if (hasContent($FORM::origCountry)) {
836 2032 sgarg
            $orig .= "<country>".normalize($FORM::origCountry)."</country>\n";
837 1929 brooke
        }
838
        $orig .= "</address>\n";
839
    }
840
841
    if (hasContent($FORM::origPhone)) {
842 2032 sgarg
        $orig .= "<phone>".normalize($FORM::origPhone)."</phone>\n";
843 1929 brooke
    }
844
    if (hasContent($FORM::origFAX)) {
845 2032 sgarg
        $orig .= "<phone phonetype=\"Fax\">".normalize($FORM::origFAX)."</phone>\n";
846 1929 brooke
    }
847
    if (hasContent($FORM::origEmail)) {
848 2032 sgarg
        $orig .= "<electronicMailAddress>".normalize($FORM::origEmail);
849 1929 brooke
        $orig .= "</electronicMailAddress>\n";
850
    }
851
    $dso = "<$role>\n$orig</$role>\n";
852
853 2049 sgarg
    if ($FORM::cfg eq 'nceas') {
854
        for (my $i = 0; $i < scalar(@FORM::wg); $i++) {
855
            $creat .= "<creator>\n";
856
            $creat .= "<organizationName>".normalize($FORM::wg[$i])."</organizationName>\n";
857
            $creat .= "</creator>\n";
858
        }
859
    } else {
860
	    $creat .= "<creator>\n";
861
	    $creat .= "<organizationName>".normalize($FORM::site)."</organizationName>\n";
862
	    $creat .= "</creator>\n";
863
    }
864
865
    if ($FORM::cfg ne 'knb') {
866
        $creat .= "<creator>\n";
867
        $creat .= "<organizationName>".normalize($organization)."</organizationName>\n";
868
        $creat .= "</creator>\n";
869
    }
870
871 1929 brooke
    $creat .= $dso;
872
873
    if ($FORM::useOrigAddress) {
874
        # Add a contact originator like the original with a different role
875
            $cont .= "<contact>\n";
876 1977 jones
        $cont .= $orig;
877
        $cont .= "</contact>\n";
878 1929 brooke
    } else {
879
        $cont .= "<contact>\n";
880
881
        $cont .= "<individualName>\n";
882 2032 sgarg
        $cont .= "<givenName>".normalize($FORM::origNamefirstContact)."</givenName>\n";
883
        $cont .= "<surName>".normalize($FORM::origNamelastContact)."</surName>\n";
884 1929 brooke
        $cont .= "</individualName>\n";
885
886 1977 jones
    if (hasContent($FORM::origNameOrgContact)) {
887 2032 sgarg
        $cont .= "<organizationName>".normalize($FORM::origNameOrgContact)."</organizationName>\n";
888 1977 jones
    }
889 1929 brooke
890
        if (hasContent($FORM::origDeliveryContact) ||
891
            hasContent($FORM::origCityContact) ||
892
            (hasContent($FORM::origStateContact) &&
893
            ($FORM::origStateContact !~ "Select state here.")) ||
894
            hasContent($FORM::origStateOtherContact) ||
895
            hasContent($FORM::origZIPContact) ||
896
            hasContent($FORM::origCountryContact)) {
897
            $cont .= "<address>\n";
898
            if (hasContent($FORM::origDeliveryContact)) {
899 2032 sgarg
                $cont .= "<deliveryPoint>".normalize($FORM::origDeliveryContact);
900 1929 brooke
                $cont .= "</deliveryPoint>\n";
901
            }
902
            if (hasContent($FORM::origCityContact)) {
903 2032 sgarg
                $cont .= "<city>".normalize($FORM::origCityContact)."</city>\n";
904 1929 brooke
            }
905
            if (hasContent($FORM::origStateContact) &&
906
                ($FORM::origStateContact !~ "Select state here.")) {
907 2032 sgarg
                $cont .= "<administrativeArea>".normalize($FORM::origStateContact);
908 1929 brooke
                $cont .= "</administrativeArea>\n";
909
            } elsif (hasContent($FORM::origStateOtherContact)) {
910 2032 sgarg
                $cont .= "<administrativeArea>".normalize($FORM::origStateOtherContact);
911 1929 brooke
                $cont .= "</administrativeArea>\n";
912
            }
913
            if (hasContent($FORM::origZIPContact)) {
914 2032 sgarg
                $cont .= "<postalCode>".normalize($FORM::origZIPContact)."</postalCode>\n";
915 1929 brooke
            }
916
            if (hasContent($FORM::origCountryContact)) {
917 2032 sgarg
                $cont .= "<country>".normalize($FORM::origCountryContact)."</country>\n";
918 1929 brooke
            }
919
            $cont .= "</address>\n";
920
        }
921
        if (hasContent($FORM::origPhoneContact)) {
922 2032 sgarg
            $cont .= "<phone>".normalize($FORM::origPhoneContact)."</phone>\n";
923 1929 brooke
        }
924 1977 jones
    if (hasContent($FORM::origFAXContact)) {
925 2032 sgarg
        $cont .= "<phone phonetype=\"Fax\">".normalize($FORM::origFAXContact)."</phone>\n";
926 1977 jones
    }
927 1929 brooke
        if (hasContent($FORM::origEmailContact)) {
928 2032 sgarg
            $cont .= "<electronicMailAddress>".normalize($FORM::origEmailContact);
929 1929 brooke
            $cont .= "</electronicMailAddress>\n";
930
        }
931 1977 jones
    $cont .= "</contact>\n";
932 1929 brooke
    }
933
934
    $metaP .= "<metadataProvider>\n";
935
    $metaP .= "<individualName>\n";
936 2032 sgarg
    $metaP .= "<givenName>".normalize($FORM::providerGivenName)."</givenName>\n";
937
    $metaP .= "<surName>".normalize($FORM::providerSurName)."</surName>\n";
938 1929 brooke
    $metaP .= "</individualName>\n";
939
    $metaP .= "</metadataProvider>\n";
940
941
    # Additional originators
942
    foreach my $tmp (param()) {
943
        if ($tmp =~ /origNamelast/){
944
            my $tmp1 = $tmp;
945
            $tmp1 =~ s/origNamelast//; # get the index of the parameter 0 to 10
946
            if ( $tmp1 eq '1'
947
                 || $tmp1 eq '2'
948
                 || $tmp1 eq '3'
949
                 || $tmp1 eq '4'
950
                 || $tmp1 eq '5'
951
                 || $tmp1 eq '6'
952
                 || $tmp1 eq '7'
953
                 || $tmp1 eq '8'
954
                 || $tmp1 eq '9'
955
                 || $tmp1 eq '10'
956
                 ) {
957
958
                # do not generate XML for empty originator fields
959
                if (hasContent(param("origNamefirst" . $tmp1))) {
960
961 1977 jones
            my $add = "";
962
            $add .= "<individualName>\n";
963
            $add .= "<givenName>";
964 2032 sgarg
            $add .= normalize(param("origNamefirst" . $tmp1));
965 1977 jones
            $add .= "</givenName>\n";
966
            $add .= "<surName>";
967 2032 sgarg
            $add .= normalize(param("origNamelast" . $tmp1));
968 1977 jones
            $add .= "</surName>\n";
969
            $add .= "</individualName>\n";
970
971
            if(param("origRole" . $tmp1) eq "Originator"){
972
            $creat .= "<creator>\n";
973
            $creat .= $add;
974
            $creat .= "</creator>\n";
975 1929 brooke
            }
976 1977 jones
            elsif(param("origRole" . $tmp1) eq "Metadata Provider"){
977
            $metaP .= "<metadataProvider>\n";
978
            $metaP .= $add;
979
            $metaP .= "</metadataProvider>\n";
980
            }
981
            elsif((param("origRole" . $tmp1) eq "Publisher")  && ($publ eq "")){
982
            $publ .= "<publisher>\n";
983
            $publ .= $add;
984
            $publ .= "</publisher>\n";
985
            }
986
            else{
987
            $apart .= "<associatedParty>\n";
988
            $apart .= $add;
989
            $apart .= "<role>";
990
            $apart .= param("origRole" . $tmp1);
991
            $apart .= "</role>\n";
992
            $apart .= "</associatedParty>\n";
993
            }
994 1929 brooke
        }
995 1977 jones
            }
996
        }
997 1929 brooke
    }
998
999
    $doc .= $creat;
1000
    $doc .= $metaP;
1001
    $doc .= $apart;
1002
1003
    $doc .= "<abstract>\n";
1004 2032 sgarg
    $doc .= "<para>".normalize($FORM::abstract)."</para>\n";
1005 1929 brooke
    $doc .= "</abstract>\n";
1006
1007
    # Keyword information
1008
    foreach my $tmp (param()) {
1009
        if ($tmp =~ /keyword/) {
1010
            my $tmp1 = $tmp;
1011
            $tmp1 =~ s/keyword//; # get the index of the parameter 0, ..., 10
1012
            if ( $tmp1 =~ /[0-9]/ ){
1013
                # don't generate xml for empty keyword fields
1014
                # don't generate taxonomic keyword fields, those go in taxonomic coverage
1015
                if (hasContent(param($tmp))) {
1016
                    $doc .= "<keywordSet>\n";
1017
                    $doc .= "<keyword ";
1018
                    if (hasContent(param("kwType" . $tmp1)) &&
1019
                       (param("kwType" . $tmp1) !~ "none") ) {
1020
                         $doc .= "keywordType=\"";
1021
                         $doc .= param("kwType" . $tmp1);
1022
                         $doc .= "\"";
1023
                    }
1024
                    $doc .= ">";
1025 2032 sgarg
                    $doc .= normalize(param("keyword" . $tmp1));
1026 1929 brooke
                    $doc .= "</keyword>\n";
1027
                    $doc .= "<keywordThesaurus>";
1028 2032 sgarg
                    $doc .= normalize(param("kwTh" . $tmp1));
1029 1929 brooke
                    $doc .= "</keywordThesaurus>\n";
1030
                    $doc .= "</keywordSet>\n";
1031
                }
1032
            }
1033
        }
1034
    }
1035
1036
    if (hasContent($FORM::addComments)) {
1037
        $doc .= "<additionalInfo>\n";
1038 2032 sgarg
        $doc .= "<para>".normalize($FORM::addComments)."</para>\n";
1039 1929 brooke
        $doc .= "</additionalInfo>\n";
1040
    }
1041
1042
    if (hasContent($FORM::useConstraints) ||
1043
        hasContent($FORM::useConstraintsOther)) {
1044
        $doc .= "<intellectualRights>\n";
1045
        if (hasContent($FORM::useConstraints)) {
1046 2032 sgarg
            $doc .= "<para>".normalize($FORM::useConstraints)."</para>\n";
1047 1929 brooke
        }
1048
        if (hasContent($FORM::useConstraintsOther)) {
1049 2032 sgarg
            $doc .= "<para>".normalize($FORM::useConstraintsOther)."</para>\n";
1050 1929 brooke
        }
1051
        $doc .= "</intellectualRights>\n";
1052
    }
1053
1054
1055
    if (hasContent($FORM::url)) {
1056 1977 jones
    $doc .= "<distribution>\n";
1057 1929 brooke
        $doc .= "<online>\n";
1058 2032 sgarg
    $doc .= "<url>".normalize($FORM::url)."</url>\n";
1059 1977 jones
    $doc .= "</online>\n";
1060
    $doc .= "</distribution>\n";
1061 1929 brooke
    }
1062
1063
    $doc .= "<distribution>\n";
1064
    $doc .= "<offline>\n";
1065 2032 sgarg
    $doc .= "<mediumName>" . normalize($FORM::dataMedium)." ".normalize($FORM::dataMediumOther);
1066 1929 brooke
    $doc .= "</mediumName>\n";
1067
    $doc .= "</offline>\n";
1068
    $doc .= "</distribution>\n";
1069
1070 2148 sgarg
    my $cov = "";
1071 1929 brooke
1072
    if (hasContent($FORM::endingYear)) {
1073 2148 sgarg
	$cov .= "<temporalCoverage>\n";
1074
	$cov .= "<rangeOfDates>\n";
1075
	if (hasContent($FORM::beginningMonth)) {
1076
	    my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1077
			 "JUL","AUG","SEP","OCT","NOV","DEC")
1078
		[$FORM::beginningMonth - 1];
1079
	    $cov .= "<beginDate>\n";
1080
	    $cov .= "<calendarDate>";
1081
	    $cov .= normalize($FORM::beginningYear)."-".normalize($FORM::beginningMonth)."-".normalize($FORM::beginningDay);
1082
	    $cov .= "</calendarDate>\n";
1083
	    $cov .= "</beginDate>\n";
1084
	} else {
1085
	    $cov .= "<beginDate>\n";
1086
	    $cov .= "<calendarDate>";
1087
	    $cov .= normalize($FORM::beginningYear);
1088
	    $cov .= "</calendarDate>\n";
1089
	    $cov .= "</beginDate>\n";
1090
	}
1091
1092
	if (hasContent($FORM::endingMonth)) {
1093
	    my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1094
			 "JUL","AUG","SEP","OCT","NOV","DEC")
1095
		[$FORM::endingMonth - 1];
1096
	    $cov .= "<endDate>\n";
1097
	    $cov .= "<calendarDate>";
1098
	    $cov .= normalize($FORM::endingYear)."-".normalize($FORM::endingMonth)."-".normalize($FORM::endingDay);
1099
	    $cov .= "</calendarDate>\n";
1100
	    $cov .= "</endDate>\n";
1101
	} else {
1102
	    $cov .= "<endDate>\n";
1103
	    $cov .= "<calendarDate>";
1104
	    $cov .= normalize($FORM::endingYear);
1105
	    $cov .= "</calendarDate>\n";
1106
	    $cov .= "</endDate>\n";
1107
	}
1108
	$cov .= "</rangeOfDates>\n";
1109
	$cov .= "</temporalCoverage>\n";
1110 1977 jones
    } else {
1111 2148 sgarg
	if(hasContent($FORM::beginningYear)) {
1112
	    $cov .= "<temporalCoverage>\n";
1113
	    $cov .= "<singleDateTime>\n";
1114
	    if (hasContent($FORM::beginningMonth)) {
1115
		my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1116
			     "JUL","AUG","SEP","OCT","NOV","DEC")
1117
		    [$FORM::beginningMonth - 1];
1118
		$cov .= "<calendarDate>";
1119
		$cov .= normalize($FORM::beginningYear)."-".normalize($FORM::beginningMonth)."-".normalize($FORM::beginningDay);
1120
		$cov .= "</calendarDate>\n";
1121
	    } else {
1122
		$cov .= "<calendarDate>";
1123
		$cov .= normalize($FORM::beginningYear);
1124
		$cov .= "</calendarDate>\n";
1125
	    }
1126
	    $cov .= "</singleDateTime>\n";
1127
	    $cov .= "</temporalCoverage>\n";
1128
	}
1129 1977 jones
    }
1130 1929 brooke
1131 2149 sgarg
    if(hasContent($FORM::geogdesc) || ($FORM::latDeg1 != 0 && $FORM::longDeg1 != 0)) {
1132 2148 sgarg
	$cov .= "<geographicCoverage>\n";
1133 1929 brooke
1134 2149 sgarg
	if(hasContent($FORM::geogdesc)) {
1135 2148 sgarg
	    $cov .= "<geographicDescription>".normalize($FORM::geogdesc)."</geographicDescription>\n";
1136
	}
1137
1138
	if($FORM::latDeg1 != 0 && $FORM::longDeg1 != 0) {
1139
	    $cov .= "<boundingCoordinates>\n";
1140
	    # if the second latitude is missing, then set the second lat/long pair
1141
	    # equal to the first this makes a point appear like a rectangle
1142
	    if ($FORM::latDeg2 == 0 && $FORM::latMin2 == 0 && $FORM::latSec2 == 0) {
1143
1144
		$latDeg2 = $latDeg1;
1145
		$latMin2 = $latMin1;
1146
		$latSec2 = $latSec1;
1147
		$hemisphLat2 = $hemisphLat1;
1148
		$longDeg2 = $longDeg1;
1149
		$longMin2 = $longMin1;
1150
		$longSec2 = $longSec1;
1151
		$hemisphLong2 = $hemisphLong1;
1152
	    }
1153
	    else
1154
	    {
1155
		$latDeg2 = $FORM::latDeg2;
1156
		$latMin2 = $FORM::latMin2;
1157
		$latSec2 = $FORM::latSec2;
1158
		$hemisphLat2 = $FORM::hemisphLat2;
1159
		$longDeg2 = $FORM::longDeg2;
1160
		$longMin2 = $FORM::longMin2;
1161
		$longSec2 = $FORM::longSec2;
1162
		$hemisphLong2 = $FORM::hemisphLong2;
1163
	    }
1164
1165
1166
	    my $hemisph;
1167
	    $hemisph = ($hemisphLong1 eq "W") ? -1 : 1;
1168
	    $cov .= "<westBoundingCoordinate>";
1169
	    $cov .= $hemisph * ($longDeg1 + (60*$longMin1+$longSec1)/3600);
1170
	    $cov .= "</westBoundingCoordinate>\n";
1171
1172
	    $hemisph = ($hemisphLong2 eq "W") ? -1 : 1;
1173
	    $cov .= "<eastBoundingCoordinate>";
1174
	    $cov .= $hemisph * ($longDeg2 + (60*$longMin2+$longSec2)/3600);
1175
	    $cov .= "</eastBoundingCoordinate>\n";
1176
1177
	    $hemisph = ($hemisphLat1 eq "S") ? -1 : 1;
1178
	    $cov .= "<northBoundingCoordinate>";
1179
	    $cov .= $hemisph * ($latDeg1 + (60*$latMin1+$latSec1)/3600);
1180
	    $cov .= "</northBoundingCoordinate>\n";
1181
1182
	    $hemisph = ($hemisphLat2 eq "S") ? -1 : 1;
1183
	    $cov .= "<southBoundingCoordinate>";
1184
	    $cov .= $hemisph * ($latDeg2 + (60*$latMin2+$latSec2)/3600);
1185
	    $cov .= "</southBoundingCoordinate>\n";
1186
1187
	    $cov .= "</boundingCoordinates>\n";
1188
	}
1189
	$cov .= "</geographicCoverage>\n";
1190 1929 brooke
    }
1191
1192 1984 jones
    # Write out the taxonomic coverage fields
1193
    my $foundFirstTaxon = 0;
1194
    foreach my $trn (param()) {
1195
        if ($trn =~ /taxonRankName/) {
1196
            my $taxIndex = $trn;
1197
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
1198
            my $trv = "taxonRankValue".$taxIndex;
1199
            if ( $taxIndex =~ /[0-9]/ ){
1200
                if (hasContent(param($trn)) && hasContent(param($trv))) {
1201
                    if (! $foundFirstTaxon) {
1202 2148 sgarg
                        $cov .= "<taxonomicCoverage>\n";
1203 1984 jones
                        $foundFirstTaxon = 1;
1204 1985 jones
                        if (hasContent($FORM::taxaAuth)) {
1205 2148 sgarg
                            $cov .= "<generalTaxonomicCoverage>".normalize($FORM::taxaAuth)."</generalTaxonomicCoverage>\n";
1206 1985 jones
                        }
1207 1984 jones
                    }
1208 2148 sgarg
                    $cov .= "<taxonomicClassification>\n";
1209
                    $cov .= "  <taxonRankName>".normalize(param($trn))."</taxonRankName>\n";
1210
                    $cov .= "  <taxonRankValue>".normalize(param($trv))."</taxonRankValue>\n";
1211
                    $cov .= "</taxonomicClassification>\n";
1212 1984 jones
                }
1213
            }
1214
        }
1215
    }
1216
    if ($foundFirstTaxon) {
1217 2148 sgarg
        $cov .= "</taxonomicCoverage>\n";
1218 1984 jones
    }
1219 1929 brooke
1220 2149 sgarg
    if($cov ne "" ){
1221
	$doc .= "<coverage>".$cov."</coverage>";
1222
    }
1223 1929 brooke
    $doc .= $cont;
1224
    $doc .= $publ;
1225 1982 jones
1226 2151 sgarg
    if ((hasContent($FORM::methodTitle)) || scalar(@FORM::methodsPara) > 0 || ($FORM::methodPara[0] ne "")) {
1227 1982 jones
        my $methods = "<methods><methodStep><description><section>\n";
1228
        if (hasContent($FORM::methodTitle)) {
1229 2032 sgarg
            $methods .= "<title>".normalize($FORM::methodTitle)."</title>\n";
1230 1982 jones
        }
1231
        for (my $i = 0; $i < scalar(@FORM::methodPara); $i++) {
1232 2032 sgarg
            $methods .= "<para>".normalize($FORM::methodPara[$i])."</para>\n";
1233 1982 jones
        }
1234 1989 jones
        $methods .= "</section></description></methodStep>\n";
1235
        if (hasContent($FORM::studyExtentDescription)) {
1236
            $methods .= "<sampling><studyExtent><description>\n";
1237 2032 sgarg
            $methods .= "<para>".normalize($FORM::studyExtentDescription)."</para>\n";
1238 1989 jones
            $methods .= "</description></studyExtent>\n";
1239
            $methods .= "<samplingDescription>\n";
1240 2032 sgarg
            $methods .= "<para>".normalize($FORM::samplingDescription)."</para>\n";
1241 1989 jones
            $methods .= "</samplingDescription>\n";
1242
            $methods .= "</sampling>\n";
1243
        }
1244
        $methods .= "</methods>\n";
1245 1982 jones
        $doc .= $methods;
1246
    }
1247 1929 brooke
1248
    $doc .= "<access authSystem=\"knb\" order=\"denyFirst\">\n";
1249
    $doc .= "<allow>\n";
1250 2005 jones
    $doc .= "<principal>$username</principal>\n";
1251 1929 brooke
    $doc .= "<permission>all</permission>\n";
1252
    $doc .= "</allow>\n";
1253
    $doc .= "<allow>\n";
1254
    $doc .= "<principal>uid=$FORM::username,o=$FORM::organization,dc=ecoinformatics,dc=org</principal>\n";
1255
    $doc .= "<permission>all</permission>\n";
1256
    $doc .= "</allow>\n";
1257
    $doc .= "<allow>\n";
1258
    $doc .= "<principal>public</principal>\n";
1259
    $doc .= "<permission>read</permission>\n";
1260
    $doc .= "</allow>\n";
1261
    $doc .= "</access>\n";
1262
1263
    $doc .= "</dataset>\n</eml:eml>\n";
1264
1265
    return $doc;
1266
}
1267
1268
1269
################################################################################
1270
#
1271
# send an email message notifying the moderator of a new submission
1272
#
1273
################################################################################
1274
sub sendNotification {
1275
    my $identifier = shift;
1276
    my $mailhost = shift;
1277
    my $sender = shift;
1278
    my $recipient = shift;
1279
1280
    my $smtp = Net::SMTP->new($mailhost);
1281
    $smtp->mail($sender);
1282
    $smtp->to($recipient);
1283
1284
    my $message = <<"    ENDOFMESSAGE";
1285
    To: $recipient
1286
    From: $sender
1287
    Subject: New data submission
1288
1289
    Data was submitted to the data registry.
1290
    The identifying information for the new data set is:
1291
1292
    Identifier: $identifier
1293
    Title: $FORM::title
1294
    Submitter: $FORM::providerGivenName $FORM::providerSurName
1295
1296
    Please review the submmission and grant public read access if appropriate.
1297
    Thanks
1298
1299
    ENDOFMESSAGE
1300
    $message =~ s/^[ \t\r\f]+//gm;
1301
1302
    $smtp->data($message);
1303
    $smtp->quit;
1304
}
1305
1306
1307
################################################################################
1308
#
1309
# read the eml document and send back a form with values filled in.
1310
#
1311
################################################################################
1312
sub modifyData {
1313
1314
    # create metacat instance
1315
    my $metacat;
1316
    my $docid = $FORM::docid;
1317
    my $httpMessage;
1318
    my $doc;
1319
    my $xmldoc;
1320
    my $findType;
1321
    my $parser = XML::LibXML->new();
1322
    my @fileArray;
1323
    my $pushDoc;
1324
    my $alreadyInArray;
1325
    my $node;
1326
    my $response;
1327
    my $element;
1328
    my $tempfile;
1329
1330
    $metacat = Metacat->new();
1331
    if ($metacat) {
1332
        $metacat->set_options( metacatUrl => $metacatUrl );
1333
    } else {
1334
        #die "failed during metacat creation\n";
1335
        push(@errorMessages, "Failed during metacat creation.");
1336
    }
1337
1338
    $httpMessage = $metacat->read($docid);
1339
    $doc = $httpMessage->content();
1340
    $xmldoc = $parser->parse_string($doc);
1341
1342 1977 jones
    #$tempfile = $xslConvDir.$docid;
1343
    #push (@fileArray, $tempfile);
1344 1929 brooke
1345
    if ($xmldoc eq "") {
1346 1977 jones
        $error ="Error in parsing the eml document";
1347
        push(@errorMessages, $error);
1348 1929 brooke
    } else {
1349 1977 jones
        $findType = $xmldoc->findnodes('//dataset/identifier');
1350
        if ($findType->size() > 0) {
1351
            # This is a eml beta6 document
1352
            # Read the documents mentioned in triples also
1353
1354
            $findType = $xmldoc->findnodes('//dataset/triple');
1355
            if ($findType->size() > 0) {
1356
                foreach $node ($findType->get_nodelist) {
1357
                    $pushDoc = findValue($node, 'subject');
1358
1359
                    # If the file is already in @fileArray then do not add it
1360
                    $alreadyInArray = 0;
1361
                    foreach $element (@fileArray) {
1362
                        $tempfile = $tmpdir."/".$pushDoc;
1363
                        if ($element eq $pushDoc) {
1364
                            $alreadyInArray = 1;
1365
                        }
1366
                    }
1367
1368
                    if (!$alreadyInArray) {
1369
                        $tempfile = $tmpdir."/".$pushDoc;
1370
                        $response = "";
1371
                        $response = $metacat->read($pushDoc);
1372
                        if (! $response) {
1373
                            # could not read
1374
                            #push(@errorMessages, $response);
1375
                            push(@errorMessages, $metacat->getMessage());
1376
                            push(@errorMessages, "Failed during reading.\n");
1377
                        } else {
1378
                            my $xdoc = $response->content();
1379
                            #$tempfile = $xslConvDir.$pushDoc;
1380
                            open (TFILE,">$tempfile") ||
1381
                                die ("Cant open xml file... $tempfile\n");
1382
                            print TFILE $xdoc;
1383
                            close(TFILE);
1384
                            push (@fileArray, $tempfile);
1385
                        }
1386
                    }
1387
                }
1388
            }
1389 1929 brooke
1390 1977 jones
            # Read the main document.
1391 1929 brooke
1392 1977 jones
            $tempfile = $tmpdir."/".$docid; #= $xslConvDir.$docid;
1393
            open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1394
            print TFILE $doc;
1395
            close(TFILE);
1396
1397
            # Transforming beta6 to eml 2
1398
            my $xslt;
1399
            my $triplesheet;
1400
            my $results;
1401
            my $stylesheet;
1402
            my $resultsheet;
1403
1404
            $xslt = XML::LibXSLT->new();
1405
            #$tempfile = $xslConvDir."triple_info.xsl";
1406
            $tempfile = $tmpdir."/"."triple_info.xsl";
1407
1408
            $triplesheet = $xslt->parse_stylesheet_file($tempfile);
1409 1929 brooke
1410 1977 jones
            #$results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1411
            $results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1412 1929 brooke
1413 1977 jones
            #$tempfile = $xslConvDir."emlb6toeml2.xsl";
1414
            $tempfile = $tmpdir."/"."emlb6toeml2.xsl";
1415
            $stylesheet = $xslt->parse_stylesheet_file($tempfile);
1416
            $resultsheet = $stylesheet->transform($results);
1417
1418
            #$tempfile = "/usr/local/apache2/htdocs/xml/test.xml";;
1419
            #open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1420
            #print TFILE $stylesheet->output_string($resultsheet);
1421
            #close(TFILE);
1422 1929 brooke
1423 1977 jones
            getFormValuesFromEml2($resultsheet);
1424
1425
            # Delete the files written earlier.
1426
            unlink @fileArray;
1427 1929 brooke
1428 1977 jones
        } else {
1429
            getFormValuesFromEml2($xmldoc);
1430
        }
1431 1929 brooke
    }
1432
1433
    if (scalar(@errorMessages)) {
1434 1979 jones
        # if any errors, print them in the response template
1435
        $$templateVars{'status'} = 'failure';
1436
        $$templateVars{'errorMessages'} = \@errorMessages;
1437
        $error = 1;
1438
        $$templateVars{'function'} = "modification";
1439
        $$templateVars{'section'} = "Modification Status";
1440
        $template->process( $responseTemplate, $templateVars);
1441 1929 brooke
    } else {
1442
        $$templateVars{'form'} = 're_entry';
1443 1977 jones
        $template->process( $entryFormTemplate, $templateVars);
1444 1929 brooke
    }
1445
}
1446
1447 1977 jones
################################################################################
1448
#
1449
# Parse an EML 2.0.0 file and extract the metadata into perl variables for
1450
# processing and returning to the template processor
1451
#
1452
################################################################################
1453 1929 brooke
sub getFormValuesFromEml2 {
1454
1455
    my $doc = shift;
1456
    my $results;
1457
    my $error;
1458
    my $node;
1459
    my $tempResult;
1460
    my $tempNode;
1461
    my $aoCount = 1;
1462
    my $foundDSO;
1463
1464 2138 sgarg
    # set variable values
1465
    $$templateVars{'hasKeyword'} = $hasKeyword;
1466 2148 sgarg
    $$templateVars{'hasTemporal'} = $hasTemporal;
1467
    $$templateVars{'hasSpatial'} = $hasSpatial;
1468
    $$templateVars{'hasTaxonomic'} = $hasTaxonomic;
1469
    $$templateVars{'hasMethod'} = $hasMethod;
1470
    $$templateVars{'spatialRequired'} = $spatialRequired;
1471
    $$templateVars{'temporalRequired'} = $temporalRequired;
1472
1473 1929 brooke
    # find out the tag <alternateIdentifier>.
1474
    $results = $doc->findnodes('//dataset/alternateIdentifier');
1475 1977 jones
    if ($results->size() > 1) {
1476
        errMoreThanOne("alternateIdentifier");
1477 1929 brooke
    } else {
1478 1977 jones
        foreach $node ($results->get_nodelist) {
1479
            $$templateVars{'identifier'} = findValue($node, '../alternateIdentifier');
1480
        }
1481 1929 brooke
    }
1482
1483
    # find out the tag <title>.
1484
    $results = $doc->findnodes('//dataset/title');
1485 1977 jones
    if ($results->size() > 1) {
1486
        errMoreThanOne("title");
1487
    } elsif ($results->size() < 1) {
1488
        $error ="Following tag not found: title. Please use Morpho to edit this document";
1489
        push(@errorMessages, $error."\n");
1490
        #if ($DEBUG == 1){ print $error;}
1491 1929 brooke
    } else {
1492 1977 jones
        foreach $node ($results->get_nodelist) {
1493
            $$templateVars{'title'} = findValue($node, '../title');
1494
        }
1495 1929 brooke
    }
1496
1497
    # find out the tag <creator>.
1498
    $results = $doc->findnodes('//dataset/creator/individualName');
1499 1979 jones
    debug("Registry: Creators: ".$results->size());
1500 2144 sgarg
     foreach $node ($results->get_nodelist) {
1501 1977 jones
            dontOccur($node, "../positionName|../onlineURL|../userId",
1502
              "positionName, onlineURL, userId");
1503
1504
            dontOccur($node, "./saluation", "saluation");
1505
1506 1979 jones
            debug("Registry: Checking a creator in loop 1...");
1507 1977 jones
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1508
            if($tempResult->size > 0) {
1509
                if($foundDSO == 0) {
1510
                    $foundDSO = 1;
1511 1929 brooke
1512 1979 jones
                    debug("Registry: Recording a creator in loop 1...");
1513 1977 jones
                    $$templateVars{'origNamefirst0'} = findValue($node, 'givenName');
1514
                    $$templateVars{'origNamelast0'} = findValue($node, 'surName');
1515
1516
                    my $tempResult2 = $node->findnodes('../address');
1517
                    if ($tempResult2->size > 1) {
1518
                        errMoreThanOne("address");
1519
                    } else {
1520
                        foreach my $tempNode2 ($tempResult2->get_nodelist) {
1521
                            $$templateVars{'origDelivery'} = findValue($tempNode2, 'deliveryPoint');
1522
                            $$templateVars{'origCity'} = findValue($tempNode2, 'city');
1523
                            $$templateVars{'origState'} = findValue($tempNode2, 'administrativeArea');
1524
                            $$templateVars{'origZIP'} = findValue($tempNode2, 'postalCode');
1525
                            $$templateVars{'origCountry'} = findValue($tempNode2, 'country');
1526
                        }
1527
                    }
1528
1529
                    my $tempResult3 = $node->findnodes('../phone');
1530
                    if ($tempResult3->size > 2) {
1531
                        errMoreThanN("phone");
1532
                    } else {
1533
                        foreach my $tempNode2 ($tempResult3->get_nodelist) {
1534
                            if ($tempNode2->hasAttributes()) {
1535
                                my @attlist = $tempNode2->attributes();
1536
                                if ($attlist[0]->value eq "Fax") {
1537
                                    $$templateVars{'origFAX'} = $tempNode2->textContent();
1538
                                } else {
1539
                                    $$templateVars{'origPhone'} = $tempNode2->textContent();
1540
                                }
1541
                            } else {
1542
                                $$templateVars{'origPhone'} = $tempNode2->textContent();
1543
                            }
1544
                        }
1545
                    }
1546
                    $$templateVars{'origEmail'} = findValue($node, '../electronicMailAddress');
1547
                    $$templateVars{'origNameOrg'} = findValue($node, '../organizationName');
1548
                } else {
1549
                    errMoreThanN("address, phone and electronicMailAddress");
1550
                }
1551
            }
1552
        }
1553
        foreach $node ($results->get_nodelist) {
1554 1979 jones
            debug("Registry: Checking a creator in loop 2...");
1555
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1556 1977 jones
            if ($tempResult->size == 0) {
1557
                if ($foundDSO == 0) {
1558 1979 jones
                    debug("Registry: Recording a creator in loop 2 block A...");
1559 1977 jones
                    $foundDSO = 1;
1560
                    $$templateVars{'origNamefirst0'} = findValue($node, 'givenName');
1561
                    $$templateVars{'origNamelast0'} = findValue($node, 'surName');
1562
                    $$templateVars{'origNameOrg'} = findValue($node, '../organizationName');
1563
                } else {
1564 1979 jones
                    debug("Registry: Recording a creator in loop 2 block B...");
1565 1977 jones
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($node, './givenName');
1566
                    $$templateVars{"origNamelast$aoCount"} =  findValue($node, './surName');
1567
                    $$templateVars{"origRole$aoCount"} = "Originator";
1568
                    $aoCount++;
1569
                }
1570
            }
1571
        }
1572 1929 brooke
1573
    $results = $doc->findnodes('//dataset/creator/organizationName');
1574 1979 jones
    my $wgroups = $doc->findnodes("//dataset/creator/organizationName[contains(text(),'(NCEAS ')]");
1575
    debug("Registry: Number Org: ".$results->size());
1576
    debug("Registry:  Number WG: ".$wgroups->size());
1577
    if ($results->size() - $wgroups->size() > 3) {
1578 1977 jones
        errMoreThanN("creator/organizationName");
1579 1929 brooke
    } else {
1580 1977 jones
        foreach $node ($results->get_nodelist) {
1581
            my $tempValue = findValue($node,'../organizationName');
1582
            $tempResult = $node->findnodes('../individualName');
1583
            if ($tempResult->size == 0 && $tempValue ne $organization) {
1584
                $$templateVars{'site'} = $tempValue;
1585
            }
1586
        }
1587 2003 jones
        if ($FORM::cfg eq 'nceas') {
1588 1979 jones
            my @wg;
1589
            foreach $node ($results->get_nodelist) {
1590
                my $tempValue = findValue($node,'../organizationName');
1591
                $wg[scalar(@wg)] = $tempValue;
1592
            }
1593
            my $projects = getProjectList();
1594
            $$templateVars{'projects'} = $projects;
1595
            $$templateVars{'wg'} = \@wg;
1596
        }
1597 1929 brooke
    }
1598
1599
    $results = $doc->findnodes('//dataset/metadataProvider');
1600 2144 sgarg
    foreach $node ($results->get_nodelist) {
1601 1977 jones
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address",
1602
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in metadataProvider");
1603
1604 2144 sgarg
	    $tempResult = $node->findnodes('./individualName');
1605 1977 jones
            if ($tempResult->size > 1) {
1606
                errMoreThanOne("metadataProvider/indvidualName");
1607
            } else {
1608
                foreach $tempNode ($tempResult->get_nodelist) {
1609
                    if ($$templateVars{'providerGivenName'} ne "") {
1610
                        $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1611
                        $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1612
                        $$templateVars{"origRole$aoCount"} = "Metadata Provider";
1613
                        $aoCount++;
1614
                    } else {
1615
                        $$templateVars{'providerGivenName'} =  findValue($tempNode, './givenName');
1616
                        $$templateVars{'providerSurName'} =  findValue($tempNode, './surName');
1617
                    }
1618
                }
1619
            }
1620
        }
1621 1929 brooke
1622
    $results = $doc->findnodes('//dataset/associatedParty');
1623 2144 sgarg
    foreach $node ($results->get_nodelist) {
1624 1977 jones
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address",
1625
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in associatedParty");
1626
1627
            $tempResult = $node->findnodes('./individualName');
1628
            if ($tempResult->size > 1) {
1629
                errMoreThanOne("associatedParty/indvidualName");
1630
            } else {
1631
                foreach $tempNode ($tempResult->get_nodelist) {
1632
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1633
                    $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1634
                    $$templateVars{"origRole$aoCount"} = findValue($tempNode, '../role');
1635
                    $aoCount++;
1636
                }
1637
            }
1638 2144 sgarg
     }
1639 1929 brooke
1640
    $results = $doc->findnodes('//dataset/publisher');
1641 2144 sgarg
#    if ($results->size() > 10) {
1642
 #       errMoreThanN("publisher");
1643
 #   } else {
1644 1977 jones
        foreach $node ($results->get_nodelist) {
1645
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address",
1646
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in associatedParty");
1647
1648
            $tempResult = $node->findnodes('./individualName');
1649
            if ($tempResult->size > 1) {
1650
                errMoreThanOne("publisher/indvidualName");
1651
            } else {
1652
                foreach $tempNode ($tempResult->get_nodelist) {
1653
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1654
                    $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1655
                    $$templateVars{"origRole$aoCount"} = "Publisher";
1656
                    $aoCount++;
1657
                }
1658
            }
1659
        }
1660 2144 sgarg
  #  }
1661 1929 brooke
1662 2144 sgarg
  #  if ($aoCount > 11) {
1663
  #      errMoreThanN("Additional Originators");
1664
 #   }
1665 1929 brooke
1666 2144 sgarg
    $$templateVars{'aoCount'} = $aoCount-1;
1667
1668 1929 brooke
    dontOccur($doc, "./pubDate", "pubDate");
1669
    dontOccur($doc, "./language", "language");
1670
    dontOccur($doc, "./series", "series");
1671
1672
    $results = $doc->findnodes('//dataset/abstract');
1673 1977 jones
    if ($results->size() > 1) {
1674
        errMoreThanOne("abstract");
1675 1929 brooke
    } else {
1676 1977 jones
        foreach my $node ($results->get_nodelist) {
1677
            dontOccur($node, "./section", "section");
1678
            $$templateVars{'abstract'} = findValueNoChild($node, "para");
1679
        }
1680 1929 brooke
    }
1681
1682
    $results = $doc->findnodes('//dataset/keywordSet');
1683 2028 sgarg
1684
    my $count = 0;
1685
    foreach $node ($results->get_nodelist) {
1686
	$tempResult = $node->findnodes('./keyword');
1687
	if ($tempResult->size() > 1) {
1688
	    errMoreThanOne("keyword");
1689
	} else {
1690 2042 sgarg
	    $count++;
1691 2028 sgarg
	    foreach $tempNode ($tempResult->get_nodelist) {
1692
		$$templateVars{"keyword$count"} = $tempNode->textContent();
1693
		if ($tempNode->hasAttributes()) {
1694
		    my @attlist = $tempNode->attributes();
1695
		    $$templateVars{"kwType$count"} = $attlist[0]->value;
1696
		}
1697 2042 sgarg
	    }
1698 2028 sgarg
	}
1699
	$$templateVars{"kwTh$count"} = findValue($node, "keywordThesaurus");
1700
    }
1701 2042 sgarg
    $$templateVars{'keyCount'} = $count;
1702 2138 sgarg
    if($count > 0 ){
1703
       $$templateVars{'hasKeyword'} = "true";
1704
    }
1705 1929 brooke
1706
    $results = $doc->findnodes('//dataset/additionalInfo');
1707 1977 jones
    if ($results->size() > 1) {
1708
        errMoreThanOne("additionalInfo");
1709 1929 brooke
    } else {
1710 1977 jones
        foreach $node ($results->get_nodelist) {
1711
            dontOccur($node, "./section", "section");
1712
            $$templateVars{'addComments'} = findValueNoChild($node, "para");
1713
        }
1714 1929 brooke
    }
1715
1716
    $$templateVars{'useConstraints'} = "";
1717
    $results = $doc->findnodes('//dataset/intellectualRights');
1718 1977 jones
    if ($results->size() > 1) {
1719
        errMoreThanOne("intellectualRights");
1720 1929 brooke
    } else {
1721 1977 jones
        foreach $node ($results->get_nodelist) {
1722
            dontOccur($node, "./section", "section in intellectualRights");
1723 1929 brooke
1724 1977 jones
            $tempResult = $node->findnodes("para");
1725
            if ($tempResult->size > 2) {
1726
                   errMoreThanN("para");
1727
            } else {
1728
                foreach $tempNode ($tempResult->get_nodelist) {
1729
                    my $childNodes = $tempNode->childNodes;
1730
                    if ($childNodes->size() > 1) {
1731
                        $error ="The tag para in intellectualRights has children which cannot be shown using the form. Please use Morpho to edit this document";
1732
                        push(@errorMessages, $error);
1733
                        #if ($DEBUG == 1){ print $error."\n";}
1734
                    } else {
1735
                        #print $tempNode->nodeName().":".$tempNode->textContent();
1736
                        #print "\n";
1737
                        if ($$templateVars{'useConstraints'} eq "") {
1738
                            $$templateVars{'useConstraints'} = $tempNode->textContent();
1739
                        } else {
1740
                            $$templateVars{'useConstraintsOther'} = $tempNode->textContent();
1741
                        }
1742
                    }
1743
                }
1744
            }
1745
        }
1746 1929 brooke
    }
1747
1748
    $results = $doc->findnodes('//dataset/distribution/online');
1749 1977 jones
    if ($results->size() > 1) {
1750
        errMoreThanOne("distribution/online");
1751 1929 brooke
    } else {
1752 1977 jones
        foreach my $tempNode ($results->get_nodelist){
1753
            $$templateVars{'url'} = findValue($tempNode, "url");
1754
            dontOccur($tempNode, "./connection", "/distribution/online/connection");
1755
            dontOccur($tempNode, "./connectionDefinition", "/distribution/online/connectionDefinition");
1756
        }
1757 1929 brooke
    }
1758
1759
    $results = $doc->findnodes('//dataset/distribution/offline');
1760 1977 jones
    if ($results->size() > 1) {
1761
        errMoreThanOne("distribution/online");
1762 1929 brooke
    } else {
1763 1977 jones
        foreach my $tempNode ($results->get_nodelist) {
1764
            $$templateVars{'dataMedium'} = findValue($tempNode, "mediumName");
1765
            dontOccur($tempNode, "./mediumDensity", "/distribution/offline/mediumDensity");
1766
            dontOccur($tempNode, "./mediumDensityUnits", "/distribution/offline/mediumDensityUnits");
1767
            dontOccur($tempNode, "./mediumVolume", "/distribution/offline/mediumVolume");
1768
            dontOccur($tempNode, "./mediumFormat", "/distribution/offline/mediumFormat");
1769
            dontOccur($tempNode, "./mediumNote", "/distribution/offline/mediumNote");
1770
        }
1771 1929 brooke
    }
1772
1773
    dontOccur($doc, "./inline", "//dataset/distribution/inline");
1774
1775
    $results = $doc->findnodes('//dataset/coverage');
1776 1977 jones
    if ($results->size() > 1) {
1777
        errMoreThanOne("coverage");
1778 1929 brooke
    } else {
1779 1977 jones
        foreach $node ($results->get_nodelist) {
1780 1985 jones
            dontOccur($node, "./temporalCoverage/rangeOfDates/beginDate/time|./temporalCoverage/rangeOfDates/beginDate/alternativeTimeScale|./temporalCoverage/rangeOfDates/endDate/time|./temporalCoverage/rangeOfDates/endDate/alternativeTimeScale|./taxonomicCoverage/taxonomicSystem|./taxonomicCoverage/taxonomicClassification/commonName|./taxonomicCoverage/taxonomicClassification/taxonomicClassification|./geographicCoverage/datasetGPolygon|./geographicCoverage/boundingCoordinates/boundingAltitudes", "temporalCoverage/rangeOfDates/beginDate/time, /temporalCoverage/rangeOfDates/beginDate/alternativeTimeScale, /temporalCoverage/rangeOfDates/endDate/time, /temporalCoverage/rangeOfDates/endDate/alternativeTimeScale, /taxonomicCoverage/taxonomicSystem, /taxonomicCoverage/taxonomicClassification/commonName, /taxonomicCoverage/taxonomicClassification/taxonomicClassification, /geographicCoverage/datasetGPolygon, /geographicCoverage/boundingCoordinates/boundingAltitudes");
1781 1929 brooke
1782 1977 jones
            $tempResult = $node->findnodes('./temporalCoverage');
1783
            if ($tempResult->size > 1) {
1784
                   errMoreThanOne("temporalCoverage");
1785
            } else {
1786
                foreach $tempNode ($tempResult->get_nodelist) {
1787
                    my $x;
1788
                    my $y;
1789
                    my $z;
1790
                    my $tempdate = findValue($tempNode, "rangeOfDates/beginDate/calendarDate");
1791
                    ($x, $y, $z) = split("-", $tempdate);
1792
                    $$templateVars{'beginningYear'} = $x;
1793
                    $$templateVars{'beginningMonth'} = $y;
1794
                    $$templateVars{'beginningDay'} = $z;
1795
1796
                    $tempdate = findValue($tempNode, "rangeOfDates/endDate/calendarDate");
1797
                    ($x, $y, $z) = split("-", $tempdate);
1798
                    $$templateVars{'endingYear'} = $x;
1799
                    $$templateVars{'endingMonth'} = $y;
1800
                    $$templateVars{'endingDay'} = $z;
1801 2148 sgarg
1802 1977 jones
                    $tempdate = "";
1803
                    $tempdate = findValue($tempNode, "singleDateTime/calendarDate");
1804
                    if($tempdate ne ""){
1805
                        ($x, $y, $z) = split("-", $tempdate);
1806
                        $$templateVars{'beginningYear'} = $x;
1807
                        $$templateVars{'beginningMonth'} = $y;
1808
                        $$templateVars{'beginningDay'} = $z;
1809
                    }
1810 2148 sgarg
1811
		    $$templateVars{'hasTemporal'} = "true";
1812 1977 jones
                }
1813
            }
1814 1929 brooke
1815 1977 jones
            $tempResult = $node->findnodes('./geographicCoverage');
1816
            if ($tempResult->size > 1) {
1817
                errMoreThanOne("geographicCoverage");
1818
            } else {
1819
                foreach $tempNode ($tempResult->get_nodelist) {
1820 1983 jones
                    my $geogdesc = findValue($tempNode, "geographicDescription");
1821
                    debug("Registry: geogdesc from xml is: $geogdesc");
1822
                    $$templateVars{'geogdesc'} = $geogdesc;
1823
                    my $coord = findValue($tempNode, "boundingCoordinates/westBoundingCoordinate");
1824 1977 jones
                    if ($coord > 0) {
1825
                        #print "+";
1826
                        $$templateVars{'hemisphLong1'} = "E";
1827
                    } else {
1828
                        #print "-";
1829
                        eval($coord = $coord * -1);
1830
                        $$templateVars{'hemisphLong1'} = "W";
1831
                    }
1832
                    eval($$templateVars{'longDeg1'} = int($coord));
1833
                    eval($coord = ($coord - int($coord))*60);
1834
                    eval($$templateVars{'longMin1'} = int($coord));
1835
                    eval($coord = ($coord - int($coord))*60);
1836
                    eval($$templateVars{'longSec1'} = int($coord));
1837
1838
                    $coord = findValue($tempNode, "boundingCoordinates/southBoundingCoordinate");
1839
                    if ($coord > 0) {
1840
                        #print "+";
1841
                        $$templateVars{'hemisphLat2'} = "N";
1842
                    } else {
1843
                        #print "-";
1844
                        eval($coord = $coord * -1);
1845
                        $$templateVars{'hemisphLat2'} = "S";
1846
                    }
1847
                    eval($$templateVars{'latDeg2'} = int($coord));
1848
                    eval($coord = ($coord - int($coord))*60);
1849
                    eval($$templateVars{'latMin2'} = int($coord));
1850
                    eval($coord = ($coord - int($coord))*60);
1851
                    eval($$templateVars{'latSec2'} = int($coord));
1852
1853
                    $coord = findValue($tempNode, "boundingCoordinates/northBoundingCoordinate");
1854
                    if ($coord > 0) {
1855
                        #print "+";
1856
                        $$templateVars{'hemisphLat1'} = "N";
1857
                    } else {
1858
                        #print "-";
1859
                        eval($coord = $coord * -1);
1860
                        $$templateVars{'hemisphLat1'} = "S";
1861
                    }
1862
                    eval($$templateVars{'latDeg1'} = int($coord));
1863
                    eval($coord = ($coord - int($coord))*60);
1864
                    eval($$templateVars{'latMin1'} = int($coord));
1865
                    eval($coord = ($coord - int($coord))*60);
1866
                    eval($$templateVars{'latSec1'} = int($coord));
1867
1868
                    $coord = findValue($tempNode, "boundingCoordinates/eastBoundingCoordinate");
1869
                    if ($coord > 0) {
1870
                        #print "+";
1871
                        $$templateVars{'hemisphLong2'} = "E";
1872
                    } else {
1873
                        #print "-";
1874
                        eval($coord = $coord * -1);
1875
                        $$templateVars{'hemisphLong2'} = "W";
1876
                    }
1877
                    eval($$templateVars{'longDeg2'} = int($coord));
1878
                    eval($coord = ($coord - int($coord))*60);
1879
                    eval($$templateVars{'longMin2'} = int($coord));
1880
                    eval($coord = ($coord - int($coord))*60);
1881
                    eval($$templateVars{'longSec2'} = int($coord));
1882 2148 sgarg
1883
		    $$templateVars{'hasSpatial'} = "true";
1884 1977 jones
                }
1885
            }
1886 1984 jones
1887
            $tempResult = $node->findnodes('./taxonomicCoverage/taxonomicClassification');
1888
            my $taxonIndex = 0;
1889
            foreach $tempNode ($tempResult->get_nodelist) {
1890
                $taxonIndex++;
1891
                my $taxonRankName = findValue($tempNode, "taxonRankName");
1892
                my $taxonRankValue = findValue($tempNode, "taxonRankValue");
1893
                $$templateVars{"taxonRankName".$taxonIndex} = $taxonRankName;
1894
                $$templateVars{"taxonRankValue".$taxonIndex} = $taxonRankValue;
1895 2148 sgarg
1896
		$$templateVars{'hasTaxonomic'} = "true";
1897 1984 jones
            }
1898
            $$templateVars{'taxaCount'} = $taxonIndex;
1899 1985 jones
            my $taxaAuth = findValue($node, "./taxonomicCoverage/generalTaxonomicCoverage");
1900
            $$templateVars{'taxaAuth'} = $taxaAuth;
1901 1977 jones
        }
1902 1929 brooke
    }
1903
    dontOccur($doc, "./purpose", "purpose");
1904
    dontOccur($doc, "./maintenance", "maintnance");
1905
1906
    $results = $doc->findnodes('//dataset/contact/individualName');
1907 1977 jones
    if ($results->size() > 1) {
1908
        errMoreThanOne("contact/individualName");
1909 1929 brooke
    } else {
1910 1977 jones
        foreach $node ($results->get_nodelist) {
1911
            dontOccur($node, "../positionName|../onlineURL|../userId",
1912
              "positionName, onlineURL, userId in contact tag");
1913
            dontOccur($node, "./saluation", "saluation in contact tag");
1914
1915
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1916
            if ($tempResult->size > 0) {
1917
                $$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
1918
                $$templateVars{'origNamelastContact'} = findValue($node, 'surName');
1919
1920
                my $tempResult2 = $node->findnodes('../address');
1921
                if ($tempResult2->size > 1) {
1922
                    errMoreThanOne("address");
1923
                } else {
1924
                    foreach my $tempNode2 ($tempResult2->get_nodelist) {
1925
                        $$templateVars{'origDeliveryContact'} = findValue($tempNode2, 'deliveryPoint');
1926
                        $$templateVars{'origCityContact'} = findValue($tempNode2, 'city');
1927
                        $$templateVars{'origStateContact'} = findValue($tempNode2, 'administrativeArea');
1928
                        $$templateVars{'origZIPContact'} = findValue($tempNode2, 'postalCode');
1929
                        $$templateVars{'origCountryContact'} = findValue($tempNode2, 'country');
1930
                    }
1931
                }
1932
1933
                my $tempResult3 = $node->findnodes('../phone');
1934
                if ($tempResult3->size > 2) {
1935
                    errMoreThanN("phone");
1936
                } else {
1937
                    foreach my $tempNode2 ($tempResult3->get_nodelist) {
1938
                        if ($tempNode2->hasAttributes()) {
1939
                            my @attlist = $tempNode2->attributes();
1940
                            if ($attlist[0]->value eq "Fax") {
1941
                                $$templateVars{'origFAXContact'} = $tempNode2->textContent();
1942
                            } else {
1943
                                $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
1944
                            }
1945
                        } else {
1946
                            $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
1947
                        }
1948
                    }
1949
                }
1950
                $$templateVars{'origEmailContact'} = findValue($node, '../electronicMailAddress');
1951
                $$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
1952
            } else {
1953
                $$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
1954
                $$templateVars{'origNamelastContact'} = findValue($node, 'surName');
1955
                $$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
1956
            }
1957
        }
1958 1929 brooke
    }
1959
1960 1989 jones
    $results = $doc->findnodes(
1961
            '//dataset/methods/methodStep/description/section');
1962 1982 jones
    debug("Registry: Number methods: ".$results->size());
1963
    if ($results->size() > 1) {
1964
        errMoreThanN("methods/methodStep/description/section");
1965
    } else {
1966
1967
        my @methodPara;
1968
        foreach $node ($results->get_nodelist) {
1969
            my @children = $node->childNodes;
1970
            for (my $i = 0; $i < scalar(@children); $i++) {
1971
                debug("Registry: Method child loop ($i)");
1972
                my $child = $children[$i];
1973
                if ($child->nodeName eq 'title') {
1974
                    my $title = $child->textContent();
1975
                    debug("Registry: Method title ($title)");
1976
                    $$templateVars{'methodTitle'} = $title;
1977
                } elsif ($child->nodeName eq 'para') {
1978
                    my $para = $child->textContent();
1979
                    debug("Registry: Method para ($para)");
1980
                    $methodPara[scalar(@methodPara)] = $para;
1981
                }
1982
            }
1983 2148 sgarg
	    $$templateVars{'hasMethod'} = "true";
1984 1982 jones
        }
1985
        if (scalar(@methodPara) > 0) {
1986
            $$templateVars{'methodPara'} = \@methodPara;
1987
        }
1988
    }
1989
1990 1989 jones
    $results = $doc->findnodes(
1991
            '//dataset/methods/sampling/studyExtent/description/para');
1992
    if ($results->size() > 1) {
1993
        errMoreThanN("methods/sampling/studyExtent/description/para");
1994
    } else {
1995
        foreach $node ($results->get_nodelist) {
1996
            my $studyExtentDescription = $node->textContent();
1997
            $$templateVars{'studyExtentDescription'} = $studyExtentDescription;
1998 2148 sgarg
1999
	    $$templateVars{'hasMethod'} = "true";
2000 1989 jones
        }
2001
    }
2002
2003
    $results = $doc->findnodes(
2004
            '//dataset/methods/sampling/samplingDescription/para');
2005
    if ($results->size() > 1) {
2006
        errMoreThanN("methods/sampling/samplingDescription/para");
2007
    } else {
2008
        foreach $node ($results->get_nodelist) {
2009
            my $samplingDescription = $node->textContent();
2010
            $$templateVars{'samplingDescription'} = $samplingDescription;
2011 2148 sgarg
2012
	    $$templateVars{'hasMethod'} = "true";
2013 1989 jones
        }
2014
    }
2015
2016
    dontOccur($doc, "//methodStep/citation", "methodStep/citation");
2017
    dontOccur($doc, "//methodStep/protocol", "methodStep/protocol");
2018
    dontOccur($doc, "//methodStep/instrumentation", "methodStep/instrumentation");
2019
    dontOccur($doc, "//methodStep/software", "methodStep/software");
2020
    dontOccur($doc, "//methodStep/subStep", "methodStep/subStep");
2021
    dontOccur($doc, "//methodStep/dataSource", "methodStep/dataSource");
2022
    dontOccur($doc, "//methods/qualityControl", "methods/qualityControl");
2023
2024
    dontOccur($doc, "//methods/sampling/spatialSamplingUnits", "methods/sampling/spatialSamplingUnits");
2025
    dontOccur($doc, "//methods/sampling/citation", "methods/sampling/citation");
2026 1929 brooke
    dontOccur($doc, "./pubPlace", "pubPlace");
2027
    dontOccur($doc, "./project", "project");
2028
2029
    dontOccur($doc, "./dataTable", "dataTable");
2030
    dontOccur($doc, "./spatialRaster", "spatialRaster");
2031
    dontOccur($doc, "./spatialVector", "spatialVector");
2032
    dontOccur($doc, "./storedProcedure", "storedProcedure");
2033
    dontOccur($doc, "./view", "view");
2034
    dontOccur($doc, "./otherEntity", "otherEntity");
2035
    dontOccur($doc, "./references", "references");
2036
2037
    dontOccur($doc, "//citation", "citation");
2038
    dontOccur($doc, "//software", "software");
2039
    dontOccur($doc, "//protocol", "protocol");
2040
    dontOccur($doc, "//additionalMetadata", "additionalMetadata");
2041
}
2042
2043
################################################################################
2044
#
2045
# Delete the eml file that has been requested for deletion.
2046
#
2047
################################################################################
2048
sub deleteData {
2049
    my $deleteAll = shift;
2050
2051
    # create metacat instance
2052
    my $metacat;
2053
    my $docid = $FORM::docid;
2054
2055
    $metacat = Metacat->new();
2056
    if ($metacat) {
2057
        $metacat->set_options( metacatUrl => $metacatUrl );
2058
    } else {
2059
        #die "failed during metacat creation\n";
2060
        push(@errorMessages, "Failed during metacat creation.");
2061
    }
2062
2063
    # Login to metacat
2064
    my $userDN = $FORM::username;
2065
    my $userOrg = $FORM::organization;
2066
    my $userPass = $FORM::password;
2067
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
2068
2069
    my $errorMessage = "";
2070
    my $response = $metacat->login($dname, $userPass);
2071
2072
    if (! $response) {
2073 1977 jones
    # Could not login
2074 1929 brooke
        push(@errorMessages, $metacat->getMessage());
2075
        push(@errorMessages, "Failed during login.\n");
2076
2077
    } else {
2078 1977 jones
    #Able to login - try to delete the file
2079 1929 brooke
2080 1977 jones
    my $parser;
2081
    my @fileArray;
2082
    my $httpMessage;
2083
    my $xmldoc;
2084
    my $doc;
2085
    my $pushDoc;
2086
    my $alreadyInArray;
2087
    my $findType;
2088 1929 brooke
        my $node;
2089 1977 jones
    my $response;
2090
    my $element;
2091 1929 brooke
2092 1977 jones
    push (@fileArray, $docid);
2093
    $parser = XML::LibXML->new();
2094 1929 brooke
2095
        $httpMessage = $metacat->read($docid);
2096 1977 jones
    $doc = $httpMessage->content();
2097
    $xmldoc = $parser->parse_string($doc);
2098 1929 brooke
2099 1977 jones
    if ($xmldoc eq "") {
2100
        $error ="Error in parsing the eml document";
2101
        push(@errorMessages, $error);
2102
    } else {
2103 1929 brooke
2104 1977 jones
        $findType = $xmldoc->findnodes('//dataset/identifier');
2105
        if($findType->size() > 0){
2106
        # This is a eml beta6 document
2107
        # Delete the documents mentioned in triples also
2108
2109
        $findType = $xmldoc->findnodes('//dataset/triple');
2110
        if($findType->size() > 0){
2111
            foreach $node ($findType->get_nodelist){
2112
            $pushDoc = findValue($node, 'subject');
2113
2114
            # If the file is already in the @fileArray then do not add it
2115
            $alreadyInArray = 0;
2116
            foreach $element (@fileArray){
2117
                if($element eq $pushDoc){
2118
                $alreadyInArray = 1;
2119
                }
2120
            }
2121
2122
            if(!$alreadyInArray){
2123
                # If not already in array then delete the file.
2124
                push (@fileArray, $pushDoc);
2125
                $response = $metacat->delete($pushDoc);
2126
2127
                if (! $response) {
2128
                # Could not delete
2129
                #push(@errorMessages, $response);
2130
                push(@errorMessages, $metacat->getMessage());
2131
                push(@errorMessages, "Failed during deleting $pushDoc. Please check if you are authorized to delete this document.\n");
2132
                }
2133
            }
2134
            }
2135
        }
2136
        }
2137 1929 brooke
    }
2138
2139 1977 jones
    # Delete the main document.
2140
    if($deleteAll){
2141
        $response = $metacat->delete($docid);
2142
        if (! $response) {
2143
        # Could not delete
2144
        #push(@errorMessages, $response);
2145
        push(@errorMessages, $metacat->getMessage());
2146
        push(@errorMessages, "Failed during deleting $docid. Please check if you are authorized to delete this document.\n");
2147
        }
2148
    }
2149
    }
2150
2151 1929 brooke
    if (scalar(@errorMessages)) {
2152 1977 jones
    # If any errors, print them in the response template
2153
    $$templateVars{'status'} = 'failure';
2154
    $$templateVars{'errorMessages'} = \@errorMessages;
2155
    $error = 1;
2156 1929 brooke
    }
2157
2158
    # Process the response template
2159
    if($deleteAll){
2160
2161 1977 jones
    $$templateVars{'function'} = "deleted";
2162
    $$templateVars{'section'} = "Deletion Status";
2163
    $template->process( $responseTemplate, $templateVars);
2164 1929 brooke
    }
2165
}
2166
2167
2168
################################################################################
2169
#
2170
# Do data validation and send the data to confirm data template.
2171
#
2172
################################################################################
2173
sub toConfirmData{
2174
    # Check if any invalid parameters
2175
2176
    my $invalidParams;
2177
    if (! $error) {
2178 1977 jones
    $invalidParams = validateParameters(0);
2179
    if (scalar(@$invalidParams)) {
2180
        $$templateVars{'status'} = 'failure';
2181
        $$templateVars{'invalidParams'} = $invalidParams;
2182
        $error = 1;
2183 1929 brooke
    }
2184 1977 jones
    }
2185 1929 brooke
2186
2187 2037 sgarg
    $$templateVars{'providerGivenName'} = normalizeCD($FORM::providerGivenName);
2188
    $$templateVars{'providerSurName'} = normalizeCD($FORM::providerSurName);
2189 1977 jones
    if($FORM::site eq "Select your station here."){
2190
        $$templateVars{'site'} = "";
2191
    }else{
2192
        $$templateVars{'site'} = $FORM::site;
2193
    }
2194
    if($FORM::cfg eq "nceas"){
2195
        $$templateVars{'wg'} = \@FORM::wg;
2196
    }
2197 2037 sgarg
    $$templateVars{'identifier'} = normalizeCD($FORM::identifier);
2198
    $$templateVars{'title'} = normalizeCD($FORM::title);
2199
    $$templateVars{'origNamefirst0'} = normalizeCD($FORM::origNamefirst0);
2200
    $$templateVars{'origNamelast0'} = normalizeCD($FORM::origNamelast0);
2201
    $$templateVars{'origNameOrg'} = normalizeCD($FORM::origNameOrg);
2202 1977 jones
    # $$templateVars{'origRole0'} = $FORM::origRole0;
2203 2037 sgarg
    $$templateVars{'origDelivery'} = normalizeCD($FORM::origDelivery);
2204
    $$templateVars{'origCity'} = normalizeCD($FORM::origCity);
2205 1977 jones
    if($FORM::origState eq "Select State Here."){
2206
        $$templateVars{'origState'} = "";
2207
    }else{
2208
        $$templateVars{'origState'} = $FORM::origState;
2209
    }
2210 2037 sgarg
    $$templateVars{'origStateOther'} = normalizeCD($FORM::origStateOther);
2211
    $$templateVars{'origZIP'} = normalizeCD($FORM::origZIP);
2212
    $$templateVars{'origCountry'} = normalizeCD($FORM::origCountry);
2213
    $$templateVars{'origPhone'} = normalizeCD($FORM::origPhone);
2214
    $$templateVars{'origFAX'} = normalizeCD($FORM::origFAX);
2215
    $$templateVars{'origEmail'} = normalizeCD($FORM::origEmail);
2216
    $$templateVars{'useOrigAddress'} = normalizeCD($FORM::useOrigAddress);
2217 1977 jones
    if($FORM::useOrigAddress eq "on"){
2218 2037 sgarg
        $$templateVars{'origNamefirstContact'} = normalizeCD($FORM::origNamefirst0);
2219
        $$templateVars{'origNamelastContact'} = normalizeCD($FORM::origNamelast0);
2220
        $$templateVars{'origNameOrgContact'} = normalizeCD($FORM::origNameOrg);
2221
        $$templateVars{'origDeliveryContact'} = normalizeCD($FORM::origDelivery);
2222
        $$templateVars{'origCityContact'} = normalizeCD($FORM::origCity);
2223 1977 jones
        if($FORM::origState eq "Select State Here."){
2224
        $$templateVars{'origStateContact'} = "";
2225
        }else{
2226
        $$templateVars{'origStateContact'} = $FORM::origState;
2227
        }
2228 2037 sgarg
        $$templateVars{'origStateOtherContact'} = normalizeCD($FORM::origStateOther);
2229
        $$templateVars{'origZIPContact'} = normalizeCD($FORM::origZIP);
2230
        $$templateVars{'origCountryContact'} = normalizeCD($FORM::origCountry);
2231
        $$templateVars{'origPhoneContact'} = normalizeCD($FORM::origPhone);
2232
        $$templateVars{'origFAXContact'} = normalizeCD($FORM::origFAX);
2233
        $$templateVars{'origEmailContact'} = normalizeCD($FORM::origEmail);
2234 1977 jones
    }else{
2235 2037 sgarg
        $$templateVars{'origNamefirstContact'} = normalizeCD($FORM::origNamefirstContact);
2236
        $$templateVars{'origNamelastContact'} = normalizeCD($FORM::origNamelastContact);
2237
        $$templateVars{'origNameOrgContact'} = normalizeCD($FORM::origNameOrgContact);
2238
        $$templateVars{'origDeliveryContact'} = normalizeCD($FORM::origDeliveryContact);
2239
        $$templateVars{'origCityContact'} = normalizeCD($FORM::origCityContact);
2240 1977 jones
        if($FORM::origStateContact eq "Select State Here."){
2241
        $$templateVars{'origStateContact'} = "";
2242
        }else{
2243
        $$templateVars{'origStateContact'} = $FORM::origStateContact;
2244
        }
2245 2037 sgarg
        $$templateVars{'origStateOtherContact'} = normalizeCD($FORM::origStateOtherContact);
2246
        $$templateVars{'origZIPContact'} = normalizeCD($FORM::origZIPContact);
2247
        $$templateVars{'origCountryContact'} = normalizeCD($FORM::origCountryContact);
2248
        $$templateVars{'origPhoneContact'} = normalizeCD($FORM::origPhoneContact);
2249
        $$templateVars{'origFAXContact'} = normalizeCD($FORM::origFAXContact);
2250
        $$templateVars{'origEmailContact'} = normalizeCD($FORM::origEmailContact);
2251 1977 jones
    }
2252 2144 sgarg
2253
    $$templateVars{'aoCount'} = $FORM::aoCount;
2254
    foreach my $origName (param()) {
2255
	if ($origName =~ /origNamefirst/) {
2256
	    my $origNameIndex = $origName;
2257
	    $origNameIndex =~ s/origNamefirst//; # get the index of the parameter 0, ..., 10
2258
	    my $origNamelast = "origNamelast".$origNameIndex;
2259
	    my $origRole = "origRole".$origNameIndex;
2260
	    if ( $origNameIndex =~ /[0-9]/  && $origNameIndex > 0){
2261
		if (hasContent(param($origName)) && hasContent(param($origNamelast)) && hasContent(param($origRole))) {
2262
		    debug("Registry processing keyword: $origName = ".param($origName)." $origNamelast = ".param($origNamelast)." $origRole = ".param($origRole));
2263
		    $$templateVars{$origName} = normalizeCD(param($origName));
2264
		    $$templateVars{$origNamelast} = normalizeCD(param($origNamelast));
2265
		    $$templateVars{$origRole} = normalizeCD(param($origRole));
2266
		}
2267
	    }
2268
	}
2269 1977 jones
    }
2270 2144 sgarg
2271 2037 sgarg
    $$templateVars{'abstract'} = normalizeCD($FORM::abstract);
2272 2028 sgarg
    $$templateVars{'keyCount'} = $FORM::keyCount;
2273
    foreach my $kyd (param()) {
2274
	if ($kyd =~ /keyword/) {
2275
	    my $keyIndex = $kyd;
2276
	    $keyIndex =~ s/keyword//; # get the index of the parameter 0, ..., 10
2277
	    my $keyType = "kwType".$keyIndex;
2278
	    my $keyTh = "kwTh".$keyIndex;
2279
	    if ( $keyIndex =~ /[0-9]/ ){
2280
		if (hasContent(param($kyd)) && hasContent(param($keyType)) && hasContent(param($keyTh))) {
2281
		    debug("Registry processing keyword: $kyd = ".param($kyd)." $keyType = ".param($keyType)." $keyTh = ".param($keyTh));
2282 2037 sgarg
		    $$templateVars{$kyd} = normalizeCD(param($kyd));
2283 2028 sgarg
		    $$templateVars{$keyType} = param($keyType);
2284
		    $$templateVars{$keyTh} = param($keyTh);
2285
		}
2286
	    }
2287
	}
2288
    }
2289 2037 sgarg
    $$templateVars{'addComments'} = normalizeCD($FORM::addComments);
2290 1977 jones
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2291
    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2292
    $$templateVars{'url'} = $FORM::url;
2293
    if($FORM::dataMedium eq "Select type of medium here."){
2294
        $$templateVars{'dataMedium'} = "";
2295
    }else{
2296
        $$templateVars{'dataMedium'} = $FORM::dataMedium;
2297
    }
2298 2037 sgarg
    $$templateVars{'dataMediumOther'} = normalizeCD($FORM::dataMediumOther);
2299 1977 jones
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2300
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2301
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2302
    $$templateVars{'endingYear'} = $FORM::endingYear;
2303
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2304
    $$templateVars{'endingDay'} = $FORM::endingDay;
2305 2037 sgarg
    $$templateVars{'geogdesc'} = normalizeCD($FORM::geogdesc);
2306 1977 jones
    $$templateVars{'useSiteCoord'} = $FORM::useSiteCoord;
2307
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2308
    $$templateVars{'latMin1'} = $FORM::latMin1;
2309
    $$templateVars{'latSec1'} = $FORM::latSec1;
2310
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2311
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2312
    $$templateVars{'longMin1'} = $FORM::longMin1;
2313
    $$templateVars{'longSec1'} = $FORM::longSec1;
2314
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2315
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2316
    $$templateVars{'latMin2'} = $FORM::latMin2;
2317
    $$templateVars{'latSec2'} = $FORM::latSec2;
2318
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2319
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2320
    $$templateVars{'longMin2'} = $FORM::longMin2;
2321
    $$templateVars{'longSec2'} = $FORM::longSec2;
2322
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2323 1984 jones
2324
    $$templateVars{'taxaCount'} = $FORM::taxaCount;
2325
    foreach my $trn (param()) {
2326
        if ($trn =~ /taxonRankName/) {
2327
            my $taxIndex = $trn;
2328
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
2329
            my $trv = "taxonRankValue".$taxIndex;
2330
            if ( $taxIndex =~ /[0-9]/ ){
2331
                if (hasContent(param($trn)) && hasContent(param($trv))) {
2332
                    debug("Registry processing taxon: $trn = ".param($trn)." $trv = ".param($trv));
2333 2037 sgarg
                    $$templateVars{$trn} = normalizeCD(param($trn));
2334
                    $$templateVars{$trv} = normalizeCD(param($trv));
2335 1984 jones
                }
2336
            }
2337
        }
2338
    }
2339 2037 sgarg
    $$templateVars{'taxaAuth'} = normalizeCD($FORM::taxaAuth);
2340 1984 jones
2341 2037 sgarg
    $$templateVars{'methodTitle'} = normalizeCD($FORM::methodTitle);
2342
2343
    my @tempMethodPara;
2344
    for (my $i = 0; $i < scalar(@FORM::methodPara); $i++) {
2345
	$tempMethodPara[$i] = normalizeCD($FORM::methodPara[$i]);
2346
    }
2347
    $$templateVars{'methodPara'} = \@tempMethodPara;
2348
    $$templateVars{'studyExtentDescription'} = normalizeCD($FORM::studyExtentDescription);
2349
    $$templateVars{'samplingDescription'} = normalizeCD($FORM::samplingDescription);
2350 2138 sgarg
    $$templateVars{'origStateContact'} = $FORM::origState;
2351
2352
    $$templateVars{'hasKeyword'} = $FORM::hasKeyword;
2353 2148 sgarg
    $$templateVars{'hasTemporal'} = $FORM::hasTemporal;
2354
    $$templateVars{'hasSpatial'} = $FORM::hasSpatial;
2355
    $$templateVars{'hasTaxonomic'} = $FORM::hasTaxonomic;
2356
    $$templateVars{'hasMethod'} = $FORM::hasMethod;
2357
    $$templateVars{'spatialRequired'} = $FORM::spatialRequired;
2358
    $$templateVars{'temporalRequired'} = $FORM::temporalRequired;
2359
2360 1977 jones
    $$templateVars{'docid'} = $FORM::docid;
2361 1929 brooke
2362 2024 sgarg
    if (! $error) {
2363
	# If no errors, then print out data in confirm Data template
2364 1929 brooke
2365 2024 sgarg
	$$templateVars{'section'} = "Confirm Data";
2366
	$template->process( $confirmDataTemplate, $templateVars);
2367
2368 1977 jones
    } else{
2369
    # Errors from validation function. print the errors out using the response template
2370
    if (scalar(@errorMessages)) {
2371
        $$templateVars{'status'} = 'failure';
2372
        $$templateVars{'errorMessages'} = \@errorMessages;
2373
        $error = 1;
2374
    }
2375 1929 brooke
        # Create our HTML response and send it back
2376 1977 jones
    $$templateVars{'function'} = "submitted";
2377
    $$templateVars{'section'} = "Submission Status";
2378
    $template->process( $responseTemplate, $templateVars);
2379 1929 brooke
    }
2380
}
2381
2382
2383
################################################################################
2384
#
2385
# From confirm Data template - user wants to make some changes.
2386
#
2387
################################################################################
2388
sub confirmDataToReEntryData{
2389
    my @sortedSites;
2390
    foreach my $site (sort @sitelist) {
2391
        push(@sortedSites, $site);
2392
    }
2393
2394
    $$templateVars{'siteList'} = \@sortedSites;
2395
    $$templateVars{'section'} = "Re-Entry Form";
2396 2136 sgarg
    copyFormToTemplateVars();
2397
    $$templateVars{'docid'} = $FORM::docid;
2398 1929 brooke
2399 2136 sgarg
    $$templateVars{'form'} = 're_entry';
2400
    $template->process( $entryFormTemplate, $templateVars);
2401
}
2402
2403
2404
################################################################################
2405
#
2406
# Copy form data to templateVars.....
2407
#
2408
################################################################################
2409
sub copyFormToTemplateVars{
2410 1929 brooke
    $$templateVars{'providerGivenName'} = $FORM::providerGivenName;
2411
    $$templateVars{'providerSurName'} = $FORM::providerSurName;
2412
    $$templateVars{'site'} = $FORM::site;
2413 1982 jones
    if ($FORM::cfg eq "nceas") {
2414 1977 jones
        my $projects = getProjectList();
2415
        $$templateVars{'projects'} = $projects;
2416
        $$templateVars{'wg'} = \@FORM::wg;
2417
    }
2418 1929 brooke
    $$templateVars{'identifier'} = $FORM::identifier;
2419
    $$templateVars{'title'} = $FORM::title;
2420
    $$templateVars{'origNamefirst0'} = $FORM::origNamefirst0;
2421
    $$templateVars{'origNamelast0'} = $FORM::origNamelast0;
2422
    $$templateVars{'origNameOrg'} = $FORM::origNameOrg;
2423
 #   $$templateVars{'origRole0'} = $FORM::origRole0;
2424
    $$templateVars{'origDelivery'} = $FORM::origDelivery;
2425
    $$templateVars{'origCity'} = $FORM::origCity;
2426
    $$templateVars{'origState'} = $FORM::origState;
2427
    $$templateVars{'origStateOther'} = $FORM::origStateOther;
2428
    $$templateVars{'origZIP'} = $FORM::origZIP;
2429
    $$templateVars{'origCountry'} = $FORM::origCountry;
2430
    $$templateVars{'origPhone'} = $FORM::origPhone;
2431
    $$templateVars{'origFAX'} = $FORM::origFAX;
2432
    $$templateVars{'origEmail'} = $FORM::origEmail;
2433 1977 jones
    if ($FORM::useSiteCoord ne "") {
2434
        $$templateVars{'useOrigAddress'} = "CHECKED";
2435 1929 brooke
    }else{
2436 1977 jones
        $$templateVars{'useOrigAddress'} = $FORM::useOrigAddress;
2437 1929 brooke
    }
2438
    $$templateVars{'origNamefirstContact'} = $FORM::origNamefirstContact;
2439
    $$templateVars{'origNamelastContact'} = $FORM::origNamelastContact;
2440
    $$templateVars{'origNameOrgContact'} = $FORM::origNameOrgContact;
2441
    $$templateVars{'origDeliveryContact'} = $FORM::origDeliveryContact;
2442
    $$templateVars{'origCityContact'} = $FORM::origCityContact;
2443
    $$templateVars{'origStateContact'} = $FORM::origStateContact;
2444
    $$templateVars{'origStateOtherContact'} = $FORM::origStateOtherContact;
2445
    $$templateVars{'origZIPContact'} = $FORM::origZIPContact;
2446
    $$templateVars{'origCountryContact'} = $FORM::origCountryContact;
2447
    $$templateVars{'origPhoneContact'} = $FORM::origPhoneContact;
2448
    $$templateVars{'origFAXContact'} = $FORM::origFAXContact;
2449
    $$templateVars{'origEmailContact'} = $FORM::origEmailContact;
2450 2144 sgarg
2451
    $$templateVars{'aoCount'} = $FORM::aoCount;
2452
    foreach my $origName (param()) {
2453
	if ($origName =~ /origNamefirst/) {
2454
	    my $origNameIndex = $origName;
2455
	    $origNameIndex =~ s/origNamefirst//; # get the index of the parameter 0, ..., 10
2456
	    my $origNamelast = "origNamelast".$origNameIndex;
2457
	    my $origRole = "origRole".$origNameIndex;
2458
	    if ( $origNameIndex =~ /[0-9]/  && $origNameIndex > 0){
2459
		if (hasContent(param($origName)) && hasContent(param($origNamelast)) && hasContent(param($origRole))) {
2460
		    debug("Registry processing keyword: $origName = ".param($origName)." $origNamelast = ".param($origNamelast)." $origRole = ".param($origRole));
2461
		    $$templateVars{$origName} = normalizeCD(param($origName));
2462
		    $$templateVars{$origNamelast} = normalizeCD(param($origNamelast));
2463
		    $$templateVars{$origRole} = normalizeCD(param($origRole));
2464
		}
2465
	    }
2466
	}
2467
    }
2468
2469 1929 brooke
    $$templateVars{'abstract'} = $FORM::abstract;
2470 2028 sgarg
    $$templateVars{'keyCount'} = $FORM::keyCount;
2471
    foreach my $kyd (param()) {
2472
	if ($kyd =~ /keyword/) {
2473
	    my $keyIndex = $kyd;
2474
	    $keyIndex =~ s/keyword//; # get the index of the parameter 0, ..., 10
2475
	    my $keyType = "kwType".$keyIndex;
2476
	    my $keyTh = "kwTh".$keyIndex;
2477
	    if ( $keyIndex =~ /[0-9]/ ){
2478
		if (hasContent(param($kyd)) && hasContent(param($keyType)) && hasContent(param($keyTh))) {
2479
		    debug("Registry processing keyword: $kyd = ".param($kyd)." $keyType = ".param($keyType)." $keyTh = ".param($keyTh));
2480
		    $$templateVars{$kyd} = param($kyd);
2481
		    $$templateVars{$keyType} = param($keyType);
2482
		    $$templateVars{$keyTh} = param($keyTh);
2483
		}
2484
	    }
2485
	}
2486
    }
2487 1929 brooke
    $$templateVars{'addComments'} = $FORM::addComments;
2488
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2489
    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2490
    $$templateVars{'url'} = $FORM::url;
2491
    $$templateVars{'dataMedium'} = $FORM::dataMedium;
2492
    $$templateVars{'dataMediumOther'} = $FORM::dataMediumOther;
2493
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2494
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2495
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2496
    $$templateVars{'endingYear'} = $FORM::endingYear;
2497
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2498
    $$templateVars{'endingDay'} = $FORM::endingDay;
2499 1983 jones
    $$templateVars{'geogdesc'} = $FORM::geogdesc;
2500 1929 brooke
    if($FORM::useSiteCoord ne ""){
2501 1977 jones
    $$templateVars{'useSiteCoord'} = "CHECKED";
2502 1929 brooke
    }else{
2503 1977 jones
    $$templateVars{'useSiteCoord'} = "";
2504 1929 brooke
    }
2505
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2506
    $$templateVars{'latMin1'} = $FORM::latMin1;
2507
    $$templateVars{'latSec1'} = $FORM::latSec1;
2508
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2509
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2510
    $$templateVars{'longMin1'} = $FORM::longMin1;
2511
    $$templateVars{'longSec1'} = $FORM::longSec1;
2512
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2513
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2514
    $$templateVars{'latMin2'} = $FORM::latMin2;
2515
    $$templateVars{'latSec2'} = $FORM::latSec2;
2516
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2517
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2518
    $$templateVars{'longMin2'} = $FORM::longMin2;
2519
    $$templateVars{'longSec2'} = $FORM::longSec2;
2520
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2521 1985 jones
    $$templateVars{'taxaCount'} = $FORM::taxaCount;
2522
    foreach my $trn (param()) {
2523
        if ($trn =~ /taxonRankName/) {
2524
            my $taxIndex = $trn;
2525
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
2526
            my $trv = "taxonRankValue".$taxIndex;
2527
            if ( $taxIndex =~ /[0-9]/ ){
2528
                if (hasContent(param($trn)) && hasContent(param($trv))) {
2529
                    debug("Registry processing taxon: $trn = ".param($trn)." $trv = ".param($trv));
2530
                    $$templateVars{$trn} = param($trn);
2531
                    $$templateVars{$trv} = param($trv);
2532
                }
2533
            }
2534
        }
2535 1982 jones
    }
2536 1985 jones
    $$templateVars{'taxaAuth'} = $FORM::taxaAuth;
2537
    $$templateVars{'methodTitle'} = $FORM::methodTitle;
2538
    $$templateVars{'methodPara'} = \@FORM::methodPara;
2539 1989 jones
    $$templateVars{'studyExtentDescription'} = $FORM::studyExtentDescription;
2540
    $$templateVars{'samplingDescription'} = $FORM::samplingDescription;
2541 2138 sgarg
2542 2148 sgarg
    $$templateVars{'hasKeyword'} = $FORM::hasKeyword;
2543
    $$templateVars{'hasTemporal'} = $FORM::hasTemporal;
2544
    $$templateVars{'hasSpatial'} = $FORM::hasSpatial;
2545
    $$templateVars{'hasTaxonomic'} = $FORM::hasTaxonomic;
2546
    $$templateVars{'hasMethod'} = $FORM::hasMethod;
2547
    $$templateVars{'spatialRequired'} = $FORM::spatialRequired;
2548
    $$templateVars{'temporalRequired'} = $FORM::temporalRequired;
2549 1929 brooke
}
2550
2551
################################################################################
2552
#
2553
# check if there is multiple occurence of the given tag and find its value.
2554
#
2555
################################################################################
2556
2557
sub findValue {
2558
    my $node = shift;
2559
    my $value = shift;
2560
    my $result;
2561
    my $tempNode;
2562
2563
    $result = $node->findnodes("./$value");
2564 1977 jones
    if ($result->size > 1) {
2565
        errMoreThanOne("$value");
2566 1929 brooke
    } else {
2567 1977 jones
        foreach $tempNode ($result->get_nodelist){
2568
            #print $tempNode->nodeName().":".$tempNode->textContent();
2569
            #print "\n";
2570
            return $tempNode->textContent();
2571
        }
2572 1929 brooke
    }
2573
}
2574
2575
2576
################################################################################
2577
#
2578
# check if given tags has any children. if not return the value
2579
#
2580
################################################################################
2581
sub findValueNoChild {
2582
    my $node = shift;
2583
    my $value = shift;
2584
    my $tempNode;
2585
    my $childNodes;
2586
    my $result;
2587
    my $error;
2588
2589
    $result = $node->findnodes("./$value");
2590 1977 jones
    if($result->size > 1){
2591
       errMoreThanOne("$value");
2592
    } else {
2593
        foreach $tempNode ($result->get_nodelist) {
2594
            $childNodes = $tempNode->childNodes;
2595
            if ($childNodes->size() > 1) {
2596
                $error ="The tag $value has children which cannot be shown using the form. Please use Morpho to edit this document";
2597
                push(@errorMessages, $error);
2598
                #if ($DEBUG == 1){ print $error."\n";}
2599
            } else {
2600
                #print $tempNode->nodeName().":".$tempNode->textContent();
2601
                #print "\n";
2602
                return $tempNode->textContent();
2603
            }
2604
        }
2605
    }
2606 1929 brooke
}
2607
2608
2609
################################################################################
2610
#
2611
# check if given tags are children of given node.
2612
#
2613
################################################################################
2614
sub dontOccur {
2615
    my $node = shift;
2616
    my $value = shift;
2617
    my $errVal = shift;
2618
2619
    my $result = $node->findnodes("$value");
2620
    if($result->size > 0){
2621 1977 jones
        $error ="One of the following tags found: $errVal. Please use Morpho to edit this document";
2622
        push(@errorMessages, $error."\n");
2623
        #if ($DEBUG == 1){ print $error;}
2624 1929 brooke
    }
2625
}
2626
2627
2628
################################################################################
2629
#
2630
# print out error for more than one occurence of a given tag
2631
#
2632
################################################################################
2633
sub errMoreThanOne {
2634
    my $value = shift;
2635
    my $error ="More than one occurence of the tag $value found. Please use Morpho to edit this document";
2636
    push(@errorMessages, $error."\n");
2637
    # if ($DEBUG == 1){ print $error;}
2638
}
2639
2640
2641
################################################################################
2642
#
2643
# print out error for more than given number of occurences of a given tag
2644
#
2645
################################################################################
2646
sub errMoreThanN {
2647
    my $value = shift;
2648
    my $error ="More occurences of the tag $value found than that can be shown in the form. Please use Morpho to edit this document";
2649
    push(@errorMessages, $error);
2650
    #if ($DEBUG == 1){ print $error."\n";}
2651
}
2652
2653
2654
################################################################################
2655
#
2656
# convert coord to degrees, minutes and seconds form.
2657
#
2658
################################################################################
2659
#sub convertCoord {
2660
#    my $wx = shift;
2661
#    print $deg." ".$min." ".$sec;
2662
#    print "\n";
2663
#}
2664
2665
2666 1955 jones
################################################################################
2667
#
2668
# print debugging messages to stderr
2669
#
2670
################################################################################
2671
sub debug {
2672
    my $msg = shift;
2673
2674
    if ($debug) {
2675
        print STDERR "$msg\n";
2676
    }
2677
}
2678 1973 jones
2679
################################################################################
2680
#
2681
# get the list of projects
2682
#
2683
################################################################################
2684
sub getProjectList {
2685
2686 1993 jones
    use NCEAS::AdminDB;
2687
    my $admindb = NCEAS::AdminDB->new();
2688
    $admindb->connect($nceas_db, $nceas_db_user, $nceas_db_password);
2689
    my $projects = $admindb->getProjects();
2690
    #my $projects = getTestProjectList();
2691
    return $projects;
2692
}
2693 1973 jones
2694 1993 jones
################################################################################
2695
#
2696
# get a test list of projects for use only in testing where the NCEAS
2697
# admin db is not available.
2698
#
2699
################################################################################
2700
sub getTestProjectList {
2701 1973 jones
    # This block is for testing only!  Remove for production use
2702
    my @row1;
2703 1974 jones
    $row1[0] = 6000; $row1[1] = 'Andelman'; $row1[2] = 'Sandy'; $row1[3] = 'The very long and windy path to an apparent ecological conclusion: statistics lie';
2704 1973 jones
    my @row2;
2705 1974 jones
    $row2[0] = 7000; $row2[1] = 'Bascompte'; $row2[2] = 'Jordi'; $row2[3] = 'Postdoctoral Fellow';
2706 1980 jones
    my @row3;
2707
    $row3[0] = 7001; $row3[1] = 'Hackett'; $row3[2] = 'Edward'; $row3[3] = 'Sociology rules the world';
2708
    my @row4;
2709
    $row4[0] = 7002; $row4[1] = 'Jones'; $row4[2] = 'Matthew'; $row4[3] = 'Informatics rules the world';
2710
    my @row5;
2711
    $row5[0] = 7003; $row5[1] = 'Schildhauer'; $row5[2] = 'Mark'; $row5[3] = 'Excel rocks my world, assuming a, b, and c';
2712
    my @row6;
2713
    $row6[0] = 7004; $row6[1] = 'Rogers'; $row6[2] = 'Bill'; $row6[3] = 'Graduate Intern';
2714
    my @row7;
2715
    $row7[0] = 7005; $row7[1] = 'Zedfried'; $row7[2] = 'Karl'; $row7[3] = 'A multivariate analysis of thing that go bump in the night';
2716 1973 jones
    my @projects;
2717
    $projects[0] = \@row1;
2718
    $projects[1] = \@row2;
2719 1980 jones
    $projects[2] = \@row3;
2720
    $projects[3] = \@row4;
2721
    $projects[4] = \@row5;
2722
    $projects[5] = \@row6;
2723
    $projects[6] = \@row7;
2724 1973 jones
    return \@projects;
2725
}