Project

General

Profile

1
#!/usr/bin/perl
2
#
3
#  '$RCSfile$'
4
#  Copyright: 2000 Regents of the University of California 
5
#
6
#   '$Author: sgarg $'
7
#     '$Date: 2004-12-16 14:33:10 -0800 (Thu, 16 Dec 2004) $'
8
# '$Revision: 2334 $' 
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
$config->define("showSiteList", { DEFAULT => 'true'} );
76
$config->define("lsite", { DEFAULT => 'station'} );
77
$config->define("usite", { DEFAULT => 'Station'} );
78
$config->define("showWgList", { DEFAULT => 'true'} );
79
$config->define("showOrganization", { DEFAULT => 'true'} );
80
$config->define("hasKeyword", { DEFAULT => 'true'} );
81
$config->define("hasTemporal", { DEFAULT => 'true'} );
82
$config->define("hasSpatial", { DEFAULT => 'true'} );
83
$config->define("hasTaxonomic", { DEFAULT => 'true'} );
84
$config->define("hasMethod", { DEFAULT => 'true'} );
85
$config->define("temporalRequired", { DEFAULT => 'true'} );
86
$config->define("spatialRequired", { DEFAULT => 'true'} );
87
$config->define("mailhost");
88
$config->define("sender");
89
$config->define("recipient");
90
$config->define("adminname");
91
if ($FORM::cfg eq 'nceas') {
92
    $config->define("nceas_db");
93
    $config->define("nceas_db_user");
94
    $config->define("nceas_db_password");
95
}
96
$config->define("responseTemplate", { DEFAULT => 'crap.tmpl'} );
97
$config->define("entryFormTemplate", { DEFAULT => 'crap.tmpl'} );
98
$config->define("guideTemplate", { DEFAULT => 'crap.tmpl'} );
99
$config->define("confirmDataTemplate", { DEFAULT => 'crap.tmpl'} );
100
$config->define("deleteDataTemplate", { DEFAULT => 'crap.tmpl'} );
101
$config->define("debug", { DEFAULT => '0'} );
102
$config->define("lat", { ARGCOUNT => ARGCOUNT_HASH} );
103
$config->define("lon", { ARGCOUNT => ARGCOUNT_HASH} );
104

    
105
if (! hasContent($FORM::cfg)) {
106
    $error = "Application misconfigured.  Please contact the administrator.";
107
    push(@errorMessages, $error);
108
} else {
109
    my $cfgfile = $cfgdir . "/" . $FORM::cfg . "/" . $FORM::cfg . ".cfg";
110
    $config->file($cfgfile);
111
}
112

    
113
my $metacatUrl = $config->metacatUrl();
114
my $username = $config->username();
115
my $password = $config->password();
116
my $ldapUrl = $config->ldapUrl();
117
my $defaultScope = $config->defaultScope();
118
my $organization = $config->organization();
119
my $orgabbrev = $config->orgabbrev();
120
my $orgurl = $config->orgurl();
121
my $orgfilter = $organization;
122
      $orgfilter =~ s/ /%20/g;
123
my $responseTemplate = $config->responseTemplate();
124
my $entryFormTemplate = $config->entryFormTemplate();
125
my $deleteDataTemplate = $config->deleteDataTemplate();
126
my $guideTemplate = $config->guideTemplate();
127
my $confirmDataTemplate = $config->confirmDataTemplate();
128
my $accesspubid = $config->accesspubid();
129
my $accesssysid = $config->accesssysid();
130
my $datasetpubid = $config->datasetpubid();
131
my $datasetsysid = $config->datasetsysid();
132
my $showSiteList = $config->showSiteList();
133
my $lsite = $config->lsite();
134
my $usite = $config->usite();
135
my $showWgList = $config->showWgList();
136
my $showOrganization = $config->showOrganization();
137
my $hasKeyword = $config->hasKeyword();
138
my $hasTemporal = $config->hasTemporal();
139
my $hasSpatial = $config->hasSpatial();
140
my $hasTaxonomic = $config->hasTaxonomic();
141
my $hasMethod = $config->hasMethod();
142
my $temporalRequired = $config->temporalRequired();
143
my $spatialRequired = $config->spatialRequired();
144
my $mailhost = $config->mailhost();
145
my $sender = $config->sender();
146
my $recipient = $config->recipient();
147
my $adminname = $config->adminname();
148
my $nceas_db;
149
my $nceas_db_user;
150
my $nceas_db_password;
151
if ($FORM::cfg eq 'nceas') {
152
    $nceas_db = $config->nceas_db();
153
    $nceas_db_user = $config->nceas_db_user();
154
    $nceas_db_password = $config->nceas_db_password();
155
}
156
my $debug = $config->debug();
157
my $lat = $config->get('lat');
158
my $lon = $config->get('lon');
159

    
160
# Convert the lat and lon configs into usable data structures
161
my @sitelist;
162
my %siteLatDMS;
163
my %siteLongDMS;
164
foreach my $newsite (keys %$lat) {
165
    my ($latd, $latm, $lats, $latdir) = split(':', $lat->{$newsite});
166
    my ($lond, $lonm, $lons, $londir) = split(':', $lon->{$newsite});
167
    push(@sitelist, $newsite);
168
    $siteLatDMS{$newsite} = [ $latd, $latm, $lats, $latdir ];
169
    $siteLongDMS{$newsite} = [ $lond, $lonm, $lons, $londir ];
170
}
171

    
172
# set some configuration options for the template object
173
my $ttConfig = {
174
             INCLUDE_PATH => $templatesdir, 
175
             INTERPOLATE  => 0,                    
176
             POST_CHOMP   => 1,                   
177
             };
178

    
179
# create an instance of the template processor
180
my $template = Template->new($ttConfig) || die $Template::ERROR, "\n";
181

    
182
print "Content-type: text/html\n\n";
183

    
184
# Set up the template information that is common to all forms
185
$$templateVars{'cfg'} = $FORM::cfg;
186
$$templateVars{'recipient'} = $recipient;
187
$$templateVars{'adminname'} = $adminname;
188
$$templateVars{'organization'} = $organization;
189
$$templateVars{'orgabbrev'} = $orgabbrev;
190
$$templateVars{'orgurl'} = $orgurl;
191
$$templateVars{'orgfilter'} = $orgfilter;
192

    
193
debug("Registry: Initialized");
194
# Process the form based on stage parameter. 
195
if ($FORM::stage =~ "guide") {
196
    # Send back the information on how to fill the form
197
    $$templateVars{'section'} = "Guide on How to Complete Registry Entries";
198
    $template->process( $guideTemplate, $templateVars);
199
    exit(0);
200

    
201
} elsif ($FORM::stage =~ "insert") {
202
    # The user has entered the data. Do data validation and send back data 
203
    # to confirm the data that has been entered. 
204
    toConfirmData();
205
    exit(0);
206

    
207
}elsif ($FORM::dataWrong =~ "No, go back to editing" && $FORM::stage =~ "confirmed") {
208
    # The user wants to correct the data that he has entered. 
209
    # Hence show the data again in entryData form. 
210
    confirmDataToReEntryData();
211
    exit(0);
212

    
213
}elsif ($FORM::stage =~ "modify") {
214
    # Modification of a file has been requested. 
215
    # Show the form will all the values filled in.
216
    my @sortedSites;
217
    foreach my $site (sort @sitelist) {
218
        push(@sortedSites, $site);
219
    }
220
    $$templateVars{'siteList'} = \@sortedSites;
221
    $$templateVars{'section'} = "Modification Form";
222
    $$templateVars{'docid'} = $FORM::docid;
223
    modifyData();
224
    exit(0);
225

    
226
}elsif ($FORM::stage =~ "delete_confirm") {
227

    
228
    # Result from deleteData form. 
229
    if($FORM::deleteData =~ "Delete data"){
230
    # delete Data
231
    deleteData(1);    
232
    exit(0);
233
    } else {
234
    # go back to search page. 
235
    exit(0);
236
    }
237

    
238
}elsif ($FORM::stage =~ "delete") {
239
    # Deletion of a file has been requested. 
240
    # Ask for username and password using deleteDataForm
241
    $$templateVars{'docid'} = $FORM::docid;
242
    $template->process( $deleteDataTemplate, $templateVars);
243
    exit(0);
244

    
245
}elsif ($FORM::stage !~ "confirmed") {
246
    # None of the stages have been reached and data is not being confirmed. 
247
    # Hence, send back entry form for entry of data.  
248
    debug("Registry: Sending form");
249
    my @sortedSites;
250
    foreach my $site (sort @sitelist) {
251
        push(@sortedSites, $site);
252
    }
253
    
254
    if ($FORM::cfg eq 'nceas') {
255
        my $projects = getProjectList();
256
        $$templateVars{'projects'} = $projects;
257
        $$templateVars{'wg'} = \@FORM::wg;
258
    }
259

    
260
    $$templateVars{'showSiteList'} = $showSiteList;
261
    $$templateVars{'lsite'} = $lsite;
262
    $$templateVars{'usite'} = $usite;
263
    $$templateVars{'showWgList'} = $showWgList;
264
    $$templateVars{'showOrganization'} = $showOrganization;
265
    $$templateVars{'hasKeyword'} = $hasKeyword;
266
    $$templateVars{'hasTemporal'} = $hasTemporal;
267
    $$templateVars{'hasSpatial'} = $hasSpatial;
268
    $$templateVars{'hasTaxonomic'} = $hasTaxonomic;
269
    $$templateVars{'hasMethod'} = $hasMethod;
270
    $$templateVars{'temporalRequired'} = $temporalRequired;
271
    $$templateVars{'spatialRequired'} = $spatialRequired;
272

    
273
    $$templateVars{'siteList'} = \@sortedSites;
274
    $$templateVars{'section'} = "Entry Form";
275
    $$templateVars{'docid'} = "";
276
    debug("Registry: Sending form: ready to process template");
277
    $template->process( $entryFormTemplate, $templateVars);
278
    debug("Registry: Sending form: template processed");
279
    exit(0);
280
}
281

    
282
# Confirm stage has been reached. Enter the data into metacat. 
283

    
284
# Initialize some global vars
285
my $latDeg1 = "";
286
my $latMin1 = "";
287
my $latSec1 = "";
288
my $hemisphLat1 = "";
289
my $longDeg1 = "";
290
my $longMin1 = "";
291
my $longSec1 = "";
292
my $hemisphLong1 = "";
293
my $latDeg2 = "";
294
my $latMin2 = "";
295
my $latSec2 = "";
296
my $hemisphLat2 = "";
297
my $longDeg2 = "";
298
my $longMin2 = "";
299
my $longSec2 = "";
300
my $hemisphLong2 = "";
301

    
302
# validate the input form parameters
303
my $invalidParams;
304

    
305
if (! $error) {
306
    $invalidParams = validateParameters(1);
307
    if (scalar(@$invalidParams)) {
308
        $$templateVars{'status'} = 'failure';
309
        $$templateVars{'invalidParams'} = $invalidParams;
310
        $error = 1;
311
    }
312
}
313

    
314

    
315
my $metacat;
316
my $docid;
317
if (! $error) {
318
    # Parameters have been validated and Create the XML document
319

    
320
    my $xmldoc = createXMLDocument();
321

    
322
    # Write out the XML file for debugging purposes
323
    #my $testFile = $tmpdir . "/test.xml";
324

    
325
    # Create a  metacat object
326
    $metacat = Metacat->new();
327
    if ($metacat) {
328
        $metacat->set_options( metacatUrl => $metacatUrl );
329
    } else {
330
        #die "failed during metacat creation\n";
331
        push(@errorMessages, "Failed during metacat creation.");
332
    }
333

    
334
    # Login to metacat
335
    my $userDN = $FORM::username;
336
    my $userOrg = $FORM::organization;
337
    my $userPass = $FORM::password;
338
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
339
    
340
    my $xmldocWithDocID = $xmldoc;
341
    
342
    my $errorMessage = "";
343
    my $response = $metacat->login($dname, $userPass);
344
    if (! $response) {
345
        push(@errorMessages, $metacat->getMessage());
346
        push(@errorMessages, "Failed during login.\n");
347
    }
348

    
349
    debug( "Registry: A");
350
    if ($FORM::docid eq "") {
351
        debug( "Registry: B1");
352
        # document is being inserted 
353
        my $notunique = "NOT_UNIQUE";
354
        while ($notunique eq "NOT_UNIQUE") {
355
            $docid = newAccessionNumber($defaultScope);
356
            
357
	    $xmldocWithDocID = $xmldoc;
358
            $xmldocWithDocID =~ s/docid/$docid/;
359

    
360
	    # Code for testing the xml file being inserted####
361
            #my $testFile = "/tmp/test.xml";
362
            #open (TFILE,">$testFile") || die ("Cant open xml file...\n");
363
            #print TFILE $xmldoc;
364
            #close(TFILE);
365
	    ####
366
    
367
            $notunique = insertMetadata($xmldocWithDocID, $docid);
368
            #  if (!$notunique) {
369
            # Write out the XML file for debugging purposes
370
            #my $testFile = $tmpdir . "/test-new.xml";
371
            #open (TFILE,">$testFile") || die ("Cant open xml file...\n");
372
            #print TFILE $newdoc;
373
            #close(TFILE);
374
            #   }
375

    
376
            # The id wasn't unique, so update our lastid file
377
            if ($notunique eq "NOT_UNIQUE") {
378
                debug( "Registry: Updating lastid (B1.1)");
379
                updateLastId($defaultScope);
380
            }
381
        }
382
        debug("Registry: B2");
383
        if ($notunique ne "SUCCESS") {
384
            debug("Registry: NO SUCCESS");
385
            debug("Message is: $notunique");
386
            push(@errorMessages, $notunique);
387
        }
388

    
389
        debug("Registry: B3");
390
    } else {
391
        # document is being modified
392
        $docid = $FORM::docid;
393
    
394
        my $x;
395
        my $y;
396
        my $z;
397

    
398
        ($x, $y, $z) = split(/\./, $docid); 
399
        $z++;
400
        $docid = "$x.$y.$z";
401
    
402
        $xmldoc =~ s/docid/$docid/;
403
        
404
        my $response = $metacat->update($docid, $xmldoc);
405

    
406
        if (! $response) {
407
            push(@errorMessages, $metacat->getMessage());
408
            push(@errorMessages, "Failed while updating.\n");  
409
        }
410

    
411
        if (scalar(@errorMessages)) {
412
            debug("Registry: ErrorMessages defined in modify.");
413

    
414
	    $$templateVars{'docid'} = $FORM::docid;
415
	    copyFormToTemplateVars();
416
            $$templateVars{'status'} = 'failure';
417
            $$templateVars{'errorMessages'} = \@errorMessages;
418
            $error = 1;
419
        } else {
420
	    $$templateVars{'docid'} = $docid;
421
	    $$templateVars{'cfg'} = $FORM::cfg;
422
	}
423

    
424
        #if (! $error) {
425
            #sendNotification($docid, $mailhost, $sender, $recipient);
426
        #}
427
    
428
        # Create our HTML response and send it back
429
        $$templateVars{'function'} = "modified";
430
        $$templateVars{'section'} = "Modification Status";
431
        $template->process( $responseTemplate, $templateVars);
432

    
433
        exit(0);
434
    }
435
}
436

    
437
debug("Registry: C");
438

    
439
if (scalar(@errorMessages)) {
440
    debug("Registry: ErrorMessages defined.");
441
    $$templateVars{'docid'} = $FORM::docid;
442
    copyFormToTemplateVars();
443
    $$templateVars{'status'} = 'failure';
444
    $$templateVars{'errorMessages'} = \@errorMessages;
445
    $error = 1;
446
} else {
447
    $$templateVars{'docid'} = $docid;
448
    $$templateVars{'cfg'} = $FORM::cfg;
449
}
450

    
451
#if (! $error) {
452
#sendNotification($docid, $mailhost, $sender, $recipient);
453
#}
454

    
455
# Create our HTML response and send it back
456
$$templateVars{'function'} = "submitted";
457
$$templateVars{'section'} = "Submission Status";
458

    
459
$template->process( $responseTemplate, $templateVars);
460

    
461
exit(0);
462

    
463

    
464
################################################################################
465
#
466
# Subroutine for updating a metacat id for a given scope to the highest value
467
#
468
################################################################################
469
sub updateLastId {
470
  my $scope = shift;
471

    
472
  my $errormsg = 0;
473
  my $docid = $metacat->getLastId($scope);
474

    
475
  if ($docid =~ /null/) {
476
      # No docids with this scope present, so do nothing
477
  } elsif ($docid) {
478
      # Update the lastid file for this scope
479
      (my $foundScope, my $id, my $rev) = split(/\./, $docid);
480
      debug("Docid is: $docid\n");
481
      debug("Lastid is: $id");
482
      my $scopeFile = $cfgdir . "/" . $FORM::cfg . "/" . $scope . ".lastid";
483
      open(LASTID, ">$scopeFile") or 
484
          die "Failed to open lastid file for writing!";
485
      print LASTID $id, "\n";
486
      close(LASTID);
487
  } else {
488
    $errormsg = $metacat->getMessage();
489
    debug("Error in getLastId: $errormsg");
490
  }
491
}
492

    
493
################################################################################
494
#
495
# Subroutine for inserting a document to metacat
496
#
497
################################################################################
498
sub insertMetadata {
499
  my $xmldoc = shift;
500
  my $docid = shift;
501

    
502
  my $notunique = "SUCCESS";
503
  debug("Registry: Starting insert (D1)");
504
  my $response = $metacat->insert($docid, $xmldoc);
505
  if (! $response) {
506
    debug("Registry: Response gotten (D2)");
507
    my $errormsg = $metacat->getMessage();
508
    debug("Registry: Error is (D3): ".$errormsg);
509
    if ($errormsg =~ /is already in use/) {
510
      $notunique = "NOT_UNIQUE";
511
      #print "Accession number already used: $docid\n";
512
    } elsif ($errormsg =~ /<login>/) {
513
      $notunique = "SUCCESS";
514
    } else {
515
      #print "<p>Dumping error on failure...</p>\n";
516
      #print "<p>", $errormsg, "</p>\n";
517
      #die "Failed during insert\n";
518
      #print "<p>Failed during insert</p>\n";
519
      $notunique = $errormsg;
520
    }
521
  }
522
  debug("Registry: Ending insert (D4)");
523

    
524
  return $notunique;
525
}
526

    
527
################################################################################
528
#
529
# Subroutine for generating a new accession number
530
#  Note: this is not threadsafe, assumes only one running process at a time
531
#  Also: need to check metacat for max id # used in this scope already
532
################################################################################
533
sub newAccessionNumber {
534
  my $scope = shift;
535
    
536
  my $docrev = 1;
537
  my $lastid = 1;
538

    
539
  my $scopeFile = $cfgdir . "/" . $FORM::cfg . "/" . $scope . ".lastid";
540
  if (-e $scopeFile) {
541
    open(LASTID, "<$scopeFile") or die "Failed to generate accession number!";
542
    $lastid = <LASTID>;
543
    chomp($lastid);
544
    $lastid++;
545
    close(LASTID);
546
  }
547
  open(LASTID, ">$scopeFile") or die "Failed to open lastid file for writing!";
548
  print LASTID $lastid, "\n";
549
  close(LASTID);
550

    
551
  my $docroot = "$scope.$lastid.";
552
  my $docid = $docroot . $docrev;
553
  return $docid;
554
}
555

    
556
################################################################################
557
# 
558
# Validate the parameters to make sure that required params are provided
559
#
560
################################################################################
561
sub validateParameters {
562
    my $chkUser = shift;
563
    my @invalidParams;
564

    
565
    push(@invalidParams, "Provider's first name is missing.")
566
        unless hasContent($FORM::providerGivenName);
567
    push(@invalidParams, "Provider's last name is missing.")
568
        unless hasContent($FORM::providerSurName);
569
    push(@invalidParams, "Name of site is missing.")
570
        unless (hasContent($FORM::site) || $FORM::site =~ /elect/ ||
571
                $FORM::cfg eq "nceas");
572
    push(@invalidParams, "Data set title is missing.")
573
        unless hasContent($FORM::title);
574
    push(@invalidParams, "Originator's first name is missing.")
575
        unless hasContent($FORM::origNamefirst0);
576
    push(@invalidParams, "Originator's last name is missing.")
577
        unless hasContent($FORM::origNamelast0);
578
    push(@invalidParams, "Abstract is missing.")
579
        unless hasContent($FORM::abstract);
580
    if($FORM::hasTemporal eq 'true'){
581
	push(@invalidParams, "Beginning year of data set is missing.")
582
	    unless (hasContent($FORM::beginningYear) || $FORM::temporalRequired ne 'true');
583
	push(@invalidParams, "Ending year has been specified but beginning year of data set is missing.")
584
	    if ((!hasContent($FORM::beginningYear)) && hasContent($FORM::endingYear));
585
    }
586
    push(@invalidParams, "Geographic description is missing.")
587
        unless (hasContent($FORM::geogdesc) || $FORM::spatialRequired ne 'true');
588

    
589
    if($FORM::beginningMonth eq "00"){
590
	if (hasContent($FORM::beginningYear)){
591
	    $FORM::beginningMonth = "01";
592
	} else {
593
	    $FORM::beginningMonth = "";
594
	}
595
    }
596
    if($FORM::beginningDay eq "00"){
597
	if (hasContent($FORM::beginningYear)){
598
	    $FORM::beginningDay = "01";
599
	} else {
600
	    $FORM::beginningDay = "";
601
	}
602
    }
603
    if($FORM::endingMonth eq "00"){
604
	if (hasContent($FORM::endingYear)){
605
	    $FORM::endingMonth = "01";
606
	} else {
607
	    $FORM::endingMonth = "";
608
	}
609
    }    
610
    if($FORM::endingDay eq "00"){
611
	if (hasContent($FORM::endingYear)){
612
	    $FORM::endingDay = "01";
613
	} else {
614
	    $FORM::endingDay = "";
615
	}
616
    }
617

    
618
    if (hasContent($FORM::beginningYear) && !($FORM::beginningYear =~ /[0-9][0-9][0-9][0-9]/)){
619
	push(@invalidParams, "Invalid beginning year specified.")
620
    }
621

    
622
    if (hasContent($FORM::endingYear) && !($FORM::endingYear =~ /[0-9][0-9][0-9][0-9]/)){
623
	push(@invalidParams, "Invalid ending year specified.")
624
    }
625
    
626
    # If the "use site" coord. box is checked and if the site is in 
627
    # the longitude hash ...  && ($siteLatDMS{$FORM::site})
628
    
629
    if($FORM::hasSpatial eq 'true'){
630
	if (($FORM::useSiteCoord) && ($siteLatDMS{$FORM::site}) ) {
631
        
632
	    $latDeg1 = $siteLatDMS{$FORM::site}[0];
633
	    $latMin1 = $siteLatDMS{$FORM::site}[1];
634
	    $latSec1 = $siteLatDMS{$FORM::site}[2];
635
	    $hemisphLat1 = $siteLatDMS{$FORM::site}[3];
636
	    $longDeg1 = $siteLongDMS{$FORM::site}[0];
637
	    $longMin1 = $siteLongDMS{$FORM::site}[1];
638
	    $longSec1 = $siteLongDMS{$FORM::site}[2];
639
	    $hemisphLong1 = $siteLongDMS{$FORM::site}[3];
640
	    
641
	}  else {
642
	    
643
	    $latDeg1 = $FORM::latDeg1;
644
	    $latMin1 = $FORM::latMin1;
645
	    $latSec1 = $FORM::latSec1;
646
	    $hemisphLat1 = $FORM::hemisphLat1;
647
	    $longDeg1 = $FORM::longDeg1;
648
	    $longMin1 = $FORM::longMin1;
649
	    $longSec1 = $FORM::longSec1;
650
	    $hemisphLong1 = $FORM::hemisphLong1;
651
	}
652

    
653
	if($latDeg1 > 90 || $latDeg1 < 0){
654
	    push(@invalidParams, "Invalid first latitude degrees specified.");
655
	}
656
	if($latMin1 > 59 || $latMin1 < 0){
657
	    push(@invalidParams, "Invalid first latitude minutes specified.");
658
	}
659
	if($latSec1 > 59 || $latSec1 < 0){
660
	    push(@invalidParams, "Invalid first latitude seconds specified.");
661
	}
662
	if($longDeg1 > 180 || $longDeg1 < 0){
663
	    push(@invalidParams, "Invalid first longitude degrees specified.");
664
	}
665
	if($longMin1 > 59 || $longMin1 < 0){
666
	    push(@invalidParams, "Invalid first longitude minutes specified.");
667
	}
668
	if($longSec1 > 59 || $longSec1 < 0){
669
	    push(@invalidParams, "Invalid first longitude seconds specified.");
670
	}
671

    
672
	if(hasContent($FORM::latDeg2) && ($FORM::latDeg2 > 90 || $FORM::latDeg2 < 0)){
673
	    push(@invalidParams, "Invalid second latitude degrees specified.");
674
	}
675
	if(hasContent($FORM::latMin2) && ($FORM::latMin2 > 59 || $FORM::latMin2 < 0)){
676
	    push(@invalidParams, "Invalid second latitude minutes specified.");
677
	}
678
	if(hasContent($FORM::latSec2) && ($FORM::latSec2 > 59 || $FORM::latSec2 < 0)){
679
	    push(@invalidParams, "Invalid second latitude seconds specified.");
680
	}
681
	if(hasContent($FORM::latDeg2) && ($FORM::longDeg2 > 180 || $FORM::longDeg2 < 0)){
682
	    push(@invalidParams, "Invalid second longitude degrees specified.");
683
	}
684
	if(hasContent($FORM::latMin2) && ($FORM::longMin2 > 59 || $FORM::longMin2 < 0)){
685
	    push(@invalidParams, "Invalid second longitude minutes specified.");
686
	}
687
	if(hasContent($FORM::latSec2) && ($FORM::longSec2 > 59 || $FORM::longSec2 < 0)){
688
	    push(@invalidParams, "Invalid second longitude seconds specified.");
689
	}
690
    }
691
    
692
    # Check if latDeg1 and longDeg1 has values if useSiteCoord is used. 
693
    # This check is required because some of the sites dont have lat 
694
    # and long mentioned in the config file. 
695

    
696

    
697
    if($FORM::hasSpatial eq 'true'){
698
	if ($FORM::useSiteCoord ) {
699
	    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.")
700
		unless(hasContent($latDeg1) && hasContent($longDeg1));
701
	}else{
702
	    push(@invalidParams, "Latitude degrees are missing.")
703
		unless (hasContent($latDeg1) || $FORM::spatialRequired ne 'true');
704
	    push(@invalidParams, "Longitude degrees are missing.")
705
		unless (hasContent($longDeg1) || $FORM::spatialRequired ne 'true');
706
	}
707
	push(@invalidParams, 
708
	     "You must provide a geographic description if you provide latitude and longitude information.")
709
	    if ((hasContent($latDeg1) || (hasContent($longDeg1))) && (!hasContent($FORM::geogdesc)));
710
    }
711

    
712
    if($FORM::hasMethod eq 'true'){
713
	push(@invalidParams, 
714
	     "You must provide a method description if you provide a method title.")
715
	    if (hasContent($FORM::methodTitle) && ( !(scalar(@FORM::methodPara) > 0) 
716
						    || (! hasContent($FORM::methodPara[0]))));
717
	push(@invalidParams, 
718
	     "You must provide a method description if you provide a study extent description.")
719
	    if (hasContent($FORM::studyExtentDescription) && (!(scalar(@FORM::methodPara) > 0) 
720
							      || (! hasContent($FORM::methodPara[0]))));
721
	push(@invalidParams, 
722
	     "You must provide both a study extent description and a sampling description, or neither.")
723
	    if (
724
                (hasContent($FORM::studyExtentDescription) && !hasContent($FORM::samplingDescription)) ||
725
                (!hasContent($FORM::studyExtentDescription) && hasContent($FORM::samplingDescription))
726
		);
727
    }
728

    
729
    push(@invalidParams, "Contact first name is missing.")
730
    unless (hasContent($FORM::origNamefirstContact) || 
731
        $FORM::useOrigAddress);
732
    push(@invalidParams, "Contact last name is missing.")
733
    unless (hasContent($FORM::origNamelastContact) || 
734
        $FORM::useOrigAddress);
735
    push(@invalidParams, "Data medium is missing.")
736
    unless (hasContent($FORM::dataMedium) || $FORM::dataMedium =~ /elect/);
737
    
738
    return \@invalidParams;
739
}
740

    
741
################################################################################
742
# 
743
# utility function to determine if a paramter is defined and not an empty string
744
#
745
################################################################################
746
sub hasContent {
747
    my $param = shift;
748

    
749
    my $paramHasContent;
750
    if (!defined($param) || $param eq '') { 
751
        $paramHasContent = 0;
752
    } else {
753
        $paramHasContent = 1;
754
    }
755
    return $paramHasContent;
756
}
757

    
758
################################################################################
759
#
760
# Subroutine for replacing characters not recognizable by XML and otherwise. 
761
#
762
################################################################################
763
sub normalize{
764
    my $val = shift;
765

    
766
    $val =~ s/&/&amp;/g;
767

    
768
    $val =~ s/</&lt;/g;
769
    $val =~ s/>/&gt;/g;
770
    $val =~ s/\"/&quot;/g;
771
    
772
    my $returnVal = "";
773
    
774
    foreach (split(//,$val)){
775
	my $var = unpack "C*", $_; 
776
	
777
	if($var<128 && $var>31){
778
	    $returnVal=$returnVal.$_;
779
	} elsif ($var<32){
780
	    if($var == 10){
781
		$returnVal=$returnVal.$_;
782
	    }
783
	    if($var == 13){
784
		$returnVal=$returnVal.$_;
785
	    }
786
	    if($var == 9){
787
		$returnVal=$returnVal.$_;
788
	    }
789
	} else { 
790
	    $returnVal=$returnVal."&#".$var.";";
791
	}
792
    }
793
    
794
    $returnVal =~ s/&/%26/g;    
795
    return $returnVal;
796
}
797

    
798

    
799
################################################################################
800
#
801
# Subroutine for replacing characters that might create problem in HTML. 
802
# Specifically written for " being used in any text field. This create a 
803
# problem in confirmData template, when you specify input name value pair 
804
# with value having a " in it.  
805
#
806
################################################################################
807
sub normalizeCD{
808
    my $val = shift;
809

    
810
    $val =~ s/\"/&quot;/g;
811
    
812
    return $val;
813
}
814

    
815

    
816
################################################################################
817
# 
818
# Create the XML document from the HTML form input
819
# returns the XML document as a string
820
#
821
################################################################################
822
sub createXMLDocument {
823

    
824
    my $orig  = "";
825
    my $role  = "associatedParty";
826
    my $creat = "";
827
    my $metaP = "";
828
    my $apart = "";
829
    my $cont  = "";
830
    my $publ  = "";
831
    my $dso   = "";
832
    my $gmt = gmtime($now);
833

    
834

    
835
    my $doc =  "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
836

    
837
    $doc .= "<eml:eml\n 
838
                     \t packageId=\"docid\" system=\"knb\"\n 
839
                     \t xmlns:eml=\"eml://ecoinformatics.org/eml-2.0.1\"\n
840
                     \t xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n 
841
                     \t xmlns:ds=\"eml://ecoinformatics.org/dataset-2.0.1\"\n 
842
                     \t xmlns:stmml=\"http://www.xml-cml.org/schema/stmml\"\n 
843
                     \t xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.0.1 eml.xsd\">\n";
844

    
845
    $doc .= "<!-- Person who filled in the catalog entry form: ";
846
    $doc .= normalize($FORM::providerGivenName)." ".normalize($FORM::providerSurName)." -->\n";
847
    $doc .= "<!-- Form filled out at $gmt GMT -->\n";
848
    $doc .= "<dataset>\n";
849
    
850
    if (hasContent($FORM::identifier)) {
851
        $doc .= "<alternateIdentifier system=\"$FORM::site\">";
852
        $doc .= normalize($FORM::identifier) . "</alternateIdentifier>\n";
853
    }
854
    
855
    if (hasContent($FORM::title)) {
856
        $doc .= "<title>".normalize($FORM::title)."</title>\n";
857
    }
858

    
859
    if (hasContent($FORM::origNamelast0)) {
860
    $role = "creator";
861
        $orig .= "<individualName>\n";
862
        $orig .= "<givenName>".normalize($FORM::origNamefirst0)."</givenName>\n";
863
        $orig .= "<surName>".normalize($FORM::origNamelast0)."</surName>\n";
864
        $orig .= "</individualName>\n";
865
    }
866

    
867
    if (hasContent($FORM::origNameOrg)) {
868
        $orig .= "<organizationName>".normalize($FORM::origNameOrg)."</organizationName>\n";
869
    }
870

    
871
    if (hasContent($FORM::origDelivery) || hasContent($FORM::origCity) ||
872
        (hasContent($FORM::origState   ) &&
873
        ($FORM::origState !~ "Select state here.")) ||
874
        hasContent($FORM::origStateOther) ||
875
        hasContent($FORM::origZIP ) || hasContent($FORM::origCountry)) {
876
        $orig .= "<address>\n";
877

    
878
        if (hasContent($FORM::origDelivery)) {
879
            $orig .= "<deliveryPoint>".normalize($FORM::origDelivery)."</deliveryPoint>\n";
880
        }
881
        if (hasContent($FORM::origCity)) {
882
            $orig .= "<city>".normalize($FORM::origCity)."</city>\n";
883
        }
884

    
885
    if (hasContent($FORM::origState) && 
886
            ($FORM::origState !~ "Select state here.")) {
887
            $orig .= "<administrativeArea>".normalize($FORM::origState);
888
            $orig .= "</administrativeArea>\n";
889
        } elsif (hasContent($FORM::origStateOther)) {
890
            $orig .= "<administrativeArea>".normalize($FORM::origStateOther);
891
            $orig .= "</administrativeArea>\n";
892
        }
893
        if (hasContent($FORM::origZIP)) {
894
            $orig .= "<postalCode>".normalize($FORM::origZIP)."</postalCode>\n";
895
        }
896
        if (hasContent($FORM::origCountry)) {
897
            $orig .= "<country>".normalize($FORM::origCountry)."</country>\n";
898
        }
899
        $orig .= "</address>\n";
900
    }
901

    
902
    if (hasContent($FORM::origPhone)) {
903
        $orig .= "<phone>".normalize($FORM::origPhone)."</phone>\n";
904
    }
905
    if (hasContent($FORM::origFAX)) {
906
        $orig .= "<phone phonetype=\"Fax\">".normalize($FORM::origFAX)."</phone>\n";
907
    }
908
    if (hasContent($FORM::origEmail)) {
909
        $orig .= "<electronicMailAddress>".normalize($FORM::origEmail);
910
        $orig .= "</electronicMailAddress>\n";
911
    }
912
    $dso = "<$role>\n$orig</$role>\n";
913
    
914
    if ($FORM::cfg eq 'nceas') {
915
        for (my $i = 0; $i < scalar(@FORM::wg); $i++) {
916
            $creat .= "<creator>\n";
917
            $creat .= "<organizationName>".normalize($FORM::wg[$i])."</organizationName>\n";
918
            $creat .= "</creator>\n";
919
        }
920
    } else {
921
	    $creat .= "<creator>\n";
922
	    $creat .= "<organizationName>".normalize($FORM::site)."</organizationName>\n";
923
	    $creat .= "</creator>\n";
924
    }
925

    
926
    if ($FORM::cfg ne 'knb') {
927
        $creat .= "<creator>\n";
928
        $creat .= "<organizationName>".normalize($organization)."</organizationName>\n";
929
        $creat .= "</creator>\n";
930
    }
931

    
932
    $creat .= $dso;
933

    
934
    if ($FORM::useOrigAddress) {
935
        # Add a contact originator like the original with a different role
936
            $cont .= "<contact>\n";
937
        $cont .= $orig;
938
        $cont .= "</contact>\n";
939
    } else {
940
        $cont .= "<contact>\n";
941

    
942
        $cont .= "<individualName>\n";
943
        $cont .= "<givenName>".normalize($FORM::origNamefirstContact)."</givenName>\n";
944
        $cont .= "<surName>".normalize($FORM::origNamelastContact)."</surName>\n";
945
        $cont .= "</individualName>\n";
946
 
947
    if (hasContent($FORM::origNameOrgContact)) {
948
        $cont .= "<organizationName>".normalize($FORM::origNameOrgContact)."</organizationName>\n";
949
    }
950

    
951
        if (hasContent($FORM::origDeliveryContact) || 
952
            hasContent($FORM::origCityContact) ||
953
            (hasContent($FORM::origStateContact) &&
954
            ($FORM::origStateContact !~ "Select state here.")) ||
955
            hasContent($FORM::origStateOtherContact) ||
956
            hasContent($FORM::origZIPContact) || 
957
            hasContent($FORM::origCountryContact)) {
958
            $cont .= "<address>\n";
959
            if (hasContent($FORM::origDeliveryContact)) {
960
                $cont .= "<deliveryPoint>".normalize($FORM::origDeliveryContact);
961
                $cont .= "</deliveryPoint>\n";
962
            }
963
            if (hasContent($FORM::origCityContact)) {
964
                $cont .= "<city>".normalize($FORM::origCityContact)."</city>\n";
965
            }
966
            if (hasContent($FORM::origStateContact) && 
967
                ($FORM::origStateContact !~ "Select state here.")) {
968
                $cont .= "<administrativeArea>".normalize($FORM::origStateContact);
969
                $cont .= "</administrativeArea>\n";
970
            } elsif (hasContent($FORM::origStateOtherContact)) {
971
                $cont .= "<administrativeArea>".normalize($FORM::origStateOtherContact);
972
                $cont .= "</administrativeArea>\n";
973
            }
974
            if (hasContent($FORM::origZIPContact)) {
975
                $cont .= "<postalCode>".normalize($FORM::origZIPContact)."</postalCode>\n";
976
            }
977
            if (hasContent($FORM::origCountryContact)) {
978
                $cont .= "<country>".normalize($FORM::origCountryContact)."</country>\n";
979
            }
980
            $cont .= "</address>\n";
981
        }
982
        if (hasContent($FORM::origPhoneContact)) {
983
            $cont .= "<phone>".normalize($FORM::origPhoneContact)."</phone>\n";
984
        }
985
    if (hasContent($FORM::origFAXContact)) {
986
        $cont .= "<phone phonetype=\"Fax\">".normalize($FORM::origFAXContact)."</phone>\n";
987
    }
988
        if (hasContent($FORM::origEmailContact)) {
989
            $cont .= "<electronicMailAddress>".normalize($FORM::origEmailContact);
990
            $cont .= "</electronicMailAddress>\n";
991
        }
992
    $cont .= "</contact>\n";
993
    }
994

    
995
    $metaP .= "<metadataProvider>\n";
996
    $metaP .= "<individualName>\n";
997
    $metaP .= "<givenName>".normalize($FORM::providerGivenName)."</givenName>\n";
998
    $metaP .= "<surName>".normalize($FORM::providerSurName)."</surName>\n";
999
    $metaP .= "</individualName>\n";
1000
    $metaP .= "</metadataProvider>\n";
1001

    
1002
    # Additional originators
1003
    foreach my $tmp (param()) {
1004
        if ($tmp =~ /origNamelast/){
1005
            my $tmp1 = $tmp;
1006
            $tmp1 =~ s/origNamelast//; # get the index of the parameter 0 to 10
1007
            if ( $tmp1 eq '1' 
1008
                 || $tmp1 eq '2'
1009
                 || $tmp1 eq '3'
1010
                 || $tmp1 eq '4'
1011
                 || $tmp1 eq '5'
1012
                 || $tmp1 eq '6'
1013
                 || $tmp1 eq '7'
1014
                 || $tmp1 eq '8'
1015
                 || $tmp1 eq '9'
1016
                 || $tmp1 eq '10'
1017
                 ) {
1018
     
1019
                # do not generate XML for empty originator fields 
1020
                if (hasContent(param("origNamefirst" . $tmp1))) {    
1021

    
1022
            my $add = "";
1023
            $add .= "<individualName>\n";
1024
            $add .= "<givenName>";
1025
            $add .= normalize(param("origNamefirst" . $tmp1));
1026
            $add .= "</givenName>\n";
1027
            $add .= "<surName>";
1028
            $add .= normalize(param("origNamelast" . $tmp1));
1029
            $add .= "</surName>\n";
1030
            $add .= "</individualName>\n";
1031
            
1032
            if(param("origRole" . $tmp1) eq "Originator"){
1033
            $creat .= "<creator>\n";
1034
            $creat .= $add;
1035
            $creat .= "</creator>\n";
1036
            }
1037
            elsif(param("origRole" . $tmp1) eq "Metadata Provider"){
1038
            $metaP .= "<metadataProvider>\n";
1039
            $metaP .= $add;
1040
            $metaP .= "</metadataProvider>\n";
1041
            }
1042
            elsif((param("origRole" . $tmp1) eq "Publisher")  && ($publ eq "")){
1043
            $publ .= "<publisher>\n";
1044
            $publ .= $add;
1045
            $publ .= "</publisher>\n";
1046
            }
1047
            else{
1048
            $apart .= "<associatedParty>\n";
1049
            $apart .= $add;
1050
            $apart .= "<role>";
1051
            $apart .= param("origRole" . $tmp1);
1052
            $apart .= "</role>\n";
1053
            $apart .= "</associatedParty>\n";
1054
            }
1055
        }
1056
            }
1057
        }
1058
    }
1059

    
1060
    $doc .= $creat;
1061
    $doc .= $metaP;
1062
    $doc .= $apart;
1063

    
1064
    $doc .= "<abstract>\n";
1065
    $doc .= "<para>".normalize($FORM::abstract)."</para>\n";
1066
    $doc .= "</abstract>\n";
1067

    
1068
    # Keyword information
1069
    foreach my $tmp (param()) {
1070
        if ($tmp =~ /keyword/) {
1071
            my $tmp1 = $tmp;
1072
            $tmp1 =~ s/keyword//; # get the index of the parameter 0, ..., 10
1073
            if ( $tmp1 =~ /[0-9]/ ){
1074
                # don't generate xml for empty keyword fields
1075
                # don't generate taxonomic keyword fields, those go in taxonomic coverage
1076
                if (hasContent(param($tmp))) {
1077
                    $doc .= "<keywordSet>\n";
1078
                    $doc .= "<keyword ";
1079
                    if (hasContent(param("kwType" . $tmp1)) &&
1080
                       (param("kwType" . $tmp1) !~ "none") ) {
1081
                         $doc .= "keywordType=\"";
1082
                         $doc .= param("kwType" . $tmp1);
1083
                         $doc .= "\"";
1084
                    }
1085
                    $doc .= ">";
1086
                    $doc .= normalize(param("keyword" . $tmp1));
1087
                    $doc .= "</keyword>\n";
1088
                    $doc .= "<keywordThesaurus>";
1089
                    $doc .= normalize(param("kwTh" . $tmp1));
1090
                    $doc .= "</keywordThesaurus>\n";
1091
                    $doc .= "</keywordSet>\n";
1092
                }
1093
            }
1094
        }
1095
    }
1096

    
1097
    if (hasContent($FORM::addComments)) {
1098
        $doc .= "<additionalInfo>\n";
1099
        $doc .= "<para>".normalize($FORM::addComments)."</para>\n";
1100
        $doc .= "</additionalInfo>\n";
1101
    }
1102

    
1103
    if (hasContent($FORM::useConstraints) || 
1104
        hasContent($FORM::useConstraintsOther)) {
1105
        $doc .= "<intellectualRights>\n";
1106
        if (hasContent($FORM::useConstraints)) {
1107
            $doc .= "<para>".normalize($FORM::useConstraints)."</para>\n";
1108
        }
1109
        if (hasContent($FORM::useConstraintsOther)) {
1110
            $doc .= "<para>".normalize($FORM::useConstraintsOther)."</para>\n";
1111
        }
1112
        $doc .= "</intellectualRights>\n";
1113
    }
1114

    
1115
    
1116
    if (hasContent($FORM::url)) {
1117
    $doc .= "<distribution>\n";
1118
        $doc .= "<online>\n";
1119
    $doc .= "<url>".normalize($FORM::url)."</url>\n";
1120
    $doc .= "</online>\n";
1121
    $doc .= "</distribution>\n";
1122
    }
1123
    
1124
    $doc .= "<distribution>\n";
1125
    $doc .= "<offline>\n";
1126
    $doc .= "<mediumName>" . normalize($FORM::dataMedium)." ".normalize($FORM::dataMediumOther);
1127
    $doc .= "</mediumName>\n";
1128
    $doc .= "</offline>\n";
1129
    $doc .= "</distribution>\n";
1130
            
1131
    my $cov = "";
1132

    
1133
    if (hasContent($FORM::endingYear)) {
1134
	$cov .= "<temporalCoverage>\n";
1135
	$cov .= "<rangeOfDates>\n";
1136
	if (hasContent($FORM::beginningMonth)) {
1137
	    my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1138
			 "JUL","AUG","SEP","OCT","NOV","DEC")
1139
		[$FORM::beginningMonth - 1];
1140
	    $cov .= "<beginDate>\n";
1141
	    $cov .= "<calendarDate>";
1142
	    $cov .= normalize($FORM::beginningYear)."-".normalize($FORM::beginningMonth)."-".normalize($FORM::beginningDay);
1143
	    $cov .= "</calendarDate>\n";
1144
	    $cov .= "</beginDate>\n";
1145
	} else {
1146
	    $cov .= "<beginDate>\n";
1147
	    $cov .= "<calendarDate>";
1148
	    $cov .= normalize($FORM::beginningYear);
1149
	    $cov .= "</calendarDate>\n";
1150
	    $cov .= "</beginDate>\n";
1151
	}
1152
	
1153
	if (hasContent($FORM::endingMonth)) {
1154
	    my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1155
			 "JUL","AUG","SEP","OCT","NOV","DEC")
1156
		[$FORM::endingMonth - 1];
1157
	    $cov .= "<endDate>\n";
1158
	    $cov .= "<calendarDate>";
1159
	    $cov .= normalize($FORM::endingYear)."-".normalize($FORM::endingMonth)."-".normalize($FORM::endingDay);
1160
	    $cov .= "</calendarDate>\n";
1161
	    $cov .= "</endDate>\n";
1162
	} else {
1163
	    $cov .= "<endDate>\n";
1164
	    $cov .= "<calendarDate>";
1165
	    $cov .= normalize($FORM::endingYear);
1166
	    $cov .= "</calendarDate>\n";
1167
	    $cov .= "</endDate>\n";
1168
	}
1169
	$cov .= "</rangeOfDates>\n";
1170
	$cov .= "</temporalCoverage>\n";
1171
    } else {
1172
	if(hasContent($FORM::beginningYear)) {
1173
	    $cov .= "<temporalCoverage>\n";
1174
	    $cov .= "<singleDateTime>\n";
1175
	    if (hasContent($FORM::beginningMonth)) {
1176
		my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1177
			     "JUL","AUG","SEP","OCT","NOV","DEC")
1178
		    [$FORM::beginningMonth - 1];
1179
		$cov .= "<calendarDate>";
1180
		$cov .= normalize($FORM::beginningYear)."-".normalize($FORM::beginningMonth)."-".normalize($FORM::beginningDay);
1181
		$cov .= "</calendarDate>\n";
1182
	    } else {
1183
		$cov .= "<calendarDate>";
1184
		$cov .= normalize($FORM::beginningYear);
1185
		$cov .= "</calendarDate>\n";
1186
	    }
1187
	    $cov .= "</singleDateTime>\n";
1188
	    $cov .= "</temporalCoverage>\n";
1189
	}
1190
    }
1191
    
1192
    if(hasContent($FORM::geogdesc) || ($FORM::latDeg1 != 0 && $FORM::longDeg1 != 0)) {
1193
	$cov .= "<geographicCoverage>\n";
1194

    
1195
	if(hasContent($FORM::geogdesc)) {
1196
	    $cov .= "<geographicDescription>".normalize($FORM::geogdesc)."</geographicDescription>\n";
1197
	}
1198
	
1199
	if($latDeg1 != 0 && $longDeg1 != 0) {
1200
	    $cov .= "<boundingCoordinates>\n";
1201
	    # if the second latitude is missing, then set the second lat/long pair 
1202
	    # equal to the first this makes a point appear like a rectangle 
1203
	    if ($FORM::useSiteCoord || ($FORM::latDeg2 == 0 && $FORM::latMin2 == 0 && $FORM::latSec2 == 0)) {
1204
		
1205
		$latDeg2 = $latDeg1;
1206
		$latMin2 = $latMin1;
1207
		$latSec2 = $latSec1;
1208
		$hemisphLat2 = $hemisphLat1;
1209
		$longDeg2 = $longDeg1;
1210
		$longMin2 = $longMin1;
1211
		$longSec2 = $longSec1;
1212
		$hemisphLong2 = $hemisphLong1;
1213
	    }
1214
	    else
1215
	    {
1216
		$latDeg2 = $FORM::latDeg2;
1217
		$latMin2 = $FORM::latMin2;
1218
		$latSec2 = $FORM::latSec2;
1219
		$hemisphLat2 = $FORM::hemisphLat2;
1220
		$longDeg2 = $FORM::longDeg2;
1221
		$longMin2 = $FORM::longMin2;
1222
		$longSec2 = $FORM::longSec2;
1223
		$hemisphLong2 = $FORM::hemisphLong2;
1224
	    } 
1225
	
1226
	
1227
	    my $hemisph;
1228
	    $hemisph = ($hemisphLong1 eq "W") ? -1 : 1;
1229
	    $cov .= "<westBoundingCoordinate>";
1230
	    my $var = $hemisph * ($longDeg1 + (60*$longMin1+$longSec1)/3600);
1231
	    $cov .= sprintf("%.4f\n", $var);
1232
	    $cov .= "</westBoundingCoordinate>\n";
1233
	    
1234
	    $hemisph = ($hemisphLong2 eq "W") ? -1 : 1;
1235
	    $cov .= "<eastBoundingCoordinate>";
1236
	    $var = $hemisph * ($longDeg2 + (60*$longMin2+$longSec2)/3600);
1237
	    $cov .= sprintf("%.4f\n", $var);
1238
	    $cov .= "</eastBoundingCoordinate>\n";
1239
	    
1240
	    $hemisph = ($hemisphLat1 eq "S") ? -1 : 1;
1241
	    $cov .= "<northBoundingCoordinate>";
1242
	    $var = $hemisph * ($latDeg1 + (60*$latMin1+$latSec1)/3600);
1243
	    $cov .= sprintf("%.4f\n", $var);	   
1244
	    $cov .= "</northBoundingCoordinate>\n";
1245
	    
1246
	    $hemisph = ($hemisphLat2 eq "S") ? -1 : 1;
1247
	    $cov .= "<southBoundingCoordinate>";
1248
	    $var = $hemisph * ($latDeg2 + (60*$latMin2+$latSec2)/3600);
1249
	    $cov .= sprintf("%.4f\n", $var);
1250
	    $cov .= "</southBoundingCoordinate>\n";
1251
	    
1252
	    $cov .= "</boundingCoordinates>\n";
1253
	}
1254
	$cov .= "</geographicCoverage>\n";
1255
    }
1256

    
1257
    # Write out the taxonomic coverage fields
1258
    my $foundFirstTaxon = 0;
1259
    foreach my $trn (param()) {
1260
        if ($trn =~ /taxonRankName/) {
1261
            my $taxIndex = $trn;
1262
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
1263
            my $trv = "taxonRankValue".$taxIndex;
1264
            if ( $taxIndex =~ /[0-9]/ ){
1265
                if (hasContent(param($trn)) && hasContent(param($trv))) {
1266
                    if (! $foundFirstTaxon) {
1267
                        $cov .= "<taxonomicCoverage>\n";
1268
                        $foundFirstTaxon = 1;
1269
                        if (hasContent($FORM::taxaAuth)) {
1270
                            $cov .= "<generalTaxonomicCoverage>".normalize($FORM::taxaAuth)."</generalTaxonomicCoverage>\n";
1271
                        }
1272
                    }
1273
                    $cov .= "<taxonomicClassification>\n";
1274
                    $cov .= "  <taxonRankName>".normalize(param($trn))."</taxonRankName>\n";
1275
                    $cov .= "  <taxonRankValue>".normalize(param($trv))."</taxonRankValue>\n";
1276
                    $cov .= "</taxonomicClassification>\n";
1277
                }
1278
            }
1279
        }
1280
    }
1281
    if ($foundFirstTaxon) {
1282
        $cov .= "</taxonomicCoverage>\n";
1283
    }
1284

    
1285
    if($cov ne "" ){
1286
	$doc .= "<coverage>".$cov."</coverage>";
1287
    }
1288
    $doc .= $cont;
1289
    $doc .= $publ;
1290
    
1291
    if ((hasContent($FORM::methodTitle)) || scalar(@FORM::methodsPara) > 0 || ($FORM::methodPara[0] ne "")) {
1292
        my $methods = "<methods><methodStep><description><section>\n";
1293
        if (hasContent($FORM::methodTitle)) {
1294
            $methods .= "<title>".normalize($FORM::methodTitle)."</title>\n";
1295
        }
1296
        for (my $i = 0; $i < scalar(@FORM::methodPara); $i++) {
1297
            $methods .= "<para>".normalize($FORM::methodPara[$i])."</para>\n";
1298
        }
1299
        $methods .= "</section></description></methodStep>\n";
1300
        if (hasContent($FORM::studyExtentDescription)) {
1301
            $methods .= "<sampling><studyExtent><description>\n";
1302
            $methods .= "<para>".normalize($FORM::studyExtentDescription)."</para>\n";
1303
            $methods .= "</description></studyExtent>\n";
1304
            $methods .= "<samplingDescription>\n";
1305
            $methods .= "<para>".normalize($FORM::samplingDescription)."</para>\n";
1306
            $methods .= "</samplingDescription>\n";
1307
            $methods .= "</sampling>\n";
1308
        }
1309
        $methods .= "</methods>\n";
1310
        $doc .= $methods;
1311
    }
1312

    
1313
    $doc .= "<access authSystem=\"knb\" order=\"denyFirst\">\n";
1314
    $doc .= "<allow>\n";
1315
    $doc .= "<principal>$username</principal>\n";
1316
    $doc .= "<permission>all</permission>\n";
1317
    $doc .= "</allow>\n";
1318
    $doc .= "<allow>\n";
1319
    $doc .= "<principal>uid=$FORM::username,o=$FORM::organization,dc=ecoinformatics,dc=org</principal>\n";
1320
    $doc .= "<permission>all</permission>\n";
1321
    $doc .= "</allow>\n";
1322
    $doc .= "<allow>\n";
1323
    $doc .= "<principal>public</principal>\n";
1324
    $doc .= "<permission>read</permission>\n";
1325
    $doc .= "</allow>\n";
1326
    $doc .= "</access>\n";
1327
    
1328
    $doc .= "</dataset>\n</eml:eml>\n";
1329

    
1330
    return $doc;
1331
}
1332

    
1333

    
1334
################################################################################
1335
# 
1336
# send an email message notifying the moderator of a new submission 
1337
#
1338
################################################################################
1339
sub sendNotification {
1340
    my $identifier = shift;
1341
    my $mailhost = shift;
1342
    my $sender = shift;
1343
    my $recipient = shift;
1344

    
1345
    my $smtp = Net::SMTP->new($mailhost);
1346
    $smtp->mail($sender);
1347
    $smtp->to($recipient);
1348

    
1349
    my $message = <<"    ENDOFMESSAGE";
1350
    To: $recipient
1351
    From: $sender
1352
    Subject: New data submission
1353
    
1354
    Data was submitted to the data registry.  
1355
    The identifying information for the new data set is:
1356

    
1357
    Identifier: $identifier
1358
    Title: $FORM::title
1359
    Submitter: $FORM::providerGivenName $FORM::providerSurName
1360

    
1361
    Please review the submmission and grant public read access if appropriate.
1362
    Thanks
1363
    
1364
    ENDOFMESSAGE
1365
    $message =~ s/^[ \t\r\f]+//gm;
1366

    
1367
    $smtp->data($message);
1368
    $smtp->quit;
1369
}
1370

    
1371

    
1372
################################################################################
1373
# 
1374
# read the eml document and send back a form with values filled in. 
1375
#
1376
################################################################################
1377
sub modifyData {
1378
    
1379
    # create metacat instance
1380
    my $metacat;
1381
    my $docid = $FORM::docid;
1382
    my $httpMessage;
1383
    my $doc;
1384
    my $xmldoc;
1385
    my $findType;
1386
    my $parser = XML::LibXML->new();
1387
    my @fileArray;
1388
    my $pushDoc;
1389
    my $alreadyInArray;
1390
    my $node;
1391
    my $response; 
1392
    my $element;
1393
    my $tempfile;
1394

    
1395
    $metacat = Metacat->new();
1396
    if ($metacat) {
1397
        $metacat->set_options( metacatUrl => $metacatUrl );
1398
    } else {
1399
        #die "failed during metacat creation\n";
1400
        push(@errorMessages, "Failed during metacat creation.");
1401
    }
1402
    
1403
    $httpMessage = $metacat->read($docid);
1404
    $doc = $httpMessage->content();
1405
    $xmldoc = $parser->parse_string($doc);
1406

    
1407
    #$tempfile = $xslConvDir.$docid;
1408
    #push (@fileArray, $tempfile);
1409

    
1410
    if ($xmldoc eq "") {
1411
        $error ="Error in parsing the eml document";
1412
        push(@errorMessages, $error);
1413
    } else {
1414
        $findType = $xmldoc->findnodes('//dataset/identifier');
1415
        if ($findType->size() > 0) {
1416
            # This is a eml beta6 document
1417
            # Read the documents mentioned in triples also
1418
        
1419
            $findType = $xmldoc->findnodes('//dataset/triple');
1420
            if ($findType->size() > 0) {
1421
                foreach $node ($findType->get_nodelist) {
1422
                    $pushDoc = findValue($node, 'subject');
1423
            
1424
                    # If the file is already in @fileArray then do not add it 
1425
                    $alreadyInArray = 0;
1426
                    foreach $element (@fileArray) {
1427
                        $tempfile = $tmpdir."/".$pushDoc;
1428
                        if ($element eq $pushDoc) {
1429
                            $alreadyInArray = 1;
1430
                        }
1431
                    }
1432
            
1433
                    if (!$alreadyInArray) {
1434
                        $tempfile = $tmpdir."/".$pushDoc;
1435
                        $response = "";
1436
                        $response = $metacat->read($pushDoc);    
1437
                        if (! $response) {
1438
                            # could not read
1439
                            #push(@errorMessages, $response);
1440
                            push(@errorMessages, $metacat->getMessage());
1441
                            push(@errorMessages, "Failed during reading.\n");
1442
                        } else {
1443
                            my $xdoc = $response->content();
1444
                            #$tempfile = $xslConvDir.$pushDoc;
1445
                            open (TFILE,">$tempfile") || 
1446
                                die ("Cant open xml file... $tempfile\n");
1447
                            print TFILE $xdoc;
1448
                            close(TFILE);
1449
                            push (@fileArray, $tempfile);
1450
                        }
1451
                    }
1452
                }
1453
            }
1454

    
1455
            # Read the main document. 
1456

    
1457
            $tempfile = $tmpdir."/".$docid; #= $xslConvDir.$docid;
1458
            open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1459
            print TFILE $doc;
1460
            close(TFILE);
1461
        
1462
            # Transforming beta6 to eml 2
1463
            my $xslt;
1464
            my $triplesheet;
1465
            my $results;
1466
            my $stylesheet;
1467
            my $resultsheet;
1468
        
1469
            $xslt = XML::LibXSLT->new();
1470
            #$tempfile = $xslConvDir."triple_info.xsl";
1471
            $tempfile = $tmpdir."/"."triple_info.xsl";
1472
    
1473
            $triplesheet = $xslt->parse_stylesheet_file($tempfile);
1474

    
1475
            #$results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1476
            $results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1477

    
1478
            #$tempfile = $xslConvDir."emlb6toeml2.xsl";
1479
            $tempfile = $tmpdir."/"."emlb6toeml2.xsl";
1480
            $stylesheet = $xslt->parse_stylesheet_file($tempfile);
1481
            $resultsheet = $stylesheet->transform($results);
1482
        
1483
            #$tempfile = "/usr/local/apache2/htdocs/xml/test.xml";;
1484
            #open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1485
            #print TFILE $stylesheet->output_string($resultsheet);
1486
            #close(TFILE);
1487

    
1488
            getFormValuesFromEml2($resultsheet);
1489
            
1490
            # Delete the files written earlier. 
1491
            unlink @fileArray;
1492

    
1493
        } else {
1494
            getFormValuesFromEml2($xmldoc);
1495
        }
1496
    }   
1497
    
1498
    if (scalar(@errorMessages)) {
1499
        # if any errors, print them in the response template 
1500
        $$templateVars{'status'} = 'failure_no_resubmit';
1501
        $$templateVars{'errorMessages'} = \@errorMessages;
1502
        $error = 1;
1503
        $$templateVars{'function'} = "modification";
1504
        $$templateVars{'section'} = "Modification Status";
1505
        $template->process( $responseTemplate, $templateVars); 
1506
    } else {
1507
        $$templateVars{'form'} = 're_entry';
1508
        $template->process( $entryFormTemplate, $templateVars);
1509
    }
1510
}
1511

    
1512
################################################################################
1513
# 
1514
# Parse an EML 2.0.0 file and extract the metadata into perl variables for 
1515
# processing and returning to the template processor
1516
#
1517
################################################################################
1518
sub getFormValuesFromEml2 {
1519
    
1520
    my $doc = shift;
1521
    my $results;
1522
    my $error;
1523
    my $node;
1524
    my $tempResult;
1525
    my $tempNode;
1526
    my $aoCount = 1;
1527
    my $foundDSO;
1528

    
1529
    # set variable values
1530
    $$templateVars{'showSiteList'} = $showSiteList;
1531
    $$templateVars{'lsite'} = $lsite;
1532
    $$templateVars{'usite'} = $usite;
1533
    $$templateVars{'showWgList'} = $showWgList;
1534
    $$templateVars{'showOrganization'} = $showOrganization;
1535
    $$templateVars{'hasKeyword'} = $hasKeyword;
1536
    $$templateVars{'hasTemporal'} = $hasTemporal;
1537
    $$templateVars{'hasSpatial'} = $hasSpatial;
1538
    $$templateVars{'hasTaxonomic'} = $hasTaxonomic;
1539
    $$templateVars{'hasMethod'} = $hasMethod;
1540
    $$templateVars{'spatialRequired'} = $spatialRequired;
1541
    $$templateVars{'temporalRequired'} = $temporalRequired;
1542

    
1543
    # find out the tag <alternateIdentifier>. 
1544
    $results = $doc->findnodes('//dataset/alternateIdentifier');
1545
    if ($results->size() > 1) {
1546
        errMoreThanOne("alternateIdentifier");
1547
    } else {
1548
        foreach $node ($results->get_nodelist) {
1549
            $$templateVars{'identifier'} = findValue($node, '../alternateIdentifier');
1550
        }
1551
    }
1552

    
1553
    # find out the tag <title>. 
1554
    $results = $doc->findnodes('//dataset/title');
1555
    if ($results->size() > 1) {
1556
        errMoreThanOne("title");
1557
    } elsif ($results->size() < 1) {
1558
        $error ="Following tag not found: title. Please use Morpho to edit this document";
1559
        push(@errorMessages, $error."\n");
1560
        #if ($DEBUG == 1){ print $error;}
1561
    } else {
1562
        foreach $node ($results->get_nodelist) {
1563
            $$templateVars{'title'} = findValue($node, '../title');
1564
        }
1565
    }
1566

    
1567
    # find out the tag <creator>. 
1568
    $results = $doc->findnodes('//dataset/creator/individualName');
1569
    debug("Registry: Creators: ".$results->size());
1570
     foreach $node ($results->get_nodelist) {
1571
            dontOccur($node, "../positionName|../onlineURL|../userId", 
1572
              "positionName, onlineURL, userId");
1573
        
1574
            dontOccur($node, "./saluation", "saluation");                
1575
        
1576
            debug("Registry: Checking a creator in loop 1...");
1577
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1578
            if($tempResult->size > 0) {
1579
                if($foundDSO == 0) {
1580
                    $foundDSO = 1;
1581
     
1582
                    debug("Registry: Recording a creator in loop 1...");
1583
                    $$templateVars{'origNamefirst0'} = findValue($node, 'givenName');
1584
                    $$templateVars{'origNamelast0'} = findValue($node, 'surName');
1585
            
1586
                    my $tempResult2 = $node->findnodes('../address');
1587
                    if ($tempResult2->size > 1) {
1588
                        errMoreThanOne("address");
1589
                    } else {
1590
                        foreach my $tempNode2 ($tempResult2->get_nodelist) {
1591
                            $$templateVars{'origDelivery'} = findValue($tempNode2, 'deliveryPoint');
1592
                            $$templateVars{'origCity'} = findValue($tempNode2, 'city');
1593
                            $$templateVars{'origState'} = findValue($tempNode2, 'administrativeArea');
1594
                            $$templateVars{'origZIP'} = findValue($tempNode2, 'postalCode');
1595
                            $$templateVars{'origCountry'} = findValue($tempNode2, 'country');
1596
                        }
1597
                    }
1598
            
1599
                    my $tempResult3 = $node->findnodes('../phone');
1600
                    if ($tempResult3->size > 2) {
1601
                        errMoreThanN("phone");
1602
                    } else {
1603
                        foreach my $tempNode2 ($tempResult3->get_nodelist) {
1604
                            if ($tempNode2->hasAttributes()) {
1605
                                my @attlist = $tempNode2->attributes();
1606
                                if ($attlist[0]->value eq "Fax") {
1607
                                    $$templateVars{'origFAX'} = $tempNode2->textContent();
1608
                                } else {
1609
                                    $$templateVars{'origPhone'} = $tempNode2->textContent();
1610
                                }
1611
                            } else {
1612
                                $$templateVars{'origPhone'} = $tempNode2->textContent();
1613
                            }
1614
                        }
1615
                    }
1616
                    $$templateVars{'origEmail'} = findValue($node, '../electronicMailAddress');
1617
                    $$templateVars{'origNameOrg'} = findValue($node, '../organizationName');
1618
                } else {
1619
                    errMoreThanN("address, phone and electronicMailAddress");
1620
                }
1621
            }
1622
        }
1623
        foreach $node ($results->get_nodelist) {
1624
            debug("Registry: Checking a creator in loop 2...");
1625
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1626
            if ($tempResult->size == 0) {
1627
                if ($foundDSO == 0) {
1628
                    debug("Registry: Recording a creator in loop 2 block A...");
1629
                    $foundDSO = 1;
1630
                    $$templateVars{'origNamefirst0'} = findValue($node, 'givenName');
1631
                    $$templateVars{'origNamelast0'} = findValue($node, 'surName');
1632
                    $$templateVars{'origNameOrg'} = findValue($node, '../organizationName');
1633
                } else {
1634
                    debug("Registry: Recording a creator in loop 2 block B...");
1635
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($node, './givenName');
1636
                    $$templateVars{"origNamelast$aoCount"} =  findValue($node, './surName');
1637
                    $$templateVars{"origRole$aoCount"} = "Originator";
1638
                    $aoCount++;
1639
                }
1640
            }
1641
        }
1642

    
1643
    $results = $doc->findnodes('//dataset/creator/organizationName');
1644
    my $wgroups = $doc->findnodes("//dataset/creator/organizationName[contains(text(),'(NCEAS ')]");
1645
    debug("Registry: Number Org: ".$results->size());
1646
    debug("Registry:  Number WG: ".$wgroups->size());
1647
    if ($results->size() - $wgroups->size() > 3) {
1648
        errMoreThanN("creator/organizationName");    
1649
    } else {
1650
        foreach $node ($results->get_nodelist) {
1651
            my $tempValue = findValue($node,'../organizationName');
1652
            $tempResult = $node->findnodes('../individualName');
1653
            if ($tempResult->size == 0 && $tempValue ne $organization) {
1654
                $$templateVars{'site'} = $tempValue;
1655
            }
1656
        }
1657
        if ($FORM::cfg eq 'nceas') {
1658
            my @wg;
1659
            foreach $node ($results->get_nodelist) {
1660
                my $tempValue = findValue($node,'../organizationName');
1661
                $wg[scalar(@wg)] = $tempValue;
1662
            }
1663
            my $projects = getProjectList();
1664
            $$templateVars{'projects'} = $projects;
1665
            $$templateVars{'wg'} = \@wg;
1666
        }
1667
    }
1668

    
1669
    $results = $doc->findnodes('//dataset/metadataProvider');
1670
    foreach $node ($results->get_nodelist) {
1671
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1672
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in metadataProvider");
1673
        
1674
	    $tempResult = $node->findnodes('./individualName');
1675
            if ($tempResult->size > 1) {
1676
                errMoreThanOne("metadataProvider/indvidualName");
1677
            } else {
1678
                foreach $tempNode ($tempResult->get_nodelist) {
1679
                    if ($$templateVars{'providerGivenName'} ne "") {
1680
                        $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1681
                        $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1682
                        $$templateVars{"origRole$aoCount"} = "Metadata Provider";
1683
                        $aoCount++;
1684
                    } else {
1685
                        $$templateVars{'providerGivenName'} =  findValue($tempNode, './givenName');
1686
                        $$templateVars{'providerSurName'} =  findValue($tempNode, './surName');
1687
                    }
1688
                }
1689
            }
1690
        }
1691

    
1692
    $results = $doc->findnodes('//dataset/associatedParty');
1693
    foreach $node ($results->get_nodelist) {
1694
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1695
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in associatedParty");
1696
       
1697
            $tempResult = $node->findnodes('./individualName');
1698
            if ($tempResult->size > 1) {
1699
                errMoreThanOne("associatedParty/indvidualName");
1700
            } else {
1701
                foreach $tempNode ($tempResult->get_nodelist) {
1702
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1703
                    $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1704
                    $$templateVars{"origRole$aoCount"} = findValue($tempNode, '../role');
1705
                    $aoCount++;           
1706
                }
1707
            }
1708
     }
1709

    
1710
    $results = $doc->findnodes('//dataset/publisher');
1711
#    if ($results->size() > 10) {
1712
 #       errMoreThanN("publisher");
1713
 #   } else {
1714
        foreach $node ($results->get_nodelist) {
1715
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1716
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in associatedParty");
1717
       
1718
            $tempResult = $node->findnodes('./individualName');
1719
            if ($tempResult->size > 1) {
1720
                errMoreThanOne("publisher/indvidualName");
1721
            } else {
1722
                foreach $tempNode ($tempResult->get_nodelist) {
1723
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1724
                    $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1725
                    $$templateVars{"origRole$aoCount"} = "Publisher";
1726
                    $aoCount++;           
1727
                }
1728
            }
1729
        }
1730
  #  }
1731

    
1732
  #  if ($aoCount > 11) {
1733
  #      errMoreThanN("Additional Originators");
1734
 #   } 
1735

    
1736
    $$templateVars{'aoCount'} = $aoCount-1;
1737
    
1738
    dontOccur($doc, "./pubDate", "pubDate");
1739
    dontOccur($doc, "./language", "language");
1740
    dontOccur($doc, "./series", "series");
1741

    
1742
    $results = $doc->findnodes('//dataset/abstract');
1743
    if ($results->size() > 1) {
1744
        errMoreThanOne("abstract");
1745
    } else {
1746
        foreach my $node ($results->get_nodelist) {
1747
            dontOccur($node, "./section", "section");
1748
            $$templateVars{'abstract'} = findValueNoChild($node, "para");
1749
        }
1750
    }
1751

    
1752
    $results = $doc->findnodes('//dataset/keywordSet');
1753

    
1754
    my $count = 0;
1755
    foreach $node ($results->get_nodelist) {
1756
	$tempResult = $node->findnodes('./keyword');
1757
	if ($tempResult->size() > 1) {
1758
	    errMoreThanOne("keyword");
1759
	} else {
1760
	    $count++;
1761
	    foreach $tempNode ($tempResult->get_nodelist) {
1762
		$$templateVars{"keyword$count"} = $tempNode->textContent();
1763
		if ($tempNode->hasAttributes()) {
1764
		    my @attlist = $tempNode->attributes();
1765
		    $$templateVars{"kwType$count"} = $attlist[0]->value;
1766
		}  
1767
	    }
1768
	}
1769
	$$templateVars{"kwTh$count"} = findValue($node, "keywordThesaurus");
1770
    }
1771
    $$templateVars{'keyCount'} = $count;
1772
    if($count > 0 ){
1773
       $$templateVars{'hasKeyword'} = "true";
1774
    }
1775

    
1776
    $results = $doc->findnodes('//dataset/additionalInfo');
1777
    if ($results->size() > 1) {
1778
        errMoreThanOne("additionalInfo");
1779
    } else {
1780
        foreach $node ($results->get_nodelist) {
1781
            dontOccur($node, "./section", "section");
1782
            $$templateVars{'addComments'} = findValueNoChild($node, "para");
1783
        }
1784
    }
1785

    
1786
    $$templateVars{'useConstraints'} = "";
1787
    $results = $doc->findnodes('//dataset/intellectualRights');
1788
    if ($results->size() > 1) {
1789
        errMoreThanOne("intellectualRights");
1790
    } else {
1791
        foreach $node ($results->get_nodelist) {
1792
            dontOccur($node, "./section", "section in intellectualRights");
1793

    
1794
            $tempResult = $node->findnodes("para");
1795
            if ($tempResult->size > 2) {
1796
                   errMoreThanN("para");
1797
            } else {
1798
                foreach $tempNode ($tempResult->get_nodelist) {
1799
                    my $childNodes = $tempNode->childNodes;
1800
                    if ($childNodes->size() > 1) {
1801
                        $error ="The tag para in intellectualRights has children which cannot be shown using the form. Please use Morpho to edit this document";    
1802
                        push(@errorMessages, $error);
1803
                        #if ($DEBUG == 1){ print $error."\n";}
1804
                    } else {
1805
                        #print $tempNode->nodeName().":".$tempNode->textContent();
1806
                        #print "\n";
1807
                        if ($$templateVars{'useConstraints'} eq "") {
1808
                            $$templateVars{'useConstraints'} = $tempNode->textContent();
1809
                        } else {
1810
                            $$templateVars{'useConstraintsOther'} = $tempNode->textContent();
1811
                        }
1812
                    }
1813
                }
1814
            }
1815
        }
1816
    }
1817

    
1818
    $results = $doc->findnodes('//dataset/distribution/online');
1819
    if ($results->size() > 1) {
1820
        errMoreThanOne("distribution/online");
1821
    } else {
1822
        foreach my $tempNode ($results->get_nodelist){
1823
            $$templateVars{'url'} = findValue($tempNode, "url");
1824
            dontOccur($tempNode, "./connection", "/distribution/online/connection");
1825
            dontOccur($tempNode, "./connectionDefinition", "/distribution/online/connectionDefinition");
1826
        }
1827
    }
1828

    
1829
    $results = $doc->findnodes('//dataset/distribution/offline');
1830
    if ($results->size() > 1) {
1831
        errMoreThanOne("distribution/online");
1832
    } else {
1833
        foreach my $tempNode ($results->get_nodelist) {
1834
            $$templateVars{'dataMedium'} = findValue($tempNode, "mediumName");
1835
            dontOccur($tempNode, "./mediumDensity", "/distribution/offline/mediumDensity");
1836
            dontOccur($tempNode, "./mediumDensityUnits", "/distribution/offline/mediumDensityUnits");
1837
            dontOccur($tempNode, "./mediumVolume", "/distribution/offline/mediumVolume");
1838
            dontOccur($tempNode, "./mediumFormat", "/distribution/offline/mediumFormat");
1839
            dontOccur($tempNode, "./mediumNote", "/distribution/offline/mediumNote");
1840
        }
1841
    }
1842

    
1843
    dontOccur($doc, "./inline", "//dataset/distribution/inline");
1844

    
1845
    $results = $doc->findnodes('//dataset/coverage');
1846
    if ($results->size() > 1) {
1847
        errMoreThanOne("coverage");
1848
    } else {
1849
        foreach $node ($results->get_nodelist) {
1850
            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");
1851

    
1852
            $tempResult = $node->findnodes('./temporalCoverage');
1853
            if ($tempResult->size > 1) {
1854
                   errMoreThanOne("temporalCoverage");
1855
            } else {
1856
                foreach $tempNode ($tempResult->get_nodelist) {
1857
                    my $x;
1858
                    my $y;
1859
                    my $z;
1860
                    my $tempdate = findValue($tempNode, "rangeOfDates/beginDate/calendarDate");
1861
                    ($x, $y, $z) = split("-", $tempdate); 
1862
                    $$templateVars{'beginningYear'} = $x;
1863
                    $$templateVars{'beginningMonth'} = $y;
1864
                    $$templateVars{'beginningDay'} = $z;
1865
    
1866
                    $tempdate = findValue($tempNode, "rangeOfDates/endDate/calendarDate");
1867
                    ($x, $y, $z) = split("-", $tempdate);
1868
                    $$templateVars{'endingYear'} = $x;
1869
                    $$templateVars{'endingMonth'} = $y;
1870
                    $$templateVars{'endingDay'} = $z;
1871

    
1872
                    $tempdate = "";
1873
                    $tempdate = findValue($tempNode, "singleDateTime/calendarDate");
1874
                    if($tempdate ne ""){
1875
                        ($x, $y, $z) = split("-", $tempdate);
1876
                        $$templateVars{'beginningYear'} = $x;
1877
                        $$templateVars{'beginningMonth'} = $y;
1878
                        $$templateVars{'beginningDay'} = $z;
1879
                    }  
1880
		    
1881
		    $$templateVars{'hasTemporal'} = "true";
1882
                }
1883
            }
1884

    
1885
            $tempResult = $node->findnodes('./geographicCoverage');
1886
            if ($tempResult->size > 1) {
1887
                errMoreThanOne("geographicCoverage");
1888
            } else {
1889
                foreach $tempNode ($tempResult->get_nodelist) {
1890
                    my $geogdesc = findValue($tempNode, "geographicDescription");
1891
                    debug("Registry: geogdesc from xml is: $geogdesc");
1892
                    $$templateVars{'geogdesc'} = $geogdesc;
1893
                    my $coord = findValue($tempNode, "boundingCoordinates/westBoundingCoordinate");
1894
                    if ($coord > 0) {
1895
                        #print "+";
1896
                        $$templateVars{'hemisphLong1'} = "E";
1897
                    } else {
1898
                        #print "-";
1899
                        eval($coord = $coord * -1);
1900
                        $$templateVars{'hemisphLong1'} = "W";
1901
                    }
1902
                    eval($$templateVars{'longDeg1'} = int($coord));
1903
                    eval($coord = ($coord - int($coord))*60);
1904
                    eval($$templateVars{'longMin1'} = int($coord));
1905
                    eval($coord = ($coord - int($coord))*60);
1906
                    eval($$templateVars{'longSec1'} = int($coord));
1907
                    
1908
                    $coord = findValue($tempNode, "boundingCoordinates/southBoundingCoordinate");
1909
                    if ($coord > 0) {
1910
                        #print "+";
1911
                        $$templateVars{'hemisphLat2'} = "N";
1912
                    } else {
1913
                        #print "-";
1914
                        eval($coord = $coord * -1);
1915
                        $$templateVars{'hemisphLat2'} = "S";
1916
                    }
1917
                    eval($$templateVars{'latDeg2'} = int($coord));
1918
                    eval($coord = ($coord - int($coord))*60);
1919
                    eval($$templateVars{'latMin2'} = int($coord));
1920
                    eval($coord = ($coord - int($coord))*60);
1921
                    eval($$templateVars{'latSec2'} = int($coord));
1922
        
1923
                    $coord = findValue($tempNode, "boundingCoordinates/northBoundingCoordinate");
1924
                    if ($coord > 0) {
1925
                        #print "+";
1926
                        $$templateVars{'hemisphLat1'} = "N";
1927
                    } else {
1928
                        #print "-";
1929
                        eval($coord = $coord * -1);
1930
                        $$templateVars{'hemisphLat1'} = "S";
1931
                    }
1932
                    eval($$templateVars{'latDeg1'} = int($coord));
1933
                    eval($coord = ($coord - int($coord))*60);
1934
                    eval($$templateVars{'latMin1'} = int($coord));
1935
                    eval($coord = ($coord - int($coord))*60);
1936
                    eval($$templateVars{'latSec1'} = int($coord));
1937
        
1938
                    $coord = findValue($tempNode, "boundingCoordinates/eastBoundingCoordinate");
1939
                    if ($coord > 0) {
1940
                        #print "+";
1941
                        $$templateVars{'hemisphLong2'} = "E";
1942
                    } else {
1943
                        #print "-";
1944
                        eval($coord = $coord * -1);
1945
                        $$templateVars{'hemisphLong2'} = "W";
1946
                    }
1947
                    eval($$templateVars{'longDeg2'} = int($coord));
1948
                    eval($coord = ($coord - int($coord))*60);
1949
                    eval($$templateVars{'longMin2'} = int($coord));
1950
                    eval($coord = ($coord - int($coord))*60);
1951
                    eval($$templateVars{'longSec2'} = int($coord));
1952

    
1953
		            $$templateVars{'hasSpatial'} = "true";
1954
                }
1955
            }
1956

    
1957
            $tempResult = $node->findnodes('./taxonomicCoverage/taxonomicClassification');
1958
            my $taxonIndex = 0;
1959
            foreach $tempNode ($tempResult->get_nodelist) {
1960
                $taxonIndex++;
1961
                my $taxonRankName = findValue($tempNode, "taxonRankName");
1962
                my $taxonRankValue = findValue($tempNode, "taxonRankValue");
1963
                $$templateVars{"taxonRankName".$taxonIndex} = $taxonRankName;
1964
                $$templateVars{"taxonRankValue".$taxonIndex} = $taxonRankValue;
1965
		
1966
		$$templateVars{'hasTaxonomic'} = "true";
1967
            }
1968
            $$templateVars{'taxaCount'} = $taxonIndex;
1969
            my $taxaAuth = findValue($node, "./taxonomicCoverage/generalTaxonomicCoverage");
1970
            $$templateVars{'taxaAuth'} = $taxaAuth;
1971
        }
1972
    }
1973
    dontOccur($doc, "./purpose", "purpose");
1974
    dontOccur($doc, "./maintenance", "maintnance");
1975

    
1976
    $results = $doc->findnodes('//dataset/contact/individualName');
1977
    if ($results->size() > 1) {
1978
        errMoreThanOne("contact/individualName");
1979
    } else {
1980
        foreach $node ($results->get_nodelist) {
1981
            dontOccur($node, "../positionName|../onlineURL|../userId", 
1982
              "positionName, onlineURL, userId in contact tag");
1983
            dontOccur($node, "./saluation", "saluation in contact tag");                
1984
        
1985
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1986
            if ($tempResult->size > 0) {
1987
                $$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
1988
                $$templateVars{'origNamelastContact'} = findValue($node, 'surName');
1989
    
1990
                my $tempResult2 = $node->findnodes('../address');
1991
                if ($tempResult2->size > 1) {
1992
                    errMoreThanOne("address");
1993
                } else {
1994
                    foreach my $tempNode2 ($tempResult2->get_nodelist) {
1995
                        $$templateVars{'origDeliveryContact'} = findValue($tempNode2, 'deliveryPoint');
1996
                        $$templateVars{'origCityContact'} = findValue($tempNode2, 'city');
1997
                        $$templateVars{'origStateContact'} = findValue($tempNode2, 'administrativeArea');
1998
                        $$templateVars{'origZIPContact'} = findValue($tempNode2, 'postalCode');
1999
                        $$templateVars{'origCountryContact'} = findValue($tempNode2, 'country');
2000
                    }
2001
                }
2002
            
2003
                my $tempResult3 = $node->findnodes('../phone');
2004
                if ($tempResult3->size > 2) {
2005
                    errMoreThanN("phone");
2006
                } else {
2007
                    foreach my $tempNode2 ($tempResult3->get_nodelist) {
2008
                        if ($tempNode2->hasAttributes()) {
2009
                            my @attlist = $tempNode2->attributes();
2010
                            if ($attlist[0]->value eq "Fax") {
2011
                                $$templateVars{'origFAXContact'} = $tempNode2->textContent();
2012
                            } else {
2013
                                $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
2014
                            }
2015
                        } else {
2016
                            $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
2017
                        }
2018
                    }
2019
                }
2020
                $$templateVars{'origEmailContact'} = findValue($node, '../electronicMailAddress');
2021
                $$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
2022
            } else {
2023
                $$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
2024
                $$templateVars{'origNamelastContact'} = findValue($node, 'surName');
2025
                $$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
2026
            }
2027
        }
2028
    }
2029
    
2030
    $results = $doc->findnodes(
2031
            '//dataset/methods/methodStep/description/section');
2032
    debug("Registry: Number methods: ".$results->size());
2033
    if ($results->size() > 1) {
2034
        errMoreThanN("methods/methodStep/description/section");    
2035
    } else {
2036

    
2037
        my @methodPara;
2038
        foreach $node ($results->get_nodelist) {
2039
            my @children = $node->childNodes;
2040
            for (my $i = 0; $i < scalar(@children); $i++) {
2041
                debug("Registry: Method child loop ($i)");
2042
                my $child = $children[$i];
2043
                if ($child->nodeName eq 'title') {
2044
                    my $title = $child->textContent();
2045
                    debug("Registry: Method title ($title)");
2046
                    $$templateVars{'methodTitle'} = $title;
2047
                } elsif ($child->nodeName eq 'para') {
2048
                    my $para = $child->textContent();
2049
                    debug("Registry: Method para ($para)");
2050
                    $methodPara[scalar(@methodPara)] = $para;
2051
                }
2052
            }
2053
	    $$templateVars{'hasMethod'} = "true";
2054
        }
2055
        if (scalar(@methodPara) > 0) {
2056
            $$templateVars{'methodPara'} = \@methodPara;
2057
        }
2058
    }
2059

    
2060
    $results = $doc->findnodes(
2061
            '//dataset/methods/sampling/studyExtent/description/para');
2062
    if ($results->size() > 1) {
2063
        errMoreThanN("methods/sampling/studyExtent/description/para");    
2064
    } else {
2065
        foreach $node ($results->get_nodelist) {
2066
            my $studyExtentDescription = $node->textContent();
2067
            $$templateVars{'studyExtentDescription'} = $studyExtentDescription;
2068

    
2069
	    $$templateVars{'hasMethod'} = "true";
2070
        }
2071
    }
2072

    
2073
    $results = $doc->findnodes(
2074
            '//dataset/methods/sampling/samplingDescription/para');
2075
    if ($results->size() > 1) {
2076
        errMoreThanN("methods/sampling/samplingDescription/para");    
2077
    } else {
2078
        foreach $node ($results->get_nodelist) {
2079
            my $samplingDescription = $node->textContent();
2080
            $$templateVars{'samplingDescription'} = $samplingDescription;
2081

    
2082
	    $$templateVars{'hasMethod'} = "true";
2083
        }
2084
    }
2085

    
2086
    dontOccur($doc, "//methodStep/citation", "methodStep/citation");
2087
    dontOccur($doc, "//methodStep/protocol", "methodStep/protocol");
2088
    dontOccur($doc, "//methodStep/instrumentation", "methodStep/instrumentation");
2089
    dontOccur($doc, "//methodStep/software", "methodStep/software");
2090
    dontOccur($doc, "//methodStep/subStep", "methodStep/subStep");
2091
    dontOccur($doc, "//methodStep/dataSource", "methodStep/dataSource");
2092
    dontOccur($doc, "//methods/qualityControl", "methods/qualityControl");
2093

    
2094
    dontOccur($doc, "//methods/sampling/spatialSamplingUnits", "methods/sampling/spatialSamplingUnits");
2095
    dontOccur($doc, "//methods/sampling/citation", "methods/sampling/citation");
2096
    dontOccur($doc, "./pubPlace", "pubPlace");
2097
    dontOccur($doc, "./project", "project");
2098
    
2099
    ############ Code for checking ACL #####################
2100
    dontOccur($doc, "//dataset/access/deny", "dataset/access/deny");
2101

    
2102
    $results = $doc->findnodes('//dataset/access/allow');
2103
    if ($results->size() != 3) {
2104
        errMoreThanN("dataset/access/allow");
2105
    } else {
2106
	my $accessError = 0;
2107
        foreach $node ($results->get_nodelist) {
2108
            my @children = $node->childNodes;
2109
	    my $principal = "";
2110
	    my $permission = "";
2111
            for (my $i = 0; $i < scalar(@children); $i++) {
2112
                my $child = $children[$i];
2113
                if ($child->nodeName eq 'principal') {
2114
                    $principal = $child->textContent();
2115
                } elsif ($child->nodeName eq 'permission') {
2116
                    $permission = $child->textContent();
2117
                }
2118
            }
2119
	
2120
	    if ($principal eq 'public' && $permission ne 'read') { $accessError = 1; }
2121
	    if ($principal eq $username && $permission ne 'all') { $accessError = 2; }
2122
	    if ($principal ne 'public' && $principal ne $username && $permission ne 'all') { $accessError = 3; }
2123
	}
2124
 
2125
	if ($accessError != 0) {
2126
	    my $error ="The ACL for this document has been changed outside the registry. Please use Morpho to edit this document";
2127
            push(@errorMessages, $error."\n");
2128
	}     
2129
    }
2130
    ########################################################
2131

    
2132

    
2133
    dontOccur($doc, "./dataTable", "dataTable");
2134
    dontOccur($doc, "./spatialRaster", "spatialRaster");
2135
    dontOccur($doc, "./spatialVector", "spatialVector");
2136
    dontOccur($doc, "./storedProcedure", "storedProcedure");
2137
    dontOccur($doc, "./view", "view");
2138
    dontOccur($doc, "./otherEntity", "otherEntity");
2139
    dontOccur($doc, "./references", "references");
2140
    
2141
    dontOccur($doc, "//citation", "citation");
2142
    dontOccur($doc, "//software", "software");
2143
    dontOccur($doc, "//protocol", "protocol");
2144
    dontOccur($doc, "//additionalMetadata", "additionalMetadata");    
2145
}
2146

    
2147
################################################################################
2148
# 
2149
# Delete the eml file that has been requested for deletion. 
2150
#
2151
################################################################################
2152
sub deleteData {
2153
    my $deleteAll = shift;
2154
    
2155
    # create metacat instance
2156
    my $metacat;
2157
    my $docid = $FORM::docid;
2158
    
2159
    $metacat = Metacat->new();
2160
    if ($metacat) {
2161
        $metacat->set_options( metacatUrl => $metacatUrl );
2162
    } else {
2163
        #die "failed during metacat creation\n";
2164
        push(@errorMessages, "Failed during metacat creation.");
2165
    }
2166

    
2167
    # Login to metacat
2168
    my $userDN = $FORM::username;
2169
    my $userOrg = $FORM::organization;
2170
    my $userPass = $FORM::password;
2171
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
2172
    
2173
    my $errorMessage = "";
2174
    my $response = $metacat->login($dname, $userPass);
2175

    
2176
    if (! $response) {
2177
    # Could not login
2178
        push(@errorMessages, $metacat->getMessage());
2179
        push(@errorMessages, "Failed during login.\n");
2180

    
2181
    } else {
2182
    #Able to login - try to delete the file    
2183

    
2184
    my $parser;
2185
    my @fileArray;
2186
    my $httpMessage;
2187
    my $xmldoc;
2188
    my $doc;
2189
    my $pushDoc;
2190
    my $alreadyInArray;
2191
    my $findType;
2192
        my $node;
2193
    my $response; 
2194
    my $element;
2195

    
2196
    push (@fileArray, $docid);
2197
    $parser = XML::LibXML->new();
2198

    
2199
        $httpMessage = $metacat->read($docid);
2200
    $doc = $httpMessage->content();    
2201
    $xmldoc = $parser->parse_string($doc);
2202

    
2203
    if ($xmldoc eq "") {
2204
        $error ="Error in parsing the eml document";
2205
        push(@errorMessages, $error);
2206
    } else {
2207

    
2208
        $findType = $xmldoc->findnodes('//dataset/identifier');
2209
        if($findType->size() > 0){
2210
        # This is a eml beta6 document
2211
        # Delete the documents mentioned in triples also
2212
        
2213
        $findType = $xmldoc->findnodes('//dataset/triple');
2214
        if($findType->size() > 0){
2215
            foreach $node ($findType->get_nodelist){
2216
            $pushDoc = findValue($node, 'subject');
2217
            
2218
            # If the file is already in the @fileArray then do not add it 
2219
            $alreadyInArray = 0;
2220
            foreach $element (@fileArray){
2221
                if($element eq $pushDoc){
2222
                $alreadyInArray = 1;
2223
                }
2224
            }
2225
            
2226
            if(!$alreadyInArray){
2227
                # If not already in array then delete the file. 
2228
                push (@fileArray, $pushDoc);
2229
                $response = $metacat->delete($pushDoc);
2230
                
2231
                if (! $response) {
2232
                # Could not delete
2233
                #push(@errorMessages, $response);
2234
                push(@errorMessages, $metacat->getMessage());
2235
                push(@errorMessages, "Failed during deleting $pushDoc. Please check if you are authorized to delete this document.\n");
2236
                }
2237
            }
2238
            }
2239
        }
2240
        }
2241
    }
2242
    
2243
    # Delete the main document. 
2244
    if($deleteAll){
2245
        $response = $metacat->delete($docid);  
2246
        if (! $response) {
2247
        # Could not delete
2248
        #push(@errorMessages, $response);
2249
        push(@errorMessages, $metacat->getMessage());
2250
        push(@errorMessages, "Failed during deleting $docid. Please check if you are authorized to delete this document.\n");
2251
        }
2252
    }
2253
    }
2254
    
2255
    if (scalar(@errorMessages)) {
2256
    # If any errors, print them in the response template 
2257
    $$templateVars{'status'} = 'failure';
2258
    $$templateVars{'errorMessages'} = \@errorMessages;
2259
    $error = 1;
2260
    }
2261
    
2262
    # Process the response template
2263
    if($deleteAll){
2264

    
2265
    $$templateVars{'function'} = "deleted";
2266
    $$templateVars{'section'} = "Deletion Status";
2267
    $template->process( $responseTemplate, $templateVars);
2268
    }
2269
}
2270

    
2271

    
2272
################################################################################
2273
# 
2274
# Do data validation and send the data to confirm data template.
2275
#
2276
################################################################################
2277
sub toConfirmData{
2278
    # Check if any invalid parameters
2279
 
2280
    my $invalidParams;
2281
    if (! $error) {
2282
    $invalidParams = validateParameters(0);
2283
    if (scalar(@$invalidParams)) {
2284
        $$templateVars{'status'} = 'failure';
2285
        $$templateVars{'invalidParams'} = $invalidParams;
2286
        $error = 1;
2287
    }
2288
    }
2289

    
2290

    
2291
    $$templateVars{'providerGivenName'} = normalizeCD($FORM::providerGivenName);
2292
    $$templateVars{'providerSurName'} = normalizeCD($FORM::providerSurName);
2293
    if($FORM::site eq "Select your station here."){
2294
        $$templateVars{'site'} = "";
2295
    }else{
2296
        $$templateVars{'site'} = $FORM::site;
2297
    }
2298
    if($FORM::cfg eq "nceas"){
2299
        $$templateVars{'wg'} = \@FORM::wg;
2300
    }
2301
    $$templateVars{'identifier'} = normalizeCD($FORM::identifier);
2302
    $$templateVars{'title'} = normalizeCD($FORM::title);
2303
    $$templateVars{'origNamefirst0'} = normalizeCD($FORM::origNamefirst0);
2304
    $$templateVars{'origNamelast0'} = normalizeCD($FORM::origNamelast0);
2305
    $$templateVars{'origNameOrg'} = normalizeCD($FORM::origNameOrg);
2306
    # $$templateVars{'origRole0'} = $FORM::origRole0;
2307
    $$templateVars{'origDelivery'} = normalizeCD($FORM::origDelivery);
2308
    $$templateVars{'origCity'} = normalizeCD($FORM::origCity);
2309
    if($FORM::origState eq "Select State Here."){
2310
        $$templateVars{'origState'} = "";
2311
    }else{
2312
        $$templateVars{'origState'} = $FORM::origState;
2313
    }
2314
    $$templateVars{'origStateOther'} = normalizeCD($FORM::origStateOther);
2315
    $$templateVars{'origZIP'} = normalizeCD($FORM::origZIP);
2316
    $$templateVars{'origCountry'} = normalizeCD($FORM::origCountry);
2317
    $$templateVars{'origPhone'} = normalizeCD($FORM::origPhone);
2318
    $$templateVars{'origFAX'} = normalizeCD($FORM::origFAX);
2319
    $$templateVars{'origEmail'} = normalizeCD($FORM::origEmail);
2320
    $$templateVars{'useOrigAddress'} = normalizeCD($FORM::useOrigAddress);
2321
    if($FORM::useOrigAddress eq "on"){
2322
        $$templateVars{'origNamefirstContact'} = normalizeCD($FORM::origNamefirst0);
2323
        $$templateVars{'origNamelastContact'} = normalizeCD($FORM::origNamelast0);
2324
        $$templateVars{'origNameOrgContact'} = normalizeCD($FORM::origNameOrg);
2325
        $$templateVars{'origDeliveryContact'} = normalizeCD($FORM::origDelivery); 
2326
        $$templateVars{'origCityContact'} = normalizeCD($FORM::origCity);
2327
        if($FORM::origState eq "Select State Here."){
2328
        $$templateVars{'origStateContact'} = "";
2329
        }else{
2330
        $$templateVars{'origStateContact'} = $FORM::origState;
2331
        }
2332
        $$templateVars{'origStateOtherContact'} = normalizeCD($FORM::origStateOther);
2333
        $$templateVars{'origZIPContact'} = normalizeCD($FORM::origZIP);
2334
        $$templateVars{'origCountryContact'} = normalizeCD($FORM::origCountry);
2335
        $$templateVars{'origPhoneContact'} = normalizeCD($FORM::origPhone);
2336
        $$templateVars{'origFAXContact'} = normalizeCD($FORM::origFAX);
2337
        $$templateVars{'origEmailContact'} = normalizeCD($FORM::origEmail);
2338
    }else{
2339
        $$templateVars{'origNamefirstContact'} = normalizeCD($FORM::origNamefirstContact);
2340
        $$templateVars{'origNamelastContact'} = normalizeCD($FORM::origNamelastContact);
2341
        $$templateVars{'origNameOrgContact'} = normalizeCD($FORM::origNameOrgContact);
2342
        $$templateVars{'origDeliveryContact'} = normalizeCD($FORM::origDeliveryContact); 
2343
        $$templateVars{'origCityContact'} = normalizeCD($FORM::origCityContact);
2344
        if($FORM::origStateContact eq "Select State Here."){
2345
        $$templateVars{'origStateContact'} = "";
2346
        }else{
2347
        $$templateVars{'origStateContact'} = $FORM::origStateContact;
2348
        }
2349
        $$templateVars{'origStateOtherContact'} = normalizeCD($FORM::origStateOtherContact);
2350
        $$templateVars{'origZIPContact'} = normalizeCD($FORM::origZIPContact);
2351
        $$templateVars{'origCountryContact'} = normalizeCD($FORM::origCountryContact);
2352
        $$templateVars{'origPhoneContact'} = normalizeCD($FORM::origPhoneContact);
2353
        $$templateVars{'origFAXContact'} = normalizeCD($FORM::origFAXContact);
2354
        $$templateVars{'origEmailContact'} = normalizeCD($FORM::origEmailContact);    
2355
    }
2356

    
2357
    $$templateVars{'aoCount'} = $FORM::aoCount;
2358
    foreach my $origName (param()) {
2359
	if ($origName =~ /origNamefirst/) {
2360
	    my $origNameIndex = $origName;
2361
	    $origNameIndex =~ s/origNamefirst//; # get the index of the parameter 0, ..., 10
2362
	    my $origNamelast = "origNamelast".$origNameIndex;
2363
	    my $origRole = "origRole".$origNameIndex;
2364
	    if ( $origNameIndex =~ /[0-9]/  && $origNameIndex > 0){
2365
		if (hasContent(param($origName)) && hasContent(param($origNamelast)) && hasContent(param($origRole))) {
2366
		    debug("Registry processing keyword: $origName = ".param($origName)." $origNamelast = ".param($origNamelast)." $origRole = ".param($origRole));
2367
		    $$templateVars{$origName} = normalizeCD(param($origName));
2368
		    $$templateVars{$origNamelast} = normalizeCD(param($origNamelast));
2369
		    $$templateVars{$origRole} = normalizeCD(param($origRole));
2370
		}
2371
	    }
2372
	}
2373
    }
2374

    
2375
    $$templateVars{'abstract'} = normalizeCD($FORM::abstract);
2376
    $$templateVars{'keyCount'} = $FORM::keyCount;
2377
    foreach my $kyd (param()) {
2378
	if ($kyd =~ /keyword/) {
2379
	    my $keyIndex = $kyd;
2380
	    $keyIndex =~ s/keyword//; # get the index of the parameter 0, ..., 10
2381
	    my $keyType = "kwType".$keyIndex;
2382
	    my $keyTh = "kwTh".$keyIndex;
2383
	    if ( $keyIndex =~ /[0-9]/ ){
2384
		if (hasContent(param($kyd)) && hasContent(param($keyType)) && hasContent(param($keyTh))) {
2385
		    debug("Registry processing keyword: $kyd = ".param($kyd)." $keyType = ".param($keyType)." $keyTh = ".param($keyTh));
2386
		    $$templateVars{$kyd} = normalizeCD(param($kyd));
2387
		    $$templateVars{$keyType} = param($keyType);
2388
		    $$templateVars{$keyTh} = param($keyTh);
2389
		}
2390
	    }
2391
	}
2392
    }
2393
    $$templateVars{'addComments'} = normalizeCD($FORM::addComments);
2394
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2395
    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2396
    $$templateVars{'url'} = $FORM::url;
2397
    if($FORM::dataMedium eq "Select type of medium here."){
2398
        $$templateVars{'dataMedium'} = "";
2399
    }else{
2400
        $$templateVars{'dataMedium'} = $FORM::dataMedium;
2401
    }    
2402
    $$templateVars{'dataMediumOther'} = normalizeCD($FORM::dataMediumOther);
2403
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2404
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2405
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2406
    $$templateVars{'endingYear'} = $FORM::endingYear;
2407
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2408
    $$templateVars{'endingDay'} = $FORM::endingDay;
2409
    $$templateVars{'geogdesc'} = normalizeCD($FORM::geogdesc);
2410
    $$templateVars{'useSiteCoord'} = $FORM::useSiteCoord;
2411
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2412
    $$templateVars{'latMin1'} = $FORM::latMin1;
2413
    $$templateVars{'latSec1'} = $FORM::latSec1;
2414
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2415
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2416
    $$templateVars{'longMin1'} = $FORM::longMin1;
2417
    $$templateVars{'longSec1'} = $FORM::longSec1;
2418
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2419
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2420
    $$templateVars{'latMin2'} = $FORM::latMin2;
2421
    $$templateVars{'latSec2'} = $FORM::latSec2;
2422
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2423
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2424
    $$templateVars{'longMin2'} = $FORM::longMin2;
2425
    $$templateVars{'longSec2'} = $FORM::longSec2;
2426
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2427

    
2428
    $$templateVars{'taxaCount'} = $FORM::taxaCount;
2429
    foreach my $trn (param()) {
2430
        if ($trn =~ /taxonRankName/) {
2431
            my $taxIndex = $trn;
2432
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
2433
            my $trv = "taxonRankValue".$taxIndex;
2434
            if ( $taxIndex =~ /[0-9]/ ){
2435
                if (hasContent(param($trn)) && hasContent(param($trv))) {
2436
                    debug("Registry processing taxon: $trn = ".param($trn)." $trv = ".param($trv));
2437
                    $$templateVars{$trn} = normalizeCD(param($trn));
2438
                    $$templateVars{$trv} = normalizeCD(param($trv));
2439
                }
2440
            }
2441
        }
2442
    }
2443
    $$templateVars{'taxaAuth'} = normalizeCD($FORM::taxaAuth);
2444

    
2445
    $$templateVars{'methodTitle'} = normalizeCD($FORM::methodTitle);
2446

    
2447
    my @tempMethodPara;
2448
    for (my $i = 0; $i < scalar(@FORM::methodPara); $i++) {
2449
	$tempMethodPara[$i] = normalizeCD($FORM::methodPara[$i]);
2450
    }
2451
    $$templateVars{'methodPara'} = \@tempMethodPara;
2452
    $$templateVars{'studyExtentDescription'} = normalizeCD($FORM::studyExtentDescription);
2453
    $$templateVars{'samplingDescription'} = normalizeCD($FORM::samplingDescription);
2454
    $$templateVars{'origStateContact'} = $FORM::origState;
2455

    
2456
    $$templateVars{'showSiteList'} = $FORM::showSiteList;
2457
    $$templateVars{'lsite'} = $FORM::lsite;
2458
    $$templateVars{'usite'} = $FORM::usite;
2459
    $$templateVars{'showWgList'} = $FORM::showWgList;
2460
    $$templateVars{'showOrganization'} = $FORM::showOrganization;
2461
    $$templateVars{'hasKeyword'} = $FORM::hasKeyword;
2462
    $$templateVars{'hasTemporal'} = $FORM::hasTemporal;
2463
    $$templateVars{'hasSpatial'} = $FORM::hasSpatial;
2464
    $$templateVars{'hasTaxonomic'} = $FORM::hasTaxonomic;
2465
    $$templateVars{'hasMethod'} = $FORM::hasMethod;
2466
    $$templateVars{'spatialRequired'} = $FORM::spatialRequired;
2467
    $$templateVars{'temporalRequired'} = $FORM::temporalRequired;
2468

    
2469
    $$templateVars{'docid'} = $FORM::docid;
2470

    
2471
    if (! $error) {
2472
	# If no errors, then print out data in confirm Data template
2473

    
2474
	$$templateVars{'section'} = "Confirm Data";
2475
	$template->process( $confirmDataTemplate, $templateVars);
2476

    
2477
    } else{    
2478
    # Errors from validation function. print the errors out using the response template
2479
    if (scalar(@errorMessages)) {
2480
        $$templateVars{'status'} = 'failure';
2481
        $$templateVars{'errorMessages'} = \@errorMessages;
2482
        $error = 1;
2483
    }
2484
        # Create our HTML response and send it back
2485
    $$templateVars{'function'} = "submitted";
2486
    $$templateVars{'section'} = "Submission Status";
2487
    $template->process( $responseTemplate, $templateVars);
2488
    }
2489
}
2490

    
2491

    
2492
################################################################################
2493
# 
2494
# From confirm Data template - user wants to make some changes.
2495
#
2496
################################################################################
2497
sub confirmDataToReEntryData{
2498
    my @sortedSites;
2499
    foreach my $site (sort @sitelist) {
2500
        push(@sortedSites, $site);
2501
    }
2502

    
2503
    $$templateVars{'siteList'} = \@sortedSites;
2504
    $$templateVars{'section'} = "Re-Entry Form";
2505
    copyFormToTemplateVars();
2506
    $$templateVars{'docid'} = $FORM::docid;
2507

    
2508
    $$templateVars{'form'} = 're_entry';
2509
    $template->process( $entryFormTemplate, $templateVars);
2510
}
2511

    
2512

    
2513
################################################################################
2514
# 
2515
# Copy form data to templateVars.....
2516
#
2517
################################################################################
2518
sub copyFormToTemplateVars{
2519
    $$templateVars{'providerGivenName'} = $FORM::providerGivenName;
2520
    $$templateVars{'providerSurName'} = $FORM::providerSurName;
2521
    $$templateVars{'site'} = $FORM::site;
2522
    if ($FORM::cfg eq "nceas") {
2523
        my $projects = getProjectList();
2524
        $$templateVars{'projects'} = $projects;
2525
        $$templateVars{'wg'} = \@FORM::wg;
2526
    }
2527
    $$templateVars{'identifier'} = $FORM::identifier;
2528
    $$templateVars{'title'} = $FORM::title;
2529
    $$templateVars{'origNamefirst0'} = $FORM::origNamefirst0;
2530
    $$templateVars{'origNamelast0'} = $FORM::origNamelast0;
2531
    $$templateVars{'origNameOrg'} = $FORM::origNameOrg;
2532
 #   $$templateVars{'origRole0'} = $FORM::origRole0;
2533
    $$templateVars{'origDelivery'} = $FORM::origDelivery;
2534
    $$templateVars{'origCity'} = $FORM::origCity;
2535
    $$templateVars{'origState'} = $FORM::origState;
2536
    $$templateVars{'origStateOther'} = $FORM::origStateOther;
2537
    $$templateVars{'origZIP'} = $FORM::origZIP;
2538
    $$templateVars{'origCountry'} = $FORM::origCountry;
2539
    $$templateVars{'origPhone'} = $FORM::origPhone;
2540
    $$templateVars{'origFAX'} = $FORM::origFAX;
2541
    $$templateVars{'origEmail'} = $FORM::origEmail;
2542
    if ($FORM::useSiteCoord ne "") {
2543
        $$templateVars{'useOrigAddress'} = "CHECKED";
2544
    }else{
2545
        $$templateVars{'useOrigAddress'} = $FORM::useOrigAddress;
2546
    }
2547
    $$templateVars{'origNamefirstContact'} = $FORM::origNamefirstContact;
2548
    $$templateVars{'origNamelastContact'} = $FORM::origNamelastContact;
2549
    $$templateVars{'origNameOrgContact'} = $FORM::origNameOrgContact;
2550
    $$templateVars{'origDeliveryContact'} = $FORM::origDeliveryContact; 
2551
    $$templateVars{'origCityContact'} = $FORM::origCityContact;
2552
    $$templateVars{'origStateContact'} = $FORM::origStateContact;
2553
    $$templateVars{'origStateOtherContact'} = $FORM::origStateOtherContact;
2554
    $$templateVars{'origZIPContact'} = $FORM::origZIPContact;
2555
    $$templateVars{'origCountryContact'} = $FORM::origCountryContact;
2556
    $$templateVars{'origPhoneContact'} = $FORM::origPhoneContact;
2557
    $$templateVars{'origFAXContact'} = $FORM::origFAXContact;
2558
    $$templateVars{'origEmailContact'} = $FORM::origEmailContact;    
2559
    
2560
    $$templateVars{'aoCount'} = $FORM::aoCount;
2561
    foreach my $origName (param()) {
2562
	if ($origName =~ /origNamefirst/) {
2563
	    my $origNameIndex = $origName;
2564
	    $origNameIndex =~ s/origNamefirst//; # get the index of the parameter 0, ..., 10
2565
	    my $origNamelast = "origNamelast".$origNameIndex;
2566
	    my $origRole = "origRole".$origNameIndex;
2567
	    if ( $origNameIndex =~ /[0-9]/  && $origNameIndex > 0){
2568
		if (hasContent(param($origName)) && hasContent(param($origNamelast)) && hasContent(param($origRole))) {
2569
		    debug("Registry processing keyword: $origName = ".param($origName)." $origNamelast = ".param($origNamelast)." $origRole = ".param($origRole));
2570
		    $$templateVars{$origName} = normalizeCD(param($origName));
2571
		    $$templateVars{$origNamelast} = normalizeCD(param($origNamelast));
2572
		    $$templateVars{$origRole} = normalizeCD(param($origRole));
2573
		}
2574
	    }
2575
	}
2576
    }
2577

    
2578
    $$templateVars{'abstract'} = $FORM::abstract;
2579
    $$templateVars{'keyCount'} = $FORM::keyCount;
2580
    foreach my $kyd (param()) {
2581
	if ($kyd =~ /keyword/) {
2582
	    my $keyIndex = $kyd;
2583
	    $keyIndex =~ s/keyword//; # get the index of the parameter 0, ..., 10
2584
	    my $keyType = "kwType".$keyIndex;
2585
	    my $keyTh = "kwTh".$keyIndex;
2586
	    if ( $keyIndex =~ /[0-9]/ ){
2587
		if (hasContent(param($kyd)) && hasContent(param($keyType)) && hasContent(param($keyTh))) {
2588
		    debug("Registry processing keyword: $kyd = ".param($kyd)." $keyType = ".param($keyType)." $keyTh = ".param($keyTh));
2589
		    $$templateVars{$kyd} = param($kyd);
2590
		    $$templateVars{$keyType} = param($keyType);
2591
		    $$templateVars{$keyTh} = param($keyTh);
2592
		}
2593
	    }
2594
	}
2595
    }
2596
    $$templateVars{'addComments'} = $FORM::addComments;
2597
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2598
    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2599
    $$templateVars{'url'} = $FORM::url;
2600
    $$templateVars{'dataMedium'} = $FORM::dataMedium;
2601
    $$templateVars{'dataMediumOther'} = $FORM::dataMediumOther;
2602
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2603
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2604
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2605
    $$templateVars{'endingYear'} = $FORM::endingYear;
2606
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2607
    $$templateVars{'endingDay'} = $FORM::endingDay;
2608
    $$templateVars{'geogdesc'} = $FORM::geogdesc;
2609
    if($FORM::useSiteCoord ne ""){
2610
    $$templateVars{'useSiteCoord'} = "CHECKED";
2611
    }else{
2612
    $$templateVars{'useSiteCoord'} = "";
2613
    }
2614
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2615
    $$templateVars{'latMin1'} = $FORM::latMin1;
2616
    $$templateVars{'latSec1'} = $FORM::latSec1;
2617
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2618
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2619
    $$templateVars{'longMin1'} = $FORM::longMin1;
2620
    $$templateVars{'longSec1'} = $FORM::longSec1;
2621
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2622
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2623
    $$templateVars{'latMin2'} = $FORM::latMin2;
2624
    $$templateVars{'latSec2'} = $FORM::latSec2;
2625
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2626
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2627
    $$templateVars{'longMin2'} = $FORM::longMin2;
2628
    $$templateVars{'longSec2'} = $FORM::longSec2;
2629
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2630
    $$templateVars{'taxaCount'} = $FORM::taxaCount;
2631
    foreach my $trn (param()) {
2632
        if ($trn =~ /taxonRankName/) {
2633
            my $taxIndex = $trn;
2634
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
2635
            my $trv = "taxonRankValue".$taxIndex;
2636
            if ( $taxIndex =~ /[0-9]/ ){
2637
                if (hasContent(param($trn)) && hasContent(param($trv))) {
2638
                    debug("Registry processing taxon: $trn = ".param($trn)." $trv = ".param($trv));
2639
                    $$templateVars{$trn} = param($trn);
2640
                    $$templateVars{$trv} = param($trv);
2641
                }
2642
            }
2643
        }
2644
    }
2645
    $$templateVars{'taxaAuth'} = $FORM::taxaAuth;
2646
    $$templateVars{'methodTitle'} = $FORM::methodTitle;
2647
    $$templateVars{'methodPara'} = \@FORM::methodPara;
2648
    $$templateVars{'studyExtentDescription'} = $FORM::studyExtentDescription;
2649
    $$templateVars{'samplingDescription'} = $FORM::samplingDescription;
2650
    
2651
    $$templateVars{'showSiteList'} = $FORM::showSiteList;
2652
    $$templateVars{'lsite'} = $FORM::lsite;
2653
    $$templateVars{'usite'} = $FORM::usite;
2654
    $$templateVars{'showWgList'} = $FORM::showWgList;
2655
    $$templateVars{'showOrganization'} = $FORM::showOrganization;
2656
    $$templateVars{'hasKeyword'} = $FORM::hasKeyword;
2657
    $$templateVars{'hasTemporal'} = $FORM::hasTemporal;
2658
    $$templateVars{'hasSpatial'} = $FORM::hasSpatial;
2659
    $$templateVars{'hasTaxonomic'} = $FORM::hasTaxonomic;
2660
    $$templateVars{'hasMethod'} = $FORM::hasMethod;
2661
    $$templateVars{'spatialRequired'} = $FORM::spatialRequired;
2662
    $$templateVars{'temporalRequired'} = $FORM::temporalRequired;
2663
}
2664

    
2665
################################################################################
2666
# 
2667
# check if there is multiple occurence of the given tag and find its value.
2668
#
2669
################################################################################
2670

    
2671
sub findValue {
2672
    my $node = shift;
2673
    my $value = shift;
2674
    my $result;
2675
    my $tempNode;
2676

    
2677
    $result = $node->findnodes("./$value");
2678
    if ($result->size > 1) {
2679
        errMoreThanOne("$value");
2680
    } else {
2681
        foreach $tempNode ($result->get_nodelist){
2682
            #print $tempNode->nodeName().":".$tempNode->textContent();
2683
            #print "\n";
2684
            return $tempNode->textContent();
2685
        }
2686
    }
2687
}
2688

    
2689

    
2690
################################################################################
2691
# 
2692
# check if given tags has any children. if not return the value
2693
#
2694
################################################################################
2695
sub findValueNoChild {
2696
    my $node = shift;
2697
    my $value = shift;
2698
    my $tempNode;
2699
    my $childNodes;
2700
    my $result;
2701
    my $error;
2702

    
2703
    $result = $node->findnodes("./$value");
2704
    if($result->size > 1){
2705
       errMoreThanOne("$value");
2706
    } else {
2707
        foreach $tempNode ($result->get_nodelist) {
2708
            $childNodes = $tempNode->childNodes;
2709
            if ($childNodes->size() > 1) {
2710
                $error ="The tag $value has children which cannot be shown using the form. Please use Morpho to edit this document";    
2711
                push(@errorMessages, $error);
2712
                #if ($DEBUG == 1){ print $error."\n";}
2713
            } else {
2714
                #print $tempNode->nodeName().":".$tempNode->textContent();
2715
                #print "\n";
2716
                return $tempNode->textContent();
2717
            }
2718
        }
2719
    }
2720
}
2721

    
2722

    
2723
################################################################################
2724
# 
2725
# check if given tags are children of given node.
2726
#
2727
################################################################################
2728
sub dontOccur {
2729
    my $node = shift;
2730
    my $value = shift;
2731
    my $errVal = shift;
2732

    
2733
    my $result = $node->findnodes("$value");
2734
    if($result->size > 0){
2735
        $error ="One of the following tags found: $errVal. Please use Morpho to edit this document";
2736
        push(@errorMessages, $error."\n");
2737
        #if ($DEBUG == 1){ print $error;}
2738
    } 
2739
}
2740

    
2741

    
2742
################################################################################
2743
# 
2744
# print out error for more than one occurence of a given tag
2745
#
2746
################################################################################
2747
sub errMoreThanOne {
2748
    my $value = shift;
2749
    my $error ="More than one occurence of the tag $value found. Please use Morpho to edit this document";
2750
    push(@errorMessages, $error."\n");
2751
    # if ($DEBUG == 1){ print $error;}
2752
}
2753

    
2754

    
2755
################################################################################
2756
# 
2757
# print out error for more than given number of occurences of a given tag
2758
#
2759
################################################################################
2760
sub errMoreThanN {
2761
    my $value = shift;
2762
    my $error ="More occurences of the tag $value found than that can be shown in the form. Please use Morpho to edit this document";
2763
    push(@errorMessages, $error);
2764
    #if ($DEBUG == 1){ print $error."\n";}
2765
}
2766

    
2767

    
2768
################################################################################
2769
# 
2770
# convert coord to degrees, minutes and seconds form. 
2771
#
2772
################################################################################
2773
#sub convertCoord {
2774
#    my $wx = shift;
2775
#    print $deg." ".$min." ".$sec;
2776
#    print "\n";
2777
#}
2778

    
2779

    
2780
################################################################################
2781
# 
2782
# print debugging messages to stderr
2783
#
2784
################################################################################
2785
sub debug {
2786
    my $msg = shift;
2787
    
2788
    if ($debug) {
2789
        print STDERR "$msg\n";
2790
    }
2791
}
2792

    
2793
################################################################################
2794
# 
2795
# get the list of projects
2796
#
2797
################################################################################
2798
sub getProjectList {
2799
    
2800
    use NCEAS::AdminDB;
2801
    my $admindb = NCEAS::AdminDB->new();
2802
    $admindb->connect($nceas_db, $nceas_db_user, $nceas_db_password);
2803
    my $projects = $admindb->getProjects();
2804
    #my $projects = getTestProjectList();
2805
    return $projects;
2806
}
2807

    
2808
################################################################################
2809
# 
2810
# get a test list of projects for use only in testing where the NCEAS
2811
# admin db is not available.
2812
#
2813
################################################################################
2814
sub getTestProjectList {
2815
    # This block is for testing only!  Remove for production use
2816
    my @row1;
2817
    $row1[0] = 6000; $row1[1] = 'Andelman'; $row1[2] = 'Sandy'; $row1[3] = 'The very long and windy path to an apparent ecological conclusion: statistics lie';
2818
    my @row2; 
2819
    $row2[0] = 7000; $row2[1] = 'Bascompte'; $row2[2] = 'Jordi'; $row2[3] = 'Postdoctoral Fellow';
2820
    my @row3; 
2821
    $row3[0] = 7001; $row3[1] = 'Hackett'; $row3[2] = 'Edward'; $row3[3] = 'Sociology rules the world';
2822
    my @row4; 
2823
    $row4[0] = 7002; $row4[1] = 'Jones'; $row4[2] = 'Matthew'; $row4[3] = 'Informatics rules the world';
2824
    my @row5; 
2825
    $row5[0] = 7003; $row5[1] = 'Schildhauer'; $row5[2] = 'Mark'; $row5[3] = 'Excel rocks my world, assuming a, b, and c';
2826
    my @row6; 
2827
    $row6[0] = 7004; $row6[1] = 'Rogers'; $row6[2] = 'Bill'; $row6[3] = 'Graduate Intern';
2828
    my @row7; 
2829
    $row7[0] = 7005; $row7[1] = 'Zedfried'; $row7[2] = 'Karl'; $row7[3] = 'A multivariate analysis of thing that go bump in the night';
2830
    my @projects;
2831
    $projects[0] = \@row1;
2832
    $projects[1] = \@row2;
2833
    $projects[2] = \@row3;
2834
    $projects[3] = \@row4;
2835
    $projects[4] = \@row5;
2836
    $projects[5] = \@row6;
2837
    $projects[6] = \@row7;
2838
    return \@projects;
2839
}
(4-4/5)