Project

General

Profile

1
#!/usr/bin/perl
2
#
3
#  '$RCSfile$'
4
#  Copyright: 2000 Regents of the University of California 
5
#
6
#   '$Author: sgarg $'
7
#     '$Date: 2005-09-30 17:29:40 -0700 (Fri, 30 Sep 2005) $'
8
# '$Revision: 2615 $' 
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 document"){
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
        $$templateVars{'status'} = 'login_failure';
350
        $$templateVars{'errorMessages'} = \@errorMessages;
351
        $$templateVars{'docid'} = $docid;
352
        $$templateVars{'cfg'} = $FORM::cfg;
353
        $$templateVars{'function'} = "submitted";
354
        $$templateVars{'section'} = "Submission Status";
355
        $template->process( $responseTemplate, $templateVars);
356
        exit(0);
357
    } else {
358

    
359
        debug( "Registry: A");
360
        if ($FORM::docid eq "") {
361
            debug( "Registry: B1");
362
            # document is being inserted 
363
            my $notunique = "NOT_UNIQUE";
364
            while ($notunique eq "NOT_UNIQUE") {
365
                $docid = newAccessionNumber($defaultScope);
366
                
367
                $xmldocWithDocID = $xmldoc;
368
                $xmldocWithDocID =~ s/docid/$docid/;
369
    
370
                # Code for testing the xml file being inserted####
371
                #my $testFile = "/tmp/test.xml";
372
                #open (TFILE,">$testFile") || die ("Cant open xml file...\n");
373
                #print TFILE $xmldoc;
374
                #close(TFILE);
375
                ####
376
        
377
                $notunique = insertMetadata($xmldocWithDocID, $docid);
378
                #  if (!$notunique) {
379
                # Write out the XML file for debugging purposes
380
                #my $testFile = $tmpdir . "/test-new.xml";
381
                #open (TFILE,">$testFile") || die ("Cant open xml file...\n");
382
                #print TFILE $newdoc;
383
                #close(TFILE);
384
                #   }
385
    
386
                # The id wasn't unique, so update our lastid file
387
                if ($notunique eq "NOT_UNIQUE") {
388
                    debug( "Registry: Updating lastid (B1.1)");
389
                    updateLastId($defaultScope);
390
                }
391
            }
392
            debug("Registry: B2");
393
            if ($notunique ne "SUCCESS") {
394
                debug("Registry: NO SUCCESS");
395
                debug("Message is: $notunique");
396
                push(@errorMessages, $notunique);
397
            }
398

    
399
            debug("Registry: B3");
400
        } else {
401
            # document is being modified
402
            $docid = $FORM::docid;
403
    
404
            my $x;
405
            my $y;
406
            my $z;
407
        
408
            ($x, $y, $z) = split(/\./, $docid); 
409
            $z++;
410
            $docid = "$x.$y.$z";
411
    
412
            $xmldoc =~ s/docid/$docid/;
413
        
414
            my $response = $metacat->update($docid, $xmldoc);
415

    
416
            if (! $response) {
417
                push(@errorMessages, $metacat->getMessage());
418
                push(@errorMessages, "Failed while updating.\n");  
419
            }
420

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

    
434
            #if (! $error) {
435
                #sendNotification($docid, $mailhost, $sender, $recipient);
436
            #}
437
    
438
            # Create our HTML response and send it back
439
            $$templateVars{'function'} = "modified";
440
            $$templateVars{'section'} = "Modification Status";
441
            $template->process( $responseTemplate, $templateVars);
442
    
443
            exit(0);
444
        }
445
    }
446
}
447

    
448
debug("Registry: C");
449

    
450
if (scalar(@errorMessages)) {
451
    debug("Registry: ErrorMessages defined.");
452
    $$templateVars{'docid'} = $FORM::docid;
453
    copyFormToTemplateVars();
454
    $$templateVars{'status'} = 'failure';
455
    $$templateVars{'errorMessages'} = \@errorMessages;
456
    $error = 1;
457
} else {
458
    $$templateVars{'docid'} = $docid;
459
    $$templateVars{'cfg'} = $FORM::cfg;
460
}
461

    
462
#if (! $error) {
463
#sendNotification($docid, $mailhost, $sender, $recipient);
464
#}
465

    
466
# Create our HTML response and send it back
467
$$templateVars{'function'} = "submitted";
468
$$templateVars{'section'} = "Submission Status";
469

    
470
$template->process( $responseTemplate, $templateVars);
471

    
472
exit(0);
473

    
474

    
475
################################################################################
476
#
477
# Subroutine for updating a metacat id for a given scope to the highest value
478
#
479
################################################################################
480
sub updateLastId {
481
  my $scope = shift;
482

    
483
  my $errormsg = 0;
484
  my $docid = $metacat->getLastId($scope);
485

    
486
  if ($docid =~ /null/) {
487
      # No docids with this scope present, so do nothing
488
  } elsif ($docid) {
489
      # Update the lastid file for this scope
490
      (my $foundScope, my $id, my $rev) = split(/\./, $docid);
491
      debug("Docid is: $docid\n");
492
      debug("Lastid is: $id");
493
      my $scopeFile = $cfgdir . "/" . $FORM::cfg . "/" . $scope . ".lastid";
494
      open(LASTID, "+>$scopeFile") or 
495
          die "Failed to open lastid file for writing!";
496
      print LASTID $id, "\n";
497
      close(LASTID);
498
  } else {
499
    $errormsg = $metacat->getMessage();
500
    debug("Error in getLastId: $errormsg");
501
  }
502
}
503

    
504
################################################################################
505
#
506
# Subroutine for inserting a document to metacat
507
#
508
################################################################################
509
sub insertMetadata {
510
  my $xmldoc = shift;
511
  my $docid = shift;
512

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

    
535
  return $notunique;
536
}
537

    
538
################################################################################
539
#
540
# Subroutine for generating a new accession number
541
#  Note: this is not threadsafe, assumes only one running process at a time
542
#  Also: need to check metacat for max id # used in this scope already
543
################################################################################
544
sub newAccessionNumber {
545
  my $scope = shift;
546
    
547
  my $docrev = 1;
548
  my $lastid = 1;
549

    
550
  my $scopeFile = $cfgdir . "/" . $FORM::cfg . "/" . $scope . ".lastid";
551
  if (-e $scopeFile) {
552
    open(LASTID, "<$scopeFile") or die "Failed to generate accession number!";
553
    $lastid = <LASTID>;
554
    chomp($lastid);
555
    $lastid++;
556
    close(LASTID);
557
  }
558
  open(LASTID, ">$scopeFile") or die "Failed to open lastid file for writing!";
559
  print LASTID $lastid, "\n";
560
  close(LASTID);
561

    
562
  my $docroot = "$scope.$lastid.";
563
  my $docid = $docroot . $docrev;
564
  return $docid;
565
}
566

    
567
################################################################################
568
# 
569
# Validate the parameters to make sure that required params are provided
570
#
571
################################################################################
572
sub validateParameters {
573
    my $chkUser = shift;
574
    my @invalidParams;
575

    
576
    push(@invalidParams, "Name of the Project is not selected in the form.")
577
        if (scalar(@FORM::wg) == 0 && $showWgList eq 'true');
578
    push(@invalidParams, "First name of person entering the form is missing.")
579
        unless hasContent($FORM::providerGivenName);
580
    push(@invalidParams, "Last name of person entering the form is missing.")
581
        unless hasContent($FORM::providerSurName);
582
    push(@invalidParams, "Dataset title is missing.")
583
        unless hasContent($FORM::title);
584
    push(@invalidParams, "Organization name is missing.")
585
        unless (hasContent($FORM::site) || $FORM::site =~ /elect/ ||
586
                $FORM::cfg eq "nceas");
587
    push(@invalidParams, "First name of principal data set owner is missing.")
588
        unless hasContent($FORM::origNamefirst0);
589
    push(@invalidParams, "Last name of principal data set owner is missing.")
590
        unless hasContent($FORM::origNamelast0);
591
    push(@invalidParams, "Dataset abstract is missing.")
592
        unless hasContent($FORM::abstract);
593
    if($FORM::hasTemporal eq 'true'){
594
	push(@invalidParams, "Year of start date is missing.")
595
	    unless (hasContent($FORM::beginningYear) || $FORM::temporalRequired ne 'true');
596
	push(@invalidParams, "Year of stop date has been specified but year of start date is missing.")
597
	    if ((!hasContent($FORM::beginningYear)) && hasContent($FORM::endingYear));
598
    }
599
    push(@invalidParams, "Geographic description is missing.")
600
        unless (hasContent($FORM::geogdesc) || $FORM::spatialRequired ne 'true');
601

    
602
    if($FORM::beginningMonth eq "00"){
603
	if (hasContent($FORM::beginningYear)){
604
	    $FORM::beginningMonth = "01";
605
	} else {
606
	    $FORM::beginningMonth = "";
607
	}
608
    }
609
    if($FORM::beginningDay eq "00"){
610
	if (hasContent($FORM::beginningYear)){
611
	    $FORM::beginningDay = "01";
612
	} else {
613
	    $FORM::beginningDay = "";
614
	}
615
    }
616
    if($FORM::endingMonth eq "00"){
617
	if (hasContent($FORM::endingYear)){
618
	    $FORM::endingMonth = "01";
619
	} else {
620
	    $FORM::endingMonth = "";
621
	}
622
    }    
623
    if($FORM::endingDay eq "00"){
624
	if (hasContent($FORM::endingYear)){
625
	    $FORM::endingDay = "01";
626
	} else {
627
	    $FORM::endingDay = "";
628
	}
629
    }
630

    
631
    if (hasContent($FORM::beginningYear) && !($FORM::beginningYear =~ /[0-9][0-9][0-9][0-9]/)){
632
	push(@invalidParams, "Invalid year of start date specified.")
633
    }
634

    
635
    if (hasContent($FORM::endingYear) && !($FORM::endingYear =~ /[0-9][0-9][0-9][0-9]/)){
636
	push(@invalidParams, "Invalid year of stop date specified.")
637
    }
638
    
639
    # If the "use site" coord. box is checked and if the site is in 
640
    # the longitude hash ...  && ($siteLatDMS{$FORM::site})
641
    
642
    if($FORM::hasSpatial eq 'true'){
643
	if (($FORM::useSiteCoord) && ($siteLatDMS{$FORM::site}) ) {
644
        
645
	    $latDeg1 = $siteLatDMS{$FORM::site}[0];
646
	    $latMin1 = $siteLatDMS{$FORM::site}[1];
647
	    $latSec1 = $siteLatDMS{$FORM::site}[2];
648
	    $hemisphLat1 = $siteLatDMS{$FORM::site}[3];
649
	    $longDeg1 = $siteLongDMS{$FORM::site}[0];
650
	    $longMin1 = $siteLongDMS{$FORM::site}[1];
651
	    $longSec1 = $siteLongDMS{$FORM::site}[2];
652
	    $hemisphLong1 = $siteLongDMS{$FORM::site}[3];
653
	    
654
	}  else {
655
	    
656
	    $latDeg1 = $FORM::latDeg1;
657
	    $latMin1 = $FORM::latMin1;
658
	    $latSec1 = $FORM::latSec1;
659
	    $hemisphLat1 = $FORM::hemisphLat1;
660
	    $longDeg1 = $FORM::longDeg1;
661
	    $longMin1 = $FORM::longMin1;
662
	    $longSec1 = $FORM::longSec1;
663
	    $hemisphLong1 = $FORM::hemisphLong1;
664
	}
665

    
666
	if($latDeg1 > 90 || $latDeg1 < 0){
667
	    push(@invalidParams, "Invalid first latitude degrees specified.");
668
	}
669
	if($latMin1 > 59 || $latMin1 < 0){
670
	    push(@invalidParams, "Invalid first latitude minutes specified.");
671
	}
672
	if($latSec1 > 59 || $latSec1 < 0){
673
	    push(@invalidParams, "Invalid first latitude seconds specified.");
674
	}
675
	if($longDeg1 > 180 || $longDeg1 < 0){
676
	    push(@invalidParams, "Invalid first longitude degrees specified.");
677
	}
678
	if($longMin1 > 59 || $longMin1 < 0){
679
	    push(@invalidParams, "Invalid first longitude minutes specified.");
680
	}
681
	if($longSec1 > 59 || $longSec1 < 0){
682
	    push(@invalidParams, "Invalid first longitude seconds specified.");
683
	}
684

    
685
	if(hasContent($FORM::latDeg2) && ($FORM::latDeg2 > 90 || $FORM::latDeg2 < 0)){
686
	    push(@invalidParams, "Invalid second latitude degrees specified.");
687
	}
688
	if(hasContent($FORM::latMin2) && ($FORM::latMin2 > 59 || $FORM::latMin2 < 0)){
689
	    push(@invalidParams, "Invalid second latitude minutes specified.");
690
	}
691
	if(hasContent($FORM::latSec2) && ($FORM::latSec2 > 59 || $FORM::latSec2 < 0)){
692
	    push(@invalidParams, "Invalid second latitude seconds specified.");
693
	}
694
	if(hasContent($FORM::latDeg2) && ($FORM::longDeg2 > 180 || $FORM::longDeg2 < 0)){
695
	    push(@invalidParams, "Invalid second longitude degrees specified.");
696
	}
697
	if(hasContent($FORM::latMin2) && ($FORM::longMin2 > 59 || $FORM::longMin2 < 0)){
698
	    push(@invalidParams, "Invalid second longitude minutes specified.");
699
	}
700
	if(hasContent($FORM::latSec2) && ($FORM::longSec2 > 59 || $FORM::longSec2 < 0)){
701
	    push(@invalidParams, "Invalid second longitude seconds specified.");
702
	}
703
    }
704
    
705
    # Check if latDeg1 and longDeg1 has values if useSiteCoord is used. 
706
    # This check is required because some of the sites dont have lat 
707
    # and long mentioned in the config file. 
708

    
709

    
710
    if($FORM::hasSpatial eq 'true' && $FORM::spatialRequired eq 'true'){
711
	if ($FORM::useSiteCoord ) {
712
	    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.")
713
		unless(hasContent($latDeg1) && hasContent($longDeg1));
714
	}else{
715
	    push(@invalidParams, "Latitude degrees are missing.")
716
		unless (hasContent($latDeg1) || $FORM::spatialRequired ne 'true');
717
	    push(@invalidParams, "Longitude degrees are missing.")
718
		unless (hasContent($longDeg1) || $FORM::spatialRequired ne 'true');
719
	}
720
	push(@invalidParams, 
721
	     "You must provide a geographic description if you provide latitude and longitude information.")
722
	    if ((hasContent($latDeg1) || (hasContent($longDeg1))) && (!hasContent($FORM::geogdesc)));
723
    }
724

    
725
    if($FORM::hasMethod eq 'true'){
726
	push(@invalidParams, 
727
	     "You must provide a method description if you provide a method title.")
728
	    if (hasContent($FORM::methodTitle) && ( !(scalar(@FORM::methodPara) > 0) 
729
						    || (! hasContent($FORM::methodPara[0]))));
730
	push(@invalidParams, 
731
	     "You must provide a method description if you provide an extent of study description.")
732
	    if (hasContent($FORM::studyExtentDescription) && (!(scalar(@FORM::methodPara) > 0) 
733
							      || (! hasContent($FORM::methodPara[0]))));
734
	push(@invalidParams, 
735
	     "You must provide both an extent of study description and a sampling description, or neither.")
736
	    if (
737
                (hasContent($FORM::studyExtentDescription) && !hasContent($FORM::samplingDescription)) ||
738
                (!hasContent($FORM::studyExtentDescription) && hasContent($FORM::samplingDescription))
739
		);
740
    }
741

    
742
    push(@invalidParams, "First name of data set contact is missing.")
743
    unless (hasContent($FORM::origNamefirstContact) || 
744
        $FORM::useOrigAddress);
745
    push(@invalidParams, "Last name of data set contact is missing.")
746
    unless (hasContent($FORM::origNamelastContact) || 
747
        $FORM::useOrigAddress);
748
    push(@invalidParams, "Data medium is missing.")
749
    unless (hasContent($FORM::dataMedium) || $FORM::dataMedium =~ /elect/);
750
    push(@invalidParams, "Usage rights are missing.")
751
    unless (hasContent($FORM::useConstraints));
752
    
753
    return \@invalidParams;
754
}
755

    
756
################################################################################
757
# 
758
# utility function to determine if a paramter is defined and not an empty string
759
#
760
################################################################################
761
sub hasContent {
762
    my $param = shift;
763

    
764
    my $paramHasContent;
765
    if (!defined($param) || $param eq '') { 
766
        $paramHasContent = 0;
767
    } else {
768
        $paramHasContent = 1;
769
    }
770
    return $paramHasContent;
771
}
772

    
773
################################################################################
774
#
775
# Subroutine for replacing characters not recognizable by XML and otherwise. 
776
#
777
################################################################################
778
sub normalize{
779
    my $val = shift;
780

    
781
    $val =~ s/&/&amp;/g;
782

    
783
    $val =~ s/</&lt;/g;
784
    $val =~ s/>/&gt;/g;
785
    $val =~ s/\"/&quot;/g;
786
    $val =~ s/%/&#37;/g;   
787
 
788
    my $returnVal = "";
789
    
790
    foreach (split(//,$val)){
791
	my $var = unpack "C*", $_; 
792
	
793
	if($var<128 && $var>31){
794
	    $returnVal=$returnVal.$_;
795
	} elsif ($var<32){
796
	    if($var == 10){
797
		$returnVal=$returnVal.$_;
798
	    }
799
	    if($var == 13){
800
		$returnVal=$returnVal.$_;
801
	    }
802
	    if($var == 9){
803
		$returnVal=$returnVal.$_;
804
	    }
805
	} else { 
806
	    $returnVal=$returnVal."&#".$var.";";
807
	}
808
    }
809
    
810
    $returnVal =~ s/&/%26/g;    
811
    return $returnVal;
812
}
813

    
814

    
815
################################################################################
816
#
817
# Subroutine for replacing characters not recognizable by XML and otherwise 
818
# except for ", > amd <.
819
#
820
################################################################################
821
sub delNormalize{
822
    my $val = shift;
823

    
824
    $val =~ s/&/&amp;/g;
825

    
826
    $val =~ s/%/&#37;/g;
827

    
828
    my $returnVal = "";
829

    
830
    foreach (split(//,$val)){
831
        my $var = unpack "C*", $_;
832

    
833
        if($var<128 && $var>31){
834
            $returnVal=$returnVal.$_;
835
        } elsif ($var<32){
836
            if($var == 10){
837
                $returnVal=$returnVal.$_;
838
            }
839
            if($var == 13){
840
                $returnVal=$returnVal.$_;
841
            }
842
            if($var == 9){
843
                $returnVal=$returnVal.$_;
844
            }
845
        } else {
846
            $returnVal=$returnVal."&#".$var.";";
847
        }
848
    }
849

    
850
    $returnVal =~ s/&/%26/g;
851
    return $returnVal;
852
}
853

    
854

    
855
################################################################################
856
#
857
# Subroutine for replacing characters that might create problem in HTML. 
858
# Specifically written for " being used in any text field. This creates a 
859
# problem in confirmData template, when you specify input name value pair 
860
# with value having a " in it.  
861
#
862
################################################################################
863
sub normalizeCD{
864
    my $val = shift;
865

    
866
    $val =~ s/\"/&quot;/g;
867
    
868
    return $val;
869
}
870

    
871

    
872
################################################################################
873
# 
874
# Create the XML document from the HTML form input
875
# returns the XML document as a string
876
#
877
################################################################################
878
sub createXMLDocument {
879

    
880
    my $orig  = "";
881
    my $role  = "associatedParty";
882
    my $creat = "";
883
    my $metaP = "";
884
    my $apart = "";
885
    my $cont  = "";
886
    my $publ  = "";
887
    my $dso   = "";
888
    my $gmt = gmtime($now);
889

    
890

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

    
893
    $doc .= "<eml:eml\n 
894
                     \t packageId=\"docid\" system=\"knb\"\n 
895
                     \t xmlns:eml=\"eml://ecoinformatics.org/eml-2.0.1\"\n
896
                     \t xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n 
897
                     \t xmlns:ds=\"eml://ecoinformatics.org/dataset-2.0.1\"\n 
898
                     \t xmlns:stmml=\"http://www.xml-cml.org/schema/stmml\"\n 
899
                     \t xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.0.1 eml.xsd\">\n";
900

    
901
    $doc .= "<!-- Person who filled in the catalog entry form: ";
902
    $doc .= normalize($FORM::providerGivenName)." ".normalize($FORM::providerSurName)." -->\n";
903
    $doc .= "<!-- Form filled out at $gmt GMT -->\n";
904
    $doc .= "<dataset>\n";
905
    
906
    if (hasContent($FORM::identifier)) {
907
        $doc .= "<alternateIdentifier system=\"$FORM::site\">";
908
        $doc .= normalize($FORM::identifier) . "</alternateIdentifier>\n";
909
    }
910
    
911
    if (hasContent($FORM::title)) {
912
        $doc .= "<title>".normalize($FORM::title)."</title>\n";
913
    }
914

    
915
    if (hasContent($FORM::origNamelast0)) {
916
    $role = "creator";
917
        $orig .= "<individualName>\n";
918
        $orig .= "<givenName>".normalize($FORM::origNamefirst0)."</givenName>\n";
919
        $orig .= "<surName>".normalize($FORM::origNamelast0)."</surName>\n";
920
        $orig .= "</individualName>\n";
921
    }
922

    
923
    if (hasContent($FORM::origNameOrg)) {
924
        $orig .= "<organizationName>".normalize($FORM::origNameOrg)."</organizationName>\n";
925
    }
926

    
927
    if (hasContent($FORM::origDelivery) || hasContent($FORM::origCity) ||
928
        (hasContent($FORM::origState   ) &&
929
        ($FORM::origState !~ "Select state here.")) ||
930
        hasContent($FORM::origStateOther) ||
931
        hasContent($FORM::origZIP ) || hasContent($FORM::origCountry)) {
932
        $orig .= "<address>\n";
933

    
934
        if (hasContent($FORM::origDelivery)) {
935
            $orig .= "<deliveryPoint>".normalize($FORM::origDelivery)."</deliveryPoint>\n";
936
        }
937
        if (hasContent($FORM::origCity)) {
938
            $orig .= "<city>".normalize($FORM::origCity)."</city>\n";
939
        }
940

    
941
    if (hasContent($FORM::origState) && 
942
            ($FORM::origState !~ "Select state here.")) {
943
            $orig .= "<administrativeArea>".normalize($FORM::origState);
944
            $orig .= "</administrativeArea>\n";
945
        } elsif (hasContent($FORM::origStateOther)) {
946
            $orig .= "<administrativeArea>".normalize($FORM::origStateOther);
947
            $orig .= "</administrativeArea>\n";
948
        }
949
        if (hasContent($FORM::origZIP)) {
950
            $orig .= "<postalCode>".normalize($FORM::origZIP)."</postalCode>\n";
951
        }
952
        if (hasContent($FORM::origCountry)) {
953
            $orig .= "<country>".normalize($FORM::origCountry)."</country>\n";
954
        }
955
        $orig .= "</address>\n";
956
    }
957

    
958
    if (hasContent($FORM::origPhone)) {
959
        $orig .= "<phone>".normalize($FORM::origPhone)."</phone>\n";
960
    }
961
    if (hasContent($FORM::origFAX)) {
962
        $orig .= "<phone phonetype=\"Fax\">".normalize($FORM::origFAX)."</phone>\n";
963
    }
964
    if (hasContent($FORM::origEmail)) {
965
        $orig .= "<electronicMailAddress>".normalize($FORM::origEmail);
966
        $orig .= "</electronicMailAddress>\n";
967
    }
968
    $dso = "<$role>\n$orig</$role>\n";
969
    
970
    if ($FORM::cfg eq 'nceas') {
971
        for (my $i = 0; $i < scalar(@FORM::wg); $i++) {
972
            $creat .= "<creator>\n";
973
            $creat .= "<organizationName>".normalize($FORM::wg[$i])."</organizationName>\n";
974
            $creat .= "</creator>\n";
975
        }
976
    } else {
977
	    $creat .= "<creator>\n";
978
	    $creat .= "<organizationName>".normalize($FORM::site)."</organizationName>\n";
979
	    $creat .= "</creator>\n";
980
    }
981

    
982
    if ($FORM::cfg ne 'knb') {
983
        $creat .= "<creator>\n";
984
        $creat .= "<organizationName>".normalize($organization)."</organizationName>\n";
985
        $creat .= "</creator>\n";
986
    }
987

    
988
    $creat .= $dso;
989

    
990
    if ($FORM::useOrigAddress) {
991
        # Add a contact originator like the original with a different role
992
            $cont .= "<contact>\n";
993
        $cont .= $orig;
994
        $cont .= "</contact>\n";
995
    } else {
996
        $cont .= "<contact>\n";
997

    
998
        $cont .= "<individualName>\n";
999
        $cont .= "<givenName>".normalize($FORM::origNamefirstContact)."</givenName>\n";
1000
        $cont .= "<surName>".normalize($FORM::origNamelastContact)."</surName>\n";
1001
        $cont .= "</individualName>\n";
1002
 
1003
    if (hasContent($FORM::origNameOrgContact)) {
1004
        $cont .= "<organizationName>".normalize($FORM::origNameOrgContact)."</organizationName>\n";
1005
    }
1006

    
1007
        if (hasContent($FORM::origDeliveryContact) || 
1008
            hasContent($FORM::origCityContact) ||
1009
            (hasContent($FORM::origStateContact) &&
1010
            ($FORM::origStateContact !~ "Select state here.")) ||
1011
            hasContent($FORM::origStateOtherContact) ||
1012
            hasContent($FORM::origZIPContact) || 
1013
            hasContent($FORM::origCountryContact)) {
1014
            $cont .= "<address>\n";
1015
            if (hasContent($FORM::origDeliveryContact)) {
1016
                $cont .= "<deliveryPoint>".normalize($FORM::origDeliveryContact);
1017
                $cont .= "</deliveryPoint>\n";
1018
            }
1019
            if (hasContent($FORM::origCityContact)) {
1020
                $cont .= "<city>".normalize($FORM::origCityContact)."</city>\n";
1021
            }
1022
            if (hasContent($FORM::origStateContact) && 
1023
                ($FORM::origStateContact !~ "Select state here.")) {
1024
                $cont .= "<administrativeArea>".normalize($FORM::origStateContact);
1025
                $cont .= "</administrativeArea>\n";
1026
            } elsif (hasContent($FORM::origStateOtherContact)) {
1027
                $cont .= "<administrativeArea>".normalize($FORM::origStateOtherContact);
1028
                $cont .= "</administrativeArea>\n";
1029
            }
1030
            if (hasContent($FORM::origZIPContact)) {
1031
                $cont .= "<postalCode>".normalize($FORM::origZIPContact)."</postalCode>\n";
1032
            }
1033
            if (hasContent($FORM::origCountryContact)) {
1034
                $cont .= "<country>".normalize($FORM::origCountryContact)."</country>\n";
1035
            }
1036
            $cont .= "</address>\n";
1037
        }
1038
        if (hasContent($FORM::origPhoneContact)) {
1039
            $cont .= "<phone>".normalize($FORM::origPhoneContact)."</phone>\n";
1040
        }
1041
    if (hasContent($FORM::origFAXContact)) {
1042
        $cont .= "<phone phonetype=\"Fax\">".normalize($FORM::origFAXContact)."</phone>\n";
1043
    }
1044
        if (hasContent($FORM::origEmailContact)) {
1045
            $cont .= "<electronicMailAddress>".normalize($FORM::origEmailContact);
1046
            $cont .= "</electronicMailAddress>\n";
1047
        }
1048
    $cont .= "</contact>\n";
1049
    }
1050

    
1051
    $metaP .= "<metadataProvider>\n";
1052
    $metaP .= "<individualName>\n";
1053
    $metaP .= "<givenName>".normalize($FORM::providerGivenName)."</givenName>\n";
1054
    $metaP .= "<surName>".normalize($FORM::providerSurName)."</surName>\n";
1055
    $metaP .= "</individualName>\n";
1056
    $metaP .= "</metadataProvider>\n";
1057

    
1058
    # Additional originators
1059
    foreach my $tmp (param()) {
1060
        if ($tmp =~ /origNamelast/){
1061
            my $tmp1 = $tmp;
1062
            $tmp1 =~ s/origNamelast//; # get the index of the parameter 0 to 10
1063
            if ( $tmp1 eq '1' 
1064
                 || $tmp1 eq '2'
1065
                 || $tmp1 eq '3'
1066
                 || $tmp1 eq '4'
1067
                 || $tmp1 eq '5'
1068
                 || $tmp1 eq '6'
1069
                 || $tmp1 eq '7'
1070
                 || $tmp1 eq '8'
1071
                 || $tmp1 eq '9'
1072
                 || $tmp1 eq '10'
1073
                 ) {
1074
     
1075
                # do not generate XML for empty originator fields 
1076
                if (hasContent(param("origNamefirst" . $tmp1))) {    
1077

    
1078
            my $add = "";
1079
            $add .= "<individualName>\n";
1080
            $add .= "<givenName>";
1081
            $add .= normalize(param("origNamefirst" . $tmp1));
1082
            $add .= "</givenName>\n";
1083
            $add .= "<surName>";
1084
            $add .= normalize(param("origNamelast" . $tmp1));
1085
            $add .= "</surName>\n";
1086
            $add .= "</individualName>\n";
1087
            
1088
            if(param("origRole" . $tmp1) eq "Originator"){
1089
            $creat .= "<creator>\n";
1090
            $creat .= $add;
1091
            $creat .= "</creator>\n";
1092
            }
1093
            elsif(param("origRole" . $tmp1) eq "Metadata Provider"){
1094
            $metaP .= "<metadataProvider>\n";
1095
            $metaP .= $add;
1096
            $metaP .= "</metadataProvider>\n";
1097
            }
1098
            elsif((param("origRole" . $tmp1) eq "Publisher")  && ($publ eq "")){
1099
            $publ .= "<publisher>\n";
1100
            $publ .= $add;
1101
            $publ .= "</publisher>\n";
1102
            }
1103
            else{
1104
            $apart .= "<associatedParty>\n";
1105
            $apart .= $add;
1106
            $apart .= "<role>";
1107
            $apart .= param("origRole" . $tmp1);
1108
            $apart .= "</role>\n";
1109
            $apart .= "</associatedParty>\n";
1110
            }
1111
        }
1112
            }
1113
        }
1114
    }
1115

    
1116
    $doc .= $creat;
1117
    $doc .= $metaP;
1118
    $doc .= $apart;
1119

    
1120
    # add the publication Date to the eml document. 
1121
    my $Second = "";
1122
    my $Minute = "";
1123
    my $Hour = "";
1124
    my $Day = "";
1125
    my $Month = "";
1126
    my $Year = "";
1127
    my $WeekDay = "";
1128
    my $DayOfYear = "";
1129
    my $IsDST = "";
1130
    ($Second, $Minute, $Hour, $Day, $Month, $Year, $WeekDay, $DayOfYear, $IsDST) = localtime(time) ;
1131
    $Month = $Month + 1;
1132
    if($Month < 10) { 
1133
	$Month = "0".$Month;
1134
    }
1135
    if($Day < 10) { 
1136
	$Day = "0".$Day;  
1137
    } 
1138
    $Year = $Year + 1900; 
1139

    
1140
    $doc .= "<pubDate>\n";
1141
    $doc .= $Year."-".$Month."-".$Day;
1142
    $doc .= "</pubDate>\n";
1143

    
1144
    $doc .= "<abstract>\n";
1145
    $doc .= "<para>".normalize($FORM::abstract)."</para>\n";
1146
    $doc .= "</abstract>\n";
1147

    
1148
    # Keyword information
1149
    foreach my $tmp (param()) {
1150
        if ($tmp =~ /keyword/) {
1151
            my $tmp1 = $tmp;
1152
            $tmp1 =~ s/keyword//; # get the index of the parameter 0, ..., 10
1153
            if ( $tmp1 =~ /[0-9]/ ){
1154
                # don't generate xml for empty keyword fields
1155
                # don't generate taxonomic keyword fields, those go in taxonomic coverage
1156
                if (hasContent(param($tmp))) {
1157
                    $doc .= "<keywordSet>\n";
1158
                    $doc .= "<keyword ";
1159
                    if (hasContent(param("kwType" . $tmp1)) &&
1160
                       (param("kwType" . $tmp1) !~ "None") ) {
1161
                         $doc .= "keywordType=\"";
1162
                         $doc .= lc(param("kwType" . $tmp1));
1163
                         $doc .= "\"";
1164
                    }
1165
                    $doc .= ">";
1166
                    $doc .= normalize(param("keyword" . $tmp1));
1167
                    $doc .= "</keyword>\n";
1168
                    $doc .= "<keywordThesaurus>";
1169
                    $doc .= normalize(param("kwTh" . $tmp1));
1170
                    $doc .= "</keywordThesaurus>\n";
1171
                    $doc .= "</keywordSet>\n";
1172
                }
1173
            }
1174
        }
1175
    }
1176

    
1177
    if (hasContent($FORM::addComments)) {
1178
        $doc .= "<additionalInfo>\n";
1179
        $doc .= "<para>".normalize($FORM::addComments)."</para>\n";
1180
        $doc .= "</additionalInfo>\n";
1181
    }
1182

    
1183
    if (hasContent($FORM::useConstraints) || 
1184
        hasContent($FORM::useConstraintsOther)) {
1185
        $doc .= "<intellectualRights>\n";
1186
        if (hasContent($FORM::useConstraints)) {
1187
            $doc .= "<para>".normalize($FORM::useConstraints)."</para>\n";
1188
        }
1189
        if (hasContent($FORM::useConstraintsOther)) {
1190
            $doc .= "<para>".normalize($FORM::useConstraintsOther)."</para>\n";
1191
        }
1192
        $doc .= "</intellectualRights>\n";
1193
    }
1194

    
1195
    
1196
    if (hasContent($FORM::url)) {
1197
    $doc .= "<distribution>\n";
1198
        $doc .= "<online>\n";
1199
    $doc .= "<url>".normalize($FORM::url)."</url>\n";
1200
    $doc .= "</online>\n";
1201
    $doc .= "</distribution>\n";
1202
    }
1203
    
1204
    $doc .= "<distribution>\n";
1205
    $doc .= "<offline>\n";
1206
    $doc .= "<mediumName>" . normalize($FORM::dataMedium)." ".normalize($FORM::dataMediumOther);
1207
    $doc .= "</mediumName>\n";
1208
    $doc .= "</offline>\n";
1209
    $doc .= "</distribution>\n";
1210
            
1211
    my $cov = "";
1212

    
1213
    if (hasContent($FORM::endingYear)) {
1214
	$cov .= "<temporalCoverage>\n";
1215
	$cov .= "<rangeOfDates>\n";
1216
	if (hasContent($FORM::beginningMonth)) {
1217
	    my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1218
			 "JUL","AUG","SEP","OCT","NOV","DEC")
1219
		[$FORM::beginningMonth - 1];
1220
	    $cov .= "<beginDate>\n";
1221
	    $cov .= "<calendarDate>";
1222
	    $cov .= normalize($FORM::beginningYear)."-".normalize($FORM::beginningMonth)."-".normalize($FORM::beginningDay);
1223
	    $cov .= "</calendarDate>\n";
1224
	    $cov .= "</beginDate>\n";
1225
	} else {
1226
	    $cov .= "<beginDate>\n";
1227
	    $cov .= "<calendarDate>";
1228
	    $cov .= normalize($FORM::beginningYear);
1229
	    $cov .= "</calendarDate>\n";
1230
	    $cov .= "</beginDate>\n";
1231
	}
1232
	
1233
	if (hasContent($FORM::endingMonth)) {
1234
	    my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1235
			 "JUL","AUG","SEP","OCT","NOV","DEC")
1236
		[$FORM::endingMonth - 1];
1237
	    $cov .= "<endDate>\n";
1238
	    $cov .= "<calendarDate>";
1239
	    $cov .= normalize($FORM::endingYear)."-".normalize($FORM::endingMonth)."-".normalize($FORM::endingDay);
1240
	    $cov .= "</calendarDate>\n";
1241
	    $cov .= "</endDate>\n";
1242
	} else {
1243
	    $cov .= "<endDate>\n";
1244
	    $cov .= "<calendarDate>";
1245
	    $cov .= normalize($FORM::endingYear);
1246
	    $cov .= "</calendarDate>\n";
1247
	    $cov .= "</endDate>\n";
1248
	}
1249
	$cov .= "</rangeOfDates>\n";
1250
	$cov .= "</temporalCoverage>\n";
1251
    } else {
1252
	if(hasContent($FORM::beginningYear)) {
1253
	    $cov .= "<temporalCoverage>\n";
1254
	    $cov .= "<singleDateTime>\n";
1255
	    if (hasContent($FORM::beginningMonth)) {
1256
		my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1257
			     "JUL","AUG","SEP","OCT","NOV","DEC")
1258
		    [$FORM::beginningMonth - 1];
1259
		$cov .= "<calendarDate>";
1260
		$cov .= normalize($FORM::beginningYear)."-".normalize($FORM::beginningMonth)."-".normalize($FORM::beginningDay);
1261
		$cov .= "</calendarDate>\n";
1262
	    } else {
1263
		$cov .= "<calendarDate>";
1264
		$cov .= normalize($FORM::beginningYear);
1265
		$cov .= "</calendarDate>\n";
1266
	    }
1267
	    $cov .= "</singleDateTime>\n";
1268
	    $cov .= "</temporalCoverage>\n";
1269
	}
1270
    }
1271
    
1272
    if(hasContent($FORM::geogdesc) || ($FORM::latDeg1 < 91 && $FORM::latDeg1 > -1 && $FORM::longDeg1 < 181 && $FORM::longDeg1 > -1)) {
1273
	$cov .= "<geographicCoverage>\n";
1274

    
1275
	if(hasContent($FORM::geogdesc)) {
1276
	    $cov .= "<geographicDescription>".normalize($FORM::geogdesc)."</geographicDescription>\n";
1277
	}
1278
	
1279
	if($latDeg1 < 91 && $latDeg1 > -1 && $longDeg1 < 181 && $longDeg1 > -1) {
1280
	    $cov .= "<boundingCoordinates>\n";
1281
	    # if the second latitude is missing, then set the second lat/long pair 
1282
	    # equal to the first this makes a point appear like a rectangle 
1283
	    if ($FORM::useSiteCoord || ($FORM::latDeg2 == "" && $FORM::latMin2 == "" && $FORM::latSec2 == "")) {
1284
		
1285
		$latDeg2 = $latDeg1;
1286
		$latMin2 = $latMin1;
1287
		$latSec2 = $latSec1;
1288
		$hemisphLat2 = $hemisphLat1;
1289
		$longDeg2 = $longDeg1;
1290
		$longMin2 = $longMin1;
1291
		$longSec2 = $longSec1;
1292
		$hemisphLong2 = $hemisphLong1;
1293
	    }
1294
	    else
1295
	    {
1296
		$latDeg2 = $FORM::latDeg2;
1297
		$latMin2 = $FORM::latMin2;
1298
		$latSec2 = $FORM::latSec2;
1299
		$hemisphLat2 = $FORM::hemisphLat2;
1300
		$longDeg2 = $FORM::longDeg2;
1301
		$longMin2 = $FORM::longMin2;
1302
		$longSec2 = $FORM::longSec2;
1303
		$hemisphLong2 = $FORM::hemisphLong2;
1304
	    } 
1305
	
1306
	
1307
	    my $hemisph;
1308
	    $hemisph = ($hemisphLong1 eq "W") ? -1 : 1;
1309
	    $cov .= "<westBoundingCoordinate>";
1310
	    my $var = $hemisph * ($longDeg1 + (60*$longMin1+$longSec1)/3600);
1311
	    $cov .= sprintf("%.4f\n", $var);
1312
	    $cov .= "</westBoundingCoordinate>\n";
1313
	    
1314
	    $hemisph = ($hemisphLong2 eq "W") ? -1 : 1;
1315
	    $cov .= "<eastBoundingCoordinate>";
1316
	    $var = $hemisph * ($longDeg2 + (60*$longMin2+$longSec2)/3600);
1317
	    $cov .= sprintf("%.4f\n", $var);
1318
	    $cov .= "</eastBoundingCoordinate>\n";
1319
	    
1320
	    $hemisph = ($hemisphLat1 eq "S") ? -1 : 1;
1321
	    $cov .= "<northBoundingCoordinate>";
1322
	    $var = $hemisph * ($latDeg1 + (60*$latMin1+$latSec1)/3600);
1323
	    $cov .= sprintf("%.4f\n", $var);	   
1324
	    $cov .= "</northBoundingCoordinate>\n";
1325
	    
1326
	    $hemisph = ($hemisphLat2 eq "S") ? -1 : 1;
1327
	    $cov .= "<southBoundingCoordinate>";
1328
	    $var = $hemisph * ($latDeg2 + (60*$latMin2+$latSec2)/3600);
1329
	    $cov .= sprintf("%.4f\n", $var);
1330
	    $cov .= "</southBoundingCoordinate>\n";
1331
	    
1332
	    $cov .= "</boundingCoordinates>\n";
1333
	}
1334
	$cov .= "</geographicCoverage>\n";
1335
    }
1336

    
1337
    # Write out the taxonomic coverage fields
1338
    my $foundFirstTaxon = 0;
1339
    foreach my $trn (param()) {
1340
        if ($trn =~ /taxonRankName/) {
1341
            my $taxIndex = $trn;
1342
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
1343
            my $trv = "taxonRankValue".$taxIndex;
1344
            if ( $taxIndex =~ /[0-9]/ ){
1345
                if (hasContent(param($trn)) && hasContent(param($trv))) {
1346
                    if (! $foundFirstTaxon) {
1347
                        $cov .= "<taxonomicCoverage>\n";
1348
                        $foundFirstTaxon = 1;
1349
                        if (hasContent($FORM::taxaAuth)) {
1350
                            $cov .= "<generalTaxonomicCoverage>".normalize($FORM::taxaAuth)."</generalTaxonomicCoverage>\n";
1351
                        }
1352
                    }
1353
                    $cov .= "<taxonomicClassification>\n";
1354
                    $cov .= "  <taxonRankName>".normalize(param($trn))."</taxonRankName>\n";
1355
                    $cov .= "  <taxonRankValue>".normalize(param($trv))."</taxonRankValue>\n";
1356
                    $cov .= "</taxonomicClassification>\n";
1357
                }
1358
            }
1359
        }
1360
    }
1361
    if ($foundFirstTaxon) {
1362
        $cov .= "</taxonomicCoverage>\n";
1363
    }
1364

    
1365
    if($cov ne "" ){
1366
	$doc .= "<coverage>".$cov."</coverage>";
1367
    }
1368
    $doc .= $cont;
1369
    $doc .= $publ;
1370
    
1371
    if ((hasContent($FORM::methodTitle)) || scalar(@FORM::methodsPara) > 0 || ($FORM::methodPara[0] ne "")) {
1372
        my $methods = "<methods><methodStep><description><section>\n";
1373
        if (hasContent($FORM::methodTitle)) {
1374
            $methods .= "<title>".normalize($FORM::methodTitle)."</title>\n";
1375
        }
1376
        for (my $i = 0; $i < scalar(@FORM::methodPara); $i++) {
1377
            $methods .= "<para>".normalize($FORM::methodPara[$i])."</para>\n";
1378
        }
1379
        $methods .= "</section></description></methodStep>\n";
1380
        if (hasContent($FORM::studyExtentDescription)) {
1381
            $methods .= "<sampling><studyExtent><description>\n";
1382
            $methods .= "<para>".normalize($FORM::studyExtentDescription)."</para>\n";
1383
            $methods .= "</description></studyExtent>\n";
1384
            $methods .= "<samplingDescription>\n";
1385
            $methods .= "<para>".normalize($FORM::samplingDescription)."</para>\n";
1386
            $methods .= "</samplingDescription>\n";
1387
            $methods .= "</sampling>\n";
1388
        }
1389
        $methods .= "</methods>\n";
1390
        $doc .= $methods;
1391
    }
1392

    
1393
    $doc .= "<access authSystem=\"knb\" order=\"denyFirst\">\n";
1394
    $doc .= "<allow>\n";
1395
    $doc .= "<principal>$username</principal>\n";
1396
    $doc .= "<permission>all</permission>\n";
1397
    $doc .= "</allow>\n";
1398
    $doc .= "<allow>\n";
1399
    $doc .= "<principal>uid=$FORM::username,o=$FORM::organization,dc=ecoinformatics,dc=org</principal>\n";
1400
    $doc .= "<permission>all</permission>\n";
1401
    $doc .= "</allow>\n";
1402
    $doc .= "<allow>\n";
1403
    $doc .= "<principal>public</principal>\n";
1404
    $doc .= "<permission>read</permission>\n";
1405
    $doc .= "</allow>\n";
1406
    $doc .= "</access>\n";
1407
    
1408
    $doc .= "</dataset>\n</eml:eml>\n";
1409

    
1410
    return $doc;
1411
}
1412

    
1413

    
1414
################################################################################
1415
# 
1416
# send an email message notifying the moderator of a new submission 
1417
#
1418
################################################################################
1419
sub sendNotification {
1420
    my $identifier = shift;
1421
    my $mailhost = shift;
1422
    my $sender = shift;
1423
    my $recipient = shift;
1424

    
1425
    my $smtp = Net::SMTP->new($mailhost);
1426
    $smtp->mail($sender);
1427
    $smtp->to($recipient);
1428

    
1429
    my $message = <<"    ENDOFMESSAGE";
1430
    To: $recipient
1431
    From: $sender
1432
    Subject: New data submission
1433
    
1434
    Data was submitted to the data registry.  
1435
    The identifying information for the new data set is:
1436

    
1437
    Identifier: $identifier
1438
    Title: $FORM::title
1439
    Submitter: $FORM::providerGivenName $FORM::providerSurName
1440

    
1441
    Please review the submmission and grant public read access if appropriate.
1442
    Thanks
1443
    
1444
    ENDOFMESSAGE
1445
    $message =~ s/^[ \t\r\f]+//gm;
1446

    
1447
    $smtp->data($message);
1448
    $smtp->quit;
1449
}
1450

    
1451

    
1452
################################################################################
1453
# 
1454
# read the eml document and send back a form with values filled in. 
1455
#
1456
################################################################################
1457
sub modifyData {
1458
    
1459
    # create metacat instance
1460
    my $metacat;
1461
    my $docid = $FORM::docid;
1462
    my $httpMessage;
1463
    my $doc;
1464
    my $xmldoc;
1465
    my $findType;
1466
    my $parser = XML::LibXML->new();
1467
    my @fileArray;
1468
    my $pushDoc;
1469
    my $alreadyInArray;
1470
    my $node;
1471
    my $response; 
1472
    my $element;
1473
    my $tempfile;
1474

    
1475
    $metacat = Metacat->new();
1476
    if ($metacat) {
1477
        $metacat->set_options( metacatUrl => $metacatUrl );
1478
    } else {
1479
        #die "failed during metacat creation\n";
1480
        push(@errorMessages, "Failed during metacat creation.");
1481
    }
1482
    
1483
    $httpMessage = $metacat->read($docid);
1484
    $doc = $httpMessage->content();
1485
    $xmldoc = $parser->parse_string($doc);
1486

    
1487
    #$tempfile = $xslConvDir.$docid;
1488
    #push (@fileArray, $tempfile);
1489

    
1490
    if ($xmldoc eq "") {
1491
        $error ="Error in parsing the eml document";
1492
        push(@errorMessages, $error);
1493
    } else {
1494
        $findType = $xmldoc->findnodes('//dataset/identifier');
1495
        if ($findType->size() > 0) {
1496
            # This is a eml beta6 document
1497
            # Read the documents mentioned in triples also
1498
        
1499
            $findType = $xmldoc->findnodes('//dataset/triple');
1500
            if ($findType->size() > 0) {
1501
                foreach $node ($findType->get_nodelist) {
1502
                    $pushDoc = findValue($node, 'subject');
1503
            
1504
                    # If the file is already in @fileArray then do not add it 
1505
                    $alreadyInArray = 0;
1506
                    foreach $element (@fileArray) {
1507
                        $tempfile = $tmpdir."/".$pushDoc;
1508
                        if ($element eq $pushDoc) {
1509
                            $alreadyInArray = 1;
1510
                        }
1511
                    }
1512
            
1513
                    if (!$alreadyInArray) {
1514
                        $tempfile = $tmpdir."/".$pushDoc;
1515
                        $response = "";
1516
                        $response = $metacat->read($pushDoc);    
1517
                        if (! $response) {
1518
                            # could not read
1519
                            #push(@errorMessages, $response);
1520
                            push(@errorMessages, $metacat->getMessage());
1521
                            push(@errorMessages, "Failed during reading.\n");
1522
                        } else {
1523
                            my $xdoc = $response->content();
1524
                            #$tempfile = $xslConvDir.$pushDoc;
1525
                            open (TFILE,">$tempfile") || 
1526
                                die ("Cant open xml file... $tempfile\n");
1527
                            print TFILE $xdoc;
1528
                            close(TFILE);
1529
                            push (@fileArray, $tempfile);
1530
                        }
1531
                    }
1532
                }
1533
            }
1534

    
1535
            # Read the main document. 
1536

    
1537
            $tempfile = $tmpdir."/".$docid; #= $xslConvDir.$docid;
1538
            open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1539
            print TFILE $doc;
1540
            close(TFILE);
1541
        
1542
            # Transforming beta6 to eml 2
1543
            my $xslt;
1544
            my $triplesheet;
1545
            my $results;
1546
            my $stylesheet;
1547
            my $resultsheet;
1548
        
1549
            $xslt = XML::LibXSLT->new();
1550
            #$tempfile = $xslConvDir."triple_info.xsl";
1551
            $tempfile = $tmpdir."/"."triple_info.xsl";
1552
    
1553
            $triplesheet = $xslt->parse_stylesheet_file($tempfile);
1554

    
1555
            #$results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1556
            $results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1557

    
1558
            #$tempfile = $xslConvDir."emlb6toeml2.xsl";
1559
            $tempfile = $tmpdir."/"."emlb6toeml2.xsl";
1560
            $stylesheet = $xslt->parse_stylesheet_file($tempfile);
1561
            $resultsheet = $stylesheet->transform($results);
1562
        
1563
            #$tempfile = "/usr/local/apache2/htdocs/xml/test.xml";;
1564
            #open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1565
            #print TFILE $stylesheet->output_string($resultsheet);
1566
            #close(TFILE);
1567

    
1568
            getFormValuesFromEml2($resultsheet);
1569
            
1570
            # Delete the files written earlier. 
1571
            unlink @fileArray;
1572

    
1573
        } else {
1574
            getFormValuesFromEml2($xmldoc);
1575
        }
1576
    }   
1577
    
1578
    if (scalar(@errorMessages)) {
1579
        # if any errors, print them in the response template 
1580
        $$templateVars{'status'} = 'failure_no_resubmit';
1581
        $$templateVars{'errorMessages'} = \@errorMessages;
1582
        $error = 1;
1583
        $$templateVars{'function'} = "modification";
1584
        $$templateVars{'section'} = "Modification Status";
1585
        $template->process( $responseTemplate, $templateVars); 
1586
    } else {
1587
        $$templateVars{'form'} = 're_entry';
1588
        $template->process( $entryFormTemplate, $templateVars);
1589
    }
1590
}
1591

    
1592
################################################################################
1593
# 
1594
# Parse an EML 2.0.0 file and extract the metadata into perl variables for 
1595
# processing and returning to the template processor
1596
#
1597
################################################################################
1598
sub getFormValuesFromEml2 {
1599
    
1600
    my $doc = shift;
1601
    my $results;
1602
    my $error;
1603
    my $node;
1604
    my $tempResult;
1605
    my $tempNode;
1606
    my $aoCount = 1;
1607
    my $foundDSO;
1608

    
1609
    # set variable values
1610
    $$templateVars{'showSiteList'} = $showSiteList;
1611
    $$templateVars{'lsite'} = $lsite;
1612
    $$templateVars{'usite'} = $usite;
1613
    $$templateVars{'showWgList'} = $showWgList;
1614
    $$templateVars{'showOrganization'} = $showOrganization;
1615
    $$templateVars{'hasKeyword'} = $hasKeyword;
1616
    $$templateVars{'hasTemporal'} = $hasTemporal;
1617
    $$templateVars{'hasSpatial'} = $hasSpatial;
1618
    $$templateVars{'hasTaxonomic'} = $hasTaxonomic;
1619
    $$templateVars{'hasMethod'} = $hasMethod;
1620
    $$templateVars{'spatialRequired'} = $spatialRequired;
1621
    $$templateVars{'temporalRequired'} = $temporalRequired;
1622

    
1623
    # find out the tag <alternateIdentifier>. 
1624
    $results = $doc->findnodes('//dataset/alternateIdentifier');
1625
    if ($results->size() > 1) {
1626
        errMoreThanOne("alternateIdentifier");
1627
    } else {
1628
        foreach $node ($results->get_nodelist) {
1629
            $$templateVars{'identifier'} = findValue($node, '../alternateIdentifier');
1630
        }
1631
    }
1632

    
1633
    # find out the tag <title>. 
1634
    $results = $doc->findnodes('//dataset/title');
1635
    if ($results->size() > 1) {
1636
        errMoreThanOne("title");
1637
    } elsif ($results->size() < 1) {
1638
        $error ="Following tag not found: title. Please use Morpho to edit this document";
1639
        push(@errorMessages, $error."\n");
1640
        #if ($DEBUG == 1){ print $error;}
1641
    } else {
1642
        foreach $node ($results->get_nodelist) {
1643
            $$templateVars{'title'} = findValue($node, '../title');
1644
        }
1645
    }
1646

    
1647
    # find out the tag <creator>. 
1648
    $results = $doc->findnodes('//dataset/creator/individualName');
1649
    debug("Registry: Creators: ".$results->size());
1650
     foreach $node ($results->get_nodelist) {
1651
            dontOccur($node, "../positionName|../onlineURL|../userId", 
1652
              "positionName, onlineURL, userId");
1653
        
1654
            dontOccur($node, "./saluation", "saluation");                
1655
        
1656
            debug("Registry: Checking a creator in loop 1...");
1657
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1658
            if($tempResult->size > 0) {
1659
                if($foundDSO == 0) {
1660
                    $foundDSO = 1;
1661
     
1662
                    debug("Registry: Recording a creator in loop 1...");
1663
                    $$templateVars{'origNamefirst0'} = findValue($node, 'givenName');
1664
                    $$templateVars{'origNamelast0'} = findValue($node, 'surName');
1665
            
1666
                    my $tempResult2 = $node->findnodes('../address');
1667
                    if ($tempResult2->size > 1) {
1668
                        errMoreThanOne("address");
1669
                    } else {
1670
                        foreach my $tempNode2 ($tempResult2->get_nodelist) {
1671
                            $$templateVars{'origDelivery'} = findValue($tempNode2, 'deliveryPoint');
1672
                            $$templateVars{'origCity'} = findValue($tempNode2, 'city');
1673
                            $$templateVars{'origState'} = findValue($tempNode2, 'administrativeArea');
1674
                            $$templateVars{'origZIP'} = findValue($tempNode2, 'postalCode');
1675
                            $$templateVars{'origCountry'} = findValue($tempNode2, 'country');
1676
                        }
1677
                    }
1678
            
1679
                    my $tempResult3 = $node->findnodes('../phone');
1680
                    if ($tempResult3->size > 2) {
1681
                        errMoreThanN("phone");
1682
                    } else {
1683
                        foreach my $tempNode2 ($tempResult3->get_nodelist) {
1684
                            if ($tempNode2->hasAttributes()) {
1685
                                my @attlist = $tempNode2->attributes();
1686
                                if ($attlist[0]->value eq "Fax") {
1687
                                    $$templateVars{'origFAX'} = $tempNode2->textContent();
1688
                                } else {
1689
                                    $$templateVars{'origPhone'} = $tempNode2->textContent();
1690
                                }
1691
                            } else {
1692
                                $$templateVars{'origPhone'} = $tempNode2->textContent();
1693
                            }
1694
                        }
1695
                    }
1696
                    $$templateVars{'origEmail'} = findValue($node, '../electronicMailAddress');
1697
                    $$templateVars{'origNameOrg'} = findValue($node, '../organizationName');
1698
                } else {
1699
                    errMoreThanN("address, phone and electronicMailAddress");
1700
                }
1701
            }
1702
        }
1703
        foreach $node ($results->get_nodelist) {
1704
            debug("Registry: Checking a creator in loop 2...");
1705
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1706
            if ($tempResult->size == 0) {
1707
                if ($foundDSO == 0) {
1708
                    debug("Registry: Recording a creator in loop 2 block A...");
1709
                    $foundDSO = 1;
1710
                    $$templateVars{'origNamefirst0'} = findValue($node, 'givenName');
1711
                    $$templateVars{'origNamelast0'} = findValue($node, 'surName');
1712
                    $$templateVars{'origNameOrg'} = findValue($node, '../organizationName');
1713
                } else {
1714
                    debug("Registry: Recording a creator in loop 2 block B...");
1715
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($node, './givenName');
1716
                    $$templateVars{"origNamelast$aoCount"} =  findValue($node, './surName');
1717
                    $$templateVars{"origRole$aoCount"} = "Originator";
1718
                    $aoCount++;
1719
                }
1720
            }
1721
        }
1722

    
1723
    $results = $doc->findnodes('//dataset/creator/organizationName');
1724
    my $wgroups = $doc->findnodes("//dataset/creator/organizationName[contains(text(),'(NCEAS ')]");
1725
    debug("Registry: Number Org: ".$results->size());
1726
    debug("Registry:  Number WG: ".$wgroups->size());
1727
    if ($results->size() - $wgroups->size() > 3) {
1728
        errMoreThanN("creator/organizationName");    
1729
    } else {
1730
        foreach $node ($results->get_nodelist) {
1731
            my $tempValue = findValue($node,'../organizationName');
1732
            $tempResult = $node->findnodes('../individualName');
1733
            if ($tempResult->size == 0 && $tempValue ne $organization) {
1734
                $$templateVars{'site'} = $tempValue;
1735
            }
1736
        }
1737
        if ($FORM::cfg eq 'nceas') {
1738
            my @wg;
1739
            foreach $node ($results->get_nodelist) {
1740
                my $tempValue = findValue($node,'../organizationName');
1741
                $wg[scalar(@wg)] = $tempValue;
1742
            }
1743
            my $projects = getProjectList();
1744
            $$templateVars{'projects'} = $projects;
1745
            $$templateVars{'wg'} = \@wg;
1746
        }
1747
    }
1748

    
1749
    $results = $doc->findnodes('//dataset/metadataProvider');
1750
    foreach $node ($results->get_nodelist) {
1751
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1752
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in metadataProvider");
1753
        
1754
	    $tempResult = $node->findnodes('./individualName');
1755
            if ($tempResult->size > 1) {
1756
                errMoreThanOne("metadataProvider/indvidualName");
1757
            } else {
1758
                foreach $tempNode ($tempResult->get_nodelist) {
1759
                    if ($$templateVars{'providerGivenName'} ne "") {
1760
                        $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1761
                        $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1762
                        $$templateVars{"origRole$aoCount"} = "Metadata Provider";
1763
                        $aoCount++;
1764
                    } else {
1765
                        $$templateVars{'providerGivenName'} =  findValue($tempNode, './givenName');
1766
                        $$templateVars{'providerSurName'} =  findValue($tempNode, './surName');
1767
                    }
1768
                }
1769
            }
1770
        }
1771

    
1772
    $results = $doc->findnodes('//dataset/associatedParty');
1773
    foreach $node ($results->get_nodelist) {
1774
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1775
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in associatedParty");
1776
       
1777
            $tempResult = $node->findnodes('./individualName');
1778
            if ($tempResult->size > 1) {
1779
                errMoreThanOne("associatedParty/indvidualName");
1780
            } else {
1781
                foreach $tempNode ($tempResult->get_nodelist) {
1782
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1783
                    $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1784
                    $$templateVars{"origRole$aoCount"} = findValue($tempNode, '../role');
1785
                    $aoCount++;           
1786
                }
1787
            }
1788
     }
1789

    
1790
    $results = $doc->findnodes('//dataset/publisher');
1791
#    if ($results->size() > 10) {
1792
 #       errMoreThanN("publisher");
1793
 #   } else {
1794
        foreach $node ($results->get_nodelist) {
1795
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1796
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in associatedParty");
1797
       
1798
            $tempResult = $node->findnodes('./individualName');
1799
            if ($tempResult->size > 1) {
1800
                errMoreThanOne("publisher/indvidualName");
1801
            } else {
1802
                foreach $tempNode ($tempResult->get_nodelist) {
1803
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1804
                    $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1805
                    $$templateVars{"origRole$aoCount"} = "Publisher";
1806
                    $aoCount++;           
1807
                }
1808
            }
1809
        }
1810
  #  }
1811

    
1812
  #  if ($aoCount > 11) {
1813
  #      errMoreThanN("Additional Originators");
1814
 #   } 
1815

    
1816
    $$templateVars{'aoCount'} = $aoCount;
1817
    
1818
    dontOccur($doc, "./pubDate", "pubDate");
1819
    dontOccur($doc, "./language", "language");
1820
    dontOccur($doc, "./series", "series");
1821

    
1822
    $results = $doc->findnodes('//dataset/abstract');
1823
    if ($results->size() > 1) {
1824
        errMoreThanOne("abstract");
1825
    } else {
1826
        foreach my $node ($results->get_nodelist) {
1827
            dontOccur($node, "./section", "section");
1828
            $$templateVars{'abstract'} = findValueNoChild($node, "para");
1829
        }
1830
    }
1831

    
1832
    $results = $doc->findnodes('//dataset/keywordSet');
1833

    
1834
    my $count = 1;
1835
    foreach $node ($results->get_nodelist) {
1836
	$tempResult = $node->findnodes('./keyword');
1837
	if ($tempResult->size() > 1) {
1838
	    errMoreThanOne("keyword");
1839
	} else {
1840
	    foreach $tempNode ($tempResult->get_nodelist) {
1841
		$$templateVars{"keyword$count"} = $tempNode->textContent();
1842
		if ($tempNode->hasAttributes()) {
1843
		    my @attlist = $tempNode->attributes();
1844
                    my $tmp = $attlist[0]->value;  #convert the first letter to upper case
1845
		    $tmp =~ s/\b(\w)/\U$1/g;
1846
		    $$templateVars{"kwType$count"} = $tmp;
1847
		}  
1848
	    }
1849
	}
1850
	$$templateVars{"kwTh$count"} = findValue($node, "keywordThesaurus");
1851
        $count++;
1852
    }
1853
    $$templateVars{'keyCount'} = $count;
1854
    if($count > 0 ){
1855
       $$templateVars{'hasKeyword'} = "true";
1856
    }
1857

    
1858
    $results = $doc->findnodes('//dataset/additionalInfo');
1859
    if ($results->size() > 1) {
1860
        errMoreThanOne("additionalInfo");
1861
    } else {
1862
        foreach $node ($results->get_nodelist) {
1863
            dontOccur($node, "./section", "section");
1864
            $$templateVars{'addComments'} = findValueNoChild($node, "para");
1865
        }
1866
    }
1867

    
1868
    $$templateVars{'useConstraints'} = "";
1869
    $results = $doc->findnodes('//dataset/intellectualRights');
1870
    if ($results->size() > 1) {
1871
        errMoreThanOne("intellectualRights");
1872
    } else {
1873
        foreach $node ($results->get_nodelist) {
1874
            dontOccur($node, "./section", "section in intellectualRights");
1875

    
1876
            $tempResult = $node->findnodes("para");
1877
            if ($tempResult->size > 2) {
1878
                   errMoreThanN("para");
1879
            } else {
1880
                foreach $tempNode ($tempResult->get_nodelist) {
1881
                    my $childNodes = $tempNode->childNodes;
1882
                    if ($childNodes->size() > 1) {
1883
                        $error ="The tag para in intellectualRights has children which cannot be shown using the form. Please use Morpho to edit this document";    
1884
                        push(@errorMessages, $error);
1885
                        #if ($DEBUG == 1){ print $error."\n";}
1886
                    } else {
1887
                        #print $tempNode->nodeName().":".$tempNode->textContent();
1888
                        #print "\n";
1889
                        if ($$templateVars{'useConstraints'} eq "") {
1890
                            $$templateVars{'useConstraints'} = $tempNode->textContent();
1891
                        } else {
1892
                            $$templateVars{'useConstraintsOther'} = $tempNode->textContent();
1893
                        }
1894
                    }
1895
                }
1896
            }
1897
        }
1898
    }
1899

    
1900
    $results = $doc->findnodes('//dataset/distribution/online');
1901
    if ($results->size() > 1) {
1902
        errMoreThanOne("distribution/online");
1903
    } else {
1904
        foreach my $tempNode ($results->get_nodelist){
1905
            $$templateVars{'url'} = findValue($tempNode, "url");
1906
            dontOccur($tempNode, "./connection", "/distribution/online/connection");
1907
            dontOccur($tempNode, "./connectionDefinition", "/distribution/online/connectionDefinition");
1908
        }
1909
    }
1910

    
1911
    $results = $doc->findnodes('//dataset/distribution/offline');
1912
    if ($results->size() > 1) {
1913
        errMoreThanOne("distribution/online");
1914
    } else {
1915
        foreach my $tempNode ($results->get_nodelist) {
1916
            my $temp = findValue($tempNode, "mediumName");
1917
            if(substr($temp, 0, 5) eq "other"){
1918
                $$templateVars{'dataMedium'} = substr($temp, 0, 5);
1919
                $$templateVars{'dataMediumOther'} = substr($temp, 5);
1920
            } else {
1921
                $$templateVars{'dataMedium'} = $temp;
1922
            }
1923
            dontOccur($tempNode, "./mediumDensity", "/distribution/offline/mediumDensity");
1924
            dontOccur($tempNode, "./mediumDensityUnits", "/distribution/offline/mediumDensityUnits");
1925
            dontOccur($tempNode, "./mediumVolume", "/distribution/offline/mediumVolume");
1926
            dontOccur($tempNode, "./mediumFormat", "/distribution/offline/mediumFormat");
1927
            dontOccur($tempNode, "./mediumNote", "/distribution/offline/mediumNote");
1928
        }
1929
    }
1930

    
1931
    dontOccur($doc, "./inline", "//dataset/distribution/inline");
1932

    
1933
    $results = $doc->findnodes('//dataset/coverage');
1934
    if ($results->size() > 1) {
1935
        errMoreThanOne("coverage");
1936
    } else {
1937
        foreach $node ($results->get_nodelist) {
1938
            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");
1939

    
1940
            $tempResult = $node->findnodes('./temporalCoverage');
1941
            if ($tempResult->size > 1) {
1942
                   errMoreThanOne("temporalCoverage");
1943
            } else {
1944
                foreach $tempNode ($tempResult->get_nodelist) {
1945
                    my $x;
1946
                    my $y;
1947
                    my $z;
1948
                    my $tempdate = findValue($tempNode, "rangeOfDates/beginDate/calendarDate");
1949
                    ($x, $y, $z) = split("-", $tempdate); 
1950
                    $$templateVars{'beginningYear'} = $x;
1951
                    $$templateVars{'beginningMonth'} = $y;
1952
                    $$templateVars{'beginningDay'} = $z;
1953
    
1954
                    $tempdate = findValue($tempNode, "rangeOfDates/endDate/calendarDate");
1955
                    ($x, $y, $z) = split("-", $tempdate);
1956
                    $$templateVars{'endingYear'} = $x;
1957
                    $$templateVars{'endingMonth'} = $y;
1958
                    $$templateVars{'endingDay'} = $z;
1959

    
1960
                    $tempdate = "";
1961
                    $tempdate = findValue($tempNode, "singleDateTime/calendarDate");
1962
                    if($tempdate ne ""){
1963
                        ($x, $y, $z) = split("-", $tempdate);
1964
                        $$templateVars{'beginningYear'} = $x;
1965
                        $$templateVars{'beginningMonth'} = $y;
1966
                        $$templateVars{'beginningDay'} = $z;
1967
                    }  
1968
		    
1969
		    $$templateVars{'hasTemporal'} = "true";
1970
                }
1971
            }
1972

    
1973
            $tempResult = $node->findnodes('./geographicCoverage');
1974
            if ($tempResult->size > 1) {
1975
                errMoreThanOne("geographicCoverage");
1976
            } else {
1977
                foreach $tempNode ($tempResult->get_nodelist) {
1978
                    my $geogdesc = findValue($tempNode, "geographicDescription");
1979
                    debug("Registry: geogdesc from xml is: $geogdesc");
1980
                    $$templateVars{'geogdesc'} = $geogdesc;
1981
                    my $coord = findValue($tempNode, "boundingCoordinates/westBoundingCoordinate");
1982
                    if ($coord > 0) {
1983
                        #print "+";
1984
                        $$templateVars{'hemisphLong1'} = "E";
1985
                    } else {
1986
                        #print "-";
1987
                        eval($coord = $coord * -1);
1988
                        $$templateVars{'hemisphLong1'} = "W";
1989
                    }
1990
                    eval($$templateVars{'longDeg1'} = int($coord));
1991
                    eval($coord = ($coord - int($coord))*60);
1992
                    eval($$templateVars{'longMin1'} = int($coord));
1993
                    eval($coord = ($coord - int($coord))*60);
1994
                    eval($$templateVars{'longSec1'} = int($coord));
1995
                    
1996
                    $coord = findValue($tempNode, "boundingCoordinates/southBoundingCoordinate");
1997
                    if ($coord > 0) {
1998
                        #print "+";
1999
                        $$templateVars{'hemisphLat2'} = "N";
2000
                    } else {
2001
                        #print "-";
2002
                        eval($coord = $coord * -1);
2003
                        $$templateVars{'hemisphLat2'} = "S";
2004
                    }
2005
                    eval($$templateVars{'latDeg2'} = int($coord));
2006
                    eval($coord = ($coord - int($coord))*60);
2007
                    eval($$templateVars{'latMin2'} = int($coord));
2008
                    eval($coord = ($coord - int($coord))*60);
2009
                    eval($$templateVars{'latSec2'} = int($coord));
2010
        
2011
                    $coord = findValue($tempNode, "boundingCoordinates/northBoundingCoordinate");
2012
                    if ($coord > 0) {
2013
                        #print "+";
2014
                        $$templateVars{'hemisphLat1'} = "N";
2015
                    } else {
2016
                        #print "-";
2017
                        eval($coord = $coord * -1);
2018
                        $$templateVars{'hemisphLat1'} = "S";
2019
                    }
2020
                    eval($$templateVars{'latDeg1'} = int($coord));
2021
                    eval($coord = ($coord - int($coord))*60);
2022
                    eval($$templateVars{'latMin1'} = int($coord));
2023
                    eval($coord = ($coord - int($coord))*60);
2024
                    eval($$templateVars{'latSec1'} = int($coord));
2025
        
2026
                    $coord = findValue($tempNode, "boundingCoordinates/eastBoundingCoordinate");
2027
                    if ($coord > 0) {
2028
                        #print "+";
2029
                        $$templateVars{'hemisphLong2'} = "E";
2030
                    } else {
2031
                        #print "-";
2032
                        eval($coord = $coord * -1);
2033
                        $$templateVars{'hemisphLong2'} = "W";
2034
                    }
2035
                    eval($$templateVars{'longDeg2'} = int($coord));
2036
                    eval($coord = ($coord - int($coord))*60);
2037
                    eval($$templateVars{'longMin2'} = int($coord));
2038
                    eval($coord = ($coord - int($coord))*60);
2039
                    eval($$templateVars{'longSec2'} = int($coord));
2040

    
2041
		            $$templateVars{'hasSpatial'} = "true";
2042
                }
2043
            }
2044

    
2045
            $tempResult = $node->findnodes('./taxonomicCoverage/taxonomicClassification');
2046
            my $taxonIndex = 0;
2047
            foreach $tempNode ($tempResult->get_nodelist) {
2048
                $taxonIndex++;
2049
                my $taxonRankName = findValue($tempNode, "taxonRankName");
2050
                my $taxonRankValue = findValue($tempNode, "taxonRankValue");
2051
                $$templateVars{"taxonRankName".$taxonIndex} = $taxonRankName;
2052
                $$templateVars{"taxonRankValue".$taxonIndex} = $taxonRankValue;
2053
		
2054
		$$templateVars{'hasTaxonomic'} = "true";
2055
            }
2056
            $$templateVars{'taxaCount'} = $taxonIndex;
2057
            my $taxaAuth = findValue($node, "./taxonomicCoverage/generalTaxonomicCoverage");
2058
            $$templateVars{'taxaAuth'} = $taxaAuth;
2059
        }
2060
    }
2061
    dontOccur($doc, "./purpose", "purpose");
2062
    dontOccur($doc, "./maintenance", "maintnance");
2063

    
2064
    $results = $doc->findnodes('//dataset/contact/individualName');
2065
    if ($results->size() > 1) {
2066
        errMoreThanOne("contact/individualName");
2067
    } else {
2068
        foreach $node ($results->get_nodelist) {
2069
            dontOccur($node, "../positionName|../onlineURL|../userId", 
2070
              "positionName, onlineURL, userId in contact tag");
2071
            dontOccur($node, "./saluation", "saluation in contact tag");                
2072
        
2073
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
2074
            if ($tempResult->size > 0) {
2075
                $$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
2076
                $$templateVars{'origNamelastContact'} = findValue($node, 'surName');
2077
    
2078
                my $tempResult2 = $node->findnodes('../address');
2079
                if ($tempResult2->size > 1) {
2080
                    errMoreThanOne("address");
2081
                } else {
2082
                    foreach my $tempNode2 ($tempResult2->get_nodelist) {
2083
                        $$templateVars{'origDeliveryContact'} = findValue($tempNode2, 'deliveryPoint');
2084
                        $$templateVars{'origCityContact'} = findValue($tempNode2, 'city');
2085
                        $$templateVars{'origStateContact'} = findValue($tempNode2, 'administrativeArea');
2086
                        $$templateVars{'origZIPContact'} = findValue($tempNode2, 'postalCode');
2087
                        $$templateVars{'origCountryContact'} = findValue($tempNode2, 'country');
2088
                    }
2089
                }
2090
            
2091
                my $tempResult3 = $node->findnodes('../phone');
2092
                if ($tempResult3->size > 2) {
2093
                    errMoreThanN("phone");
2094
                } else {
2095
                    foreach my $tempNode2 ($tempResult3->get_nodelist) {
2096
                        if ($tempNode2->hasAttributes()) {
2097
                            my @attlist = $tempNode2->attributes();
2098
                            if ($attlist[0]->value eq "Fax") {
2099
                                $$templateVars{'origFAXContact'} = $tempNode2->textContent();
2100
                            } else {
2101
                                $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
2102
                            }
2103
                        } else {
2104
                            $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
2105
                        }
2106
                    }
2107
                }
2108
                $$templateVars{'origEmailContact'} = findValue($node, '../electronicMailAddress');
2109
                $$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
2110
            } else {
2111
                $$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
2112
                $$templateVars{'origNamelastContact'} = findValue($node, 'surName');
2113
                $$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
2114
            }
2115
        }
2116
    }
2117
    
2118
    $results = $doc->findnodes(
2119
            '//dataset/methods/methodStep/description/section');
2120
    debug("Registry: Number methods: ".$results->size());
2121
    if ($results->size() > 1) {
2122
        errMoreThanN("methods/methodStep/description/section");    
2123
    } else {
2124

    
2125
        my @methodPara;
2126
        foreach $node ($results->get_nodelist) {
2127
            my @children = $node->childNodes;
2128
            for (my $i = 0; $i < scalar(@children); $i++) {
2129
                debug("Registry: Method child loop ($i)");
2130
                my $child = $children[$i];
2131
                if ($child->nodeName eq 'title') {
2132
                    my $title = $child->textContent();
2133
                    debug("Registry: Method title ($title)");
2134
                    $$templateVars{'methodTitle'} = $title;
2135
                } elsif ($child->nodeName eq 'para') {
2136
                    my $para = $child->textContent();
2137
                    debug("Registry: Method para ($para)");
2138
                    $methodPara[scalar(@methodPara)] = $para;
2139
                }
2140
            }
2141
	    $$templateVars{'hasMethod'} = "true";
2142
        }
2143
        if (scalar(@methodPara) > 0) {
2144
            $$templateVars{'methodPara'} = \@methodPara;
2145
        }
2146
    }
2147

    
2148
    $results = $doc->findnodes(
2149
            '//dataset/methods/sampling/studyExtent/description/para');
2150
    if ($results->size() > 1) {
2151
        errMoreThanN("methods/sampling/studyExtent/description/para");    
2152
    } else {
2153
        foreach $node ($results->get_nodelist) {
2154
            my $studyExtentDescription = $node->textContent();
2155
            $$templateVars{'studyExtentDescription'} = $studyExtentDescription;
2156

    
2157
	    $$templateVars{'hasMethod'} = "true";
2158
        }
2159
    }
2160

    
2161
    $results = $doc->findnodes(
2162
            '//dataset/methods/sampling/samplingDescription/para');
2163
    if ($results->size() > 1) {
2164
        errMoreThanN("methods/sampling/samplingDescription/para");    
2165
    } else {
2166
        foreach $node ($results->get_nodelist) {
2167
            my $samplingDescription = $node->textContent();
2168
            $$templateVars{'samplingDescription'} = $samplingDescription;
2169

    
2170
	    $$templateVars{'hasMethod'} = "true";
2171
        }
2172
    }
2173

    
2174
    dontOccur($doc, "//methodStep/citation", "methodStep/citation");
2175
    dontOccur($doc, "//methodStep/protocol", "methodStep/protocol");
2176
    dontOccur($doc, "//methodStep/instrumentation", "methodStep/instrumentation");
2177
    dontOccur($doc, "//methodStep/software", "methodStep/software");
2178
    dontOccur($doc, "//methodStep/subStep", "methodStep/subStep");
2179
    dontOccur($doc, "//methodStep/dataSource", "methodStep/dataSource");
2180
    dontOccur($doc, "//methods/qualityControl", "methods/qualityControl");
2181

    
2182
    dontOccur($doc, "//methods/sampling/spatialSamplingUnits", "methods/sampling/spatialSamplingUnits");
2183
    dontOccur($doc, "//methods/sampling/citation", "methods/sampling/citation");
2184
    dontOccur($doc, "./pubPlace", "pubPlace");
2185
    dontOccur($doc, "./project", "project");
2186
    
2187
    ############ Code for checking ACL #####################
2188
    dontOccur($doc, "//dataset/access/deny", "dataset/access/deny");
2189

    
2190
    $results = $doc->findnodes('//dataset/access/allow');
2191
    if ($results->size() != 3) {
2192
        errMoreThanN("dataset/access/allow");
2193
    } else {
2194
	my $accessError = 0;
2195
        foreach $node ($results->get_nodelist) {
2196
            my @children = $node->childNodes;
2197
	    my $principal = "";
2198
	    my $permission = "";
2199
            for (my $i = 0; $i < scalar(@children); $i++) {
2200
                my $child = $children[$i];
2201
                if ($child->nodeName eq 'principal') {
2202
                    $principal = $child->textContent();
2203
                } elsif ($child->nodeName eq 'permission') {
2204
                    $permission = $child->textContent();
2205
                }
2206
            }
2207
	
2208
	    if ($principal eq 'public' && $permission ne 'read') { $accessError = 1; }
2209
	    if ($principal eq $username && $permission ne 'all') { $accessError = 2; }
2210
	    if ($principal ne 'public' && $principal ne $username && $permission ne 'all') { $accessError = 3; }
2211
	}
2212
 
2213
	if ($accessError != 0) {
2214
	    my $error ="The ACL for this document has been changed outside the registry. Please use Morpho to edit this document";
2215
            push(@errorMessages, $error."\n");
2216
	}     
2217
    }
2218
    ########################################################
2219

    
2220

    
2221
    dontOccur($doc, "./dataTable", "dataTable");
2222
    dontOccur($doc, "./spatialRaster", "spatialRaster");
2223
    dontOccur($doc, "./spatialVector", "spatialVector");
2224
    dontOccur($doc, "./storedProcedure", "storedProcedure");
2225
    dontOccur($doc, "./view", "view");
2226
    dontOccur($doc, "./otherEntity", "otherEntity");
2227
    dontOccur($doc, "./references", "references");
2228
    
2229
    dontOccur($doc, "//citation", "citation");
2230
    dontOccur($doc, "//software", "software");
2231
    dontOccur($doc, "//protocol", "protocol");
2232
    dontOccur($doc, "//additionalMetadata", "additionalMetadata");    
2233
}
2234

    
2235
################################################################################
2236
# 
2237
# Delete the eml file that has been requested for deletion. 
2238
#
2239
################################################################################
2240
sub deleteData {
2241
    my $deleteAll = shift;
2242
    
2243
    # create metacat instance
2244
    my $metacat;
2245
    my $docid = $FORM::docid;
2246
    
2247
    $metacat = Metacat->new();
2248
    if ($metacat) {
2249
        $metacat->set_options( metacatUrl => $metacatUrl );
2250
    } else {
2251
        #die "failed during metacat creation\n";
2252
        push(@errorMessages, "Failed during metacat creation.");
2253
    }
2254

    
2255
    # Login to metacat
2256
    my $userDN = $FORM::username;
2257
    my $userOrg = $FORM::organization;
2258
    my $userPass = $FORM::password;
2259
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
2260
    
2261
    my $errorMessage = "";
2262
    my $response = $metacat->login($dname, $userPass);
2263

    
2264
    if (! $response) {
2265
    # Could not login
2266
        push(@errorMessages, $metacat->getMessage());
2267
        push(@errorMessages, "Failed during login.\n");
2268

    
2269
    } else {
2270
    #Able to login - try to delete the file    
2271

    
2272
    my $parser;
2273
    my @fileArray;
2274
    my $httpMessage;
2275
    my $xmldoc;
2276
    my $doc;
2277
    my $pushDoc;
2278
    my $alreadyInArray;
2279
    my $findType;
2280
        my $node;
2281
    my $response; 
2282
    my $element;
2283

    
2284
    push (@fileArray, $docid);
2285
    $parser = XML::LibXML->new();
2286

    
2287
        $httpMessage = $metacat->read($docid);
2288
    $doc = $httpMessage->content();    
2289
    $doc = delNormalize($doc);
2290
    $xmldoc = $parser->parse_string($doc);
2291

    
2292
    if ($xmldoc eq "") {
2293
        $error ="Error in parsing the eml document";
2294
        push(@errorMessages, $error);
2295
    } else {
2296

    
2297
        $findType = $xmldoc->findnodes('//dataset/identifier');
2298
        if($findType->size() > 0){
2299
        # This is a eml beta6 document
2300
        # Delete the documents mentioned in triples also
2301
        
2302
        $findType = $xmldoc->findnodes('//dataset/triple');
2303
        if($findType->size() > 0){
2304
            foreach $node ($findType->get_nodelist){
2305
            $pushDoc = findValue($node, 'subject');
2306
            
2307
            # If the file is already in the @fileArray then do not add it 
2308
            $alreadyInArray = 0;
2309
            foreach $element (@fileArray){
2310
                if($element eq $pushDoc){
2311
                $alreadyInArray = 1;
2312
                }
2313
            }
2314
            
2315
            if(!$alreadyInArray){
2316
                # If not already in array then delete the file. 
2317
                push (@fileArray, $pushDoc);
2318
                $response = $metacat->delete($pushDoc);
2319
                
2320
                if (! $response) {
2321
                # Could not delete
2322
                #push(@errorMessages, $response);
2323
                push(@errorMessages, $metacat->getMessage());
2324
                push(@errorMessages, "Failed during deleting $pushDoc. Please check if you are authorized to delete this document.\n");
2325
                }
2326
            }
2327
            }
2328
        }
2329
        }
2330
    }
2331
    
2332
    # Delete the main document. 
2333
    if($deleteAll){
2334
        $response = $metacat->delete($docid);  
2335
        if (! $response) {
2336
        # Could not delete
2337
        #push(@errorMessages, $response);
2338
        push(@errorMessages, $metacat->getMessage());
2339
        push(@errorMessages, "Failed during deleting $docid. Please check if you are authorized to delete this document.\n");
2340
        }
2341
    }
2342
    }
2343
    
2344
    if (scalar(@errorMessages)) {
2345
    # If any errors, print them in the response template 
2346
    $$templateVars{'status'} = 'failure';
2347
    $$templateVars{'errorMessages'} = \@errorMessages;
2348
    $error = 1;
2349
    }
2350
    
2351
    # Process the response template
2352
    if($deleteAll){
2353

    
2354
    $$templateVars{'function'} = "deleted";
2355
    $$templateVars{'section'} = "Deletion Status";
2356
    $template->process( $responseTemplate, $templateVars);
2357
    }
2358
}
2359

    
2360

    
2361
################################################################################
2362
# 
2363
# Do data validation and send the data to confirm data template.
2364
#
2365
################################################################################
2366
sub toConfirmData{
2367
    # Check if any invalid parameters
2368
 
2369
    my $invalidParams;
2370
    if (! $error) {
2371
    $invalidParams = validateParameters(0);
2372
    if (scalar(@$invalidParams)) {
2373
        $$templateVars{'status'} = 'failure';
2374
        $$templateVars{'invalidParams'} = $invalidParams;
2375
        $error = 1;
2376
    }
2377
    }
2378

    
2379

    
2380
    $$templateVars{'providerGivenName'} = normalizeCD($FORM::providerGivenName);
2381
    $$templateVars{'providerSurName'} = normalizeCD($FORM::providerSurName);
2382
    if($FORM::site eq "Select your station here."){
2383
        $$templateVars{'site'} = "";
2384
    }else{
2385
        $$templateVars{'site'} = $FORM::site;
2386
    }
2387
    if($FORM::cfg eq "nceas"){
2388
        $$templateVars{'wg'} = \@FORM::wg;
2389
    }
2390
    $$templateVars{'identifier'} = normalizeCD($FORM::identifier);
2391
    $$templateVars{'title'} = normalizeCD($FORM::title);
2392
    $$templateVars{'origNamefirst0'} = normalizeCD($FORM::origNamefirst0);
2393
    $$templateVars{'origNamelast0'} = normalizeCD($FORM::origNamelast0);
2394
    $$templateVars{'origNameOrg'} = normalizeCD($FORM::origNameOrg);
2395
    # $$templateVars{'origRole0'} = $FORM::origRole0;
2396
    $$templateVars{'origDelivery'} = normalizeCD($FORM::origDelivery);
2397
    $$templateVars{'origCity'} = normalizeCD($FORM::origCity);
2398
    if($FORM::origState eq "Select State Here."){
2399
        $$templateVars{'origState'} = "";
2400
    }else{
2401
        $$templateVars{'origState'} = $FORM::origState;
2402
    }
2403
    $$templateVars{'origStateOther'} = normalizeCD($FORM::origStateOther);
2404
    $$templateVars{'origZIP'} = normalizeCD($FORM::origZIP);
2405
    $$templateVars{'origCountry'} = normalizeCD($FORM::origCountry);
2406
    $$templateVars{'origPhone'} = normalizeCD($FORM::origPhone);
2407
    $$templateVars{'origFAX'} = normalizeCD($FORM::origFAX);
2408
    $$templateVars{'origEmail'} = normalizeCD($FORM::origEmail);
2409
    $$templateVars{'useOrigAddress'} = normalizeCD($FORM::useOrigAddress);
2410
    if($FORM::useOrigAddress eq "on"){
2411
        $$templateVars{'origNamefirstContact'} = normalizeCD($FORM::origNamefirst0);
2412
        $$templateVars{'origNamelastContact'} = normalizeCD($FORM::origNamelast0);
2413
        $$templateVars{'origNameOrgContact'} = normalizeCD($FORM::origNameOrg);
2414
        $$templateVars{'origDeliveryContact'} = normalizeCD($FORM::origDelivery); 
2415
        $$templateVars{'origCityContact'} = normalizeCD($FORM::origCity);
2416
        if($FORM::origState eq "Select State Here."){
2417
        $$templateVars{'origStateContact'} = "";
2418
        }else{
2419
        $$templateVars{'origStateContact'} = $FORM::origState;
2420
        }
2421
        $$templateVars{'origStateOtherContact'} = normalizeCD($FORM::origStateOther);
2422
        $$templateVars{'origZIPContact'} = normalizeCD($FORM::origZIP);
2423
        $$templateVars{'origCountryContact'} = normalizeCD($FORM::origCountry);
2424
        $$templateVars{'origPhoneContact'} = normalizeCD($FORM::origPhone);
2425
        $$templateVars{'origFAXContact'} = normalizeCD($FORM::origFAX);
2426
        $$templateVars{'origEmailContact'} = normalizeCD($FORM::origEmail);
2427
    }else{
2428
        $$templateVars{'origNamefirstContact'} = normalizeCD($FORM::origNamefirstContact);
2429
        $$templateVars{'origNamelastContact'} = normalizeCD($FORM::origNamelastContact);
2430
        $$templateVars{'origNameOrgContact'} = normalizeCD($FORM::origNameOrgContact);
2431
        $$templateVars{'origDeliveryContact'} = normalizeCD($FORM::origDeliveryContact); 
2432
        $$templateVars{'origCityContact'} = normalizeCD($FORM::origCityContact);
2433
        if($FORM::origStateContact eq "Select State Here."){
2434
        $$templateVars{'origStateContact'} = "";
2435
        }else{
2436
        $$templateVars{'origStateContact'} = $FORM::origStateContact;
2437
        }
2438
        $$templateVars{'origStateOtherContact'} = normalizeCD($FORM::origStateOtherContact);
2439
        $$templateVars{'origZIPContact'} = normalizeCD($FORM::origZIPContact);
2440
        $$templateVars{'origCountryContact'} = normalizeCD($FORM::origCountryContact);
2441
        $$templateVars{'origPhoneContact'} = normalizeCD($FORM::origPhoneContact);
2442
        $$templateVars{'origFAXContact'} = normalizeCD($FORM::origFAXContact);
2443
        $$templateVars{'origEmailContact'} = normalizeCD($FORM::origEmailContact);    
2444
    }
2445

    
2446
    my $aoFNArray = \@FORM::aoFirstName;
2447
    my $aoLNArray = \@FORM::aoLastName;
2448
    my $aoRoleArray = \@FORM::aoRole;
2449
    my $aoCount = 1;
2450

    
2451
    for(my $i = 0; $i <= $#$aoRoleArray; $i++){
2452
        if (hasContent($aoFNArray->[$i]) && hasContent($aoLNArray->[$i])) {
2453
            debug("Registry processing Associated Party: origName = ".$aoFNArray->[$i]
2454
                  ." origNamelast = ".$aoLNArray->[$i]." origRole = "
2455
                  .$aoRoleArray->[$i]);
2456
            $$templateVars{"origNamefirst".$aoCount} = normalizeCD($aoFNArray->[$i]);
2457
            $$templateVars{"origNamelast".$aoCount} = normalizeCD($aoLNArray->[$i]);
2458
            $$templateVars{"origRole".$aoCount} = normalizeCD($aoRoleArray->[$i]);
2459
            $aoCount++;
2460
	}    
2461
    }
2462

    
2463
    $$templateVars{'aoCount'} = $aoCount;
2464
    $$templateVars{'abstract'} = normalizeCD($FORM::abstract);
2465
   
2466
   
2467
    my $keywordArray = \@FORM::keyword;
2468
    my $keywordTypeArray = \@FORM::keywordType;
2469
    my $keywordThArray = \@FORM::keywordTh;
2470
    my $keyCount = 1;
2471
   
2472
    for(my $i = 0; $i <= $#$keywordArray; $i++){
2473
        if (hasContent($keywordArray->[$i])) {
2474
            debug("Registry processing keyword: keyword = ".$keywordArray->[$i]."
2475
                  keywordType = ".$keywordTypeArray->[$i]."
2476
                  keywordTh = ".$keywordThArray->[$i]);
2477
            $$templateVars{"keyword".$keyCount} = normalizeCD($keywordArray->[$i]);
2478
            $$templateVars{"kwType".$keyCount} = normalizeCD($keywordTypeArray->[$i]);
2479
            $$templateVars{"kwTh".$keyCount} = normalizeCD($keywordThArray->[$i]);
2480
            $keyCount++;
2481
	}    
2482
    }    
2483
    $$templateVars{'keyCount'} = $keyCount;
2484
    
2485
    $$templateVars{'addComments'} = normalizeCD($FORM::addComments);
2486
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2487
    if($FORM::useConstraints eq "other"){
2488
        $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2489
    }
2490
    $$templateVars{'url'} = $FORM::url;
2491
    $$templateVars{'dataMedium'} = $FORM::dataMedium;
2492
    if($FORM::dataMedium eq "other"){
2493
        $$templateVars{'dataMediumOther'} = normalizeCD($FORM::dataMediumOther);
2494
    }
2495
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2496
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2497
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2498
    $$templateVars{'endingYear'} = $FORM::endingYear;
2499
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2500
    $$templateVars{'endingDay'} = $FORM::endingDay;
2501
    $$templateVars{'geogdesc'} = normalizeCD($FORM::geogdesc);
2502
    $$templateVars{'useSiteCoord'} = $FORM::useSiteCoord;
2503
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2504
    $$templateVars{'latMin1'} = $FORM::latMin1;
2505
    $$templateVars{'latSec1'} = $FORM::latSec1;
2506
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2507
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2508
    $$templateVars{'longMin1'} = $FORM::longMin1;
2509
    $$templateVars{'longSec1'} = $FORM::longSec1;
2510
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2511
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2512
    $$templateVars{'latMin2'} = $FORM::latMin2;
2513
    $$templateVars{'latSec2'} = $FORM::latSec2;
2514
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2515
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2516
    $$templateVars{'longMin2'} = $FORM::longMin2;
2517
    $$templateVars{'longSec2'} = $FORM::longSec2;
2518
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2519

    
2520
    my $taxonRankArray = \@FORM::taxonRank;
2521
    my $taxonNameArray = \@FORM::taxonName;
2522
    my $taxonCount = 1;
2523

    
2524
    for(my $i = 0; $i <= $#$taxonNameArray; $i++){
2525
        if (hasContent($taxonRankArray->[$i]) && hasContent($taxonNameArray->[$i])) {
2526
            debug("Registry processing keyword: trv = ".$taxonRankArray->[$i]
2527
                    ." trn = ".$taxonNameArray->[$i]);
2528
            $$templateVars{"taxonRankName".$taxonCount} = normalizeCD($taxonNameArray->[$i]);
2529
            $$templateVars{"taxonRankValue".$taxonCount} = normalizeCD($taxonRankArray->[$i]);
2530
            $taxonCount++;
2531
	}    
2532
    }
2533

    
2534
    $$templateVars{'taxaCount'} = $taxonCount-1;
2535
    $$templateVars{'taxaAuth'} = normalizeCD($FORM::taxaAuth);
2536

    
2537
    $$templateVars{'methodTitle'} = normalizeCD($FORM::methodTitle);
2538
 
2539
    my @tempMethodPara;
2540
    for (my $i = 0; $i < scalar(@FORM::methodPara); $i++) {
2541
	$tempMethodPara[$i] = normalizeCD($FORM::methodPara[$i]);
2542
    }
2543
    $$templateVars{'methodPara'} = \@tempMethodPara;
2544
    $$templateVars{'studyExtentDescription'} = normalizeCD($FORM::studyExtentDescription);
2545
    $$templateVars{'samplingDescription'} = normalizeCD($FORM::samplingDescription);
2546
    $$templateVars{'origStateContact'} = $FORM::origState;
2547

    
2548
    $$templateVars{'showSiteList'} = $FORM::showSiteList;
2549
    $$templateVars{'lsite'} = $FORM::lsite;
2550
    $$templateVars{'usite'} = $FORM::usite;
2551
    $$templateVars{'showWgList'} = $FORM::showWgList;
2552
    $$templateVars{'showOrganization'} = $FORM::showOrganization;
2553
    $$templateVars{'hasKeyword'} = $FORM::hasKeyword;
2554
    $$templateVars{'hasTemporal'} = $FORM::hasTemporal;
2555
    $$templateVars{'hasSpatial'} = $FORM::hasSpatial;
2556
    $$templateVars{'hasTaxonomic'} = $FORM::hasTaxonomic;
2557
    $$templateVars{'hasMethod'} = $FORM::hasMethod;
2558
    $$templateVars{'spatialRequired'} = $FORM::spatialRequired;
2559
    $$templateVars{'temporalRequired'} = $FORM::temporalRequired;
2560

    
2561
    $$templateVars{'docid'} = $FORM::docid;
2562

    
2563
    if (! $error) {
2564
	# If no errors, then print out data in confirm Data template
2565

    
2566
	$$templateVars{'section'} = "Confirm Data";
2567
	$template->process( $confirmDataTemplate, $templateVars);
2568

    
2569
    } else{    
2570
    # Errors from validation function. print the errors out using the response template
2571
    if (scalar(@errorMessages)) {
2572
        $$templateVars{'status'} = 'failure';
2573
        $$templateVars{'errorMessages'} = \@errorMessages;
2574
        $error = 1;
2575
    }
2576
        # Create our HTML response and send it back
2577
    $$templateVars{'function'} = "submitted";
2578
    $$templateVars{'section'} = "Submission Status";
2579
    $template->process( $responseTemplate, $templateVars);
2580
    }
2581
}
2582

    
2583

    
2584
################################################################################
2585
# 
2586
# From confirm Data template - user wants to make some changes.
2587
#
2588
################################################################################
2589
sub confirmDataToReEntryData{
2590
    my @sortedSites;
2591
    foreach my $site (sort @sitelist) {
2592
        push(@sortedSites, $site);
2593
    }
2594

    
2595
    $$templateVars{'siteList'} = \@sortedSites;
2596
    $$templateVars{'section'} = "Re-Entry Form";
2597
    copyFormToTemplateVars();
2598
    $$templateVars{'docid'} = $FORM::docid;
2599

    
2600
    $$templateVars{'form'} = 're_entry';
2601
    $template->process( $entryFormTemplate, $templateVars);
2602
}
2603

    
2604

    
2605
################################################################################
2606
# 
2607
# Copy form data to templateVars.....
2608
#
2609
################################################################################
2610
sub copyFormToTemplateVars{
2611
    $$templateVars{'providerGivenName'} = $FORM::providerGivenName;
2612
    $$templateVars{'providerSurName'} = $FORM::providerSurName;
2613
    $$templateVars{'site'} = $FORM::site;
2614
    if ($FORM::cfg eq "nceas") {
2615
        my $projects = getProjectList();
2616
        $$templateVars{'projects'} = $projects;
2617
        $$templateVars{'wg'} = \@FORM::wg;
2618
    }
2619
    $$templateVars{'identifier'} = $FORM::identifier;
2620
    $$templateVars{'title'} = $FORM::title;
2621
    $$templateVars{'origNamefirst0'} = $FORM::origNamefirst0;
2622
    $$templateVars{'origNamelast0'} = $FORM::origNamelast0;
2623
    $$templateVars{'origNameOrg'} = $FORM::origNameOrg;
2624
 #   $$templateVars{'origRole0'} = $FORM::origRole0;
2625
    $$templateVars{'origDelivery'} = $FORM::origDelivery;
2626
    $$templateVars{'origCity'} = $FORM::origCity;
2627
    $$templateVars{'origState'} = $FORM::origState;
2628
    $$templateVars{'origStateOther'} = $FORM::origStateOther;
2629
    $$templateVars{'origZIP'} = $FORM::origZIP;
2630
    $$templateVars{'origCountry'} = $FORM::origCountry;
2631
    $$templateVars{'origPhone'} = $FORM::origPhone;
2632
    $$templateVars{'origFAX'} = $FORM::origFAX;
2633
    $$templateVars{'origEmail'} = $FORM::origEmail;
2634
    if ($FORM::useSiteCoord ne "") {
2635
        $$templateVars{'useOrigAddress'} = "CHECKED";
2636
    }else{
2637
        $$templateVars{'useOrigAddress'} = $FORM::useOrigAddress;
2638
    }
2639
    $$templateVars{'origNamefirstContact'} = $FORM::origNamefirstContact;
2640
    $$templateVars{'origNamelastContact'} = $FORM::origNamelastContact;
2641
    $$templateVars{'origNameOrgContact'} = $FORM::origNameOrgContact;
2642
    $$templateVars{'origDeliveryContact'} = $FORM::origDeliveryContact; 
2643
    $$templateVars{'origCityContact'} = $FORM::origCityContact;
2644
    $$templateVars{'origStateContact'} = $FORM::origStateContact;
2645
    $$templateVars{'origStateOtherContact'} = $FORM::origStateOtherContact;
2646
    $$templateVars{'origZIPContact'} = $FORM::origZIPContact;
2647
    $$templateVars{'origCountryContact'} = $FORM::origCountryContact;
2648
    $$templateVars{'origPhoneContact'} = $FORM::origPhoneContact;
2649
    $$templateVars{'origFAXContact'} = $FORM::origFAXContact;
2650
    $$templateVars{'origEmailContact'} = $FORM::origEmailContact;    
2651
    
2652
    $$templateVars{'aoCount'} = $FORM::aoCount;
2653
    foreach my $origName (param()) {
2654
	if ($origName =~ /origNamefirst/) {
2655
	    my $origNameIndex = $origName;
2656
	    $origNameIndex =~ s/origNamefirst//; # get the index of the parameter 0, ..., 10
2657
	    my $origNamelast = "origNamelast".$origNameIndex;
2658
	    my $origRole = "origRole".$origNameIndex;
2659
	    if ( $origNameIndex =~ /[0-9]/  && $origNameIndex > 0){
2660
		if (hasContent(param($origName)) && hasContent(param($origNamelast)) && hasContent(param($origRole))) {
2661
		    debug("Registry processing keyword: $origName = ".param($origName)." $origNamelast = ".param($origNamelast)." $origRole = ".param($origRole));
2662
		    $$templateVars{$origName} = normalizeCD(param($origName));
2663
		    $$templateVars{$origNamelast} = normalizeCD(param($origNamelast));
2664
		    $$templateVars{$origRole} = normalizeCD(param($origRole));
2665
		}
2666
	    }
2667
	}
2668
    }
2669

    
2670
    $$templateVars{'abstract'} = $FORM::abstract;
2671
    $$templateVars{'keyCount'} = $FORM::keyCount;
2672
    foreach my $kyd (param()) {
2673
	if ($kyd =~ /keyword/) {
2674
	    my $keyIndex = $kyd;
2675
	    $keyIndex =~ s/keyword//; # get the index of the parameter 0, ..., 10
2676
	    my $keyType = "kwType".$keyIndex;
2677
	    my $keyTh = "kwTh".$keyIndex;
2678
	    if ( $keyIndex =~ /[0-9]/ ){
2679
		if (hasContent(param($kyd)) && hasContent(param($keyType)) && hasContent(param($keyTh))) {
2680
		    debug("Registry processing keyword: $kyd = ".param($kyd)." $keyType = ".param($keyType)." $keyTh = ".param($keyTh));
2681
		    $$templateVars{$kyd} = param($kyd); 
2682
                    my $tmp = param($keyType);  #convert the first letter to upper case
2683
		    $tmp =~ s/\b(\w)/\U$1/g;
2684
                    $$templateVars{$keyType} = $tmp;
2685
		    $$templateVars{$keyTh} = param($keyTh);
2686
		}
2687
	    }
2688
	}
2689
    }
2690
    $$templateVars{'addComments'} = $FORM::addComments;
2691
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2692
    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2693
    $$templateVars{'url'} = $FORM::url;
2694
    $$templateVars{'dataMedium'} = $FORM::dataMedium;
2695
    $$templateVars{'dataMediumOther'} = $FORM::dataMediumOther;
2696
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2697
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2698
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2699
    $$templateVars{'endingYear'} = $FORM::endingYear;
2700
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2701
    $$templateVars{'endingDay'} = $FORM::endingDay;
2702
    $$templateVars{'geogdesc'} = $FORM::geogdesc;
2703
    if($FORM::useSiteCoord ne ""){
2704
    $$templateVars{'useSiteCoord'} = "CHECKED";
2705
    }else{
2706
    $$templateVars{'useSiteCoord'} = "";
2707
    }
2708
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2709
    $$templateVars{'latMin1'} = $FORM::latMin1;
2710
    $$templateVars{'latSec1'} = $FORM::latSec1;
2711
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2712
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2713
    $$templateVars{'longMin1'} = $FORM::longMin1;
2714
    $$templateVars{'longSec1'} = $FORM::longSec1;
2715
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2716
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2717
    $$templateVars{'latMin2'} = $FORM::latMin2;
2718
    $$templateVars{'latSec2'} = $FORM::latSec2;
2719
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2720
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2721
    $$templateVars{'longMin2'} = $FORM::longMin2;
2722
    $$templateVars{'longSec2'} = $FORM::longSec2;
2723
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2724
    $$templateVars{'taxaCount'} = $FORM::taxaCount;
2725
    foreach my $trn (param()) {
2726
        if ($trn =~ /taxonRankName/) {
2727
            my $taxIndex = $trn;
2728
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
2729
            my $trv = "taxonRankValue".$taxIndex;
2730
            if ( $taxIndex =~ /[0-9]/ ){
2731
                if (hasContent(param($trn)) && hasContent(param($trv))) {
2732
                    debug("Registry processing taxon: $trn = ".param($trn)." $trv = ".param($trv));
2733
                    $$templateVars{$trn} = param($trn);
2734
                    $$templateVars{$trv} = param($trv);
2735
                }
2736
            }
2737
        }
2738
    }
2739
    $$templateVars{'taxaAuth'} = $FORM::taxaAuth;
2740
    $$templateVars{'methodTitle'} = $FORM::methodTitle;
2741
    $$templateVars{'methodPara'} = \@FORM::methodPara;
2742
    $$templateVars{'studyExtentDescription'} = $FORM::studyExtentDescription;
2743
    $$templateVars{'samplingDescription'} = $FORM::samplingDescription;
2744
    
2745
    $$templateVars{'showSiteList'} = $FORM::showSiteList;
2746
    $$templateVars{'lsite'} = $FORM::lsite;
2747
    $$templateVars{'usite'} = $FORM::usite;
2748
    $$templateVars{'showWgList'} = $FORM::showWgList;
2749
    $$templateVars{'showOrganization'} = $FORM::showOrganization;
2750
    $$templateVars{'hasKeyword'} = $FORM::hasKeyword;
2751
    $$templateVars{'hasTemporal'} = $FORM::hasTemporal;
2752
    $$templateVars{'hasSpatial'} = $FORM::hasSpatial;
2753
    $$templateVars{'hasTaxonomic'} = $FORM::hasTaxonomic;
2754
    $$templateVars{'hasMethod'} = $FORM::hasMethod;
2755
    $$templateVars{'spatialRequired'} = $FORM::spatialRequired;
2756
    $$templateVars{'temporalRequired'} = $FORM::temporalRequired;
2757
}
2758

    
2759
################################################################################
2760
# 
2761
# check if there is multiple occurence of the given tag and find its value.
2762
#
2763
################################################################################
2764

    
2765
sub findValue {
2766
    my $node = shift;
2767
    my $value = shift;
2768
    my $result;
2769
    my $tempNode;
2770

    
2771
    $result = $node->findnodes("./$value");
2772
    if ($result->size > 1) {
2773
        errMoreThanOne("$value");
2774
    } else {
2775
        foreach $tempNode ($result->get_nodelist){
2776
            #print $tempNode->nodeName().":".$tempNode->textContent();
2777
            #print "\n";
2778
            return $tempNode->textContent();
2779
        }
2780
    }
2781
}
2782

    
2783

    
2784
################################################################################
2785
# 
2786
# check if given tags has any children. if not return the value
2787
#
2788
################################################################################
2789
sub findValueNoChild {
2790
    my $node = shift;
2791
    my $value = shift;
2792
    my $tempNode;
2793
    my $childNodes;
2794
    my $result;
2795
    my $error;
2796

    
2797
    $result = $node->findnodes("./$value");
2798
    if($result->size > 1){
2799
       errMoreThanOne("$value");
2800
    } else {
2801
        foreach $tempNode ($result->get_nodelist) {
2802
            $childNodes = $tempNode->childNodes;
2803
            if ($childNodes->size() > 1) {
2804
                $error ="The tag $value has children which cannot be shown using the form. Please use Morpho to edit this document";    
2805
                push(@errorMessages, $error);
2806
                #if ($DEBUG == 1){ print $error."\n";}
2807
            } else {
2808
                #print $tempNode->nodeName().":".$tempNode->textContent();
2809
                #print "\n";
2810
                return $tempNode->textContent();
2811
            }
2812
        }
2813
    }
2814
}
2815

    
2816

    
2817
################################################################################
2818
# 
2819
# check if given tags are children of given node.
2820
#
2821
################################################################################
2822
sub dontOccur {
2823
    my $node = shift;
2824
    my $value = shift;
2825
    my $errVal = shift;
2826

    
2827
    my $result = $node->findnodes("$value");
2828
    if($result->size > 0){
2829
        $error ="One of the following tags found: $errVal. Please use Morpho to edit this document";
2830
        push(@errorMessages, $error."\n");
2831
        #if ($DEBUG == 1){ print $error;}
2832
    } 
2833
}
2834

    
2835

    
2836
################################################################################
2837
# 
2838
# print out error for more than one occurence of a given tag
2839
#
2840
################################################################################
2841
sub errMoreThanOne {
2842
    my $value = shift;
2843
    my $error ="More than one occurence of the tag $value found. Please use Morpho to edit this document";
2844
    push(@errorMessages, $error."\n");
2845
    # if ($DEBUG == 1){ print $error;}
2846
}
2847

    
2848

    
2849
################################################################################
2850
# 
2851
# print out error for more than given number of occurences of a given tag
2852
#
2853
################################################################################
2854
sub errMoreThanN {
2855
    my $value = shift;
2856
    my $error ="More occurences of the tag $value found than that can be shown in the form. Please use Morpho to edit this document";
2857
    push(@errorMessages, $error);
2858
    #if ($DEBUG == 1){ print $error."\n";}
2859
}
2860

    
2861

    
2862
################################################################################
2863
# 
2864
# convert coord to degrees, minutes and seconds form. 
2865
#
2866
################################################################################
2867
#sub convertCoord {
2868
#    my $wx = shift;
2869
#    print $deg." ".$min." ".$sec;
2870
#    print "\n";
2871
#}
2872

    
2873

    
2874
################################################################################
2875
# 
2876
# print debugging messages to stderr
2877
#
2878
################################################################################
2879
sub debug {
2880
    my $msg = shift;
2881
    
2882
    if ($debug) {
2883
        print STDERR "$msg\n";
2884
    }
2885
}
2886

    
2887
################################################################################
2888
# 
2889
# get the list of projects
2890
#
2891
################################################################################
2892
sub getProjectList {
2893
    
2894
    #use NCEAS::AdminDB;
2895
    #my $admindb = NCEAS::AdminDB->new();
2896
    #$admindb->connect($nceas_db, $nceas_db_user, $nceas_db_password);
2897
    #my $projects = $admindb->getProjects();
2898
    my $projects = getTestProjectList();
2899
    return $projects;
2900
}
2901

    
2902
################################################################################
2903
# 
2904
# get a test list of projects for use only in testing where the NCEAS
2905
# admin db is not available.
2906
#
2907
################################################################################
2908
sub getTestProjectList {
2909
    # This block is for testing only!  Remove for production use
2910
    my @row1;
2911
    $row1[0] = 6000; $row1[1] = 'Andelman'; $row1[2] = 'Sandy'; $row1[3] = 'The very long and windy path to an apparent ecological conclusion: statistics lie';
2912
    my @row2; 
2913
    $row2[0] = 7000; $row2[1] = 'Bascompte'; $row2[2] = 'Jordi'; $row2[3] = 'Postdoctoral Fellow';
2914
    my @row3; 
2915
    $row3[0] = 7001; $row3[1] = 'Hackett'; $row3[2] = 'Edward'; $row3[3] = 'Sociology rules the world';
2916
    my @row4; 
2917
    $row4[0] = 7002; $row4[1] = 'Jones'; $row4[2] = 'Matthew'; $row4[3] = 'Informatics rules the world';
2918
    my @row5; 
2919
    $row5[0] = 7003; $row5[1] = 'Schildhauer'; $row5[2] = 'Mark'; $row5[3] = 'Excel rocks my world, assuming a, b, and c';
2920
    my @row6; 
2921
    $row6[0] = 7004; $row6[1] = 'Rogers'; $row6[2] = 'Bill'; $row6[3] = 'Graduate Intern';
2922
    my @row7; 
2923
    $row7[0] = 7005; $row7[1] = 'Zedfried'; $row7[2] = 'Karl'; $row7[3] = 'A multivariate analysis of thing that go bump in the night';
2924
    my @projects;
2925
    $projects[0] = \@row1;
2926
    $projects[1] = \@row2;
2927
    $projects[2] = \@row3;
2928
    $projects[3] = \@row4;
2929
    $projects[4] = \@row5;
2930
    $projects[5] = \@row6;
2931
    $projects[6] = \@row7;
2932
    return \@projects;
2933
}
(6-6/7)