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 10:54:34 -0800 (Tue, 21 Dec 2004) $'
8
# '$Revision: 2345 $' 
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
    
774
    my $returnVal = "";
775
    
776
    foreach (split(//,$val)){
777
	my $var = unpack "C*", $_; 
778
	
779
	if($var<128 && $var>31){
780
	    $returnVal=$returnVal.$_;
781
	} elsif ($var<32){
782
	    if($var == 10){
783
		$returnVal=$returnVal.$_;
784
	    }
785
	    if($var == 13){
786
		$returnVal=$returnVal.$_;
787
	    }
788
	    if($var == 9){
789
		$returnVal=$returnVal.$_;
790
	    }
791
	} else { 
792
	    $returnVal=$returnVal."&#".$var.";";
793
	}
794
    }
795
    
796
    $returnVal =~ s/&/%26/g;    
797
    return $returnVal;
798
}
799

    
800

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

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

    
817

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

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

    
836

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

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

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

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

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

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

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

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

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

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

    
934
    $creat .= $dso;
935

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1332
    return $doc;
1333
}
1334

    
1335

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

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

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

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

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

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

    
1373

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

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

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

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

    
1457
            # Read the main document. 
1458

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2134

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

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

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

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

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

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

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

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

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

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

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

    
2273

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

    
2292

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

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

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

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

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

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

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

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

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

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

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

    
2493

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

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

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

    
2514

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

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

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

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

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

    
2691

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

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

    
2724

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

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

    
2743

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

    
2756

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

    
2769

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

    
2781

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

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

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