Project

General

Profile

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
228
    # Result from deleteData form. 
229
    if($FORM::deleteData =~ "Delete data"){
230
    # delete Data
231
    deleteData(1);    
232
    exit(0);
233
    } else {
234
    $$templateVars{'status'} = "Cancel";
235
    $$templateVars{'function'} = "cancel";
236
    $template->process( $responseTemplate, $templateVars);
237
    exit(0);
238
    }
239

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

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

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

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

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

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

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

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

    
316

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

    
322
    my $xmldoc = createXMLDocument();
323

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

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

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

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

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

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

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

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

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

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

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

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

    
435
        exit(0);
436
    }
437
}
438

    
439
debug("Registry: C");
440

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

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

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

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

    
463
exit(0);
464

    
465

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

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

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

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

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

    
526
  return $notunique;
527
}
528

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

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

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

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

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

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

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

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

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

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

    
698

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

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

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

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

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

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

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

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

    
801

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

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

    
818

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

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

    
837

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

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

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

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

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

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

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

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

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

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

    
935
    $creat .= $dso;
936

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1333
    return $doc;
1334
}
1335

    
1336

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

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

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

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

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

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

    
1374

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

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

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

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

    
1458
            # Read the main document. 
1459

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1846
    dontOccur($doc, "./inline", "//dataset/distribution/inline");
1847

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

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

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

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

    
1956
		            $$templateVars{'hasSpatial'} = "true";
1957
                }
1958
            }
1959

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

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

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

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

    
2072
	    $$templateVars{'hasMethod'} = "true";
2073
        }
2074
    }
2075

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

    
2085
	    $$templateVars{'hasMethod'} = "true";
2086
        }
2087
    }
2088

    
2089
    dontOccur($doc, "//methodStep/citation", "methodStep/citation");
2090
    dontOccur($doc, "//methodStep/protocol", "methodStep/protocol");
2091
    dontOccur($doc, "//methodStep/instrumentation", "methodStep/instrumentation");
2092
    dontOccur($doc, "//methodStep/software", "methodStep/software");
2093
    dontOccur($doc, "//methodStep/subStep", "methodStep/subStep");
2094
    dontOccur($doc, "//methodStep/dataSource", "methodStep/dataSource");
2095
    dontOccur($doc, "//methods/qualityControl", "methods/qualityControl");
2096

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

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

    
2135

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

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

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

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

    
2184
    } else {
2185
    #Able to login - try to delete the file    
2186

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

    
2199
    push (@fileArray, $docid);
2200
    $parser = XML::LibXML->new();
2201

    
2202
        $httpMessage = $metacat->read($docid);
2203
    $doc = $httpMessage->content();    
2204
    $xmldoc = $parser->parse_string($doc);
2205

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

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

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

    
2274

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

    
2293

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

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

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

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

    
2448
    $$templateVars{'methodTitle'} = normalizeCD($FORM::methodTitle);
2449

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

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

    
2472
    $$templateVars{'docid'} = $FORM::docid;
2473

    
2474
    if (! $error) {
2475
	# If no errors, then print out data in confirm Data template
2476

    
2477
	$$templateVars{'section'} = "Confirm Data";
2478
	$template->process( $confirmDataTemplate, $templateVars);
2479

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

    
2494

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

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

    
2511
    $$templateVars{'form'} = 're_entry';
2512
    $template->process( $entryFormTemplate, $templateVars);
2513
}
2514

    
2515

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

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

    
2668
################################################################################
2669
# 
2670
# check if there is multiple occurence of the given tag and find its value.
2671
#
2672
################################################################################
2673

    
2674
sub findValue {
2675
    my $node = shift;
2676
    my $value = shift;
2677
    my $result;
2678
    my $tempNode;
2679

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

    
2692

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

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

    
2725

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

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

    
2744

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

    
2757

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

    
2770

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

    
2782

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

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

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