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: 2005-03-08 14:30:05 -0800 (Tue, 08 Mar 2005) $'
8
# '$Revision: 2403 $' 
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
    $$templateVars{'status'} = "Cancel";
235
    $$templateVars{'function'} = "cancel";
236
    $template->process( $responseTemplate, $templateVars);
237
    exit(0);
238
    }
239

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

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

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

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

    
284
# Confirm stage has been reached. Enter the data into metacat. 
285

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

    
304
# validate the input form parameters
305
my $invalidParams;
306

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

    
316

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

    
322
    my $xmldoc = createXMLDocument();
323

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

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

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

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

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

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

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

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

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

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

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

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

    
435
        exit(0);
436
    }
437
}
438

    
439
debug("Registry: C");
440

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

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

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

    
461
$template->process( $responseTemplate, $templateVars);
462

    
463
exit(0);
464

    
465

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

    
474
  my $errormsg = 0;
475
  my $docid = $metacat->getLastId($scope);
476

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

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

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

    
526
  return $notunique;
527
}
528

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

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

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

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

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

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

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

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

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

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

    
698

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

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

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

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

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

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

    
768
    $val =~ s/&/&amp;/g;
769

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

    
801

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

    
813
    $val =~ s/\"/&quot;/g;
814
    
815
    return $val;
816
}
817

    
818

    
819
################################################################################
820
# 
821
# Create the XML document from the HTML form input
822
# returns the XML document as a string
823
#
824
################################################################################
825
sub createXMLDocument {
826

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

    
837

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

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

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

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

    
870
    if (hasContent($FORM::origNameOrg)) {
871
        $orig .= "<organizationName>".normalize($FORM::origNameOrg)."</organizationName>\n";
872
    }
873

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

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

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

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

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

    
935
    $creat .= $dso;
936

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

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

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

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

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

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

    
1063
    $doc .= $creat;
1064
    $doc .= $metaP;
1065
    $doc .= $apart;
1066

    
1067
    $doc .= "<abstract>\n";
1068
    $doc .= "<para>".normalize($FORM::abstract)."</para>\n";
1069
    $doc .= "</abstract>\n";
1070

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

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

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

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

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

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

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

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

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

    
1333
    return $doc;
1334
}
1335

    
1336

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

    
1348
    my $smtp = Net::SMTP->new($mailhost);
1349
    $smtp->mail($sender);
1350
    $smtp->to($recipient);
1351

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

    
1360
    Identifier: $identifier
1361
    Title: $FORM::title
1362
    Submitter: $FORM::providerGivenName $FORM::providerSurName
1363

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

    
1370
    $smtp->data($message);
1371
    $smtp->quit;
1372
}
1373

    
1374

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

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

    
1410
    #$tempfile = $xslConvDir.$docid;
1411
    #push (@fileArray, $tempfile);
1412

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

    
1458
            # Read the main document. 
1459

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

    
1478
            #$results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1479
            $results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1480

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

    
1491
            getFormValuesFromEml2($resultsheet);
1492
            
1493
            # Delete the files written earlier. 
1494
            unlink @fileArray;
1495

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

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

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

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

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

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

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

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

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

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

    
1735
  #  if ($aoCount > 11) {
1736
  #      errMoreThanN("Additional Originators");
1737
 #   } 
1738

    
1739
    $$templateVars{'aoCount'} = $aoCount;
1740
    
1741
    dontOccur($doc, "./pubDate", "pubDate");
1742
    dontOccur($doc, "./language", "language");
1743
    dontOccur($doc, "./series", "series");
1744

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

    
1755
    $results = $doc->findnodes('//dataset/keywordSet');
1756

    
1757
    my $count = 1;
1758
    foreach $node ($results->get_nodelist) {
1759
	$tempResult = $node->findnodes('./keyword');
1760
	if ($tempResult->size() > 1) {
1761
	    errMoreThanOne("keyword");
1762
	} else {
1763
	    foreach $tempNode ($tempResult->get_nodelist) {
1764
		$$templateVars{"keyword$count"} = $tempNode->textContent();
1765
		if ($tempNode->hasAttributes()) {
1766
		    my @attlist = $tempNode->attributes();
1767
                    my $tmp = $attlist[0]->value;  #convert the first letter to upper case
1768
		    $tmp =~ s/\b(\w)/\U$1/g;
1769
		    $$templateVars{"kwType$count"} = $tmp;
1770
		}  
1771
	    }
1772
	}
1773
	$$templateVars{"kwTh$count"} = findValue($node, "keywordThesaurus");
1774
        $count++;
1775
    }
1776
    $$templateVars{'keyCount'} = $count;
1777
    if($count > 0 ){
1778
       $$templateVars{'hasKeyword'} = "true";
1779
    }
1780

    
1781
    $results = $doc->findnodes('//dataset/additionalInfo');
1782
    if ($results->size() > 1) {
1783
        errMoreThanOne("additionalInfo");
1784
    } else {
1785
        foreach $node ($results->get_nodelist) {
1786
            dontOccur($node, "./section", "section");
1787
            $$templateVars{'addComments'} = findValueNoChild($node, "para");
1788
        }
1789
    }
1790

    
1791
    $$templateVars{'useConstraints'} = "";
1792
    $results = $doc->findnodes('//dataset/intellectualRights');
1793
    if ($results->size() > 1) {
1794
        errMoreThanOne("intellectualRights");
1795
    } else {
1796
        foreach $node ($results->get_nodelist) {
1797
            dontOccur($node, "./section", "section in intellectualRights");
1798

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

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

    
1834
    $results = $doc->findnodes('//dataset/distribution/offline');
1835
    if ($results->size() > 1) {
1836
        errMoreThanOne("distribution/online");
1837
    } else {
1838
        foreach my $tempNode ($results->get_nodelist) {
1839
            my $temp = findValue($tempNode, "mediumName");
1840
            if(substr($temp, 0, 5) eq "other"){
1841
                $$templateVars{'dataMedium'} = substr($temp, 0, 5);
1842
                $$templateVars{'dataMediumOther'} = substr($temp, 5);
1843
            } else {
1844
                $$templateVars{'dataMedium'} = $temp;
1845
            }
1846
            dontOccur($tempNode, "./mediumDensity", "/distribution/offline/mediumDensity");
1847
            dontOccur($tempNode, "./mediumDensityUnits", "/distribution/offline/mediumDensityUnits");
1848
            dontOccur($tempNode, "./mediumVolume", "/distribution/offline/mediumVolume");
1849
            dontOccur($tempNode, "./mediumFormat", "/distribution/offline/mediumFormat");
1850
            dontOccur($tempNode, "./mediumNote", "/distribution/offline/mediumNote");
1851
        }
1852
    }
1853

    
1854
    dontOccur($doc, "./inline", "//dataset/distribution/inline");
1855

    
1856
    $results = $doc->findnodes('//dataset/coverage');
1857
    if ($results->size() > 1) {
1858
        errMoreThanOne("coverage");
1859
    } else {
1860
        foreach $node ($results->get_nodelist) {
1861
            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");
1862

    
1863
            $tempResult = $node->findnodes('./temporalCoverage');
1864
            if ($tempResult->size > 1) {
1865
                   errMoreThanOne("temporalCoverage");
1866
            } else {
1867
                foreach $tempNode ($tempResult->get_nodelist) {
1868
                    my $x;
1869
                    my $y;
1870
                    my $z;
1871
                    my $tempdate = findValue($tempNode, "rangeOfDates/beginDate/calendarDate");
1872
                    ($x, $y, $z) = split("-", $tempdate); 
1873
                    $$templateVars{'beginningYear'} = $x;
1874
                    $$templateVars{'beginningMonth'} = $y;
1875
                    $$templateVars{'beginningDay'} = $z;
1876
    
1877
                    $tempdate = findValue($tempNode, "rangeOfDates/endDate/calendarDate");
1878
                    ($x, $y, $z) = split("-", $tempdate);
1879
                    $$templateVars{'endingYear'} = $x;
1880
                    $$templateVars{'endingMonth'} = $y;
1881
                    $$templateVars{'endingDay'} = $z;
1882

    
1883
                    $tempdate = "";
1884
                    $tempdate = findValue($tempNode, "singleDateTime/calendarDate");
1885
                    if($tempdate ne ""){
1886
                        ($x, $y, $z) = split("-", $tempdate);
1887
                        $$templateVars{'beginningYear'} = $x;
1888
                        $$templateVars{'beginningMonth'} = $y;
1889
                        $$templateVars{'beginningDay'} = $z;
1890
                    }  
1891
		    
1892
		    $$templateVars{'hasTemporal'} = "true";
1893
                }
1894
            }
1895

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

    
1964
		            $$templateVars{'hasSpatial'} = "true";
1965
                }
1966
            }
1967

    
1968
            $tempResult = $node->findnodes('./taxonomicCoverage/taxonomicClassification');
1969
            my $taxonIndex = 0;
1970
            foreach $tempNode ($tempResult->get_nodelist) {
1971
                $taxonIndex++;
1972
                my $taxonRankName = findValue($tempNode, "taxonRankName");
1973
                my $taxonRankValue = findValue($tempNode, "taxonRankValue");
1974
                $$templateVars{"taxonRankName".$taxonIndex} = $taxonRankName;
1975
                $$templateVars{"taxonRankValue".$taxonIndex} = $taxonRankValue;
1976
		
1977
		$$templateVars{'hasTaxonomic'} = "true";
1978
            }
1979
            $$templateVars{'taxaCount'} = $taxonIndex;
1980
            my $taxaAuth = findValue($node, "./taxonomicCoverage/generalTaxonomicCoverage");
1981
            $$templateVars{'taxaAuth'} = $taxaAuth;
1982
        }
1983
    }
1984
    dontOccur($doc, "./purpose", "purpose");
1985
    dontOccur($doc, "./maintenance", "maintnance");
1986

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

    
2048
        my @methodPara;
2049
        foreach $node ($results->get_nodelist) {
2050
            my @children = $node->childNodes;
2051
            for (my $i = 0; $i < scalar(@children); $i++) {
2052
                debug("Registry: Method child loop ($i)");
2053
                my $child = $children[$i];
2054
                if ($child->nodeName eq 'title') {
2055
                    my $title = $child->textContent();
2056
                    debug("Registry: Method title ($title)");
2057
                    $$templateVars{'methodTitle'} = $title;
2058
                } elsif ($child->nodeName eq 'para') {
2059
                    my $para = $child->textContent();
2060
                    debug("Registry: Method para ($para)");
2061
                    $methodPara[scalar(@methodPara)] = $para;
2062
                }
2063
            }
2064
	    $$templateVars{'hasMethod'} = "true";
2065
        }
2066
        if (scalar(@methodPara) > 0) {
2067
            $$templateVars{'methodPara'} = \@methodPara;
2068
        }
2069
    }
2070

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

    
2080
	    $$templateVars{'hasMethod'} = "true";
2081
        }
2082
    }
2083

    
2084
    $results = $doc->findnodes(
2085
            '//dataset/methods/sampling/samplingDescription/para');
2086
    if ($results->size() > 1) {
2087
        errMoreThanN("methods/sampling/samplingDescription/para");    
2088
    } else {
2089
        foreach $node ($results->get_nodelist) {
2090
            my $samplingDescription = $node->textContent();
2091
            $$templateVars{'samplingDescription'} = $samplingDescription;
2092

    
2093
	    $$templateVars{'hasMethod'} = "true";
2094
        }
2095
    }
2096

    
2097
    dontOccur($doc, "//methodStep/citation", "methodStep/citation");
2098
    dontOccur($doc, "//methodStep/protocol", "methodStep/protocol");
2099
    dontOccur($doc, "//methodStep/instrumentation", "methodStep/instrumentation");
2100
    dontOccur($doc, "//methodStep/software", "methodStep/software");
2101
    dontOccur($doc, "//methodStep/subStep", "methodStep/subStep");
2102
    dontOccur($doc, "//methodStep/dataSource", "methodStep/dataSource");
2103
    dontOccur($doc, "//methods/qualityControl", "methods/qualityControl");
2104

    
2105
    dontOccur($doc, "//methods/sampling/spatialSamplingUnits", "methods/sampling/spatialSamplingUnits");
2106
    dontOccur($doc, "//methods/sampling/citation", "methods/sampling/citation");
2107
    dontOccur($doc, "./pubPlace", "pubPlace");
2108
    dontOccur($doc, "./project", "project");
2109
    
2110
    ############ Code for checking ACL #####################
2111
    dontOccur($doc, "//dataset/access/deny", "dataset/access/deny");
2112

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

    
2143

    
2144
    dontOccur($doc, "./dataTable", "dataTable");
2145
    dontOccur($doc, "./spatialRaster", "spatialRaster");
2146
    dontOccur($doc, "./spatialVector", "spatialVector");
2147
    dontOccur($doc, "./storedProcedure", "storedProcedure");
2148
    dontOccur($doc, "./view", "view");
2149
    dontOccur($doc, "./otherEntity", "otherEntity");
2150
    dontOccur($doc, "./references", "references");
2151
    
2152
    dontOccur($doc, "//citation", "citation");
2153
    dontOccur($doc, "//software", "software");
2154
    dontOccur($doc, "//protocol", "protocol");
2155
    dontOccur($doc, "//additionalMetadata", "additionalMetadata");    
2156
}
2157

    
2158
################################################################################
2159
# 
2160
# Delete the eml file that has been requested for deletion. 
2161
#
2162
################################################################################
2163
sub deleteData {
2164
    my $deleteAll = shift;
2165
    
2166
    # create metacat instance
2167
    my $metacat;
2168
    my $docid = $FORM::docid;
2169
    
2170
    $metacat = Metacat->new();
2171
    if ($metacat) {
2172
        $metacat->set_options( metacatUrl => $metacatUrl );
2173
    } else {
2174
        #die "failed during metacat creation\n";
2175
        push(@errorMessages, "Failed during metacat creation.");
2176
    }
2177

    
2178
    # Login to metacat
2179
    my $userDN = $FORM::username;
2180
    my $userOrg = $FORM::organization;
2181
    my $userPass = $FORM::password;
2182
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
2183
    
2184
    my $errorMessage = "";
2185
    my $response = $metacat->login($dname, $userPass);
2186

    
2187
    if (! $response) {
2188
    # Could not login
2189
        push(@errorMessages, $metacat->getMessage());
2190
        push(@errorMessages, "Failed during login.\n");
2191

    
2192
    } else {
2193
    #Able to login - try to delete the file    
2194

    
2195
    my $parser;
2196
    my @fileArray;
2197
    my $httpMessage;
2198
    my $xmldoc;
2199
    my $doc;
2200
    my $pushDoc;
2201
    my $alreadyInArray;
2202
    my $findType;
2203
        my $node;
2204
    my $response; 
2205
    my $element;
2206

    
2207
    push (@fileArray, $docid);
2208
    $parser = XML::LibXML->new();
2209

    
2210
        $httpMessage = $metacat->read($docid);
2211
    $doc = $httpMessage->content();    
2212
    $doc = normalize($doc);
2213
    $xmldoc = $parser->parse_string($doc);
2214

    
2215
    if ($xmldoc eq "") {
2216
        $error ="Error in parsing the eml document";
2217
        push(@errorMessages, $error);
2218
    } else {
2219

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

    
2277
    $$templateVars{'function'} = "deleted";
2278
    $$templateVars{'section'} = "Deletion Status";
2279
    $template->process( $responseTemplate, $templateVars);
2280
    }
2281
}
2282

    
2283

    
2284
################################################################################
2285
# 
2286
# Do data validation and send the data to confirm data template.
2287
#
2288
################################################################################
2289
sub toConfirmData{
2290
    # Check if any invalid parameters
2291
 
2292
    my $invalidParams;
2293
    if (! $error) {
2294
    $invalidParams = validateParameters(0);
2295
    if (scalar(@$invalidParams)) {
2296
        $$templateVars{'status'} = 'failure';
2297
        $$templateVars{'invalidParams'} = $invalidParams;
2298
        $error = 1;
2299
    }
2300
    }
2301

    
2302

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

    
2369
    my $aoFNArray = \@FORM::aoFirstName;
2370
    my $aoLNArray = \@FORM::aoLastName;
2371
    my $aoRoleArray = \@FORM::aoRole;
2372
    my $aoCount = 1;
2373

    
2374
    for(my $i = 0; $i <= $#$aoRoleArray; $i++){
2375
        if (hasContent($aoFNArray->[$i]) && hasContent($aoLNArray->[$i])) {
2376
            debug("Registry processing Associated Party: origName = ".$aoFNArray->[$i]
2377
                  ." origNamelast = ".$aoLNArray->[$i]." origRole = "
2378
                  .$aoRoleArray->[$i]);
2379
            $$templateVars{"origNamefirst".$aoCount} = normalizeCD($aoFNArray->[$i]);
2380
            $$templateVars{"origNamelast".$aoCount} = normalizeCD($aoLNArray->[$i]);
2381
            $$templateVars{"origRole".$aoCount} = normalizeCD($aoRoleArray->[$i]);
2382
            $aoCount++;
2383
	}    
2384
    }
2385

    
2386
    $$templateVars{'aoCount'} = $aoCount;
2387
    $$templateVars{'abstract'} = normalizeCD($FORM::abstract);
2388
   
2389
   
2390
    my $keywordArray = \@FORM::keyword;
2391
    my $keywordTypeArray = \@FORM::keywordType;
2392
    my $keywordThArray = \@FORM::keywordTh;
2393
    my $keyCount = 1;
2394
   
2395
    for(my $i = 0; $i <= $#$keywordArray; $i++){
2396
        if (hasContent($keywordArray->[$i])) {
2397
            debug("Registry processing keyword: keyword = ".$keywordArray->[$i]."
2398
                  keywordType = ".$keywordTypeArray->[$i]."
2399
                  keywordTh = ".$keywordThArray->[$i]);
2400
            $$templateVars{"keyword".$keyCount} = normalizeCD($keywordArray->[$i]);
2401
            $$templateVars{"kwType".$keyCount} = normalizeCD($keywordTypeArray->[$i]);
2402
            $$templateVars{"kwTh".$keyCount} = normalizeCD($keywordThArray->[$i]);
2403
            $keyCount++;
2404
	}    
2405
    }    
2406
    $$templateVars{'keyCount'} = $keyCount;
2407
    
2408
    $$templateVars{'addComments'} = normalizeCD($FORM::addComments);
2409
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2410
    if($FORM::useConstraints eq "other"){
2411
        $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2412
    }
2413
    $$templateVars{'url'} = $FORM::url;
2414
    $$templateVars{'dataMedium'} = $FORM::dataMedium;
2415
    if($FORM::dataMedium eq "other"){
2416
        $$templateVars{'dataMediumOther'} = normalizeCD($FORM::dataMediumOther);
2417
    }
2418
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2419
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2420
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2421
    $$templateVars{'endingYear'} = $FORM::endingYear;
2422
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2423
    $$templateVars{'endingDay'} = $FORM::endingDay;
2424
    $$templateVars{'geogdesc'} = normalizeCD($FORM::geogdesc);
2425
    $$templateVars{'useSiteCoord'} = $FORM::useSiteCoord;
2426
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2427
    $$templateVars{'latMin1'} = $FORM::latMin1;
2428
    $$templateVars{'latSec1'} = $FORM::latSec1;
2429
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2430
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2431
    $$templateVars{'longMin1'} = $FORM::longMin1;
2432
    $$templateVars{'longSec1'} = $FORM::longSec1;
2433
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2434
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2435
    $$templateVars{'latMin2'} = $FORM::latMin2;
2436
    $$templateVars{'latSec2'} = $FORM::latSec2;
2437
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2438
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2439
    $$templateVars{'longMin2'} = $FORM::longMin2;
2440
    $$templateVars{'longSec2'} = $FORM::longSec2;
2441
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2442

    
2443
    my $taxonRankArray = \@FORM::taxonRank;
2444
    my $taxonNameArray = \@FORM::taxonName;
2445
    my $taxonCount = 1;
2446

    
2447
    for(my $i = 0; $i <= $#$taxonNameArray; $i++){
2448
        if (hasContent($taxonRankArray->[$i]) && hasContent($taxonNameArray->[$i])) {
2449
            debug("Registry processing keyword: trv = ".$taxonRankArray->[$i]
2450
                    ." trn = ".$taxonNameArray->[$i]);
2451
            $$templateVars{"taxonRankName".$taxonCount} = normalizeCD($taxonNameArray->[$i]);
2452
            $$templateVars{"taxonRankValue".$taxonCount} = normalizeCD($taxonRankArray->[$i]);
2453
            $taxonCount++;
2454
	}    
2455
    }
2456

    
2457
    $$templateVars{'taxaCount'} = $taxonCount-1;
2458
    $$templateVars{'taxaAuth'} = normalizeCD($FORM::taxaAuth);
2459

    
2460
    $$templateVars{'methodTitle'} = normalizeCD($FORM::methodTitle);
2461
 
2462
    my @tempMethodPara;
2463
    for (my $i = 0; $i < scalar(@FORM::methodPara); $i++) {
2464
	$tempMethodPara[$i] = normalizeCD($FORM::methodPara[$i]);
2465
    }
2466
    $$templateVars{'methodPara'} = \@tempMethodPara;
2467
    $$templateVars{'studyExtentDescription'} = normalizeCD($FORM::studyExtentDescription);
2468
    $$templateVars{'samplingDescription'} = normalizeCD($FORM::samplingDescription);
2469
    $$templateVars{'origStateContact'} = $FORM::origState;
2470

    
2471
    $$templateVars{'showSiteList'} = $FORM::showSiteList;
2472
    $$templateVars{'lsite'} = $FORM::lsite;
2473
    $$templateVars{'usite'} = $FORM::usite;
2474
    $$templateVars{'showWgList'} = $FORM::showWgList;
2475
    $$templateVars{'showOrganization'} = $FORM::showOrganization;
2476
    $$templateVars{'hasKeyword'} = $FORM::hasKeyword;
2477
    $$templateVars{'hasTemporal'} = $FORM::hasTemporal;
2478
    $$templateVars{'hasSpatial'} = $FORM::hasSpatial;
2479
    $$templateVars{'hasTaxonomic'} = $FORM::hasTaxonomic;
2480
    $$templateVars{'hasMethod'} = $FORM::hasMethod;
2481
    $$templateVars{'spatialRequired'} = $FORM::spatialRequired;
2482
    $$templateVars{'temporalRequired'} = $FORM::temporalRequired;
2483

    
2484
    $$templateVars{'docid'} = $FORM::docid;
2485

    
2486
    if (! $error) {
2487
	# If no errors, then print out data in confirm Data template
2488

    
2489
	$$templateVars{'section'} = "Confirm Data";
2490
	$template->process( $confirmDataTemplate, $templateVars);
2491

    
2492
    } else{    
2493
    # Errors from validation function. print the errors out using the response template
2494
    if (scalar(@errorMessages)) {
2495
        $$templateVars{'status'} = 'failure';
2496
        $$templateVars{'errorMessages'} = \@errorMessages;
2497
        $error = 1;
2498
    }
2499
        # Create our HTML response and send it back
2500
    $$templateVars{'function'} = "submitted";
2501
    $$templateVars{'section'} = "Submission Status";
2502
    $template->process( $responseTemplate, $templateVars);
2503
    }
2504
}
2505

    
2506

    
2507
################################################################################
2508
# 
2509
# From confirm Data template - user wants to make some changes.
2510
#
2511
################################################################################
2512
sub confirmDataToReEntryData{
2513
    my @sortedSites;
2514
    foreach my $site (sort @sitelist) {
2515
        push(@sortedSites, $site);
2516
    }
2517

    
2518
    $$templateVars{'siteList'} = \@sortedSites;
2519
    $$templateVars{'section'} = "Re-Entry Form";
2520
    copyFormToTemplateVars();
2521
    $$templateVars{'docid'} = $FORM::docid;
2522

    
2523
    $$templateVars{'form'} = 're_entry';
2524
    $template->process( $entryFormTemplate, $templateVars);
2525
}
2526

    
2527

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

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

    
2682
################################################################################
2683
# 
2684
# check if there is multiple occurence of the given tag and find its value.
2685
#
2686
################################################################################
2687

    
2688
sub findValue {
2689
    my $node = shift;
2690
    my $value = shift;
2691
    my $result;
2692
    my $tempNode;
2693

    
2694
    $result = $node->findnodes("./$value");
2695
    if ($result->size > 1) {
2696
        errMoreThanOne("$value");
2697
    } else {
2698
        foreach $tempNode ($result->get_nodelist){
2699
            #print $tempNode->nodeName().":".$tempNode->textContent();
2700
            #print "\n";
2701
            return $tempNode->textContent();
2702
        }
2703
    }
2704
}
2705

    
2706

    
2707
################################################################################
2708
# 
2709
# check if given tags has any children. if not return the value
2710
#
2711
################################################################################
2712
sub findValueNoChild {
2713
    my $node = shift;
2714
    my $value = shift;
2715
    my $tempNode;
2716
    my $childNodes;
2717
    my $result;
2718
    my $error;
2719

    
2720
    $result = $node->findnodes("./$value");
2721
    if($result->size > 1){
2722
       errMoreThanOne("$value");
2723
    } else {
2724
        foreach $tempNode ($result->get_nodelist) {
2725
            $childNodes = $tempNode->childNodes;
2726
            if ($childNodes->size() > 1) {
2727
                $error ="The tag $value has children which cannot be shown using the form. Please use Morpho to edit this document";    
2728
                push(@errorMessages, $error);
2729
                #if ($DEBUG == 1){ print $error."\n";}
2730
            } else {
2731
                #print $tempNode->nodeName().":".$tempNode->textContent();
2732
                #print "\n";
2733
                return $tempNode->textContent();
2734
            }
2735
        }
2736
    }
2737
}
2738

    
2739

    
2740
################################################################################
2741
# 
2742
# check if given tags are children of given node.
2743
#
2744
################################################################################
2745
sub dontOccur {
2746
    my $node = shift;
2747
    my $value = shift;
2748
    my $errVal = shift;
2749

    
2750
    my $result = $node->findnodes("$value");
2751
    if($result->size > 0){
2752
        $error ="One of the following tags found: $errVal. Please use Morpho to edit this document";
2753
        push(@errorMessages, $error."\n");
2754
        #if ($DEBUG == 1){ print $error;}
2755
    } 
2756
}
2757

    
2758

    
2759
################################################################################
2760
# 
2761
# print out error for more than one occurence of a given tag
2762
#
2763
################################################################################
2764
sub errMoreThanOne {
2765
    my $value = shift;
2766
    my $error ="More than one occurence of the tag $value found. Please use Morpho to edit this document";
2767
    push(@errorMessages, $error."\n");
2768
    # if ($DEBUG == 1){ print $error;}
2769
}
2770

    
2771

    
2772
################################################################################
2773
# 
2774
# print out error for more than given number of occurences of a given tag
2775
#
2776
################################################################################
2777
sub errMoreThanN {
2778
    my $value = shift;
2779
    my $error ="More occurences of the tag $value found than that can be shown in the form. Please use Morpho to edit this document";
2780
    push(@errorMessages, $error);
2781
    #if ($DEBUG == 1){ print $error."\n";}
2782
}
2783

    
2784

    
2785
################################################################################
2786
# 
2787
# convert coord to degrees, minutes and seconds form. 
2788
#
2789
################################################################################
2790
#sub convertCoord {
2791
#    my $wx = shift;
2792
#    print $deg." ".$min." ".$sec;
2793
#    print "\n";
2794
#}
2795

    
2796

    
2797
################################################################################
2798
# 
2799
# print debugging messages to stderr
2800
#
2801
################################################################################
2802
sub debug {
2803
    my $msg = shift;
2804
    
2805
    if ($debug) {
2806
        print STDERR "$msg\n";
2807
    }
2808
}
2809

    
2810
################################################################################
2811
# 
2812
# get the list of projects
2813
#
2814
################################################################################
2815
sub getProjectList {
2816
    
2817
    use NCEAS::AdminDB;
2818
    my $admindb = NCEAS::AdminDB->new();
2819
    $admindb->connect($nceas_db, $nceas_db_user, $nceas_db_password);
2820
    my $projects = $admindb->getProjects();
2821
    #my $projects = getTestProjectList();
2822
    return $projects;
2823
}
2824

    
2825
################################################################################
2826
# 
2827
# get a test list of projects for use only in testing where the NCEAS
2828
# admin db is not available.
2829
#
2830
################################################################################
2831
sub getTestProjectList {
2832
    # This block is for testing only!  Remove for production use
2833
    my @row1;
2834
    $row1[0] = 6000; $row1[1] = 'Andelman'; $row1[2] = 'Sandy'; $row1[3] = 'The very long and windy path to an apparent ecological conclusion: statistics lie';
2835
    my @row2; 
2836
    $row2[0] = 7000; $row2[1] = 'Bascompte'; $row2[2] = 'Jordi'; $row2[3] = 'Postdoctoral Fellow';
2837
    my @row3; 
2838
    $row3[0] = 7001; $row3[1] = 'Hackett'; $row3[2] = 'Edward'; $row3[3] = 'Sociology rules the world';
2839
    my @row4; 
2840
    $row4[0] = 7002; $row4[1] = 'Jones'; $row4[2] = 'Matthew'; $row4[3] = 'Informatics rules the world';
2841
    my @row5; 
2842
    $row5[0] = 7003; $row5[1] = 'Schildhauer'; $row5[2] = 'Mark'; $row5[3] = 'Excel rocks my world, assuming a, b, and c';
2843
    my @row6; 
2844
    $row6[0] = 7004; $row6[1] = 'Rogers'; $row6[2] = 'Bill'; $row6[3] = 'Graduate Intern';
2845
    my @row7; 
2846
    $row7[0] = 7005; $row7[1] = 'Zedfried'; $row7[2] = 'Karl'; $row7[3] = 'A multivariate analysis of thing that go bump in the night';
2847
    my @projects;
2848
    $projects[0] = \@row1;
2849
    $projects[1] = \@row2;
2850
    $projects[2] = \@row3;
2851
    $projects[3] = \@row4;
2852
    $projects[4] = \@row5;
2853
    $projects[5] = \@row6;
2854
    $projects[6] = \@row7;
2855
    return \@projects;
2856
}
(4-4/5)