Project

General

Profile

metacat / src / perl / register-dataset.cgi @ 2280

1
#!/usr/bin/perl
2
#
3
#  '$RCSfile$'
4
#  Copyright: 2000 Regents of the University of California 
5
#
6
#   '$Author: sgarg $'
7
#     '$Date: 2004-09-15 14:00:04 -0700 (Wed, 15 Sep 2004) $'
8
# '$Revision: 2280 $' 
9
# 
10
# This program is free software; you can redistribute it and/or modify
11
# it under the terms of the GNU General Public License as published by
12
# the Free Software Foundation; either version 2 of the License, or
13
# (at your option) any later version.
14
#
15
# This program is distributed in the hope that it will be useful,
16
# but WITHOUT ANY WARRANTY; without even the implied warranty of
17
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
# GNU General Public License for more details.
19
#
20
# You should have received a copy of the GNU General Public License
21
# along with this program; if not, write to the Free Software
22
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23
#
24

    
25
#
26
# This is a CGI application for inserting metadata documents into
27
# the Metacat database.  It utilizes the Metacat.pm module for most work.
28
# In this script, we process the form fields passed in from a POST, insert a
29
# metadata document and an ACL document.
30

    
31
use Metacat;
32
use AppConfig qw(:expand :argcount);
33
use XML::LibXML;
34
use XML::LibXSLT;
35
use Template;
36
use Net::SMTP;
37
use CGI qw/:standard :html3/;
38
use strict;
39

    
40
# Global configuration paramters
41
#my $cfgdir = "@install-dir@";
42
#my $cfgdir = "/usr/local/devtools/tomcat/webapps/knb/style/skins";
43
my $cfgdir = "@install-dir@@style-skins-relpath@";
44
my $tmpdir = "@temp-dir@";
45
my $templatesdir = "@install-dir@@style-common-relpath@/templates";
46
my $now = time;
47
my $xslConvDir = "$cfgdir/lib/style/";
48

    
49
# Import all of the HTML form fields as variables
50
import_names('FORM');
51

    
52
# Set up the hash for returning data to the HTML templates
53
my $templateVars = { 'status' => 'success' };
54
my $error = 0;
55
my @errorMessages;
56

    
57
# create a new AppConfig object and load our config parameters
58
# note that this requires the form submission to have a "cfg" paramter
59
# to determine which config file to load
60
my $config = AppConfig->new({
61
    GLOBAL => { ARGCOUNT => ARGCOUNT_ONE, } });
62

    
63
$config->define("metacatUrl");
64
$config->define("username");
65
$config->define("password");
66
$config->define("ldapUrl");
67
$config->define("defaultScope");
68
$config->define("organization");
69
$config->define("orgabbrev");
70
$config->define("orgurl");
71
$config->define("accesspubid");
72
$config->define("accesssysid");
73
$config->define("datasetpubid");
74
$config->define("datasetsysid");
75
$config->define("showSiteList", { DEFAULT => 'true'} );
76
$config->define("lsite", { DEFAULT => 'station'} );
77
$config->define("usite", { DEFAULT => 'Station'} );
78
$config->define("showWgList", { DEFAULT => 'true'} );
79
$config->define("showOrganization", { DEFAULT => 'true'} );
80
$config->define("hasKeyword", { DEFAULT => 'true'} );
81
$config->define("hasTemporal", { DEFAULT => 'true'} );
82
$config->define("hasSpatial", { DEFAULT => 'true'} );
83
$config->define("hasTaxonomic", { DEFAULT => 'true'} );
84
$config->define("hasMethod", { DEFAULT => 'true'} );
85
$config->define("temporalRequired", { DEFAULT => 'true'} );
86
$config->define("spatialRequired", { DEFAULT => 'true'} );
87
$config->define("mailhost");
88
$config->define("sender");
89
$config->define("recipient");
90
$config->define("adminname");
91
if ($FORM::cfg eq 'nceas') {
92
    $config->define("nceas_db");
93
    $config->define("nceas_db_user");
94
    $config->define("nceas_db_password");
95
}
96
$config->define("responseTemplate", { DEFAULT => 'crap.tmpl'} );
97
$config->define("entryFormTemplate", { DEFAULT => 'crap.tmpl'} );
98
$config->define("guideTemplate", { DEFAULT => 'crap.tmpl'} );
99
$config->define("confirmDataTemplate", { DEFAULT => 'crap.tmpl'} );
100
$config->define("deleteDataTemplate", { DEFAULT => 'crap.tmpl'} );
101
$config->define("debug", { DEFAULT => '0'} );
102
$config->define("lat", { ARGCOUNT => ARGCOUNT_HASH} );
103
$config->define("lon", { ARGCOUNT => ARGCOUNT_HASH} );
104

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
314

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

    
320
    my $xmldoc = createXMLDocument();
321

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

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

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

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

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

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

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

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

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

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

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

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

    
433
        exit(0);
434
    }
435
}
436

    
437
debug("Registry: C");
438

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

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

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

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

    
461
exit(0);
462

    
463

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

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

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

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

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

    
524
  return $notunique;
525
}
526

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

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

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

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

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

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

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

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

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

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

    
696

    
697
    if($FORM::hasSpatial eq 'true'){
698
	if ($FORM::useSiteCoord ) {
699
	    push(@invalidParams, "The Data Registry doesn't have latitude and longitude information for the site that you chose. Please go back and enter the spatial information.")
700
		unless(hasContent($latDeg1) && hasContent($longDeg1));
701
	}else{
702
	    push(@invalidParams, "Latitude degrees are missing.")
703
		unless (hasContent($latDeg1) || $FORM::spatialRequired ne 'true');
704
	    push(@invalidParams, "Longitude degrees are missing.")
705
		unless (hasContent($longDeg1) || $FORM::spatialRequired ne 'true');
706
	}
707
	push(@invalidParams, 
708
	     "You must provide a geographic description if you provide latitude and longitude information.")
709
	    if ((hasContent($latDeg1) || (hasContent($longDeg1))) && (!hasContent($FORM::geogdesc)));
710
    }
711

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

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

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

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

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

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

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

    
798

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

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

    
815

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

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

    
834

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

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

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

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

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

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

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

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

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

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

    
932
    $creat .= $dso;
933

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1330
    return $doc;
1331
}
1332

    
1333

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

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

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

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

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

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

    
1371

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

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

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

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

    
1455
            # Read the main document. 
1456

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1845
    $results = $doc->findnodes('//dataset/coverage');
1846
    if ($results->size() > 1) {
1847
        errMoreThanOne("coverage");
1848
    } else {
1849
        foreach $node ($results->get_nodelist) {
1850
            dontOccur($node, "./temporalCoverage/rangeOfDates/beginDate/time|./temporalCoverage/rangeOfDates/beginDate/alternativeTimeScale|./temporalCoverage/rangeOfDates/endDate/time|./temporalCoverage/rangeOfDates/endDate/alternativeTimeScale|./taxonomicCoverage/taxonomicSystem|./taxonomicCoverage/taxonomicClassification/commonName|./taxonomicCoverage/taxonomicClassification/taxonomicClassification|./geographicCoverage/datasetGPolygon|./geographicCoverage/boundingCoordinates/boundingAltitudes", "temporalCoverage/rangeOfDates/beginDate/time, /temporalCoverage/rangeOfDates/beginDate/alternativeTimeScale, /temporalCoverage/rangeOfDates/endDate/time, /temporalCoverage/rangeOfDates/endDate/alternativeTimeScale, /taxonomicCoverage/taxonomicSystem, /taxonomicCoverage/taxonomicClassification/commonName, /taxonomicCoverage/taxonomicClassification/taxonomicClassification, /geographicCoverage/datasetGPolygon, /geographicCoverage/boundingCoordinates/boundingAltitudes");
1851

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

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

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

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

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

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

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

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

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

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

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

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

    
2094
    dontOccur($doc, "//methods/sampling/spatialSamplingUnits", "methods/sampling/spatialSamplingUnits");
2095
    dontOccur($doc, "//methods/sampling/citation", "methods/sampling/citation");
2096
    dontOccur($doc, "./pubPlace", "pubPlace");
2097
    dontOccur($doc, "./project", "project");
2098
    
2099
    dontOccur($doc, "./dataTable", "dataTable");
2100
    dontOccur($doc, "./spatialRaster", "spatialRaster");
2101
    dontOccur($doc, "./spatialVector", "spatialVector");
2102
    dontOccur($doc, "./storedProcedure", "storedProcedure");
2103
    dontOccur($doc, "./view", "view");
2104
    dontOccur($doc, "./otherEntity", "otherEntity");
2105
    dontOccur($doc, "./references", "references");
2106
    
2107
    dontOccur($doc, "//citation", "citation");
2108
    dontOccur($doc, "//software", "software");
2109
    dontOccur($doc, "//protocol", "protocol");
2110
    dontOccur($doc, "//additionalMetadata", "additionalMetadata");    
2111
}
2112

    
2113
################################################################################
2114
# 
2115
# Delete the eml file that has been requested for deletion. 
2116
#
2117
################################################################################
2118
sub deleteData {
2119
    my $deleteAll = shift;
2120
    
2121
    # create metacat instance
2122
    my $metacat;
2123
    my $docid = $FORM::docid;
2124
    
2125
    $metacat = Metacat->new();
2126
    if ($metacat) {
2127
        $metacat->set_options( metacatUrl => $metacatUrl );
2128
    } else {
2129
        #die "failed during metacat creation\n";
2130
        push(@errorMessages, "Failed during metacat creation.");
2131
    }
2132

    
2133
    # Login to metacat
2134
    my $userDN = $FORM::username;
2135
    my $userOrg = $FORM::organization;
2136
    my $userPass = $FORM::password;
2137
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
2138
    
2139
    my $errorMessage = "";
2140
    my $response = $metacat->login($dname, $userPass);
2141

    
2142
    if (! $response) {
2143
    # Could not login
2144
        push(@errorMessages, $metacat->getMessage());
2145
        push(@errorMessages, "Failed during login.\n");
2146

    
2147
    } else {
2148
    #Able to login - try to delete the file    
2149

    
2150
    my $parser;
2151
    my @fileArray;
2152
    my $httpMessage;
2153
    my $xmldoc;
2154
    my $doc;
2155
    my $pushDoc;
2156
    my $alreadyInArray;
2157
    my $findType;
2158
        my $node;
2159
    my $response; 
2160
    my $element;
2161

    
2162
    push (@fileArray, $docid);
2163
    $parser = XML::LibXML->new();
2164

    
2165
        $httpMessage = $metacat->read($docid);
2166
    $doc = $httpMessage->content();    
2167
    $xmldoc = $parser->parse_string($doc);
2168

    
2169
    if ($xmldoc eq "") {
2170
        $error ="Error in parsing the eml document";
2171
        push(@errorMessages, $error);
2172
    } else {
2173

    
2174
        $findType = $xmldoc->findnodes('//dataset/identifier');
2175
        if($findType->size() > 0){
2176
        # This is a eml beta6 document
2177
        # Delete the documents mentioned in triples also
2178
        
2179
        $findType = $xmldoc->findnodes('//dataset/triple');
2180
        if($findType->size() > 0){
2181
            foreach $node ($findType->get_nodelist){
2182
            $pushDoc = findValue($node, 'subject');
2183
            
2184
            # If the file is already in the @fileArray then do not add it 
2185
            $alreadyInArray = 0;
2186
            foreach $element (@fileArray){
2187
                if($element eq $pushDoc){
2188
                $alreadyInArray = 1;
2189
                }
2190
            }
2191
            
2192
            if(!$alreadyInArray){
2193
                # If not already in array then delete the file. 
2194
                push (@fileArray, $pushDoc);
2195
                $response = $metacat->delete($pushDoc);
2196
                
2197
                if (! $response) {
2198
                # Could not delete
2199
                #push(@errorMessages, $response);
2200
                push(@errorMessages, $metacat->getMessage());
2201
                push(@errorMessages, "Failed during deleting $pushDoc. Please check if you are authorized to delete this document.\n");
2202
                }
2203
            }
2204
            }
2205
        }
2206
        }
2207
    }
2208
    
2209
    # Delete the main document. 
2210
    if($deleteAll){
2211
        $response = $metacat->delete($docid);  
2212
        if (! $response) {
2213
        # Could not delete
2214
        #push(@errorMessages, $response);
2215
        push(@errorMessages, $metacat->getMessage());
2216
        push(@errorMessages, "Failed during deleting $docid. Please check if you are authorized to delete this document.\n");
2217
        }
2218
    }
2219
    }
2220
    
2221
    if (scalar(@errorMessages)) {
2222
    # If any errors, print them in the response template 
2223
    $$templateVars{'status'} = 'failure';
2224
    $$templateVars{'errorMessages'} = \@errorMessages;
2225
    $error = 1;
2226
    }
2227
    
2228
    # Process the response template
2229
    if($deleteAll){
2230

    
2231
    $$templateVars{'function'} = "deleted";
2232
    $$templateVars{'section'} = "Deletion Status";
2233
    $template->process( $responseTemplate, $templateVars);
2234
    }
2235
}
2236

    
2237

    
2238
################################################################################
2239
# 
2240
# Do data validation and send the data to confirm data template.
2241
#
2242
################################################################################
2243
sub toConfirmData{
2244
    # Check if any invalid parameters
2245
 
2246
    my $invalidParams;
2247
    if (! $error) {
2248
    $invalidParams = validateParameters(0);
2249
    if (scalar(@$invalidParams)) {
2250
        $$templateVars{'status'} = 'failure';
2251
        $$templateVars{'invalidParams'} = $invalidParams;
2252
        $error = 1;
2253
    }
2254
    }
2255

    
2256

    
2257
    $$templateVars{'providerGivenName'} = normalizeCD($FORM::providerGivenName);
2258
    $$templateVars{'providerSurName'} = normalizeCD($FORM::providerSurName);
2259
    if($FORM::site eq "Select your station here."){
2260
        $$templateVars{'site'} = "";
2261
    }else{
2262
        $$templateVars{'site'} = $FORM::site;
2263
    }
2264
    if($FORM::cfg eq "nceas"){
2265
        $$templateVars{'wg'} = \@FORM::wg;
2266
    }
2267
    $$templateVars{'identifier'} = normalizeCD($FORM::identifier);
2268
    $$templateVars{'title'} = normalizeCD($FORM::title);
2269
    $$templateVars{'origNamefirst0'} = normalizeCD($FORM::origNamefirst0);
2270
    $$templateVars{'origNamelast0'} = normalizeCD($FORM::origNamelast0);
2271
    $$templateVars{'origNameOrg'} = normalizeCD($FORM::origNameOrg);
2272
    # $$templateVars{'origRole0'} = $FORM::origRole0;
2273
    $$templateVars{'origDelivery'} = normalizeCD($FORM::origDelivery);
2274
    $$templateVars{'origCity'} = normalizeCD($FORM::origCity);
2275
    if($FORM::origState eq "Select State Here."){
2276
        $$templateVars{'origState'} = "";
2277
    }else{
2278
        $$templateVars{'origState'} = $FORM::origState;
2279
    }
2280
    $$templateVars{'origStateOther'} = normalizeCD($FORM::origStateOther);
2281
    $$templateVars{'origZIP'} = normalizeCD($FORM::origZIP);
2282
    $$templateVars{'origCountry'} = normalizeCD($FORM::origCountry);
2283
    $$templateVars{'origPhone'} = normalizeCD($FORM::origPhone);
2284
    $$templateVars{'origFAX'} = normalizeCD($FORM::origFAX);
2285
    $$templateVars{'origEmail'} = normalizeCD($FORM::origEmail);
2286
    $$templateVars{'useOrigAddress'} = normalizeCD($FORM::useOrigAddress);
2287
    if($FORM::useOrigAddress eq "on"){
2288
        $$templateVars{'origNamefirstContact'} = normalizeCD($FORM::origNamefirst0);
2289
        $$templateVars{'origNamelastContact'} = normalizeCD($FORM::origNamelast0);
2290
        $$templateVars{'origNameOrgContact'} = normalizeCD($FORM::origNameOrg);
2291
        $$templateVars{'origDeliveryContact'} = normalizeCD($FORM::origDelivery); 
2292
        $$templateVars{'origCityContact'} = normalizeCD($FORM::origCity);
2293
        if($FORM::origState eq "Select State Here."){
2294
        $$templateVars{'origStateContact'} = "";
2295
        }else{
2296
        $$templateVars{'origStateContact'} = $FORM::origState;
2297
        }
2298
        $$templateVars{'origStateOtherContact'} = normalizeCD($FORM::origStateOther);
2299
        $$templateVars{'origZIPContact'} = normalizeCD($FORM::origZIP);
2300
        $$templateVars{'origCountryContact'} = normalizeCD($FORM::origCountry);
2301
        $$templateVars{'origPhoneContact'} = normalizeCD($FORM::origPhone);
2302
        $$templateVars{'origFAXContact'} = normalizeCD($FORM::origFAX);
2303
        $$templateVars{'origEmailContact'} = normalizeCD($FORM::origEmail);
2304
    }else{
2305
        $$templateVars{'origNamefirstContact'} = normalizeCD($FORM::origNamefirstContact);
2306
        $$templateVars{'origNamelastContact'} = normalizeCD($FORM::origNamelastContact);
2307
        $$templateVars{'origNameOrgContact'} = normalizeCD($FORM::origNameOrgContact);
2308
        $$templateVars{'origDeliveryContact'} = normalizeCD($FORM::origDeliveryContact); 
2309
        $$templateVars{'origCityContact'} = normalizeCD($FORM::origCityContact);
2310
        if($FORM::origStateContact eq "Select State Here."){
2311
        $$templateVars{'origStateContact'} = "";
2312
        }else{
2313
        $$templateVars{'origStateContact'} = $FORM::origStateContact;
2314
        }
2315
        $$templateVars{'origStateOtherContact'} = normalizeCD($FORM::origStateOtherContact);
2316
        $$templateVars{'origZIPContact'} = normalizeCD($FORM::origZIPContact);
2317
        $$templateVars{'origCountryContact'} = normalizeCD($FORM::origCountryContact);
2318
        $$templateVars{'origPhoneContact'} = normalizeCD($FORM::origPhoneContact);
2319
        $$templateVars{'origFAXContact'} = normalizeCD($FORM::origFAXContact);
2320
        $$templateVars{'origEmailContact'} = normalizeCD($FORM::origEmailContact);    
2321
    }
2322

    
2323
    $$templateVars{'aoCount'} = $FORM::aoCount;
2324
    foreach my $origName (param()) {
2325
	if ($origName =~ /origNamefirst/) {
2326
	    my $origNameIndex = $origName;
2327
	    $origNameIndex =~ s/origNamefirst//; # get the index of the parameter 0, ..., 10
2328
	    my $origNamelast = "origNamelast".$origNameIndex;
2329
	    my $origRole = "origRole".$origNameIndex;
2330
	    if ( $origNameIndex =~ /[0-9]/  && $origNameIndex > 0){
2331
		if (hasContent(param($origName)) && hasContent(param($origNamelast)) && hasContent(param($origRole))) {
2332
		    debug("Registry processing keyword: $origName = ".param($origName)." $origNamelast = ".param($origNamelast)." $origRole = ".param($origRole));
2333
		    $$templateVars{$origName} = normalizeCD(param($origName));
2334
		    $$templateVars{$origNamelast} = normalizeCD(param($origNamelast));
2335
		    $$templateVars{$origRole} = normalizeCD(param($origRole));
2336
		}
2337
	    }
2338
	}
2339
    }
2340

    
2341
    $$templateVars{'abstract'} = normalizeCD($FORM::abstract);
2342
    $$templateVars{'keyCount'} = $FORM::keyCount;
2343
    foreach my $kyd (param()) {
2344
	if ($kyd =~ /keyword/) {
2345
	    my $keyIndex = $kyd;
2346
	    $keyIndex =~ s/keyword//; # get the index of the parameter 0, ..., 10
2347
	    my $keyType = "kwType".$keyIndex;
2348
	    my $keyTh = "kwTh".$keyIndex;
2349
	    if ( $keyIndex =~ /[0-9]/ ){
2350
		if (hasContent(param($kyd)) && hasContent(param($keyType)) && hasContent(param($keyTh))) {
2351
		    debug("Registry processing keyword: $kyd = ".param($kyd)." $keyType = ".param($keyType)." $keyTh = ".param($keyTh));
2352
		    $$templateVars{$kyd} = normalizeCD(param($kyd));
2353
		    $$templateVars{$keyType} = param($keyType);
2354
		    $$templateVars{$keyTh} = param($keyTh);
2355
		}
2356
	    }
2357
	}
2358
    }
2359
    $$templateVars{'addComments'} = normalizeCD($FORM::addComments);
2360
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2361
    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2362
    $$templateVars{'url'} = $FORM::url;
2363
    if($FORM::dataMedium eq "Select type of medium here."){
2364
        $$templateVars{'dataMedium'} = "";
2365
    }else{
2366
        $$templateVars{'dataMedium'} = $FORM::dataMedium;
2367
    }    
2368
    $$templateVars{'dataMediumOther'} = normalizeCD($FORM::dataMediumOther);
2369
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2370
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2371
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2372
    $$templateVars{'endingYear'} = $FORM::endingYear;
2373
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2374
    $$templateVars{'endingDay'} = $FORM::endingDay;
2375
    $$templateVars{'geogdesc'} = normalizeCD($FORM::geogdesc);
2376
    $$templateVars{'useSiteCoord'} = $FORM::useSiteCoord;
2377
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2378
    $$templateVars{'latMin1'} = $FORM::latMin1;
2379
    $$templateVars{'latSec1'} = $FORM::latSec1;
2380
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2381
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2382
    $$templateVars{'longMin1'} = $FORM::longMin1;
2383
    $$templateVars{'longSec1'} = $FORM::longSec1;
2384
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2385
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2386
    $$templateVars{'latMin2'} = $FORM::latMin2;
2387
    $$templateVars{'latSec2'} = $FORM::latSec2;
2388
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2389
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2390
    $$templateVars{'longMin2'} = $FORM::longMin2;
2391
    $$templateVars{'longSec2'} = $FORM::longSec2;
2392
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2393

    
2394
    $$templateVars{'taxaCount'} = $FORM::taxaCount;
2395
    foreach my $trn (param()) {
2396
        if ($trn =~ /taxonRankName/) {
2397
            my $taxIndex = $trn;
2398
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
2399
            my $trv = "taxonRankValue".$taxIndex;
2400
            if ( $taxIndex =~ /[0-9]/ ){
2401
                if (hasContent(param($trn)) && hasContent(param($trv))) {
2402
                    debug("Registry processing taxon: $trn = ".param($trn)." $trv = ".param($trv));
2403
                    $$templateVars{$trn} = normalizeCD(param($trn));
2404
                    $$templateVars{$trv} = normalizeCD(param($trv));
2405
                }
2406
            }
2407
        }
2408
    }
2409
    $$templateVars{'taxaAuth'} = normalizeCD($FORM::taxaAuth);
2410

    
2411
    $$templateVars{'methodTitle'} = normalizeCD($FORM::methodTitle);
2412

    
2413
    my @tempMethodPara;
2414
    for (my $i = 0; $i < scalar(@FORM::methodPara); $i++) {
2415
	$tempMethodPara[$i] = normalizeCD($FORM::methodPara[$i]);
2416
    }
2417
    $$templateVars{'methodPara'} = \@tempMethodPara;
2418
    $$templateVars{'studyExtentDescription'} = normalizeCD($FORM::studyExtentDescription);
2419
    $$templateVars{'samplingDescription'} = normalizeCD($FORM::samplingDescription);
2420
    $$templateVars{'origStateContact'} = $FORM::origState;
2421

    
2422
    $$templateVars{'showSiteList'} = $FORM::showSiteList;
2423
    $$templateVars{'lsite'} = $FORM::lsite;
2424
    $$templateVars{'usite'} = $FORM::usite;
2425
    $$templateVars{'showWgList'} = $FORM::showWgList;
2426
    $$templateVars{'showOrganization'} = $FORM::showOrganization;
2427
    $$templateVars{'hasKeyword'} = $FORM::hasKeyword;
2428
    $$templateVars{'hasTemporal'} = $FORM::hasTemporal;
2429
    $$templateVars{'hasSpatial'} = $FORM::hasSpatial;
2430
    $$templateVars{'hasTaxonomic'} = $FORM::hasTaxonomic;
2431
    $$templateVars{'hasMethod'} = $FORM::hasMethod;
2432
    $$templateVars{'spatialRequired'} = $FORM::spatialRequired;
2433
    $$templateVars{'temporalRequired'} = $FORM::temporalRequired;
2434

    
2435
    $$templateVars{'docid'} = $FORM::docid;
2436

    
2437
    if (! $error) {
2438
	# If no errors, then print out data in confirm Data template
2439

    
2440
	$$templateVars{'section'} = "Confirm Data";
2441
	$template->process( $confirmDataTemplate, $templateVars);
2442

    
2443
    } else{    
2444
    # Errors from validation function. print the errors out using the response template
2445
    if (scalar(@errorMessages)) {
2446
        $$templateVars{'status'} = 'failure';
2447
        $$templateVars{'errorMessages'} = \@errorMessages;
2448
        $error = 1;
2449
    }
2450
        # Create our HTML response and send it back
2451
    $$templateVars{'function'} = "submitted";
2452
    $$templateVars{'section'} = "Submission Status";
2453
    $template->process( $responseTemplate, $templateVars);
2454
    }
2455
}
2456

    
2457

    
2458
################################################################################
2459
# 
2460
# From confirm Data template - user wants to make some changes.
2461
#
2462
################################################################################
2463
sub confirmDataToReEntryData{
2464
    my @sortedSites;
2465
    foreach my $site (sort @sitelist) {
2466
        push(@sortedSites, $site);
2467
    }
2468

    
2469
    $$templateVars{'siteList'} = \@sortedSites;
2470
    $$templateVars{'section'} = "Re-Entry Form";
2471
    copyFormToTemplateVars();
2472
    $$templateVars{'docid'} = $FORM::docid;
2473

    
2474
    $$templateVars{'form'} = 're_entry';
2475
    $template->process( $entryFormTemplate, $templateVars);
2476
}
2477

    
2478

    
2479
################################################################################
2480
# 
2481
# Copy form data to templateVars.....
2482
#
2483
################################################################################
2484
sub copyFormToTemplateVars{
2485
    $$templateVars{'providerGivenName'} = $FORM::providerGivenName;
2486
    $$templateVars{'providerSurName'} = $FORM::providerSurName;
2487
    $$templateVars{'site'} = $FORM::site;
2488
    if ($FORM::cfg eq "nceas") {
2489
        my $projects = getProjectList();
2490
        $$templateVars{'projects'} = $projects;
2491
        $$templateVars{'wg'} = \@FORM::wg;
2492
    }
2493
    $$templateVars{'identifier'} = $FORM::identifier;
2494
    $$templateVars{'title'} = $FORM::title;
2495
    $$templateVars{'origNamefirst0'} = $FORM::origNamefirst0;
2496
    $$templateVars{'origNamelast0'} = $FORM::origNamelast0;
2497
    $$templateVars{'origNameOrg'} = $FORM::origNameOrg;
2498
 #   $$templateVars{'origRole0'} = $FORM::origRole0;
2499
    $$templateVars{'origDelivery'} = $FORM::origDelivery;
2500
    $$templateVars{'origCity'} = $FORM::origCity;
2501
    $$templateVars{'origState'} = $FORM::origState;
2502
    $$templateVars{'origStateOther'} = $FORM::origStateOther;
2503
    $$templateVars{'origZIP'} = $FORM::origZIP;
2504
    $$templateVars{'origCountry'} = $FORM::origCountry;
2505
    $$templateVars{'origPhone'} = $FORM::origPhone;
2506
    $$templateVars{'origFAX'} = $FORM::origFAX;
2507
    $$templateVars{'origEmail'} = $FORM::origEmail;
2508
    if ($FORM::useSiteCoord ne "") {
2509
        $$templateVars{'useOrigAddress'} = "CHECKED";
2510
    }else{
2511
        $$templateVars{'useOrigAddress'} = $FORM::useOrigAddress;
2512
    }
2513
    $$templateVars{'origNamefirstContact'} = $FORM::origNamefirstContact;
2514
    $$templateVars{'origNamelastContact'} = $FORM::origNamelastContact;
2515
    $$templateVars{'origNameOrgContact'} = $FORM::origNameOrgContact;
2516
    $$templateVars{'origDeliveryContact'} = $FORM::origDeliveryContact; 
2517
    $$templateVars{'origCityContact'} = $FORM::origCityContact;
2518
    $$templateVars{'origStateContact'} = $FORM::origStateContact;
2519
    $$templateVars{'origStateOtherContact'} = $FORM::origStateOtherContact;
2520
    $$templateVars{'origZIPContact'} = $FORM::origZIPContact;
2521
    $$templateVars{'origCountryContact'} = $FORM::origCountryContact;
2522
    $$templateVars{'origPhoneContact'} = $FORM::origPhoneContact;
2523
    $$templateVars{'origFAXContact'} = $FORM::origFAXContact;
2524
    $$templateVars{'origEmailContact'} = $FORM::origEmailContact;    
2525
    
2526
    $$templateVars{'aoCount'} = $FORM::aoCount;
2527
    foreach my $origName (param()) {
2528
	if ($origName =~ /origNamefirst/) {
2529
	    my $origNameIndex = $origName;
2530
	    $origNameIndex =~ s/origNamefirst//; # get the index of the parameter 0, ..., 10
2531
	    my $origNamelast = "origNamelast".$origNameIndex;
2532
	    my $origRole = "origRole".$origNameIndex;
2533
	    if ( $origNameIndex =~ /[0-9]/  && $origNameIndex > 0){
2534
		if (hasContent(param($origName)) && hasContent(param($origNamelast)) && hasContent(param($origRole))) {
2535
		    debug("Registry processing keyword: $origName = ".param($origName)." $origNamelast = ".param($origNamelast)." $origRole = ".param($origRole));
2536
		    $$templateVars{$origName} = normalizeCD(param($origName));
2537
		    $$templateVars{$origNamelast} = normalizeCD(param($origNamelast));
2538
		    $$templateVars{$origRole} = normalizeCD(param($origRole));
2539
		}
2540
	    }
2541
	}
2542
    }
2543

    
2544
    $$templateVars{'abstract'} = $FORM::abstract;
2545
    $$templateVars{'keyCount'} = $FORM::keyCount;
2546
    foreach my $kyd (param()) {
2547
	if ($kyd =~ /keyword/) {
2548
	    my $keyIndex = $kyd;
2549
	    $keyIndex =~ s/keyword//; # get the index of the parameter 0, ..., 10
2550
	    my $keyType = "kwType".$keyIndex;
2551
	    my $keyTh = "kwTh".$keyIndex;
2552
	    if ( $keyIndex =~ /[0-9]/ ){
2553
		if (hasContent(param($kyd)) && hasContent(param($keyType)) && hasContent(param($keyTh))) {
2554
		    debug("Registry processing keyword: $kyd = ".param($kyd)." $keyType = ".param($keyType)." $keyTh = ".param($keyTh));
2555
		    $$templateVars{$kyd} = param($kyd);
2556
		    $$templateVars{$keyType} = param($keyType);
2557
		    $$templateVars{$keyTh} = param($keyTh);
2558
		}
2559
	    }
2560
	}
2561
    }
2562
    $$templateVars{'addComments'} = $FORM::addComments;
2563
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2564
    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2565
    $$templateVars{'url'} = $FORM::url;
2566
    $$templateVars{'dataMedium'} = $FORM::dataMedium;
2567
    $$templateVars{'dataMediumOther'} = $FORM::dataMediumOther;
2568
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2569
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2570
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2571
    $$templateVars{'endingYear'} = $FORM::endingYear;
2572
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2573
    $$templateVars{'endingDay'} = $FORM::endingDay;
2574
    $$templateVars{'geogdesc'} = $FORM::geogdesc;
2575
    if($FORM::useSiteCoord ne ""){
2576
    $$templateVars{'useSiteCoord'} = "CHECKED";
2577
    }else{
2578
    $$templateVars{'useSiteCoord'} = "";
2579
    }
2580
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2581
    $$templateVars{'latMin1'} = $FORM::latMin1;
2582
    $$templateVars{'latSec1'} = $FORM::latSec1;
2583
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2584
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2585
    $$templateVars{'longMin1'} = $FORM::longMin1;
2586
    $$templateVars{'longSec1'} = $FORM::longSec1;
2587
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2588
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2589
    $$templateVars{'latMin2'} = $FORM::latMin2;
2590
    $$templateVars{'latSec2'} = $FORM::latSec2;
2591
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2592
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2593
    $$templateVars{'longMin2'} = $FORM::longMin2;
2594
    $$templateVars{'longSec2'} = $FORM::longSec2;
2595
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2596
    $$templateVars{'taxaCount'} = $FORM::taxaCount;
2597
    foreach my $trn (param()) {
2598
        if ($trn =~ /taxonRankName/) {
2599
            my $taxIndex = $trn;
2600
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
2601
            my $trv = "taxonRankValue".$taxIndex;
2602
            if ( $taxIndex =~ /[0-9]/ ){
2603
                if (hasContent(param($trn)) && hasContent(param($trv))) {
2604
                    debug("Registry processing taxon: $trn = ".param($trn)." $trv = ".param($trv));
2605
                    $$templateVars{$trn} = param($trn);
2606
                    $$templateVars{$trv} = param($trv);
2607
                }
2608
            }
2609
        }
2610
    }
2611
    $$templateVars{'taxaAuth'} = $FORM::taxaAuth;
2612
    $$templateVars{'methodTitle'} = $FORM::methodTitle;
2613
    $$templateVars{'methodPara'} = \@FORM::methodPara;
2614
    $$templateVars{'studyExtentDescription'} = $FORM::studyExtentDescription;
2615
    $$templateVars{'samplingDescription'} = $FORM::samplingDescription;
2616
    
2617
    $$templateVars{'showSiteList'} = $FORM::showSiteList;
2618
    $$templateVars{'lsite'} = $FORM::lsite;
2619
    $$templateVars{'usite'} = $FORM::usite;
2620
    $$templateVars{'showWgList'} = $FORM::showWgList;
2621
    $$templateVars{'showOrganization'} = $FORM::showOrganization;
2622
    $$templateVars{'hasKeyword'} = $FORM::hasKeyword;
2623
    $$templateVars{'hasTemporal'} = $FORM::hasTemporal;
2624
    $$templateVars{'hasSpatial'} = $FORM::hasSpatial;
2625
    $$templateVars{'hasTaxonomic'} = $FORM::hasTaxonomic;
2626
    $$templateVars{'hasMethod'} = $FORM::hasMethod;
2627
    $$templateVars{'spatialRequired'} = $FORM::spatialRequired;
2628
    $$templateVars{'temporalRequired'} = $FORM::temporalRequired;
2629
}
2630

    
2631
################################################################################
2632
# 
2633
# check if there is multiple occurence of the given tag and find its value.
2634
#
2635
################################################################################
2636

    
2637
sub findValue {
2638
    my $node = shift;
2639
    my $value = shift;
2640
    my $result;
2641
    my $tempNode;
2642

    
2643
    $result = $node->findnodes("./$value");
2644
    if ($result->size > 1) {
2645
        errMoreThanOne("$value");
2646
    } else {
2647
        foreach $tempNode ($result->get_nodelist){
2648
            #print $tempNode->nodeName().":".$tempNode->textContent();
2649
            #print "\n";
2650
            return $tempNode->textContent();
2651
        }
2652
    }
2653
}
2654

    
2655

    
2656
################################################################################
2657
# 
2658
# check if given tags has any children. if not return the value
2659
#
2660
################################################################################
2661
sub findValueNoChild {
2662
    my $node = shift;
2663
    my $value = shift;
2664
    my $tempNode;
2665
    my $childNodes;
2666
    my $result;
2667
    my $error;
2668

    
2669
    $result = $node->findnodes("./$value");
2670
    if($result->size > 1){
2671
       errMoreThanOne("$value");
2672
    } else {
2673
        foreach $tempNode ($result->get_nodelist) {
2674
            $childNodes = $tempNode->childNodes;
2675
            if ($childNodes->size() > 1) {
2676
                $error ="The tag $value has children which cannot be shown using the form. Please use Morpho to edit this document";    
2677
                push(@errorMessages, $error);
2678
                #if ($DEBUG == 1){ print $error."\n";}
2679
            } else {
2680
                #print $tempNode->nodeName().":".$tempNode->textContent();
2681
                #print "\n";
2682
                return $tempNode->textContent();
2683
            }
2684
        }
2685
    }
2686
}
2687

    
2688

    
2689
################################################################################
2690
# 
2691
# check if given tags are children of given node.
2692
#
2693
################################################################################
2694
sub dontOccur {
2695
    my $node = shift;
2696
    my $value = shift;
2697
    my $errVal = shift;
2698

    
2699
    my $result = $node->findnodes("$value");
2700
    if($result->size > 0){
2701
        $error ="One of the following tags found: $errVal. Please use Morpho to edit this document";
2702
        push(@errorMessages, $error."\n");
2703
        #if ($DEBUG == 1){ print $error;}
2704
    } 
2705
}
2706

    
2707

    
2708
################################################################################
2709
# 
2710
# print out error for more than one occurence of a given tag
2711
#
2712
################################################################################
2713
sub errMoreThanOne {
2714
    my $value = shift;
2715
    my $error ="More than one occurence of the tag $value found. Please use Morpho to edit this document";
2716
    push(@errorMessages, $error."\n");
2717
    # if ($DEBUG == 1){ print $error;}
2718
}
2719

    
2720

    
2721
################################################################################
2722
# 
2723
# print out error for more than given number of occurences of a given tag
2724
#
2725
################################################################################
2726
sub errMoreThanN {
2727
    my $value = shift;
2728
    my $error ="More occurences of the tag $value found than that can be shown in the form. Please use Morpho to edit this document";
2729
    push(@errorMessages, $error);
2730
    #if ($DEBUG == 1){ print $error."\n";}
2731
}
2732

    
2733

    
2734
################################################################################
2735
# 
2736
# convert coord to degrees, minutes and seconds form. 
2737
#
2738
################################################################################
2739
#sub convertCoord {
2740
#    my $wx = shift;
2741
#    print $deg." ".$min." ".$sec;
2742
#    print "\n";
2743
#}
2744

    
2745

    
2746
################################################################################
2747
# 
2748
# print debugging messages to stderr
2749
#
2750
################################################################################
2751
sub debug {
2752
    my $msg = shift;
2753
    
2754
    if ($debug) {
2755
        print STDERR "$msg\n";
2756
    }
2757
}
2758

    
2759
################################################################################
2760
# 
2761
# get the list of projects
2762
#
2763
################################################################################
2764
sub getProjectList {
2765
    
2766
    use NCEAS::AdminDB;
2767
    my $admindb = NCEAS::AdminDB->new();
2768
    $admindb->connect($nceas_db, $nceas_db_user, $nceas_db_password);
2769
    my $projects = $admindb->getProjects();
2770
    #my $projects = getTestProjectList();
2771
    return $projects;
2772
}
2773

    
2774
################################################################################
2775
# 
2776
# get a test list of projects for use only in testing where the NCEAS
2777
# admin db is not available.
2778
#
2779
################################################################################
2780
sub getTestProjectList {
2781
    # This block is for testing only!  Remove for production use
2782
    my @row1;
2783
    $row1[0] = 6000; $row1[1] = 'Andelman'; $row1[2] = 'Sandy'; $row1[3] = 'The very long and windy path to an apparent ecological conclusion: statistics lie';
2784
    my @row2; 
2785
    $row2[0] = 7000; $row2[1] = 'Bascompte'; $row2[2] = 'Jordi'; $row2[3] = 'Postdoctoral Fellow';
2786
    my @row3; 
2787
    $row3[0] = 7001; $row3[1] = 'Hackett'; $row3[2] = 'Edward'; $row3[3] = 'Sociology rules the world';
2788
    my @row4; 
2789
    $row4[0] = 7002; $row4[1] = 'Jones'; $row4[2] = 'Matthew'; $row4[3] = 'Informatics rules the world';
2790
    my @row5; 
2791
    $row5[0] = 7003; $row5[1] = 'Schildhauer'; $row5[2] = 'Mark'; $row5[3] = 'Excel rocks my world, assuming a, b, and c';
2792
    my @row6; 
2793
    $row6[0] = 7004; $row6[1] = 'Rogers'; $row6[2] = 'Bill'; $row6[3] = 'Graduate Intern';
2794
    my @row7; 
2795
    $row7[0] = 7005; $row7[1] = 'Zedfried'; $row7[2] = 'Karl'; $row7[3] = 'A multivariate analysis of thing that go bump in the night';
2796
    my @projects;
2797
    $projects[0] = \@row1;
2798
    $projects[1] = \@row2;
2799
    $projects[2] = \@row3;
2800
    $projects[3] = \@row4;
2801
    $projects[4] = \@row5;
2802
    $projects[5] = \@row6;
2803
    $projects[6] = \@row7;
2804
    return \@projects;
2805
}