Project

General

Profile

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

    
100
if (! hasContent($FORM::cfg)) {
101
    $error = "Application misconfigured.  Please contact the administrator.";
102
    push(@errorMessages, $error);
103
} else {
104
    my $cfgfile = $cfgdir . "/" . $FORM::cfg . "/" . $FORM::cfg . ".cfg";
105
    $config->file($cfgfile);
106
}
107

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

    
150
# Convert the lat and lon configs into usable data structures
151
my @sitelist;
152
my %siteLatDMS;
153
my %siteLongDMS;
154
foreach my $newsite (keys %$lat) {
155
    my ($latd, $latm, $lats, $latdir) = split(':', $lat->{$newsite});
156
    my ($lond, $lonm, $lons, $londir) = split(':', $lon->{$newsite});
157
    push(@sitelist, $newsite);
158
    $siteLatDMS{$newsite} = [ $latd, $latm, $lats, $latdir ];
159
    $siteLongDMS{$newsite} = [ $lond, $lonm, $lons, $londir ];
160
}
161

    
162
# set some configuration options for the template object
163
my $ttConfig = {
164
             INCLUDE_PATH => $templatesdir, 
165
             INTERPOLATE  => 0,                    
166
             POST_CHOMP   => 1,                   
167
             };
168

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

    
172
print "Content-type: text/html\n\n";
173

    
174
# Set up the template information that is common to all forms
175
$$templateVars{'cfg'} = $FORM::cfg;
176
$$templateVars{'recipient'} = $recipient;
177
$$templateVars{'adminname'} = $adminname;
178
$$templateVars{'organization'} = $organization;
179
$$templateVars{'orgabbrev'} = $orgabbrev;
180
$$templateVars{'orgurl'} = $orgurl;
181
$$templateVars{'orgfilter'} = $orgfilter;
182

    
183
debug("Registry: Initialized");
184
# Process the form based on stage parameter. 
185
if ($FORM::stage =~ "guide") {
186
    # Send back the information on how to fill the form
187
    $$templateVars{'section'} = "Guide on How to Complete Registry Entries";
188
    $template->process( $guideTemplate, $templateVars);
189
    exit(0);
190

    
191
} elsif ($FORM::stage =~ "insert") {
192
    # The user has entered the data. Do data validation and send back data 
193
    # to confirm the data that has been entered. 
194
    toConfirmData();
195
    exit(0);
196

    
197
}elsif ($FORM::dataWrong =~ "No, go back to editing" && $FORM::stage =~ "confirmed") {
198
    # The user wants to correct the data that he has entered. 
199
    # Hence show the data again in entryData form. 
200
    confirmDataToReEntryData();
201
    exit(0);
202

    
203
}elsif ($FORM::stage =~ "modify") {
204
    # Modification of a file has been requested. 
205
    # Show the form will all the values filled in.
206
    my @sortedSites;
207
    foreach my $site (sort @sitelist) {
208
        push(@sortedSites, $site);
209
    }
210
    $$templateVars{'siteList'} = \@sortedSites;
211
    $$templateVars{'section'} = "Modification Form";
212
    $$templateVars{'docid'} = $FORM::docid;
213
    modifyData();
214
    exit(0);
215

    
216
}elsif ($FORM::stage =~ "delete_confirm") {
217

    
218
    # Result from deleteData form. 
219
    if($FORM::deleteData =~ "Delete data"){
220
    # delete Data
221
    deleteData(1);    
222
    exit(0);
223
    } else {
224
    # go back to search page. 
225
    exit(0);
226
    }
227

    
228
}elsif ($FORM::stage =~ "delete") {
229
    # Deletion of a file has been requested. 
230
    # Ask for username and password using deleteDataForm
231
    $$templateVars{'docid'} = $FORM::docid;
232
    $template->process( $deleteDataTemplate, $templateVars);
233
    exit(0);
234

    
235
}elsif ($FORM::stage !~ "confirmed") {
236
    # None of the stages have been reached and data is not being confirmed. 
237
    # Hence, send back entry form for entry of data.  
238
    debug("Registry: Sending form");
239
    my @sortedSites;
240
    foreach my $site (sort @sitelist) {
241
        push(@sortedSites, $site);
242
    }
243
    
244
    if ($FORM::cfg eq 'nceas') {
245
        my $projects = getProjectList();
246
        $$templateVars{'projects'} = $projects;
247
        $$templateVars{'wg'} = \@FORM::wg;
248
    }
249

    
250
    $$templateVars{'hasKeyword'} = $hasKeyword;
251
    $$templateVars{'hasTemporal'} = $hasTemporal;
252
    $$templateVars{'hasSpatial'} = $hasSpatial;
253
    $$templateVars{'hasTaxonomic'} = $hasTaxonomic;
254
    $$templateVars{'hasMethod'} = $hasMethod;
255
    $$templateVars{'temporalRequired'} = $temporalRequired;
256
    $$templateVars{'spatialRequired'} = $spatialRequired;
257

    
258
    $$templateVars{'siteList'} = \@sortedSites;
259
    $$templateVars{'section'} = "Entry Form";
260
    $$templateVars{'docid'} = "";
261
    debug("Registry: Sending form: ready to process template");
262
    $template->process( $entryFormTemplate, $templateVars);
263
    debug("Registry: Sending form: template processed");
264
    exit(0);
265
}
266

    
267
# Confirm stage has been reached. Enter the data into metacat. 
268

    
269
# Initialize some global vars
270
my $latDeg1 = "";
271
my $latMin1 = "";
272
my $latSec1 = "";
273
my $hemisphLat1 = "";
274
my $longDeg1 = "";
275
my $longMin1 = "";
276
my $longSec1 = "";
277
my $hemisphLong1 = "";
278
my $latDeg2 = "";
279
my $latMin2 = "";
280
my $latSec2 = "";
281
my $hemisphLat2 = "";
282
my $longDeg2 = "";
283
my $longMin2 = "";
284
my $longSec2 = "";
285
my $hemisphLong2 = "";
286

    
287
# validate the input form parameters
288
my $invalidParams;
289

    
290
if (! $error) {
291
    $invalidParams = validateParameters(1);
292
    if (scalar(@$invalidParams)) {
293
        $$templateVars{'status'} = 'failure';
294
        $$templateVars{'invalidParams'} = $invalidParams;
295
        $error = 1;
296
    }
297
}
298

    
299

    
300
my $metacat;
301
my $docid;
302
if (! $error) {
303
    # Parameters have been validated and Create the XML document
304

    
305
    my $xmldoc = createXMLDocument();
306

    
307
    # Write out the XML file for debugging purposes
308
    #my $testFile = $tmpdir . "/test.xml";
309

    
310
    # Create a  metacat object
311
    $metacat = Metacat->new();
312
    if ($metacat) {
313
        $metacat->set_options( metacatUrl => $metacatUrl );
314
    } else {
315
        #die "failed during metacat creation\n";
316
        push(@errorMessages, "Failed during metacat creation.");
317
    }
318

    
319
    # Login to metacat
320
    my $userDN = $FORM::username;
321
    my $userOrg = $FORM::organization;
322
    my $userPass = $FORM::password;
323
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
324
    
325
    my $xmldocWithDocID = $xmldoc;
326
    
327
    my $errorMessage = "";
328
    my $response = $metacat->login($dname, $userPass);
329
    if (! $response) {
330
        push(@errorMessages, $metacat->getMessage());
331
        push(@errorMessages, "Failed during login.\n");
332
    }
333

    
334
    debug( "Registry: A");
335
    if ($FORM::docid eq "") {
336
        debug( "Registry: B1");
337
        # document is being inserted 
338
        my $notunique = "NOT_UNIQUE";
339
        while ($notunique eq "NOT_UNIQUE") {
340
            $docid = newAccessionNumber($defaultScope);
341
            
342
	    $xmldocWithDocID = $xmldoc;
343
            $xmldocWithDocID =~ s/docid/$docid/;
344

    
345
	    # Code for testing the xml file being inserted####
346
            #my $testFile = "/tmp/test.xml";
347
            #open (TFILE,">$testFile") || die ("Cant open xml file...\n");
348
            #print TFILE $xmldoc;
349
            #close(TFILE);
350
	    ####
351
    
352
            $notunique = insertMetadata($xmldocWithDocID, $docid);
353
            #  if (!$notunique) {
354
            # Write out the XML file for debugging purposes
355
            #my $testFile = $tmpdir . "/test-new.xml";
356
            #open (TFILE,">$testFile") || die ("Cant open xml file...\n");
357
            #print TFILE $newdoc;
358
            #close(TFILE);
359
            #   }
360

    
361
            # The id wasn't unique, so update our lastid file
362
            if ($notunique eq "NOT_UNIQUE") {
363
                debug( "Registry: Updating lastid (B1.1)");
364
                updateLastId($defaultScope);
365
            }
366
        }
367
        debug("Registry: B2");
368
        if ($notunique ne "SUCCESS") {
369
            debug("Registry: NO SUCCESS");
370
            debug("Message is: $notunique");
371
            push(@errorMessages, $notunique);
372
        }
373

    
374
        debug("Registry: B3");
375
    } else {
376
        # document is being modified
377
        $docid = $FORM::docid;
378
    
379
        my $x;
380
        my $y;
381
        my $z;
382

    
383
        ($x, $y, $z) = split(/\./, $docid); 
384
        $z++;
385
        $docid = "$x.$y.$z";
386
    
387
        $xmldoc =~ s/docid/$docid/;
388
        
389
        my $response = $metacat->update($docid, $xmldoc);
390

    
391
        if (! $response) {
392
            push(@errorMessages, $metacat->getMessage());
393
            push(@errorMessages, "Failed while updating.\n");  
394
        }
395

    
396
        if (scalar(@errorMessages)) {
397
            debug("Registry: ErrorMessages defined in modify.");
398

    
399
	    $$templateVars{'docid'} = $FORM::docid;
400
	    copyFormToTemplateVars();
401
            $$templateVars{'status'} = 'failure';
402
            $$templateVars{'errorMessages'} = \@errorMessages;
403
            $error = 1;
404
        } else {
405
	    $$templateVars{'docid'} = $docid;
406
	    $$templateVars{'cfg'} = $FORM::cfg;
407
	}
408

    
409
        #if (! $error) {
410
            #sendNotification($docid, $mailhost, $sender, $recipient);
411
        #}
412
    
413
        # Create our HTML response and send it back
414
        $$templateVars{'function'} = "modified";
415
        $$templateVars{'section'} = "Modification Status";
416
        $template->process( $responseTemplate, $templateVars);
417

    
418
        exit(0);
419
    }
420
}
421

    
422
debug("Registry: C");
423

    
424
if (scalar(@errorMessages)) {
425
    debug("Registry: ErrorMessages defined.");
426
    $$templateVars{'docid'} = $FORM::docid;
427
    copyFormToTemplateVars();
428
    $$templateVars{'status'} = 'failure';
429
    $$templateVars{'errorMessages'} = \@errorMessages;
430
    $error = 1;
431
} else {
432
    $$templateVars{'docid'} = $docid;
433
    $$templateVars{'cfg'} = $FORM::cfg;
434
}
435

    
436
#if (! $error) {
437
#sendNotification($docid, $mailhost, $sender, $recipient);
438
#}
439

    
440
# Create our HTML response and send it back
441
$$templateVars{'function'} = "submitted";
442
$$templateVars{'section'} = "Submission Status";
443

    
444
$template->process( $responseTemplate, $templateVars);
445

    
446
exit(0);
447

    
448

    
449
################################################################################
450
#
451
# Subroutine for updating a metacat id for a given scope to the highest value
452
#
453
################################################################################
454
sub updateLastId {
455
  my $scope = shift;
456

    
457
  my $errormsg = 0;
458
  my $docid = $metacat->getLastId($scope);
459

    
460
  if ($docid =~ /null/) {
461
      # No docids with this scope present, so do nothing
462
  } elsif ($docid) {
463
      # Update the lastid file for this scope
464
      (my $foundScope, my $id, my $rev) = split(/\./, $docid);
465
      debug("Docid is: $docid\n");
466
      debug("Lastid is: $id");
467
      my $scopeFile = $cfgdir . "/" . $FORM::cfg . "/" . $scope . ".lastid";
468
      open(LASTID, ">$scopeFile") or 
469
          die "Failed to open lastid file for writing!";
470
      print LASTID $id, "\n";
471
      close(LASTID);
472
  } else {
473
    $errormsg = $metacat->getMessage();
474
    debug("Error in getLastId: $errormsg");
475
  }
476
}
477

    
478
################################################################################
479
#
480
# Subroutine for inserting a document to metacat
481
#
482
################################################################################
483
sub insertMetadata {
484
  my $xmldoc = shift;
485
  my $docid = shift;
486

    
487
  my $notunique = "SUCCESS";
488
  debug("Registry: Starting insert (D1)");
489
  my $response = $metacat->insert($docid, $xmldoc);
490
  if (! $response) {
491
    debug("Registry: Response gotten (D2)");
492
    my $errormsg = $metacat->getMessage();
493
    debug("Registry: Error is (D3): ".$errormsg);
494
    if ($errormsg =~ /is already in use/) {
495
      $notunique = "NOT_UNIQUE";
496
      #print "Accession number already used: $docid\n";
497
    } elsif ($errormsg =~ /<login>/) {
498
      $notunique = "SUCCESS";
499
    } else {
500
      #print "<p>Dumping error on failure...</p>\n";
501
      #print "<p>", $errormsg, "</p>\n";
502
      #die "Failed during insert\n";
503
      #print "<p>Failed during insert</p>\n";
504
      $notunique = $errormsg;
505
    }
506
  }
507
  debug("Registry: Ending insert (D4)");
508

    
509
  return $notunique;
510
}
511

    
512
################################################################################
513
#
514
# Subroutine for generating a new accession number
515
#  Note: this is not threadsafe, assumes only one running process at a time
516
#  Also: need to check metacat for max id # used in this scope already
517
################################################################################
518
sub newAccessionNumber {
519
  my $scope = shift;
520
    
521
  my $docrev = 1;
522
  my $lastid = 1;
523

    
524
  my $scopeFile = $cfgdir . "/" . $FORM::cfg . "/" . $scope . ".lastid";
525
  if (-e $scopeFile) {
526
    open(LASTID, "<$scopeFile") or die "Failed to generate accession number!";
527
    $lastid = <LASTID>;
528
    chomp($lastid);
529
    $lastid++;
530
    close(LASTID);
531
  }
532
  open(LASTID, ">$scopeFile") or die "Failed to open lastid file for writing!";
533
  print LASTID $lastid, "\n";
534
  close(LASTID);
535

    
536
  my $docroot = "$scope.$lastid.";
537
  my $docid = $docroot . $docrev;
538
  return $docid;
539
}
540

    
541
################################################################################
542
# 
543
# Validate the parameters to make sure that required params are provided
544
#
545
################################################################################
546
sub validateParameters {
547
    my $chkUser = shift;
548
    my @invalidParams;
549

    
550
    push(@invalidParams, "Provider's first name is missing.")
551
        unless hasContent($FORM::providerGivenName);
552
    push(@invalidParams, "Provider's last name is missing.")
553
        unless hasContent($FORM::providerSurName);
554
    push(@invalidParams, "Name of site is missing.")
555
        unless (hasContent($FORM::site) || $FORM::site =~ /elect/ ||
556
                $FORM::cfg eq "nceas");
557
    push(@invalidParams, "Data set title is missing.")
558
        unless hasContent($FORM::title);
559
    push(@invalidParams, "Originator's first name is missing.")
560
        unless hasContent($FORM::origNamefirst0);
561
    push(@invalidParams, "Originator's last name is missing.")
562
        unless hasContent($FORM::origNamelast0);
563
    push(@invalidParams, "Abstract is missing.")
564
        unless hasContent($FORM::abstract);
565
    if($FORM::hasTemporal eq 'true'){
566
	push(@invalidParams, "Beginning year of data set is missing.")
567
	    unless (hasContent($FORM::beginningYear) || $FORM::temporalRequired ne 'true');
568
	push(@invalidParams, "Ending year has been specified but beginning year of data set is missing.")
569
	    if ((!hasContent($FORM::beginningYear)) && hasContent($FORM::endingYear));
570
    }
571
    push(@invalidParams, "Geographic description is missing.")
572
        unless (hasContent($FORM::geogdesc) || $FORM::spatialRequired ne 'true');
573

    
574
    if($FORM::beginningMonth eq "00"){
575
	if (hasContent($FORM::beginningYear)){
576
	    $FORM::beginningMonth = "01";
577
	} else {
578
	    $FORM::beginningMonth = "";
579
	}
580
    }
581
    if($FORM::beginningDay eq "00"){
582
	if (hasContent($FORM::beginningYear)){
583
	    $FORM::beginningDay = "01";
584
	} else {
585
	    $FORM::beginningDay = "";
586
	}
587
    }
588
    if($FORM::endingMonth eq "00"){
589
	if (hasContent($FORM::endingYear)){
590
	    $FORM::endingMonth = "01";
591
	} else {
592
	    $FORM::endingMonth = "";
593
	}
594
    }    
595
    if($FORM::endingDay eq "00"){
596
	if (hasContent($FORM::endingYear)){
597
	    $FORM::endingDay = "01";
598
	} else {
599
	    $FORM::endingDay = "";
600
	}
601
    }
602

    
603
    if (hasContent($FORM::beginningYear) && !($FORM::beginningYear =~ /[0-9][0-9][0-9][0-9]/)){
604
	push(@invalidParams, "Invalid beginning year specified.")
605
    }
606

    
607
    if (hasContent($FORM::endingYear) && !($FORM::endingYear =~ /[0-9][0-9][0-9][0-9]/)){
608
	push(@invalidParams, "Invalid ending year specified.")
609
    }
610
    
611
    # If the "use site" coord. box is checked and if the site is in 
612
    # the longitude hash ...  && ($siteLatDMS{$FORM::site})
613
    
614
    if($FORM::hasSpatial eq 'true'){
615
	if (($FORM::useSiteCoord) && ($siteLatDMS{$FORM::site}) ) {
616
        
617
	    $latDeg1 = $siteLatDMS{$FORM::site}[0];
618
	    $latMin1 = $siteLatDMS{$FORM::site}[1];
619
	    $latSec1 = $siteLatDMS{$FORM::site}[2];
620
	    $hemisphLat1 = $siteLatDMS{$FORM::site}[3];
621
	    $longDeg1 = $siteLongDMS{$FORM::site}[0];
622
	    $longMin1 = $siteLongDMS{$FORM::site}[1];
623
	    $longSec1 = $siteLongDMS{$FORM::site}[2];
624
	    $hemisphLong1 = $siteLongDMS{$FORM::site}[3];
625
	    
626
	}  else {
627
	    
628
	    $latDeg1 = $FORM::latDeg1;
629
	    $latMin1 = $FORM::latMin1;
630
	    $latSec1 = $FORM::latSec1;
631
	    $hemisphLat1 = $FORM::hemisphLat1;
632
	    $longDeg1 = $FORM::longDeg1;
633
	    $longMin1 = $FORM::longMin1;
634
	    $longSec1 = $FORM::longSec1;
635
	    $hemisphLong1 = $FORM::hemisphLong1;
636
	}
637

    
638
	if($latDeg1 > 90 || $latDeg1 < 0){
639
	    push(@invalidParams, "Invalid first latitude degrees specified.");
640
	}
641
	if($latMin1 > 59 || $latMin1 < 0){
642
	    push(@invalidParams, "Invalid first latitude minutes specified.");
643
	}
644
	if($latSec1 > 59 || $latSec1 < 0){
645
	    push(@invalidParams, "Invalid first latitude seconds specified.");
646
	}
647
	if($longDeg1 > 180 || $longDeg1 < 0){
648
	    push(@invalidParams, "Invalid first longitude degrees specified.");
649
	}
650
	if($longMin1 > 59 || $longMin1 < 0){
651
	    push(@invalidParams, "Invalid first longitude minutes specified.");
652
	}
653
	if($longSec1 > 59 || $longSec1 < 0){
654
	    push(@invalidParams, "Invalid first longitude seconds specified.");
655
	}
656

    
657
	if(hasContent($FORM::latDeg2) && ($FORM::latDeg2 > 90 || $FORM::latDeg2 < 0)){
658
	    push(@invalidParams, "Invalid second latitude degrees specified.");
659
	}
660
	if(hasContent($FORM::latMin2) && ($FORM::latMin2 > 59 || $FORM::latMin2 < 0)){
661
	    push(@invalidParams, "Invalid second latitude minutes specified.");
662
	}
663
	if(hasContent($FORM::latSec2) && ($FORM::latSec2 > 59 || $FORM::latSec2 < 0)){
664
	    push(@invalidParams, "Invalid second latitude seconds specified.");
665
	}
666
	if(hasContent($FORM::latDeg2) && ($FORM::longDeg2 > 180 || $FORM::longDeg2 < 0)){
667
	    push(@invalidParams, "Invalid second longitude degrees specified.");
668
	}
669
	if(hasContent($FORM::latMin2) && ($FORM::longMin2 > 59 || $FORM::longMin2 < 0)){
670
	    push(@invalidParams, "Invalid second longitude minutes specified.");
671
	}
672
	if(hasContent($FORM::latSec2) && ($FORM::longSec2 > 59 || $FORM::longSec2 < 0)){
673
	    push(@invalidParams, "Invalid second longitude seconds specified.");
674
	}
675
    }
676
    
677
    # Check if latDeg1 and longDeg1 has values if useSiteCoord is used. 
678
    # This check is required because some of the sites dont have lat 
679
    # and long mentioned in the config file. 
680

    
681

    
682
    if($FORM::hasSpatial eq 'true'){
683
	if ($FORM::useSiteCoord ) {
684
	    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.")
685
		unless(hasContent($latDeg1) && hasContent($longDeg1));
686
	}else{
687
	    push(@invalidParams, "Latitude degrees are missing.")
688
		unless (hasContent($latDeg1) || $FORM::spatialRequired ne 'true');
689
	    push(@invalidParams, "Longitude degrees are missing.")
690
		unless (hasContent($longDeg1) || $FORM::spatialRequired ne 'true');
691
	}
692
	push(@invalidParams, 
693
	     "You must provide a geographic description if you provide latitude and longitude information.")
694
	    if ((hasContent($latDeg1) || (hasContent($longDeg1))) && (!hasContent($FORM::geogdesc)));
695
    }
696

    
697
    if($FORM::hasMethod eq 'true'){
698
	push(@invalidParams, 
699
	     "You must provide a method description if you provide a method title.")
700
	    if (hasContent($FORM::methodTitle) && ( !(scalar(@FORM::methodPara) > 0) 
701
						    || (! hasContent($FORM::methodPara[0]))));
702
	push(@invalidParams, 
703
	     "You must provide a method description if you provide a study extent description.")
704
	    if (hasContent($FORM::studyExtentDescription) && (!(scalar(@FORM::methodPara) > 0) 
705
							      || (! hasContent($FORM::methodPara[0]))));
706
	push(@invalidParams, 
707
	     "You must provide both a study extent description and a sampling description, or neither.")
708
	    if (
709
                (hasContent($FORM::studyExtentDescription) && !hasContent($FORM::samplingDescription)) ||
710
                (!hasContent($FORM::studyExtentDescription) && hasContent($FORM::samplingDescription))
711
		);
712
    }
713

    
714
    push(@invalidParams, "Contact first name is missing.")
715
    unless (hasContent($FORM::origNamefirstContact) || 
716
        $FORM::useOrigAddress);
717
    push(@invalidParams, "Contact last name is missing.")
718
    unless (hasContent($FORM::origNamelastContact) || 
719
        $FORM::useOrigAddress);
720
    push(@invalidParams, "Data medium is missing.")
721
    unless (hasContent($FORM::dataMedium) || $FORM::dataMedium =~ /elect/);
722
    
723
    return \@invalidParams;
724
}
725

    
726
################################################################################
727
# 
728
# utility function to determine if a paramter is defined and not an empty string
729
#
730
################################################################################
731
sub hasContent {
732
    my $param = shift;
733

    
734
    my $paramHasContent;
735
    if (!defined($param) || $param eq '') { 
736
        $paramHasContent = 0;
737
    } else {
738
        $paramHasContent = 1;
739
    }
740
    return $paramHasContent;
741
}
742

    
743
################################################################################
744
#
745
# Subroutine for replacing characters not recognizable by XML and otherwise. 
746
#
747
################################################################################
748
sub normalize{
749
    my $val = shift;
750

    
751
    $val =~ s/&/&amp;/g;
752

    
753
    $val =~ s/</&lt;/g;
754
    $val =~ s/>/&gt;/g;
755
    $val =~ s/\"/&quot;/g;
756
    
757
    my $returnVal = "";
758
    
759
    foreach (split(//,$val)){
760
	my $var = unpack "C*", $_; 
761
	
762
	if($var<128 && $var>31){
763
	    $returnVal=$returnVal.$_;
764
	} elsif ($var<32){
765
	    if($var == 10){
766
		$returnVal=$returnVal.$_;
767
	    }
768
	    if($var == 13){
769
		$returnVal=$returnVal.$_;
770
	    }
771
	    if($var == 9){
772
		$returnVal=$returnVal.$_;
773
	    }
774
	} else { 
775
	    $returnVal=$returnVal."&#".$var.";";
776
	}
777
    }
778
    
779
    $returnVal =~ s/&/%26/g;    
780
    return $returnVal;
781
}
782

    
783

    
784
################################################################################
785
#
786
# Subroutine for replacing characters that might create problem in HTML. 
787
# Specifically written for " being used in any text field. This create a 
788
# problem in confirmData template, when you specify input name value pair 
789
# with value having a " in it.  
790
#
791
################################################################################
792
sub normalizeCD{
793
    my $val = shift;
794

    
795
    $val =~ s/\"/&quot;/g;
796
    
797
    return $val;
798
}
799

    
800

    
801
################################################################################
802
# 
803
# Create the XML document from the HTML form input
804
# returns the XML document as a string
805
#
806
################################################################################
807
sub createXMLDocument {
808

    
809
    my $orig  = "";
810
    my $role  = "associatedParty";
811
    my $creat = "";
812
    my $metaP = "";
813
    my $apart = "";
814
    my $cont  = "";
815
    my $publ  = "";
816
    my $dso   = "";
817
    my $gmt = gmtime($now);
818

    
819

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

    
822
    $doc .= "<eml:eml\n 
823
                     \t packageId=\"docid\" system=\"knb\"\n 
824
                     \t xmlns:eml=\"eml://ecoinformatics.org/eml-2.0.1\"\n
825
                     \t xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n 
826
                     \t xmlns:ds=\"eml://ecoinformatics.org/dataset-2.0.1\"\n 
827
                     \t xmlns:stmml=\"http://www.xml-cml.org/schema/stmml\"\n 
828
                     \t xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.0.1 eml.xsd\">\n";
829

    
830
    $doc .= "<!-- Person who filled in the catalog entry form: ";
831
    $doc .= normalize($FORM::providerGivenName)." ".normalize($FORM::providerSurName)." -->\n";
832
    $doc .= "<!-- Form filled out at $gmt GMT -->\n";
833
    $doc .= "<dataset>\n";
834
    
835
    if (hasContent($FORM::identifier)) {
836
        $doc .= "<alternateIdentifier system=\"$FORM::site\">";
837
        $doc .= normalize($FORM::identifier) . "</alternateIdentifier>\n";
838
    }
839
    
840
    if (hasContent($FORM::title)) {
841
        $doc .= "<title>".normalize($FORM::title)."</title>\n";
842
    }
843

    
844
    if (hasContent($FORM::origNamelast0)) {
845
    $role = "creator";
846
        $orig .= "<individualName>\n";
847
        $orig .= "<givenName>".normalize($FORM::origNamefirst0)."</givenName>\n";
848
        $orig .= "<surName>".normalize($FORM::origNamelast0)."</surName>\n";
849
        $orig .= "</individualName>\n";
850
    }
851

    
852
    if (hasContent($FORM::origNameOrg)) {
853
        $orig .= "<organizationName>".normalize($FORM::origNameOrg)."</organizationName>\n";
854
    }
855

    
856
    if (hasContent($FORM::origDelivery) || hasContent($FORM::origCity) ||
857
        (hasContent($FORM::origState   ) &&
858
        ($FORM::origState !~ "Select state here.")) ||
859
        hasContent($FORM::origStateOther) ||
860
        hasContent($FORM::origZIP ) || hasContent($FORM::origCountry)) {
861
        $orig .= "<address>\n";
862

    
863
        if (hasContent($FORM::origDelivery)) {
864
            $orig .= "<deliveryPoint>".normalize($FORM::origDelivery)."</deliveryPoint>\n";
865
        }
866
        if (hasContent($FORM::origCity)) {
867
            $orig .= "<city>".normalize($FORM::origCity)."</city>\n";
868
        }
869

    
870
    if (hasContent($FORM::origState) && 
871
            ($FORM::origState !~ "Select state here.")) {
872
            $orig .= "<administrativeArea>".normalize($FORM::origState);
873
            $orig .= "</administrativeArea>\n";
874
        } elsif (hasContent($FORM::origStateOther)) {
875
            $orig .= "<administrativeArea>".normalize($FORM::origStateOther);
876
            $orig .= "</administrativeArea>\n";
877
        }
878
        if (hasContent($FORM::origZIP)) {
879
            $orig .= "<postalCode>".normalize($FORM::origZIP)."</postalCode>\n";
880
        }
881
        if (hasContent($FORM::origCountry)) {
882
            $orig .= "<country>".normalize($FORM::origCountry)."</country>\n";
883
        }
884
        $orig .= "</address>\n";
885
    }
886

    
887
    if (hasContent($FORM::origPhone)) {
888
        $orig .= "<phone>".normalize($FORM::origPhone)."</phone>\n";
889
    }
890
    if (hasContent($FORM::origFAX)) {
891
        $orig .= "<phone phonetype=\"Fax\">".normalize($FORM::origFAX)."</phone>\n";
892
    }
893
    if (hasContent($FORM::origEmail)) {
894
        $orig .= "<electronicMailAddress>".normalize($FORM::origEmail);
895
        $orig .= "</electronicMailAddress>\n";
896
    }
897
    $dso = "<$role>\n$orig</$role>\n";
898
    
899
    if ($FORM::cfg eq 'nceas') {
900
        for (my $i = 0; $i < scalar(@FORM::wg); $i++) {
901
            $creat .= "<creator>\n";
902
            $creat .= "<organizationName>".normalize($FORM::wg[$i])."</organizationName>\n";
903
            $creat .= "</creator>\n";
904
        }
905
    } else {
906
	    $creat .= "<creator>\n";
907
	    $creat .= "<organizationName>".normalize($FORM::site)."</organizationName>\n";
908
	    $creat .= "</creator>\n";
909
    }
910

    
911
    if ($FORM::cfg ne 'knb') {
912
        $creat .= "<creator>\n";
913
        $creat .= "<organizationName>".normalize($organization)."</organizationName>\n";
914
        $creat .= "</creator>\n";
915
    }
916

    
917
    $creat .= $dso;
918

    
919
    if ($FORM::useOrigAddress) {
920
        # Add a contact originator like the original with a different role
921
            $cont .= "<contact>\n";
922
        $cont .= $orig;
923
        $cont .= "</contact>\n";
924
    } else {
925
        $cont .= "<contact>\n";
926

    
927
        $cont .= "<individualName>\n";
928
        $cont .= "<givenName>".normalize($FORM::origNamefirstContact)."</givenName>\n";
929
        $cont .= "<surName>".normalize($FORM::origNamelastContact)."</surName>\n";
930
        $cont .= "</individualName>\n";
931
 
932
    if (hasContent($FORM::origNameOrgContact)) {
933
        $cont .= "<organizationName>".normalize($FORM::origNameOrgContact)."</organizationName>\n";
934
    }
935

    
936
        if (hasContent($FORM::origDeliveryContact) || 
937
            hasContent($FORM::origCityContact) ||
938
            (hasContent($FORM::origStateContact) &&
939
            ($FORM::origStateContact !~ "Select state here.")) ||
940
            hasContent($FORM::origStateOtherContact) ||
941
            hasContent($FORM::origZIPContact) || 
942
            hasContent($FORM::origCountryContact)) {
943
            $cont .= "<address>\n";
944
            if (hasContent($FORM::origDeliveryContact)) {
945
                $cont .= "<deliveryPoint>".normalize($FORM::origDeliveryContact);
946
                $cont .= "</deliveryPoint>\n";
947
            }
948
            if (hasContent($FORM::origCityContact)) {
949
                $cont .= "<city>".normalize($FORM::origCityContact)."</city>\n";
950
            }
951
            if (hasContent($FORM::origStateContact) && 
952
                ($FORM::origStateContact !~ "Select state here.")) {
953
                $cont .= "<administrativeArea>".normalize($FORM::origStateContact);
954
                $cont .= "</administrativeArea>\n";
955
            } elsif (hasContent($FORM::origStateOtherContact)) {
956
                $cont .= "<administrativeArea>".normalize($FORM::origStateOtherContact);
957
                $cont .= "</administrativeArea>\n";
958
            }
959
            if (hasContent($FORM::origZIPContact)) {
960
                $cont .= "<postalCode>".normalize($FORM::origZIPContact)."</postalCode>\n";
961
            }
962
            if (hasContent($FORM::origCountryContact)) {
963
                $cont .= "<country>".normalize($FORM::origCountryContact)."</country>\n";
964
            }
965
            $cont .= "</address>\n";
966
        }
967
        if (hasContent($FORM::origPhoneContact)) {
968
            $cont .= "<phone>".normalize($FORM::origPhoneContact)."</phone>\n";
969
        }
970
    if (hasContent($FORM::origFAXContact)) {
971
        $cont .= "<phone phonetype=\"Fax\">".normalize($FORM::origFAXContact)."</phone>\n";
972
    }
973
        if (hasContent($FORM::origEmailContact)) {
974
            $cont .= "<electronicMailAddress>".normalize($FORM::origEmailContact);
975
            $cont .= "</electronicMailAddress>\n";
976
        }
977
    $cont .= "</contact>\n";
978
    }
979

    
980
    $metaP .= "<metadataProvider>\n";
981
    $metaP .= "<individualName>\n";
982
    $metaP .= "<givenName>".normalize($FORM::providerGivenName)."</givenName>\n";
983
    $metaP .= "<surName>".normalize($FORM::providerSurName)."</surName>\n";
984
    $metaP .= "</individualName>\n";
985
    $metaP .= "</metadataProvider>\n";
986

    
987
    # Additional originators
988
    foreach my $tmp (param()) {
989
        if ($tmp =~ /origNamelast/){
990
            my $tmp1 = $tmp;
991
            $tmp1 =~ s/origNamelast//; # get the index of the parameter 0 to 10
992
            if ( $tmp1 eq '1' 
993
                 || $tmp1 eq '2'
994
                 || $tmp1 eq '3'
995
                 || $tmp1 eq '4'
996
                 || $tmp1 eq '5'
997
                 || $tmp1 eq '6'
998
                 || $tmp1 eq '7'
999
                 || $tmp1 eq '8'
1000
                 || $tmp1 eq '9'
1001
                 || $tmp1 eq '10'
1002
                 ) {
1003
     
1004
                # do not generate XML for empty originator fields 
1005
                if (hasContent(param("origNamefirst" . $tmp1))) {    
1006

    
1007
            my $add = "";
1008
            $add .= "<individualName>\n";
1009
            $add .= "<givenName>";
1010
            $add .= normalize(param("origNamefirst" . $tmp1));
1011
            $add .= "</givenName>\n";
1012
            $add .= "<surName>";
1013
            $add .= normalize(param("origNamelast" . $tmp1));
1014
            $add .= "</surName>\n";
1015
            $add .= "</individualName>\n";
1016
            
1017
            if(param("origRole" . $tmp1) eq "Originator"){
1018
            $creat .= "<creator>\n";
1019
            $creat .= $add;
1020
            $creat .= "</creator>\n";
1021
            }
1022
            elsif(param("origRole" . $tmp1) eq "Metadata Provider"){
1023
            $metaP .= "<metadataProvider>\n";
1024
            $metaP .= $add;
1025
            $metaP .= "</metadataProvider>\n";
1026
            }
1027
            elsif((param("origRole" . $tmp1) eq "Publisher")  && ($publ eq "")){
1028
            $publ .= "<publisher>\n";
1029
            $publ .= $add;
1030
            $publ .= "</publisher>\n";
1031
            }
1032
            else{
1033
            $apart .= "<associatedParty>\n";
1034
            $apart .= $add;
1035
            $apart .= "<role>";
1036
            $apart .= param("origRole" . $tmp1);
1037
            $apart .= "</role>\n";
1038
            $apart .= "</associatedParty>\n";
1039
            }
1040
        }
1041
            }
1042
        }
1043
    }
1044

    
1045
    $doc .= $creat;
1046
    $doc .= $metaP;
1047
    $doc .= $apart;
1048

    
1049
    $doc .= "<abstract>\n";
1050
    $doc .= "<para>".normalize($FORM::abstract)."</para>\n";
1051
    $doc .= "</abstract>\n";
1052

    
1053
    # Keyword information
1054
    foreach my $tmp (param()) {
1055
        if ($tmp =~ /keyword/) {
1056
            my $tmp1 = $tmp;
1057
            $tmp1 =~ s/keyword//; # get the index of the parameter 0, ..., 10
1058
            if ( $tmp1 =~ /[0-9]/ ){
1059
                # don't generate xml for empty keyword fields
1060
                # don't generate taxonomic keyword fields, those go in taxonomic coverage
1061
                if (hasContent(param($tmp))) {
1062
                    $doc .= "<keywordSet>\n";
1063
                    $doc .= "<keyword ";
1064
                    if (hasContent(param("kwType" . $tmp1)) &&
1065
                       (param("kwType" . $tmp1) !~ "none") ) {
1066
                         $doc .= "keywordType=\"";
1067
                         $doc .= param("kwType" . $tmp1);
1068
                         $doc .= "\"";
1069
                    }
1070
                    $doc .= ">";
1071
                    $doc .= normalize(param("keyword" . $tmp1));
1072
                    $doc .= "</keyword>\n";
1073
                    $doc .= "<keywordThesaurus>";
1074
                    $doc .= normalize(param("kwTh" . $tmp1));
1075
                    $doc .= "</keywordThesaurus>\n";
1076
                    $doc .= "</keywordSet>\n";
1077
                }
1078
            }
1079
        }
1080
    }
1081

    
1082
    if (hasContent($FORM::addComments)) {
1083
        $doc .= "<additionalInfo>\n";
1084
        $doc .= "<para>".normalize($FORM::addComments)."</para>\n";
1085
        $doc .= "</additionalInfo>\n";
1086
    }
1087

    
1088
    if (hasContent($FORM::useConstraints) || 
1089
        hasContent($FORM::useConstraintsOther)) {
1090
        $doc .= "<intellectualRights>\n";
1091
        if (hasContent($FORM::useConstraints)) {
1092
            $doc .= "<para>".normalize($FORM::useConstraints)."</para>\n";
1093
        }
1094
        if (hasContent($FORM::useConstraintsOther)) {
1095
            $doc .= "<para>".normalize($FORM::useConstraintsOther)."</para>\n";
1096
        }
1097
        $doc .= "</intellectualRights>\n";
1098
    }
1099

    
1100
    
1101
    if (hasContent($FORM::url)) {
1102
    $doc .= "<distribution>\n";
1103
        $doc .= "<online>\n";
1104
    $doc .= "<url>".normalize($FORM::url)."</url>\n";
1105
    $doc .= "</online>\n";
1106
    $doc .= "</distribution>\n";
1107
    }
1108
    
1109
    $doc .= "<distribution>\n";
1110
    $doc .= "<offline>\n";
1111
    $doc .= "<mediumName>" . normalize($FORM::dataMedium)." ".normalize($FORM::dataMediumOther);
1112
    $doc .= "</mediumName>\n";
1113
    $doc .= "</offline>\n";
1114
    $doc .= "</distribution>\n";
1115
            
1116
    my $cov = "";
1117

    
1118
    if (hasContent($FORM::endingYear)) {
1119
	$cov .= "<temporalCoverage>\n";
1120
	$cov .= "<rangeOfDates>\n";
1121
	if (hasContent($FORM::beginningMonth)) {
1122
	    my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1123
			 "JUL","AUG","SEP","OCT","NOV","DEC")
1124
		[$FORM::beginningMonth - 1];
1125
	    $cov .= "<beginDate>\n";
1126
	    $cov .= "<calendarDate>";
1127
	    $cov .= normalize($FORM::beginningYear)."-".normalize($FORM::beginningMonth)."-".normalize($FORM::beginningDay);
1128
	    $cov .= "</calendarDate>\n";
1129
	    $cov .= "</beginDate>\n";
1130
	} else {
1131
	    $cov .= "<beginDate>\n";
1132
	    $cov .= "<calendarDate>";
1133
	    $cov .= normalize($FORM::beginningYear);
1134
	    $cov .= "</calendarDate>\n";
1135
	    $cov .= "</beginDate>\n";
1136
	}
1137
	
1138
	if (hasContent($FORM::endingMonth)) {
1139
	    my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1140
			 "JUL","AUG","SEP","OCT","NOV","DEC")
1141
		[$FORM::endingMonth - 1];
1142
	    $cov .= "<endDate>\n";
1143
	    $cov .= "<calendarDate>";
1144
	    $cov .= normalize($FORM::endingYear)."-".normalize($FORM::endingMonth)."-".normalize($FORM::endingDay);
1145
	    $cov .= "</calendarDate>\n";
1146
	    $cov .= "</endDate>\n";
1147
	} else {
1148
	    $cov .= "<endDate>\n";
1149
	    $cov .= "<calendarDate>";
1150
	    $cov .= normalize($FORM::endingYear);
1151
	    $cov .= "</calendarDate>\n";
1152
	    $cov .= "</endDate>\n";
1153
	}
1154
	$cov .= "</rangeOfDates>\n";
1155
	$cov .= "</temporalCoverage>\n";
1156
    } else {
1157
	if(hasContent($FORM::beginningYear)) {
1158
	    $cov .= "<temporalCoverage>\n";
1159
	    $cov .= "<singleDateTime>\n";
1160
	    if (hasContent($FORM::beginningMonth)) {
1161
		my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1162
			     "JUL","AUG","SEP","OCT","NOV","DEC")
1163
		    [$FORM::beginningMonth - 1];
1164
		$cov .= "<calendarDate>";
1165
		$cov .= normalize($FORM::beginningYear)."-".normalize($FORM::beginningMonth)."-".normalize($FORM::beginningDay);
1166
		$cov .= "</calendarDate>\n";
1167
	    } else {
1168
		$cov .= "<calendarDate>";
1169
		$cov .= normalize($FORM::beginningYear);
1170
		$cov .= "</calendarDate>\n";
1171
	    }
1172
	    $cov .= "</singleDateTime>\n";
1173
	    $cov .= "</temporalCoverage>\n";
1174
	}
1175
    }
1176
    
1177
    if(hasContent($FORM::geogdesc) || ($FORM::latDeg1 != 0 && $FORM::longDeg1 != 0)) {
1178
	$cov .= "<geographicCoverage>\n";
1179

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

    
1242
    # Write out the taxonomic coverage fields
1243
    my $foundFirstTaxon = 0;
1244
    foreach my $trn (param()) {
1245
        if ($trn =~ /taxonRankName/) {
1246
            my $taxIndex = $trn;
1247
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
1248
            my $trv = "taxonRankValue".$taxIndex;
1249
            if ( $taxIndex =~ /[0-9]/ ){
1250
                if (hasContent(param($trn)) && hasContent(param($trv))) {
1251
                    if (! $foundFirstTaxon) {
1252
                        $cov .= "<taxonomicCoverage>\n";
1253
                        $foundFirstTaxon = 1;
1254
                        if (hasContent($FORM::taxaAuth)) {
1255
                            $cov .= "<generalTaxonomicCoverage>".normalize($FORM::taxaAuth)."</generalTaxonomicCoverage>\n";
1256
                        }
1257
                    }
1258
                    $cov .= "<taxonomicClassification>\n";
1259
                    $cov .= "  <taxonRankName>".normalize(param($trn))."</taxonRankName>\n";
1260
                    $cov .= "  <taxonRankValue>".normalize(param($trv))."</taxonRankValue>\n";
1261
                    $cov .= "</taxonomicClassification>\n";
1262
                }
1263
            }
1264
        }
1265
    }
1266
    if ($foundFirstTaxon) {
1267
        $cov .= "</taxonomicCoverage>\n";
1268
    }
1269

    
1270
    if($cov ne "" ){
1271
	$doc .= "<coverage>".$cov."</coverage>";
1272
    }
1273
    $doc .= $cont;
1274
    $doc .= $publ;
1275
    
1276
    if ((hasContent($FORM::methodTitle)) || scalar(@FORM::methodsPara) > 0 || ($FORM::methodPara[0] ne "")) {
1277
        my $methods = "<methods><methodStep><description><section>\n";
1278
        if (hasContent($FORM::methodTitle)) {
1279
            $methods .= "<title>".normalize($FORM::methodTitle)."</title>\n";
1280
        }
1281
        for (my $i = 0; $i < scalar(@FORM::methodPara); $i++) {
1282
            $methods .= "<para>".normalize($FORM::methodPara[$i])."</para>\n";
1283
        }
1284
        $methods .= "</section></description></methodStep>\n";
1285
        if (hasContent($FORM::studyExtentDescription)) {
1286
            $methods .= "<sampling><studyExtent><description>\n";
1287
            $methods .= "<para>".normalize($FORM::studyExtentDescription)."</para>\n";
1288
            $methods .= "</description></studyExtent>\n";
1289
            $methods .= "<samplingDescription>\n";
1290
            $methods .= "<para>".normalize($FORM::samplingDescription)."</para>\n";
1291
            $methods .= "</samplingDescription>\n";
1292
            $methods .= "</sampling>\n";
1293
        }
1294
        $methods .= "</methods>\n";
1295
        $doc .= $methods;
1296
    }
1297

    
1298
    $doc .= "<access authSystem=\"knb\" order=\"denyFirst\">\n";
1299
    $doc .= "<allow>\n";
1300
    $doc .= "<principal>$username</principal>\n";
1301
    $doc .= "<permission>all</permission>\n";
1302
    $doc .= "</allow>\n";
1303
    $doc .= "<allow>\n";
1304
    $doc .= "<principal>uid=$FORM::username,o=$FORM::organization,dc=ecoinformatics,dc=org</principal>\n";
1305
    $doc .= "<permission>all</permission>\n";
1306
    $doc .= "</allow>\n";
1307
    $doc .= "<allow>\n";
1308
    $doc .= "<principal>public</principal>\n";
1309
    $doc .= "<permission>read</permission>\n";
1310
    $doc .= "</allow>\n";
1311
    $doc .= "</access>\n";
1312
    
1313
    $doc .= "</dataset>\n</eml:eml>\n";
1314

    
1315
    return $doc;
1316
}
1317

    
1318

    
1319
################################################################################
1320
# 
1321
# send an email message notifying the moderator of a new submission 
1322
#
1323
################################################################################
1324
sub sendNotification {
1325
    my $identifier = shift;
1326
    my $mailhost = shift;
1327
    my $sender = shift;
1328
    my $recipient = shift;
1329

    
1330
    my $smtp = Net::SMTP->new($mailhost);
1331
    $smtp->mail($sender);
1332
    $smtp->to($recipient);
1333

    
1334
    my $message = <<"    ENDOFMESSAGE";
1335
    To: $recipient
1336
    From: $sender
1337
    Subject: New data submission
1338
    
1339
    Data was submitted to the data registry.  
1340
    The identifying information for the new data set is:
1341

    
1342
    Identifier: $identifier
1343
    Title: $FORM::title
1344
    Submitter: $FORM::providerGivenName $FORM::providerSurName
1345

    
1346
    Please review the submmission and grant public read access if appropriate.
1347
    Thanks
1348
    
1349
    ENDOFMESSAGE
1350
    $message =~ s/^[ \t\r\f]+//gm;
1351

    
1352
    $smtp->data($message);
1353
    $smtp->quit;
1354
}
1355

    
1356

    
1357
################################################################################
1358
# 
1359
# read the eml document and send back a form with values filled in. 
1360
#
1361
################################################################################
1362
sub modifyData {
1363
    
1364
    # create metacat instance
1365
    my $metacat;
1366
    my $docid = $FORM::docid;
1367
    my $httpMessage;
1368
    my $doc;
1369
    my $xmldoc;
1370
    my $findType;
1371
    my $parser = XML::LibXML->new();
1372
    my @fileArray;
1373
    my $pushDoc;
1374
    my $alreadyInArray;
1375
    my $node;
1376
    my $response; 
1377
    my $element;
1378
    my $tempfile;
1379

    
1380
    $metacat = Metacat->new();
1381
    if ($metacat) {
1382
        $metacat->set_options( metacatUrl => $metacatUrl );
1383
    } else {
1384
        #die "failed during metacat creation\n";
1385
        push(@errorMessages, "Failed during metacat creation.");
1386
    }
1387
    
1388
    $httpMessage = $metacat->read($docid);
1389
    $doc = $httpMessage->content();
1390
    $xmldoc = $parser->parse_string($doc);
1391

    
1392
    #$tempfile = $xslConvDir.$docid;
1393
    #push (@fileArray, $tempfile);
1394

    
1395
    if ($xmldoc eq "") {
1396
        $error ="Error in parsing the eml document";
1397
        push(@errorMessages, $error);
1398
    } else {
1399
        $findType = $xmldoc->findnodes('//dataset/identifier');
1400
        if ($findType->size() > 0) {
1401
            # This is a eml beta6 document
1402
            # Read the documents mentioned in triples also
1403
        
1404
            $findType = $xmldoc->findnodes('//dataset/triple');
1405
            if ($findType->size() > 0) {
1406
                foreach $node ($findType->get_nodelist) {
1407
                    $pushDoc = findValue($node, 'subject');
1408
            
1409
                    # If the file is already in @fileArray then do not add it 
1410
                    $alreadyInArray = 0;
1411
                    foreach $element (@fileArray) {
1412
                        $tempfile = $tmpdir."/".$pushDoc;
1413
                        if ($element eq $pushDoc) {
1414
                            $alreadyInArray = 1;
1415
                        }
1416
                    }
1417
            
1418
                    if (!$alreadyInArray) {
1419
                        $tempfile = $tmpdir."/".$pushDoc;
1420
                        $response = "";
1421
                        $response = $metacat->read($pushDoc);    
1422
                        if (! $response) {
1423
                            # could not read
1424
                            #push(@errorMessages, $response);
1425
                            push(@errorMessages, $metacat->getMessage());
1426
                            push(@errorMessages, "Failed during reading.\n");
1427
                        } else {
1428
                            my $xdoc = $response->content();
1429
                            #$tempfile = $xslConvDir.$pushDoc;
1430
                            open (TFILE,">$tempfile") || 
1431
                                die ("Cant open xml file... $tempfile\n");
1432
                            print TFILE $xdoc;
1433
                            close(TFILE);
1434
                            push (@fileArray, $tempfile);
1435
                        }
1436
                    }
1437
                }
1438
            }
1439

    
1440
            # Read the main document. 
1441

    
1442
            $tempfile = $tmpdir."/".$docid; #= $xslConvDir.$docid;
1443
            open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1444
            print TFILE $doc;
1445
            close(TFILE);
1446
        
1447
            # Transforming beta6 to eml 2
1448
            my $xslt;
1449
            my $triplesheet;
1450
            my $results;
1451
            my $stylesheet;
1452
            my $resultsheet;
1453
        
1454
            $xslt = XML::LibXSLT->new();
1455
            #$tempfile = $xslConvDir."triple_info.xsl";
1456
            $tempfile = $tmpdir."/"."triple_info.xsl";
1457
    
1458
            $triplesheet = $xslt->parse_stylesheet_file($tempfile);
1459

    
1460
            #$results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1461
            $results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1462

    
1463
            #$tempfile = $xslConvDir."emlb6toeml2.xsl";
1464
            $tempfile = $tmpdir."/"."emlb6toeml2.xsl";
1465
            $stylesheet = $xslt->parse_stylesheet_file($tempfile);
1466
            $resultsheet = $stylesheet->transform($results);
1467
        
1468
            #$tempfile = "/usr/local/apache2/htdocs/xml/test.xml";;
1469
            #open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1470
            #print TFILE $stylesheet->output_string($resultsheet);
1471
            #close(TFILE);
1472

    
1473
            getFormValuesFromEml2($resultsheet);
1474
            
1475
            # Delete the files written earlier. 
1476
            unlink @fileArray;
1477

    
1478
        } else {
1479
            getFormValuesFromEml2($xmldoc);
1480
        }
1481
    }   
1482
    
1483
    if (scalar(@errorMessages)) {
1484
        # if any errors, print them in the response template 
1485
        $$templateVars{'status'} = 'failure';
1486
        $$templateVars{'errorMessages'} = \@errorMessages;
1487
        $error = 1;
1488
        $$templateVars{'function'} = "modification";
1489
        $$templateVars{'section'} = "Modification Status";
1490
        $template->process( $responseTemplate, $templateVars); 
1491
    } else {
1492
        $$templateVars{'form'} = 're_entry';
1493
        $template->process( $entryFormTemplate, $templateVars);
1494
    }
1495
}
1496

    
1497
################################################################################
1498
# 
1499
# Parse an EML 2.0.0 file and extract the metadata into perl variables for 
1500
# processing and returning to the template processor
1501
#
1502
################################################################################
1503
sub getFormValuesFromEml2 {
1504
    
1505
    my $doc = shift;
1506
    my $results;
1507
    my $error;
1508
    my $node;
1509
    my $tempResult;
1510
    my $tempNode;
1511
    my $aoCount = 1;
1512
    my $foundDSO;
1513

    
1514
    # set variable values
1515
    $$templateVars{'hasKeyword'} = $hasKeyword;
1516
    $$templateVars{'hasTemporal'} = $hasTemporal;
1517
    $$templateVars{'hasSpatial'} = $hasSpatial;
1518
    $$templateVars{'hasTaxonomic'} = $hasTaxonomic;
1519
    $$templateVars{'hasMethod'} = $hasMethod;
1520
    $$templateVars{'spatialRequired'} = $spatialRequired;
1521
    $$templateVars{'temporalRequired'} = $temporalRequired;
1522

    
1523
    # find out the tag <alternateIdentifier>. 
1524
    $results = $doc->findnodes('//dataset/alternateIdentifier');
1525
    if ($results->size() > 1) {
1526
        errMoreThanOne("alternateIdentifier");
1527
    } else {
1528
        foreach $node ($results->get_nodelist) {
1529
            $$templateVars{'identifier'} = findValue($node, '../alternateIdentifier');
1530
        }
1531
    }
1532

    
1533
    # find out the tag <title>. 
1534
    $results = $doc->findnodes('//dataset/title');
1535
    if ($results->size() > 1) {
1536
        errMoreThanOne("title");
1537
    } elsif ($results->size() < 1) {
1538
        $error ="Following tag not found: title. Please use Morpho to edit this document";
1539
        push(@errorMessages, $error."\n");
1540
        #if ($DEBUG == 1){ print $error;}
1541
    } else {
1542
        foreach $node ($results->get_nodelist) {
1543
            $$templateVars{'title'} = findValue($node, '../title');
1544
        }
1545
    }
1546

    
1547
    # find out the tag <creator>. 
1548
    $results = $doc->findnodes('//dataset/creator/individualName');
1549
    debug("Registry: Creators: ".$results->size());
1550
     foreach $node ($results->get_nodelist) {
1551
            dontOccur($node, "../positionName|../onlineURL|../userId", 
1552
              "positionName, onlineURL, userId");
1553
        
1554
            dontOccur($node, "./saluation", "saluation");                
1555
        
1556
            debug("Registry: Checking a creator in loop 1...");
1557
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1558
            if($tempResult->size > 0) {
1559
                if($foundDSO == 0) {
1560
                    $foundDSO = 1;
1561
     
1562
                    debug("Registry: Recording a creator in loop 1...");
1563
                    $$templateVars{'origNamefirst0'} = findValue($node, 'givenName');
1564
                    $$templateVars{'origNamelast0'} = findValue($node, 'surName');
1565
            
1566
                    my $tempResult2 = $node->findnodes('../address');
1567
                    if ($tempResult2->size > 1) {
1568
                        errMoreThanOne("address");
1569
                    } else {
1570
                        foreach my $tempNode2 ($tempResult2->get_nodelist) {
1571
                            $$templateVars{'origDelivery'} = findValue($tempNode2, 'deliveryPoint');
1572
                            $$templateVars{'origCity'} = findValue($tempNode2, 'city');
1573
                            $$templateVars{'origState'} = findValue($tempNode2, 'administrativeArea');
1574
                            $$templateVars{'origZIP'} = findValue($tempNode2, 'postalCode');
1575
                            $$templateVars{'origCountry'} = findValue($tempNode2, 'country');
1576
                        }
1577
                    }
1578
            
1579
                    my $tempResult3 = $node->findnodes('../phone');
1580
                    if ($tempResult3->size > 2) {
1581
                        errMoreThanN("phone");
1582
                    } else {
1583
                        foreach my $tempNode2 ($tempResult3->get_nodelist) {
1584
                            if ($tempNode2->hasAttributes()) {
1585
                                my @attlist = $tempNode2->attributes();
1586
                                if ($attlist[0]->value eq "Fax") {
1587
                                    $$templateVars{'origFAX'} = $tempNode2->textContent();
1588
                                } else {
1589
                                    $$templateVars{'origPhone'} = $tempNode2->textContent();
1590
                                }
1591
                            } else {
1592
                                $$templateVars{'origPhone'} = $tempNode2->textContent();
1593
                            }
1594
                        }
1595
                    }
1596
                    $$templateVars{'origEmail'} = findValue($node, '../electronicMailAddress');
1597
                    $$templateVars{'origNameOrg'} = findValue($node, '../organizationName');
1598
                } else {
1599
                    errMoreThanN("address, phone and electronicMailAddress");
1600
                }
1601
            }
1602
        }
1603
        foreach $node ($results->get_nodelist) {
1604
            debug("Registry: Checking a creator in loop 2...");
1605
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1606
            if ($tempResult->size == 0) {
1607
                if ($foundDSO == 0) {
1608
                    debug("Registry: Recording a creator in loop 2 block A...");
1609
                    $foundDSO = 1;
1610
                    $$templateVars{'origNamefirst0'} = findValue($node, 'givenName');
1611
                    $$templateVars{'origNamelast0'} = findValue($node, 'surName');
1612
                    $$templateVars{'origNameOrg'} = findValue($node, '../organizationName');
1613
                } else {
1614
                    debug("Registry: Recording a creator in loop 2 block B...");
1615
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($node, './givenName');
1616
                    $$templateVars{"origNamelast$aoCount"} =  findValue($node, './surName');
1617
                    $$templateVars{"origRole$aoCount"} = "Originator";
1618
                    $aoCount++;
1619
                }
1620
            }
1621
        }
1622

    
1623
    $results = $doc->findnodes('//dataset/creator/organizationName');
1624
    my $wgroups = $doc->findnodes("//dataset/creator/organizationName[contains(text(),'(NCEAS ')]");
1625
    debug("Registry: Number Org: ".$results->size());
1626
    debug("Registry:  Number WG: ".$wgroups->size());
1627
    if ($results->size() - $wgroups->size() > 3) {
1628
        errMoreThanN("creator/organizationName");    
1629
    } else {
1630
        foreach $node ($results->get_nodelist) {
1631
            my $tempValue = findValue($node,'../organizationName');
1632
            $tempResult = $node->findnodes('../individualName');
1633
            if ($tempResult->size == 0 && $tempValue ne $organization) {
1634
                $$templateVars{'site'} = $tempValue;
1635
            }
1636
        }
1637
        if ($FORM::cfg eq 'nceas') {
1638
            my @wg;
1639
            foreach $node ($results->get_nodelist) {
1640
                my $tempValue = findValue($node,'../organizationName');
1641
                $wg[scalar(@wg)] = $tempValue;
1642
            }
1643
            my $projects = getProjectList();
1644
            $$templateVars{'projects'} = $projects;
1645
            $$templateVars{'wg'} = \@wg;
1646
        }
1647
    }
1648

    
1649
    $results = $doc->findnodes('//dataset/metadataProvider');
1650
    foreach $node ($results->get_nodelist) {
1651
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1652
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in metadataProvider");
1653
        
1654
	    $tempResult = $node->findnodes('./individualName');
1655
            if ($tempResult->size > 1) {
1656
                errMoreThanOne("metadataProvider/indvidualName");
1657
            } else {
1658
                foreach $tempNode ($tempResult->get_nodelist) {
1659
                    if ($$templateVars{'providerGivenName'} ne "") {
1660
                        $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1661
                        $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1662
                        $$templateVars{"origRole$aoCount"} = "Metadata Provider";
1663
                        $aoCount++;
1664
                    } else {
1665
                        $$templateVars{'providerGivenName'} =  findValue($tempNode, './givenName');
1666
                        $$templateVars{'providerSurName'} =  findValue($tempNode, './surName');
1667
                    }
1668
                }
1669
            }
1670
        }
1671

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

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

    
1712
  #  if ($aoCount > 11) {
1713
  #      errMoreThanN("Additional Originators");
1714
 #   } 
1715

    
1716
    $$templateVars{'aoCount'} = $aoCount-1;
1717
    
1718
    dontOccur($doc, "./pubDate", "pubDate");
1719
    dontOccur($doc, "./language", "language");
1720
    dontOccur($doc, "./series", "series");
1721

    
1722
    $results = $doc->findnodes('//dataset/abstract');
1723
    if ($results->size() > 1) {
1724
        errMoreThanOne("abstract");
1725
    } else {
1726
        foreach my $node ($results->get_nodelist) {
1727
            dontOccur($node, "./section", "section");
1728
            $$templateVars{'abstract'} = findValueNoChild($node, "para");
1729
        }
1730
    }
1731

    
1732
    $results = $doc->findnodes('//dataset/keywordSet');
1733

    
1734
    my $count = 0;
1735
    foreach $node ($results->get_nodelist) {
1736
	$tempResult = $node->findnodes('./keyword');
1737
	if ($tempResult->size() > 1) {
1738
	    errMoreThanOne("keyword");
1739
	} else {
1740
	    $count++;
1741
	    foreach $tempNode ($tempResult->get_nodelist) {
1742
		$$templateVars{"keyword$count"} = $tempNode->textContent();
1743
		if ($tempNode->hasAttributes()) {
1744
		    my @attlist = $tempNode->attributes();
1745
		    $$templateVars{"kwType$count"} = $attlist[0]->value;
1746
		}  
1747
	    }
1748
	}
1749
	$$templateVars{"kwTh$count"} = findValue($node, "keywordThesaurus");
1750
    }
1751
    $$templateVars{'keyCount'} = $count;
1752
    if($count > 0 ){
1753
       $$templateVars{'hasKeyword'} = "true";
1754
    }
1755

    
1756
    $results = $doc->findnodes('//dataset/additionalInfo');
1757
    if ($results->size() > 1) {
1758
        errMoreThanOne("additionalInfo");
1759
    } else {
1760
        foreach $node ($results->get_nodelist) {
1761
            dontOccur($node, "./section", "section");
1762
            $$templateVars{'addComments'} = findValueNoChild($node, "para");
1763
        }
1764
    }
1765

    
1766
    $$templateVars{'useConstraints'} = "";
1767
    $results = $doc->findnodes('//dataset/intellectualRights');
1768
    if ($results->size() > 1) {
1769
        errMoreThanOne("intellectualRights");
1770
    } else {
1771
        foreach $node ($results->get_nodelist) {
1772
            dontOccur($node, "./section", "section in intellectualRights");
1773

    
1774
            $tempResult = $node->findnodes("para");
1775
            if ($tempResult->size > 2) {
1776
                   errMoreThanN("para");
1777
            } else {
1778
                foreach $tempNode ($tempResult->get_nodelist) {
1779
                    my $childNodes = $tempNode->childNodes;
1780
                    if ($childNodes->size() > 1) {
1781
                        $error ="The tag para in intellectualRights has children which cannot be shown using the form. Please use Morpho to edit this document";    
1782
                        push(@errorMessages, $error);
1783
                        #if ($DEBUG == 1){ print $error."\n";}
1784
                    } else {
1785
                        #print $tempNode->nodeName().":".$tempNode->textContent();
1786
                        #print "\n";
1787
                        if ($$templateVars{'useConstraints'} eq "") {
1788
                            $$templateVars{'useConstraints'} = $tempNode->textContent();
1789
                        } else {
1790
                            $$templateVars{'useConstraintsOther'} = $tempNode->textContent();
1791
                        }
1792
                    }
1793
                }
1794
            }
1795
        }
1796
    }
1797

    
1798
    $results = $doc->findnodes('//dataset/distribution/online');
1799
    if ($results->size() > 1) {
1800
        errMoreThanOne("distribution/online");
1801
    } else {
1802
        foreach my $tempNode ($results->get_nodelist){
1803
            $$templateVars{'url'} = findValue($tempNode, "url");
1804
            dontOccur($tempNode, "./connection", "/distribution/online/connection");
1805
            dontOccur($tempNode, "./connectionDefinition", "/distribution/online/connectionDefinition");
1806
        }
1807
    }
1808

    
1809
    $results = $doc->findnodes('//dataset/distribution/offline');
1810
    if ($results->size() > 1) {
1811
        errMoreThanOne("distribution/online");
1812
    } else {
1813
        foreach my $tempNode ($results->get_nodelist) {
1814
            $$templateVars{'dataMedium'} = findValue($tempNode, "mediumName");
1815
            dontOccur($tempNode, "./mediumDensity", "/distribution/offline/mediumDensity");
1816
            dontOccur($tempNode, "./mediumDensityUnits", "/distribution/offline/mediumDensityUnits");
1817
            dontOccur($tempNode, "./mediumVolume", "/distribution/offline/mediumVolume");
1818
            dontOccur($tempNode, "./mediumFormat", "/distribution/offline/mediumFormat");
1819
            dontOccur($tempNode, "./mediumNote", "/distribution/offline/mediumNote");
1820
        }
1821
    }
1822

    
1823
    dontOccur($doc, "./inline", "//dataset/distribution/inline");
1824

    
1825
    $results = $doc->findnodes('//dataset/coverage');
1826
    if ($results->size() > 1) {
1827
        errMoreThanOne("coverage");
1828
    } else {
1829
        foreach $node ($results->get_nodelist) {
1830
            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");
1831

    
1832
            $tempResult = $node->findnodes('./temporalCoverage');
1833
            if ($tempResult->size > 1) {
1834
                   errMoreThanOne("temporalCoverage");
1835
            } else {
1836
                foreach $tempNode ($tempResult->get_nodelist) {
1837
                    my $x;
1838
                    my $y;
1839
                    my $z;
1840
                    my $tempdate = findValue($tempNode, "rangeOfDates/beginDate/calendarDate");
1841
                    ($x, $y, $z) = split("-", $tempdate); 
1842
                    $$templateVars{'beginningYear'} = $x;
1843
                    $$templateVars{'beginningMonth'} = $y;
1844
                    $$templateVars{'beginningDay'} = $z;
1845
    
1846
                    $tempdate = findValue($tempNode, "rangeOfDates/endDate/calendarDate");
1847
                    ($x, $y, $z) = split("-", $tempdate);
1848
                    $$templateVars{'endingYear'} = $x;
1849
                    $$templateVars{'endingMonth'} = $y;
1850
                    $$templateVars{'endingDay'} = $z;
1851

    
1852
                    $tempdate = "";
1853
                    $tempdate = findValue($tempNode, "singleDateTime/calendarDate");
1854
                    if($tempdate ne ""){
1855
                        ($x, $y, $z) = split("-", $tempdate);
1856
                        $$templateVars{'beginningYear'} = $x;
1857
                        $$templateVars{'beginningMonth'} = $y;
1858
                        $$templateVars{'beginningDay'} = $z;
1859
                    }  
1860
		    
1861
		    $$templateVars{'hasTemporal'} = "true";
1862
                }
1863
            }
1864

    
1865
            $tempResult = $node->findnodes('./geographicCoverage');
1866
            if ($tempResult->size > 1) {
1867
                errMoreThanOne("geographicCoverage");
1868
            } else {
1869
                foreach $tempNode ($tempResult->get_nodelist) {
1870
                    my $geogdesc = findValue($tempNode, "geographicDescription");
1871
                    debug("Registry: geogdesc from xml is: $geogdesc");
1872
                    $$templateVars{'geogdesc'} = $geogdesc;
1873
                    my $coord = findValue($tempNode, "boundingCoordinates/westBoundingCoordinate");
1874
                    if ($coord > 0) {
1875
                        #print "+";
1876
                        $$templateVars{'hemisphLong1'} = "E";
1877
                    } else {
1878
                        #print "-";
1879
                        eval($coord = $coord * -1);
1880
                        $$templateVars{'hemisphLong1'} = "W";
1881
                    }
1882
                    eval($$templateVars{'longDeg1'} = int($coord));
1883
                    eval($coord = ($coord - int($coord))*60);
1884
                    eval($$templateVars{'longMin1'} = int($coord));
1885
                    eval($coord = ($coord - int($coord))*60);
1886
                    eval($$templateVars{'longSec1'} = int($coord));
1887
                    
1888
                    $coord = findValue($tempNode, "boundingCoordinates/southBoundingCoordinate");
1889
                    if ($coord > 0) {
1890
                        #print "+";
1891
                        $$templateVars{'hemisphLat2'} = "N";
1892
                    } else {
1893
                        #print "-";
1894
                        eval($coord = $coord * -1);
1895
                        $$templateVars{'hemisphLat2'} = "S";
1896
                    }
1897
                    eval($$templateVars{'latDeg2'} = int($coord));
1898
                    eval($coord = ($coord - int($coord))*60);
1899
                    eval($$templateVars{'latMin2'} = int($coord));
1900
                    eval($coord = ($coord - int($coord))*60);
1901
                    eval($$templateVars{'latSec2'} = int($coord));
1902
        
1903
                    $coord = findValue($tempNode, "boundingCoordinates/northBoundingCoordinate");
1904
                    if ($coord > 0) {
1905
                        #print "+";
1906
                        $$templateVars{'hemisphLat1'} = "N";
1907
                    } else {
1908
                        #print "-";
1909
                        eval($coord = $coord * -1);
1910
                        $$templateVars{'hemisphLat1'} = "S";
1911
                    }
1912
                    eval($$templateVars{'latDeg1'} = int($coord));
1913
                    eval($coord = ($coord - int($coord))*60);
1914
                    eval($$templateVars{'latMin1'} = int($coord));
1915
                    eval($coord = ($coord - int($coord))*60);
1916
                    eval($$templateVars{'latSec1'} = int($coord));
1917
        
1918
                    $coord = findValue($tempNode, "boundingCoordinates/eastBoundingCoordinate");
1919
                    if ($coord > 0) {
1920
                        #print "+";
1921
                        $$templateVars{'hemisphLong2'} = "E";
1922
                    } else {
1923
                        #print "-";
1924
                        eval($coord = $coord * -1);
1925
                        $$templateVars{'hemisphLong2'} = "W";
1926
                    }
1927
                    eval($$templateVars{'longDeg2'} = int($coord));
1928
                    eval($coord = ($coord - int($coord))*60);
1929
                    eval($$templateVars{'longMin2'} = int($coord));
1930
                    eval($coord = ($coord - int($coord))*60);
1931
                    eval($$templateVars{'longSec2'} = int($coord));
1932

    
1933
		    $$templateVars{'hasSpatial'} = "true";
1934
                }
1935
            }
1936

    
1937
            $tempResult = $node->findnodes('./taxonomicCoverage/taxonomicClassification');
1938
            my $taxonIndex = 0;
1939
            foreach $tempNode ($tempResult->get_nodelist) {
1940
                $taxonIndex++;
1941
                my $taxonRankName = findValue($tempNode, "taxonRankName");
1942
                my $taxonRankValue = findValue($tempNode, "taxonRankValue");
1943
                $$templateVars{"taxonRankName".$taxonIndex} = $taxonRankName;
1944
                $$templateVars{"taxonRankValue".$taxonIndex} = $taxonRankValue;
1945
		
1946
		$$templateVars{'hasTaxonomic'} = "true";
1947
            }
1948
            $$templateVars{'taxaCount'} = $taxonIndex;
1949
            my $taxaAuth = findValue($node, "./taxonomicCoverage/generalTaxonomicCoverage");
1950
            $$templateVars{'taxaAuth'} = $taxaAuth;
1951
        }
1952
    }
1953
    dontOccur($doc, "./purpose", "purpose");
1954
    dontOccur($doc, "./maintenance", "maintnance");
1955

    
1956
    $results = $doc->findnodes('//dataset/contact/individualName');
1957
    if ($results->size() > 1) {
1958
        errMoreThanOne("contact/individualName");
1959
    } else {
1960
        foreach $node ($results->get_nodelist) {
1961
            dontOccur($node, "../positionName|../onlineURL|../userId", 
1962
              "positionName, onlineURL, userId in contact tag");
1963
            dontOccur($node, "./saluation", "saluation in contact tag");                
1964
        
1965
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1966
            if ($tempResult->size > 0) {
1967
                $$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
1968
                $$templateVars{'origNamelastContact'} = findValue($node, 'surName');
1969
    
1970
                my $tempResult2 = $node->findnodes('../address');
1971
                if ($tempResult2->size > 1) {
1972
                    errMoreThanOne("address");
1973
                } else {
1974
                    foreach my $tempNode2 ($tempResult2->get_nodelist) {
1975
                        $$templateVars{'origDeliveryContact'} = findValue($tempNode2, 'deliveryPoint');
1976
                        $$templateVars{'origCityContact'} = findValue($tempNode2, 'city');
1977
                        $$templateVars{'origStateContact'} = findValue($tempNode2, 'administrativeArea');
1978
                        $$templateVars{'origZIPContact'} = findValue($tempNode2, 'postalCode');
1979
                        $$templateVars{'origCountryContact'} = findValue($tempNode2, 'country');
1980
                    }
1981
                }
1982
            
1983
                my $tempResult3 = $node->findnodes('../phone');
1984
                if ($tempResult3->size > 2) {
1985
                    errMoreThanN("phone");
1986
                } else {
1987
                    foreach my $tempNode2 ($tempResult3->get_nodelist) {
1988
                        if ($tempNode2->hasAttributes()) {
1989
                            my @attlist = $tempNode2->attributes();
1990
                            if ($attlist[0]->value eq "Fax") {
1991
                                $$templateVars{'origFAXContact'} = $tempNode2->textContent();
1992
                            } else {
1993
                                $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
1994
                            }
1995
                        } else {
1996
                            $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
1997
                        }
1998
                    }
1999
                }
2000
                $$templateVars{'origEmailContact'} = findValue($node, '../electronicMailAddress');
2001
                $$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
2002
            } else {
2003
                $$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
2004
                $$templateVars{'origNamelastContact'} = findValue($node, 'surName');
2005
                $$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
2006
            }
2007
        }
2008
    }
2009
    
2010
    $results = $doc->findnodes(
2011
            '//dataset/methods/methodStep/description/section');
2012
    debug("Registry: Number methods: ".$results->size());
2013
    if ($results->size() > 1) {
2014
        errMoreThanN("methods/methodStep/description/section");    
2015
    } else {
2016

    
2017
        my @methodPara;
2018
        foreach $node ($results->get_nodelist) {
2019
            my @children = $node->childNodes;
2020
            for (my $i = 0; $i < scalar(@children); $i++) {
2021
                debug("Registry: Method child loop ($i)");
2022
                my $child = $children[$i];
2023
                if ($child->nodeName eq 'title') {
2024
                    my $title = $child->textContent();
2025
                    debug("Registry: Method title ($title)");
2026
                    $$templateVars{'methodTitle'} = $title;
2027
                } elsif ($child->nodeName eq 'para') {
2028
                    my $para = $child->textContent();
2029
                    debug("Registry: Method para ($para)");
2030
                    $methodPara[scalar(@methodPara)] = $para;
2031
                }
2032
            }
2033
	    $$templateVars{'hasMethod'} = "true";
2034
        }
2035
        if (scalar(@methodPara) > 0) {
2036
            $$templateVars{'methodPara'} = \@methodPara;
2037
        }
2038
    }
2039

    
2040
    $results = $doc->findnodes(
2041
            '//dataset/methods/sampling/studyExtent/description/para');
2042
    if ($results->size() > 1) {
2043
        errMoreThanN("methods/sampling/studyExtent/description/para");    
2044
    } else {
2045
        foreach $node ($results->get_nodelist) {
2046
            my $studyExtentDescription = $node->textContent();
2047
            $$templateVars{'studyExtentDescription'} = $studyExtentDescription;
2048

    
2049
	    $$templateVars{'hasMethod'} = "true";
2050
        }
2051
    }
2052

    
2053
    $results = $doc->findnodes(
2054
            '//dataset/methods/sampling/samplingDescription/para');
2055
    if ($results->size() > 1) {
2056
        errMoreThanN("methods/sampling/samplingDescription/para");    
2057
    } else {
2058
        foreach $node ($results->get_nodelist) {
2059
            my $samplingDescription = $node->textContent();
2060
            $$templateVars{'samplingDescription'} = $samplingDescription;
2061

    
2062
	    $$templateVars{'hasMethod'} = "true";
2063
        }
2064
    }
2065

    
2066
    dontOccur($doc, "//methodStep/citation", "methodStep/citation");
2067
    dontOccur($doc, "//methodStep/protocol", "methodStep/protocol");
2068
    dontOccur($doc, "//methodStep/instrumentation", "methodStep/instrumentation");
2069
    dontOccur($doc, "//methodStep/software", "methodStep/software");
2070
    dontOccur($doc, "//methodStep/subStep", "methodStep/subStep");
2071
    dontOccur($doc, "//methodStep/dataSource", "methodStep/dataSource");
2072
    dontOccur($doc, "//methods/qualityControl", "methods/qualityControl");
2073

    
2074
    dontOccur($doc, "//methods/sampling/spatialSamplingUnits", "methods/sampling/spatialSamplingUnits");
2075
    dontOccur($doc, "//methods/sampling/citation", "methods/sampling/citation");
2076
    dontOccur($doc, "./pubPlace", "pubPlace");
2077
    dontOccur($doc, "./project", "project");
2078
    
2079
    dontOccur($doc, "./dataTable", "dataTable");
2080
    dontOccur($doc, "./spatialRaster", "spatialRaster");
2081
    dontOccur($doc, "./spatialVector", "spatialVector");
2082
    dontOccur($doc, "./storedProcedure", "storedProcedure");
2083
    dontOccur($doc, "./view", "view");
2084
    dontOccur($doc, "./otherEntity", "otherEntity");
2085
    dontOccur($doc, "./references", "references");
2086
    
2087
    dontOccur($doc, "//citation", "citation");
2088
    dontOccur($doc, "//software", "software");
2089
    dontOccur($doc, "//protocol", "protocol");
2090
    dontOccur($doc, "//additionalMetadata", "additionalMetadata");    
2091
}
2092

    
2093
################################################################################
2094
# 
2095
# Delete the eml file that has been requested for deletion. 
2096
#
2097
################################################################################
2098
sub deleteData {
2099
    my $deleteAll = shift;
2100
    
2101
    # create metacat instance
2102
    my $metacat;
2103
    my $docid = $FORM::docid;
2104
    
2105
    $metacat = Metacat->new();
2106
    if ($metacat) {
2107
        $metacat->set_options( metacatUrl => $metacatUrl );
2108
    } else {
2109
        #die "failed during metacat creation\n";
2110
        push(@errorMessages, "Failed during metacat creation.");
2111
    }
2112

    
2113
    # Login to metacat
2114
    my $userDN = $FORM::username;
2115
    my $userOrg = $FORM::organization;
2116
    my $userPass = $FORM::password;
2117
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
2118
    
2119
    my $errorMessage = "";
2120
    my $response = $metacat->login($dname, $userPass);
2121

    
2122
    if (! $response) {
2123
    # Could not login
2124
        push(@errorMessages, $metacat->getMessage());
2125
        push(@errorMessages, "Failed during login.\n");
2126

    
2127
    } else {
2128
    #Able to login - try to delete the file    
2129

    
2130
    my $parser;
2131
    my @fileArray;
2132
    my $httpMessage;
2133
    my $xmldoc;
2134
    my $doc;
2135
    my $pushDoc;
2136
    my $alreadyInArray;
2137
    my $findType;
2138
        my $node;
2139
    my $response; 
2140
    my $element;
2141

    
2142
    push (@fileArray, $docid);
2143
    $parser = XML::LibXML->new();
2144

    
2145
        $httpMessage = $metacat->read($docid);
2146
    $doc = $httpMessage->content();    
2147
    $xmldoc = $parser->parse_string($doc);
2148

    
2149
    if ($xmldoc eq "") {
2150
        $error ="Error in parsing the eml document";
2151
        push(@errorMessages, $error);
2152
    } else {
2153

    
2154
        $findType = $xmldoc->findnodes('//dataset/identifier');
2155
        if($findType->size() > 0){
2156
        # This is a eml beta6 document
2157
        # Delete the documents mentioned in triples also
2158
        
2159
        $findType = $xmldoc->findnodes('//dataset/triple');
2160
        if($findType->size() > 0){
2161
            foreach $node ($findType->get_nodelist){
2162
            $pushDoc = findValue($node, 'subject');
2163
            
2164
            # If the file is already in the @fileArray then do not add it 
2165
            $alreadyInArray = 0;
2166
            foreach $element (@fileArray){
2167
                if($element eq $pushDoc){
2168
                $alreadyInArray = 1;
2169
                }
2170
            }
2171
            
2172
            if(!$alreadyInArray){
2173
                # If not already in array then delete the file. 
2174
                push (@fileArray, $pushDoc);
2175
                $response = $metacat->delete($pushDoc);
2176
                
2177
                if (! $response) {
2178
                # Could not delete
2179
                #push(@errorMessages, $response);
2180
                push(@errorMessages, $metacat->getMessage());
2181
                push(@errorMessages, "Failed during deleting $pushDoc. Please check if you are authorized to delete this document.\n");
2182
                }
2183
            }
2184
            }
2185
        }
2186
        }
2187
    }
2188
    
2189
    # Delete the main document. 
2190
    if($deleteAll){
2191
        $response = $metacat->delete($docid);  
2192
        if (! $response) {
2193
        # Could not delete
2194
        #push(@errorMessages, $response);
2195
        push(@errorMessages, $metacat->getMessage());
2196
        push(@errorMessages, "Failed during deleting $docid. Please check if you are authorized to delete this document.\n");
2197
        }
2198
    }
2199
    }
2200
    
2201
    if (scalar(@errorMessages)) {
2202
    # If any errors, print them in the response template 
2203
    $$templateVars{'status'} = 'failure';
2204
    $$templateVars{'errorMessages'} = \@errorMessages;
2205
    $error = 1;
2206
    }
2207
    
2208
    # Process the response template
2209
    if($deleteAll){
2210

    
2211
    $$templateVars{'function'} = "deleted";
2212
    $$templateVars{'section'} = "Deletion Status";
2213
    $template->process( $responseTemplate, $templateVars);
2214
    }
2215
}
2216

    
2217

    
2218
################################################################################
2219
# 
2220
# Do data validation and send the data to confirm data template.
2221
#
2222
################################################################################
2223
sub toConfirmData{
2224
    # Check if any invalid parameters
2225
 
2226
    my $invalidParams;
2227
    if (! $error) {
2228
    $invalidParams = validateParameters(0);
2229
    if (scalar(@$invalidParams)) {
2230
        $$templateVars{'status'} = 'failure';
2231
        $$templateVars{'invalidParams'} = $invalidParams;
2232
        $error = 1;
2233
    }
2234
    }
2235

    
2236

    
2237
    $$templateVars{'providerGivenName'} = normalizeCD($FORM::providerGivenName);
2238
    $$templateVars{'providerSurName'} = normalizeCD($FORM::providerSurName);
2239
    if($FORM::site eq "Select your station here."){
2240
        $$templateVars{'site'} = "";
2241
    }else{
2242
        $$templateVars{'site'} = $FORM::site;
2243
    }
2244
    if($FORM::cfg eq "nceas"){
2245
        $$templateVars{'wg'} = \@FORM::wg;
2246
    }
2247
    $$templateVars{'identifier'} = normalizeCD($FORM::identifier);
2248
    $$templateVars{'title'} = normalizeCD($FORM::title);
2249
    $$templateVars{'origNamefirst0'} = normalizeCD($FORM::origNamefirst0);
2250
    $$templateVars{'origNamelast0'} = normalizeCD($FORM::origNamelast0);
2251
    $$templateVars{'origNameOrg'} = normalizeCD($FORM::origNameOrg);
2252
    # $$templateVars{'origRole0'} = $FORM::origRole0;
2253
    $$templateVars{'origDelivery'} = normalizeCD($FORM::origDelivery);
2254
    $$templateVars{'origCity'} = normalizeCD($FORM::origCity);
2255
    if($FORM::origState eq "Select State Here."){
2256
        $$templateVars{'origState'} = "";
2257
    }else{
2258
        $$templateVars{'origState'} = $FORM::origState;
2259
    }
2260
    $$templateVars{'origStateOther'} = normalizeCD($FORM::origStateOther);
2261
    $$templateVars{'origZIP'} = normalizeCD($FORM::origZIP);
2262
    $$templateVars{'origCountry'} = normalizeCD($FORM::origCountry);
2263
    $$templateVars{'origPhone'} = normalizeCD($FORM::origPhone);
2264
    $$templateVars{'origFAX'} = normalizeCD($FORM::origFAX);
2265
    $$templateVars{'origEmail'} = normalizeCD($FORM::origEmail);
2266
    $$templateVars{'useOrigAddress'} = normalizeCD($FORM::useOrigAddress);
2267
    if($FORM::useOrigAddress eq "on"){
2268
        $$templateVars{'origNamefirstContact'} = normalizeCD($FORM::origNamefirst0);
2269
        $$templateVars{'origNamelastContact'} = normalizeCD($FORM::origNamelast0);
2270
        $$templateVars{'origNameOrgContact'} = normalizeCD($FORM::origNameOrg);
2271
        $$templateVars{'origDeliveryContact'} = normalizeCD($FORM::origDelivery); 
2272
        $$templateVars{'origCityContact'} = normalizeCD($FORM::origCity);
2273
        if($FORM::origState eq "Select State Here."){
2274
        $$templateVars{'origStateContact'} = "";
2275
        }else{
2276
        $$templateVars{'origStateContact'} = $FORM::origState;
2277
        }
2278
        $$templateVars{'origStateOtherContact'} = normalizeCD($FORM::origStateOther);
2279
        $$templateVars{'origZIPContact'} = normalizeCD($FORM::origZIP);
2280
        $$templateVars{'origCountryContact'} = normalizeCD($FORM::origCountry);
2281
        $$templateVars{'origPhoneContact'} = normalizeCD($FORM::origPhone);
2282
        $$templateVars{'origFAXContact'} = normalizeCD($FORM::origFAX);
2283
        $$templateVars{'origEmailContact'} = normalizeCD($FORM::origEmail);
2284
    }else{
2285
        $$templateVars{'origNamefirstContact'} = normalizeCD($FORM::origNamefirstContact);
2286
        $$templateVars{'origNamelastContact'} = normalizeCD($FORM::origNamelastContact);
2287
        $$templateVars{'origNameOrgContact'} = normalizeCD($FORM::origNameOrgContact);
2288
        $$templateVars{'origDeliveryContact'} = normalizeCD($FORM::origDeliveryContact); 
2289
        $$templateVars{'origCityContact'} = normalizeCD($FORM::origCityContact);
2290
        if($FORM::origStateContact eq "Select State Here."){
2291
        $$templateVars{'origStateContact'} = "";
2292
        }else{
2293
        $$templateVars{'origStateContact'} = $FORM::origStateContact;
2294
        }
2295
        $$templateVars{'origStateOtherContact'} = normalizeCD($FORM::origStateOtherContact);
2296
        $$templateVars{'origZIPContact'} = normalizeCD($FORM::origZIPContact);
2297
        $$templateVars{'origCountryContact'} = normalizeCD($FORM::origCountryContact);
2298
        $$templateVars{'origPhoneContact'} = normalizeCD($FORM::origPhoneContact);
2299
        $$templateVars{'origFAXContact'} = normalizeCD($FORM::origFAXContact);
2300
        $$templateVars{'origEmailContact'} = normalizeCD($FORM::origEmailContact);    
2301
    }
2302

    
2303
    $$templateVars{'aoCount'} = $FORM::aoCount;
2304
    foreach my $origName (param()) {
2305
	if ($origName =~ /origNamefirst/) {
2306
	    my $origNameIndex = $origName;
2307
	    $origNameIndex =~ s/origNamefirst//; # get the index of the parameter 0, ..., 10
2308
	    my $origNamelast = "origNamelast".$origNameIndex;
2309
	    my $origRole = "origRole".$origNameIndex;
2310
	    if ( $origNameIndex =~ /[0-9]/  && $origNameIndex > 0){
2311
		if (hasContent(param($origName)) && hasContent(param($origNamelast)) && hasContent(param($origRole))) {
2312
		    debug("Registry processing keyword: $origName = ".param($origName)." $origNamelast = ".param($origNamelast)." $origRole = ".param($origRole));
2313
		    $$templateVars{$origName} = normalizeCD(param($origName));
2314
		    $$templateVars{$origNamelast} = normalizeCD(param($origNamelast));
2315
		    $$templateVars{$origRole} = normalizeCD(param($origRole));
2316
		}
2317
	    }
2318
	}
2319
    }
2320

    
2321
    $$templateVars{'abstract'} = normalizeCD($FORM::abstract);
2322
    $$templateVars{'keyCount'} = $FORM::keyCount;
2323
    foreach my $kyd (param()) {
2324
	if ($kyd =~ /keyword/) {
2325
	    my $keyIndex = $kyd;
2326
	    $keyIndex =~ s/keyword//; # get the index of the parameter 0, ..., 10
2327
	    my $keyType = "kwType".$keyIndex;
2328
	    my $keyTh = "kwTh".$keyIndex;
2329
	    if ( $keyIndex =~ /[0-9]/ ){
2330
		if (hasContent(param($kyd)) && hasContent(param($keyType)) && hasContent(param($keyTh))) {
2331
		    debug("Registry processing keyword: $kyd = ".param($kyd)." $keyType = ".param($keyType)." $keyTh = ".param($keyTh));
2332
		    $$templateVars{$kyd} = normalizeCD(param($kyd));
2333
		    $$templateVars{$keyType} = param($keyType);
2334
		    $$templateVars{$keyTh} = param($keyTh);
2335
		}
2336
	    }
2337
	}
2338
    }
2339
    $$templateVars{'addComments'} = normalizeCD($FORM::addComments);
2340
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2341
    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2342
    $$templateVars{'url'} = $FORM::url;
2343
    if($FORM::dataMedium eq "Select type of medium here."){
2344
        $$templateVars{'dataMedium'} = "";
2345
    }else{
2346
        $$templateVars{'dataMedium'} = $FORM::dataMedium;
2347
    }    
2348
    $$templateVars{'dataMediumOther'} = normalizeCD($FORM::dataMediumOther);
2349
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2350
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2351
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2352
    $$templateVars{'endingYear'} = $FORM::endingYear;
2353
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2354
    $$templateVars{'endingDay'} = $FORM::endingDay;
2355
    $$templateVars{'geogdesc'} = normalizeCD($FORM::geogdesc);
2356
    $$templateVars{'useSiteCoord'} = $FORM::useSiteCoord;
2357
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2358
    $$templateVars{'latMin1'} = $FORM::latMin1;
2359
    $$templateVars{'latSec1'} = $FORM::latSec1;
2360
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2361
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2362
    $$templateVars{'longMin1'} = $FORM::longMin1;
2363
    $$templateVars{'longSec1'} = $FORM::longSec1;
2364
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2365
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2366
    $$templateVars{'latMin2'} = $FORM::latMin2;
2367
    $$templateVars{'latSec2'} = $FORM::latSec2;
2368
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2369
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2370
    $$templateVars{'longMin2'} = $FORM::longMin2;
2371
    $$templateVars{'longSec2'} = $FORM::longSec2;
2372
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2373

    
2374
    $$templateVars{'taxaCount'} = $FORM::taxaCount;
2375
    foreach my $trn (param()) {
2376
        if ($trn =~ /taxonRankName/) {
2377
            my $taxIndex = $trn;
2378
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
2379
            my $trv = "taxonRankValue".$taxIndex;
2380
            if ( $taxIndex =~ /[0-9]/ ){
2381
                if (hasContent(param($trn)) && hasContent(param($trv))) {
2382
                    debug("Registry processing taxon: $trn = ".param($trn)." $trv = ".param($trv));
2383
                    $$templateVars{$trn} = normalizeCD(param($trn));
2384
                    $$templateVars{$trv} = normalizeCD(param($trv));
2385
                }
2386
            }
2387
        }
2388
    }
2389
    $$templateVars{'taxaAuth'} = normalizeCD($FORM::taxaAuth);
2390

    
2391
    $$templateVars{'methodTitle'} = normalizeCD($FORM::methodTitle);
2392

    
2393
    my @tempMethodPara;
2394
    for (my $i = 0; $i < scalar(@FORM::methodPara); $i++) {
2395
	$tempMethodPara[$i] = normalizeCD($FORM::methodPara[$i]);
2396
    }
2397
    $$templateVars{'methodPara'} = \@tempMethodPara;
2398
    $$templateVars{'studyExtentDescription'} = normalizeCD($FORM::studyExtentDescription);
2399
    $$templateVars{'samplingDescription'} = normalizeCD($FORM::samplingDescription);
2400
    $$templateVars{'origStateContact'} = $FORM::origState;
2401

    
2402
    $$templateVars{'hasKeyword'} = $FORM::hasKeyword;
2403
    $$templateVars{'hasTemporal'} = $FORM::hasTemporal;
2404
    $$templateVars{'hasSpatial'} = $FORM::hasSpatial;
2405
    $$templateVars{'hasTaxonomic'} = $FORM::hasTaxonomic;
2406
    $$templateVars{'hasMethod'} = $FORM::hasMethod;
2407
    $$templateVars{'spatialRequired'} = $FORM::spatialRequired;
2408
    $$templateVars{'temporalRequired'} = $FORM::temporalRequired;
2409

    
2410
    $$templateVars{'docid'} = $FORM::docid;
2411

    
2412
    if (! $error) {
2413
	# If no errors, then print out data in confirm Data template
2414

    
2415
	$$templateVars{'section'} = "Confirm Data";
2416
	$template->process( $confirmDataTemplate, $templateVars);
2417

    
2418
    } else{    
2419
    # Errors from validation function. print the errors out using the response template
2420
    if (scalar(@errorMessages)) {
2421
        $$templateVars{'status'} = 'failure';
2422
        $$templateVars{'errorMessages'} = \@errorMessages;
2423
        $error = 1;
2424
    }
2425
        # Create our HTML response and send it back
2426
    $$templateVars{'function'} = "submitted";
2427
    $$templateVars{'section'} = "Submission Status";
2428
    $template->process( $responseTemplate, $templateVars);
2429
    }
2430
}
2431

    
2432

    
2433
################################################################################
2434
# 
2435
# From confirm Data template - user wants to make some changes.
2436
#
2437
################################################################################
2438
sub confirmDataToReEntryData{
2439
    my @sortedSites;
2440
    foreach my $site (sort @sitelist) {
2441
        push(@sortedSites, $site);
2442
    }
2443

    
2444
    $$templateVars{'siteList'} = \@sortedSites;
2445
    $$templateVars{'section'} = "Re-Entry Form";
2446
    copyFormToTemplateVars();
2447
    $$templateVars{'docid'} = $FORM::docid;
2448

    
2449
    $$templateVars{'form'} = 're_entry';
2450
    $template->process( $entryFormTemplate, $templateVars);
2451
}
2452

    
2453

    
2454
################################################################################
2455
# 
2456
# Copy form data to templateVars.....
2457
#
2458
################################################################################
2459
sub copyFormToTemplateVars{
2460
    $$templateVars{'providerGivenName'} = $FORM::providerGivenName;
2461
    $$templateVars{'providerSurName'} = $FORM::providerSurName;
2462
    $$templateVars{'site'} = $FORM::site;
2463
    if ($FORM::cfg eq "nceas") {
2464
        my $projects = getProjectList();
2465
        $$templateVars{'projects'} = $projects;
2466
        $$templateVars{'wg'} = \@FORM::wg;
2467
    }
2468
    $$templateVars{'identifier'} = $FORM::identifier;
2469
    $$templateVars{'title'} = $FORM::title;
2470
    $$templateVars{'origNamefirst0'} = $FORM::origNamefirst0;
2471
    $$templateVars{'origNamelast0'} = $FORM::origNamelast0;
2472
    $$templateVars{'origNameOrg'} = $FORM::origNameOrg;
2473
 #   $$templateVars{'origRole0'} = $FORM::origRole0;
2474
    $$templateVars{'origDelivery'} = $FORM::origDelivery;
2475
    $$templateVars{'origCity'} = $FORM::origCity;
2476
    $$templateVars{'origState'} = $FORM::origState;
2477
    $$templateVars{'origStateOther'} = $FORM::origStateOther;
2478
    $$templateVars{'origZIP'} = $FORM::origZIP;
2479
    $$templateVars{'origCountry'} = $FORM::origCountry;
2480
    $$templateVars{'origPhone'} = $FORM::origPhone;
2481
    $$templateVars{'origFAX'} = $FORM::origFAX;
2482
    $$templateVars{'origEmail'} = $FORM::origEmail;
2483
    if ($FORM::useSiteCoord ne "") {
2484
        $$templateVars{'useOrigAddress'} = "CHECKED";
2485
    }else{
2486
        $$templateVars{'useOrigAddress'} = $FORM::useOrigAddress;
2487
    }
2488
    $$templateVars{'origNamefirstContact'} = $FORM::origNamefirstContact;
2489
    $$templateVars{'origNamelastContact'} = $FORM::origNamelastContact;
2490
    $$templateVars{'origNameOrgContact'} = $FORM::origNameOrgContact;
2491
    $$templateVars{'origDeliveryContact'} = $FORM::origDeliveryContact; 
2492
    $$templateVars{'origCityContact'} = $FORM::origCityContact;
2493
    $$templateVars{'origStateContact'} = $FORM::origStateContact;
2494
    $$templateVars{'origStateOtherContact'} = $FORM::origStateOtherContact;
2495
    $$templateVars{'origZIPContact'} = $FORM::origZIPContact;
2496
    $$templateVars{'origCountryContact'} = $FORM::origCountryContact;
2497
    $$templateVars{'origPhoneContact'} = $FORM::origPhoneContact;
2498
    $$templateVars{'origFAXContact'} = $FORM::origFAXContact;
2499
    $$templateVars{'origEmailContact'} = $FORM::origEmailContact;    
2500
    
2501
    $$templateVars{'aoCount'} = $FORM::aoCount;
2502
    foreach my $origName (param()) {
2503
	if ($origName =~ /origNamefirst/) {
2504
	    my $origNameIndex = $origName;
2505
	    $origNameIndex =~ s/origNamefirst//; # get the index of the parameter 0, ..., 10
2506
	    my $origNamelast = "origNamelast".$origNameIndex;
2507
	    my $origRole = "origRole".$origNameIndex;
2508
	    if ( $origNameIndex =~ /[0-9]/  && $origNameIndex > 0){
2509
		if (hasContent(param($origName)) && hasContent(param($origNamelast)) && hasContent(param($origRole))) {
2510
		    debug("Registry processing keyword: $origName = ".param($origName)." $origNamelast = ".param($origNamelast)." $origRole = ".param($origRole));
2511
		    $$templateVars{$origName} = normalizeCD(param($origName));
2512
		    $$templateVars{$origNamelast} = normalizeCD(param($origNamelast));
2513
		    $$templateVars{$origRole} = normalizeCD(param($origRole));
2514
		}
2515
	    }
2516
	}
2517
    }
2518

    
2519
    $$templateVars{'abstract'} = $FORM::abstract;
2520
    $$templateVars{'keyCount'} = $FORM::keyCount;
2521
    foreach my $kyd (param()) {
2522
	if ($kyd =~ /keyword/) {
2523
	    my $keyIndex = $kyd;
2524
	    $keyIndex =~ s/keyword//; # get the index of the parameter 0, ..., 10
2525
	    my $keyType = "kwType".$keyIndex;
2526
	    my $keyTh = "kwTh".$keyIndex;
2527
	    if ( $keyIndex =~ /[0-9]/ ){
2528
		if (hasContent(param($kyd)) && hasContent(param($keyType)) && hasContent(param($keyTh))) {
2529
		    debug("Registry processing keyword: $kyd = ".param($kyd)." $keyType = ".param($keyType)." $keyTh = ".param($keyTh));
2530
		    $$templateVars{$kyd} = param($kyd);
2531
		    $$templateVars{$keyType} = param($keyType);
2532
		    $$templateVars{$keyTh} = param($keyTh);
2533
		}
2534
	    }
2535
	}
2536
    }
2537
    $$templateVars{'addComments'} = $FORM::addComments;
2538
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2539
    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2540
    $$templateVars{'url'} = $FORM::url;
2541
    $$templateVars{'dataMedium'} = $FORM::dataMedium;
2542
    $$templateVars{'dataMediumOther'} = $FORM::dataMediumOther;
2543
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2544
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2545
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2546
    $$templateVars{'endingYear'} = $FORM::endingYear;
2547
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2548
    $$templateVars{'endingDay'} = $FORM::endingDay;
2549
    $$templateVars{'geogdesc'} = $FORM::geogdesc;
2550
    if($FORM::useSiteCoord ne ""){
2551
    $$templateVars{'useSiteCoord'} = "CHECKED";
2552
    }else{
2553
    $$templateVars{'useSiteCoord'} = "";
2554
    }
2555
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2556
    $$templateVars{'latMin1'} = $FORM::latMin1;
2557
    $$templateVars{'latSec1'} = $FORM::latSec1;
2558
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2559
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2560
    $$templateVars{'longMin1'} = $FORM::longMin1;
2561
    $$templateVars{'longSec1'} = $FORM::longSec1;
2562
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2563
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2564
    $$templateVars{'latMin2'} = $FORM::latMin2;
2565
    $$templateVars{'latSec2'} = $FORM::latSec2;
2566
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2567
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2568
    $$templateVars{'longMin2'} = $FORM::longMin2;
2569
    $$templateVars{'longSec2'} = $FORM::longSec2;
2570
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2571
    $$templateVars{'taxaCount'} = $FORM::taxaCount;
2572
    foreach my $trn (param()) {
2573
        if ($trn =~ /taxonRankName/) {
2574
            my $taxIndex = $trn;
2575
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
2576
            my $trv = "taxonRankValue".$taxIndex;
2577
            if ( $taxIndex =~ /[0-9]/ ){
2578
                if (hasContent(param($trn)) && hasContent(param($trv))) {
2579
                    debug("Registry processing taxon: $trn = ".param($trn)." $trv = ".param($trv));
2580
                    $$templateVars{$trn} = param($trn);
2581
                    $$templateVars{$trv} = param($trv);
2582
                }
2583
            }
2584
        }
2585
    }
2586
    $$templateVars{'taxaAuth'} = $FORM::taxaAuth;
2587
    $$templateVars{'methodTitle'} = $FORM::methodTitle;
2588
    $$templateVars{'methodPara'} = \@FORM::methodPara;
2589
    $$templateVars{'studyExtentDescription'} = $FORM::studyExtentDescription;
2590
    $$templateVars{'samplingDescription'} = $FORM::samplingDescription;
2591
    
2592
    $$templateVars{'hasKeyword'} = $FORM::hasKeyword;
2593
    $$templateVars{'hasTemporal'} = $FORM::hasTemporal;
2594
    $$templateVars{'hasSpatial'} = $FORM::hasSpatial;
2595
    $$templateVars{'hasTaxonomic'} = $FORM::hasTaxonomic;
2596
    $$templateVars{'hasMethod'} = $FORM::hasMethod;
2597
    $$templateVars{'spatialRequired'} = $FORM::spatialRequired;
2598
    $$templateVars{'temporalRequired'} = $FORM::temporalRequired;
2599
}
2600

    
2601
################################################################################
2602
# 
2603
# check if there is multiple occurence of the given tag and find its value.
2604
#
2605
################################################################################
2606

    
2607
sub findValue {
2608
    my $node = shift;
2609
    my $value = shift;
2610
    my $result;
2611
    my $tempNode;
2612

    
2613
    $result = $node->findnodes("./$value");
2614
    if ($result->size > 1) {
2615
        errMoreThanOne("$value");
2616
    } else {
2617
        foreach $tempNode ($result->get_nodelist){
2618
            #print $tempNode->nodeName().":".$tempNode->textContent();
2619
            #print "\n";
2620
            return $tempNode->textContent();
2621
        }
2622
    }
2623
}
2624

    
2625

    
2626
################################################################################
2627
# 
2628
# check if given tags has any children. if not return the value
2629
#
2630
################################################################################
2631
sub findValueNoChild {
2632
    my $node = shift;
2633
    my $value = shift;
2634
    my $tempNode;
2635
    my $childNodes;
2636
    my $result;
2637
    my $error;
2638

    
2639
    $result = $node->findnodes("./$value");
2640
    if($result->size > 1){
2641
       errMoreThanOne("$value");
2642
    } else {
2643
        foreach $tempNode ($result->get_nodelist) {
2644
            $childNodes = $tempNode->childNodes;
2645
            if ($childNodes->size() > 1) {
2646
                $error ="The tag $value has children which cannot be shown using the form. Please use Morpho to edit this document";    
2647
                push(@errorMessages, $error);
2648
                #if ($DEBUG == 1){ print $error."\n";}
2649
            } else {
2650
                #print $tempNode->nodeName().":".$tempNode->textContent();
2651
                #print "\n";
2652
                return $tempNode->textContent();
2653
            }
2654
        }
2655
    }
2656
}
2657

    
2658

    
2659
################################################################################
2660
# 
2661
# check if given tags are children of given node.
2662
#
2663
################################################################################
2664
sub dontOccur {
2665
    my $node = shift;
2666
    my $value = shift;
2667
    my $errVal = shift;
2668

    
2669
    my $result = $node->findnodes("$value");
2670
    if($result->size > 0){
2671
        $error ="One of the following tags found: $errVal. Please use Morpho to edit this document";
2672
        push(@errorMessages, $error."\n");
2673
        #if ($DEBUG == 1){ print $error;}
2674
    } 
2675
}
2676

    
2677

    
2678
################################################################################
2679
# 
2680
# print out error for more than one occurence of a given tag
2681
#
2682
################################################################################
2683
sub errMoreThanOne {
2684
    my $value = shift;
2685
    my $error ="More than one occurence of the tag $value found. Please use Morpho to edit this document";
2686
    push(@errorMessages, $error."\n");
2687
    # if ($DEBUG == 1){ print $error;}
2688
}
2689

    
2690

    
2691
################################################################################
2692
# 
2693
# print out error for more than given number of occurences of a given tag
2694
#
2695
################################################################################
2696
sub errMoreThanN {
2697
    my $value = shift;
2698
    my $error ="More occurences of the tag $value found than that can be shown in the form. Please use Morpho to edit this document";
2699
    push(@errorMessages, $error);
2700
    #if ($DEBUG == 1){ print $error."\n";}
2701
}
2702

    
2703

    
2704
################################################################################
2705
# 
2706
# convert coord to degrees, minutes and seconds form. 
2707
#
2708
################################################################################
2709
#sub convertCoord {
2710
#    my $wx = shift;
2711
#    print $deg." ".$min." ".$sec;
2712
#    print "\n";
2713
#}
2714

    
2715

    
2716
################################################################################
2717
# 
2718
# print debugging messages to stderr
2719
#
2720
################################################################################
2721
sub debug {
2722
    my $msg = shift;
2723
    
2724
    if ($debug) {
2725
        print STDERR "$msg\n";
2726
    }
2727
}
2728

    
2729
################################################################################
2730
# 
2731
# get the list of projects
2732
#
2733
################################################################################
2734
sub getProjectList {
2735
    
2736
    use NCEAS::AdminDB;
2737
    my $admindb = NCEAS::AdminDB->new();
2738
    $admindb->connect($nceas_db, $nceas_db_user, $nceas_db_password);
2739
    my $projects = $admindb->getProjects();
2740
    #my $projects = getTestProjectList();
2741
    return $projects;
2742
}
2743

    
2744
################################################################################
2745
# 
2746
# get a test list of projects for use only in testing where the NCEAS
2747
# admin db is not available.
2748
#
2749
################################################################################
2750
sub getTestProjectList {
2751
    # This block is for testing only!  Remove for production use
2752
    my @row1;
2753
    $row1[0] = 6000; $row1[1] = 'Andelman'; $row1[2] = 'Sandy'; $row1[3] = 'The very long and windy path to an apparent ecological conclusion: statistics lie';
2754
    my @row2; 
2755
    $row2[0] = 7000; $row2[1] = 'Bascompte'; $row2[2] = 'Jordi'; $row2[3] = 'Postdoctoral Fellow';
2756
    my @row3; 
2757
    $row3[0] = 7001; $row3[1] = 'Hackett'; $row3[2] = 'Edward'; $row3[3] = 'Sociology rules the world';
2758
    my @row4; 
2759
    $row4[0] = 7002; $row4[1] = 'Jones'; $row4[2] = 'Matthew'; $row4[3] = 'Informatics rules the world';
2760
    my @row5; 
2761
    $row5[0] = 7003; $row5[1] = 'Schildhauer'; $row5[2] = 'Mark'; $row5[3] = 'Excel rocks my world, assuming a, b, and c';
2762
    my @row6; 
2763
    $row6[0] = 7004; $row6[1] = 'Rogers'; $row6[2] = 'Bill'; $row6[3] = 'Graduate Intern';
2764
    my @row7; 
2765
    $row7[0] = 7005; $row7[1] = 'Zedfried'; $row7[2] = 'Karl'; $row7[3] = 'A multivariate analysis of thing that go bump in the night';
2766
    my @projects;
2767
    $projects[0] = \@row1;
2768
    $projects[1] = \@row2;
2769
    $projects[2] = \@row3;
2770
    $projects[3] = \@row4;
2771
    $projects[4] = \@row5;
2772
    $projects[5] = \@row6;
2773
    $projects[6] = \@row7;
2774
    return \@projects;
2775
}
(2-2/3)