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-10-04 12:20:45 -0700 (Tue, 04 Oct 2005) $'
8
# '$Revision: 2645 $' 
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("publicReadable", { DEFAULT => 'true'} );
88
$config->define("accessPrincipals", { DEFAULT => ''} );
89
$config->define("accessType", { DEFAULT => ''} );
90
$config->define("mailhost");
91
$config->define("sender");
92
$config->define("recipient");
93
$config->define("adminname");
94
if ($FORM::cfg eq 'nceas') {
95
    $config->define("nceas_db");
96
    $config->define("nceas_db_user");
97
    $config->define("nceas_db_password");
98
}
99
$config->define("responseTemplate", { DEFAULT => 'crap.tmpl'} );
100
$config->define("entryFormTemplate", { DEFAULT => 'crap.tmpl'} );
101
$config->define("guideTemplate", { DEFAULT => 'crap.tmpl'} );
102
$config->define("confirmDataTemplate", { DEFAULT => 'crap.tmpl'} );
103
$config->define("deleteDataTemplate", { DEFAULT => 'crap.tmpl'} );
104
$config->define("debug", { DEFAULT => '0'} );
105
$config->define("lat", { ARGCOUNT => ARGCOUNT_HASH} );
106
$config->define("lon", { ARGCOUNT => ARGCOUNT_HASH} );
107

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

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

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

    
178
# set some configuration options for the template object
179
my $ttConfig = {
180
             INCLUDE_PATH => $templatesdir, 
181
             INTERPOLATE  => 0,                    
182
             POST_CHOMP   => 1,                   
183
             };
184

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

    
188
print "Content-type: text/html\n\n";
189

    
190
# Set up the template information that is common to all forms
191
$$templateVars{'cfg'} = $FORM::cfg;
192
$$templateVars{'recipient'} = $recipient;
193
$$templateVars{'adminname'} = $adminname;
194
$$templateVars{'organization'} = $organization;
195
$$templateVars{'orgabbrev'} = $orgabbrev;
196
$$templateVars{'orgurl'} = $orgurl;
197
$$templateVars{'orgfilter'} = $orgfilter;
198

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

    
207
} elsif ($FORM::stage =~ "insert") {
208
    # The user has entered the data. Do data validation and send back data 
209
    # to confirm the data that has been entered. 
210
    toConfirmData();
211
    exit(0);
212

    
213
}elsif ($FORM::dataWrong =~ "No, go back to editing" && $FORM::stage =~ "confirmed") {
214
    # The user wants to correct the data that he has entered. 
215
    # Hence show the data again in entryData form. 
216
    confirmDataToReEntryData();
217
    exit(0);
218

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

    
232
}elsif ($FORM::stage =~ "delete_confirm") {
233

    
234
    # Result from deleteData form. 
235
    if($FORM::deleteData =~ "Delete document"){
236
    # delete Data
237
    deleteData(1);    
238
    exit(0);
239
    } else {
240
    $$templateVars{'status'} = "Cancel";
241
    $$templateVars{'function'} = "cancel";
242
    $template->process( $responseTemplate, $templateVars);
243
    exit(0);
244
    }
245

    
246
}elsif ($FORM::stage =~ "delete") {
247
    # Deletion of a file has been requested. 
248
    # Ask for username and password using deleteDataForm
249
    $$templateVars{'docid'} = $FORM::docid;
250
    $template->process( $deleteDataTemplate, $templateVars);
251
    exit(0);
252

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

    
268
    $$templateVars{'showSiteList'} = $showSiteList;
269
    $$templateVars{'lsite'} = $lsite;
270
    $$templateVars{'usite'} = $usite;
271
    $$templateVars{'showWgList'} = $showWgList;
272
    $$templateVars{'showOrganization'} = $showOrganization;
273
    $$templateVars{'hasKeyword'} = $hasKeyword;
274
    $$templateVars{'hasTemporal'} = $hasTemporal;
275
    $$templateVars{'hasSpatial'} = $hasSpatial;
276
    $$templateVars{'hasTaxonomic'} = $hasTaxonomic;
277
    $$templateVars{'hasMethod'} = $hasMethod;
278
    $$templateVars{'temporalRequired'} = $temporalRequired;
279
    $$templateVars{'spatialRequired'} = $spatialRequired;
280

    
281
    $$templateVars{'siteList'} = \@sortedSites;
282
    $$templateVars{'section'} = "Entry Form";
283
    $$templateVars{'docid'} = "";
284
    debug("Registry: Sending form: ready to process template");
285
    $template->process( $entryFormTemplate, $templateVars);
286
    debug("Registry: Sending form: template processed");
287
    exit(0);
288
}
289

    
290
# Confirm stage has been reached. Enter the data into metacat. 
291

    
292
# Initialize some global vars
293
my $latDeg1 = "";
294
my $latMin1 = "";
295
my $latSec1 = "";
296
my $hemisphLat1 = "";
297
my $longDeg1 = "";
298
my $longMin1 = "";
299
my $longSec1 = "";
300
my $hemisphLong1 = "";
301
my $latDeg2 = "";
302
my $latMin2 = "";
303
my $latSec2 = "";
304
my $hemisphLat2 = "";
305
my $longDeg2 = "";
306
my $longMin2 = "";
307
my $longSec2 = "";
308
my $hemisphLong2 = "";
309

    
310
# validate the input form parameters
311
my $invalidParams;
312

    
313
if (! $error) {
314
    $invalidParams = validateParameters(1);
315
    if (scalar(@$invalidParams)) {
316
        $$templateVars{'status'} = 'failure';
317
        $$templateVars{'invalidParams'} = $invalidParams;
318
        $error = 1;
319
    }
320
}
321

    
322

    
323
my $metacat;
324
my $docid;
325
if (! $error) {
326
    # Parameters have been validated and Create the XML document
327

    
328
    my $xmldoc = createXMLDocument();
329

    
330
    # Write out the XML file for debugging purposes
331
    #my $testFile = $tmpdir . "/test.xml";
332

    
333
    # Create a  metacat object
334
    $metacat = Metacat->new();
335
    if ($metacat) {
336
        $metacat->set_options( metacatUrl => $metacatUrl );
337
    } else {
338
        #die "failed during metacat creation\n";
339
        push(@errorMessages, "Failed during metacat creation.");
340
    }
341

    
342
    # Login to metacat
343
    my $userDN = $FORM::username;
344
    my $userOrg = $FORM::organization;
345
    my $userPass = $FORM::password;
346
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
347
    
348
    my $xmldocWithDocID = $xmldoc;
349
    
350
    my $errorMessage = "";
351
    my $response = $metacat->login($dname, $userPass);
352
    if (! $response) {
353
        push(@errorMessages, $metacat->getMessage());
354
        push(@errorMessages, "Failed during login.\n");
355
        $$templateVars{'status'} = 'login_failure';
356
        $$templateVars{'errorMessages'} = \@errorMessages;
357
        $$templateVars{'docid'} = $docid;
358
        $$templateVars{'cfg'} = $FORM::cfg;
359
        $$templateVars{'function'} = "submitted";
360
        $$templateVars{'section'} = "Submission Status";
361
        $template->process( $responseTemplate, $templateVars);
362
        exit(0);
363
    } else {
364

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

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

    
422
            if (! $response) {
423
                push(@errorMessages, $metacat->getMessage());
424
                push(@errorMessages, "Failed while updating.\n");  
425
            }
426

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

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

    
454
debug("Registry: C");
455

    
456
if (scalar(@errorMessages)) {
457
    debug("Registry: ErrorMessages defined.");
458
    $$templateVars{'docid'} = $FORM::docid;
459
    copyFormToTemplateVars();
460
    $$templateVars{'status'} = 'failure';
461
    $$templateVars{'errorMessages'} = \@errorMessages;
462
    $error = 1;
463
} else {
464
    $$templateVars{'docid'} = $docid;
465
    $$templateVars{'cfg'} = $FORM::cfg;
466
}
467

    
468
#if (! $error) {
469
#sendNotification($docid, $mailhost, $sender, $recipient);
470
#}
471

    
472
# Create our HTML response and send it back
473
$$templateVars{'function'} = "submitted";
474
$$templateVars{'section'} = "Submission Status";
475

    
476
$template->process( $responseTemplate, $templateVars);
477

    
478
exit(0);
479

    
480

    
481
################################################################################
482
#
483
# Subroutine for updating a metacat id for a given scope to the highest value
484
#
485
################################################################################
486
sub updateLastId {
487
  my $scope = shift;
488

    
489
  my $errormsg = 0;
490
  my $docid = $metacat->getLastId($scope);
491

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

    
510
################################################################################
511
#
512
# Subroutine for inserting a document to metacat
513
#
514
################################################################################
515
sub insertMetadata {
516
  my $xmldoc = shift;
517
  my $docid = shift;
518

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

    
541
  return $notunique;
542
}
543

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

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

    
568
  my $docroot = "$scope.$lastid.";
569
  my $docid = $docroot . $docrev;
570
  return $docid;
571
}
572

    
573
################################################################################
574
# 
575
# Validate the parameters to make sure that required params are provided
576
#
577
################################################################################
578
sub validateParameters {
579
    my $chkUser = shift;
580
    my @invalidParams;
581

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

    
608
    if($FORM::beginningMonth eq "MM"){
609
	#if (hasContent($FORM::beginningYear)){
610
	#    $FORM::beginningMonth = "01";
611
	#} else {
612
	    $FORM::beginningMonth = "";
613
	#}
614
    }
615
    if($FORM::beginningDay eq "DD"){
616
	#if (hasContent($FORM::beginningYear)){
617
	#    $FORM::beginningDay = "01";
618
	#} else {
619
	    $FORM::beginningDay = "";
620
	#}
621
    }
622
    if($FORM::endingMonth eq "MM"){
623
	#if (hasContent($FORM::endingYear)){
624
	#    $FORM::endingMonth = "01";
625
	#} else {
626
	    $FORM::endingMonth = "";
627
	#}
628
    }    
629
    if($FORM::endingDay eq "DD"){
630
	#if (hasContent($FORM::endingYear)){
631
	#    $FORM::endingDay = "01";
632
	#} else {
633
	    $FORM::endingDay = "";
634
	#}
635
    }
636

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

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

    
672
	if($latDeg1 > 90 || $latDeg1 < 0){
673
	    push(@invalidParams, "Invalid first latitude degrees specified.");
674
	}
675
	if($latMin1 > 59 || $latMin1 < 0){
676
	    push(@invalidParams, "Invalid first latitude minutes specified.");
677
	}
678
	if($latSec1 > 59 || $latSec1 < 0){
679
	    push(@invalidParams, "Invalid first latitude seconds specified.");
680
	}
681
	if($longDeg1 > 180 || $longDeg1 < 0){
682
	    push(@invalidParams, "Invalid first longitude degrees specified.");
683
	}
684
	if($longMin1 > 59 || $longMin1 < 0){
685
	    push(@invalidParams, "Invalid first longitude minutes specified.");
686
	}
687
	if($longSec1 > 59 || $longSec1 < 0){
688
	    push(@invalidParams, "Invalid first longitude seconds specified.");
689
	}
690

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

    
715

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

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

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

    
762
################################################################################
763
# 
764
# utility function to determine if a paramter is defined and not an empty string
765
#
766
################################################################################
767
sub hasContent {
768
    my $param = shift;
769

    
770
    my $paramHasContent;
771
    if (!defined($param) || $param eq '') { 
772
        $paramHasContent = 0;
773
    } else {
774
        $paramHasContent = 1;
775
    }
776
    return $paramHasContent;
777
}
778

    
779
################################################################################
780
#
781
# Subroutine for replacing characters not recognizable by XML and otherwise. 
782
#
783
################################################################################
784
sub normalize{
785
    my $val = shift;
786

    
787
    $val =~ s/&/&amp;/g;
788

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

    
820

    
821
################################################################################
822
#
823
# Subroutine for replacing characters not recognizable by XML and otherwise 
824
# except for ", > amd <.
825
#
826
################################################################################
827
sub delNormalize{
828
    my $val = shift;
829

    
830
    $val =~ s/&/&amp;/g;
831

    
832
    $val =~ s/%/&#37;/g;
833

    
834
    my $returnVal = "";
835

    
836
    foreach (split(//,$val)){
837
        my $var = unpack "C*", $_;
838

    
839
        if($var<128 && $var>31){
840
            $returnVal=$returnVal.$_;
841
        } elsif ($var<32){
842
            if($var == 10){
843
                $returnVal=$returnVal.$_;
844
            }
845
            if($var == 13){
846
                $returnVal=$returnVal.$_;
847
            }
848
            if($var == 9){
849
                $returnVal=$returnVal.$_;
850
            }
851
        } else {
852
            $returnVal=$returnVal."&#".$var.";";
853
        }
854
    }
855

    
856
    $returnVal =~ s/&/%26/g;
857
    return $returnVal;
858
}
859

    
860

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

    
872
    $val =~ s/\"/&quot;/g;
873
    
874
    return $val;
875
}
876

    
877

    
878
################################################################################
879
# 
880
# Create the XML document from the HTML form input
881
# returns the XML document as a string
882
#
883
################################################################################
884
sub createXMLDocument {
885

    
886
    my $orig  = "";
887
    my $role  = "associatedParty";
888
    my $creat = "";
889
    my $metaP = "";
890
    my $apart = "";
891
    my $cont  = "";
892
    my $publ  = "";
893
    my $dso   = "";
894
    my $gmt = gmtime($now);
895

    
896

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

    
899
    $doc .= "<eml:eml\n 
900
                     \t packageId=\"docid\" system=\"knb\"\n 
901
                     \t xmlns:eml=\"eml://ecoinformatics.org/eml-2.0.1\"\n
902
                     \t xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n 
903
                     \t xmlns:ds=\"eml://ecoinformatics.org/dataset-2.0.1\"\n 
904
                     \t xmlns:stmml=\"http://www.xml-cml.org/schema/stmml\"\n 
905
                     \t xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.0.1 eml.xsd\">\n";
906

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

    
921
    if (hasContent($FORM::origNamelast0)) {
922
    $role = "creator";
923
        $orig .= "<individualName>\n";
924
        $orig .= "<givenName>".normalize($FORM::origNamefirst0)."</givenName>\n";
925
        $orig .= "<surName>".normalize($FORM::origNamelast0)."</surName>\n";
926
        $orig .= "</individualName>\n";
927
    }
928

    
929
    if (hasContent($FORM::origNameOrg)) {
930
        $orig .= "<organizationName>".normalize($FORM::origNameOrg)."</organizationName>\n";
931
    }
932

    
933
    if (hasContent($FORM::origDelivery) || hasContent($FORM::origCity) ||
934
        (hasContent($FORM::origState   ) &&
935
        ($FORM::origState !~ "Select state here.")) ||
936
        hasContent($FORM::origStateOther) ||
937
        hasContent($FORM::origZIP ) || hasContent($FORM::origCountry)) {
938
        $orig .= "<address>\n";
939

    
940
        if (hasContent($FORM::origDelivery)) {
941
            $orig .= "<deliveryPoint>".normalize($FORM::origDelivery)."</deliveryPoint>\n";
942
        }
943
        if (hasContent($FORM::origCity)) {
944
            $orig .= "<city>".normalize($FORM::origCity)."</city>\n";
945
        }
946

    
947
    if (hasContent($FORM::origState) && 
948
            ($FORM::origState !~ "Select state here.")) {
949
            $orig .= "<administrativeArea>".normalize($FORM::origState);
950
            $orig .= "</administrativeArea>\n";
951
        } elsif (hasContent($FORM::origStateOther)) {
952
            $orig .= "<administrativeArea>".normalize($FORM::origStateOther);
953
            $orig .= "</administrativeArea>\n";
954
        }
955
        if (hasContent($FORM::origZIP)) {
956
            $orig .= "<postalCode>".normalize($FORM::origZIP)."</postalCode>\n";
957
        }
958
        if (hasContent($FORM::origCountry)) {
959
            $orig .= "<country>".normalize($FORM::origCountry)."</country>\n";
960
        }
961
        $orig .= "</address>\n";
962
    }
963

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

    
988
    if ($FORM::cfg ne 'knb') {
989
        $creat .= "<creator>\n";
990
        $creat .= "<organizationName>".normalize($organization)."</organizationName>\n";
991
        $creat .= "</creator>\n";
992
    }
993

    
994
    $creat .= $dso;
995

    
996
    if ($FORM::useOrigAddress) {
997
        # Add a contact originator like the original with a different role
998
            $cont .= "<contact>\n";
999
        $cont .= $orig;
1000
        $cont .= "</contact>\n";
1001
    } else {
1002
        $cont .= "<contact>\n";
1003

    
1004
        $cont .= "<individualName>\n";
1005
        $cont .= "<givenName>".normalize($FORM::origNamefirstContact)."</givenName>\n";
1006
        $cont .= "<surName>".normalize($FORM::origNamelastContact)."</surName>\n";
1007
        $cont .= "</individualName>\n";
1008
 
1009
    if (hasContent($FORM::origNameOrgContact)) {
1010
        $cont .= "<organizationName>".normalize($FORM::origNameOrgContact)."</organizationName>\n";
1011
    }
1012

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

    
1057
    $metaP .= "<metadataProvider>\n";
1058
    $metaP .= "<individualName>\n";
1059
    $metaP .= "<givenName>".normalize($FORM::providerGivenName)."</givenName>\n";
1060
    $metaP .= "<surName>".normalize($FORM::providerSurName)."</surName>\n";
1061
    $metaP .= "</individualName>\n";
1062
    $metaP .= "</metadataProvider>\n";
1063

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

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

    
1122
    $doc .= $creat;
1123
    $doc .= $metaP;
1124
    $doc .= $apart;
1125

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

    
1146
    $doc .= "<pubDate>\n";
1147
    $doc .= $Year."-".$Month."-".$Day;
1148
    $doc .= "</pubDate>\n";
1149

    
1150
    $doc .= "<abstract>\n";
1151
    $doc .= "<para>".normalize($FORM::abstract)."</para>\n";
1152
    $doc .= "</abstract>\n";
1153

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

    
1183
    if (hasContent($FORM::addComments)) {
1184
        $doc .= "<additionalInfo>\n";
1185
        $doc .= "<para>".normalize($FORM::addComments)."</para>\n";
1186
        $doc .= "</additionalInfo>\n";
1187
    }
1188

    
1189
    if (hasContent($FORM::useConstraints) || 
1190
        hasContent($FORM::useConstraintsOther)) {
1191
        $doc .= "<intellectualRights>\n";
1192
        if (hasContent($FORM::useConstraints)) {
1193
            $doc .= "<para>".normalize($FORM::useConstraints)."</para>\n";
1194
        }
1195
        if (hasContent($FORM::useConstraintsOther)) {
1196
            $doc .= "<para>".normalize($FORM::useConstraintsOther)."</para>\n";
1197
        }
1198
        $doc .= "</intellectualRights>\n";
1199
    }
1200

    
1201
    
1202
    if (hasContent($FORM::url)) {
1203
    $doc .= "<distribution>\n";
1204
        $doc .= "<online>\n";
1205
    $doc .= "<url>".normalize($FORM::url)."</url>\n";
1206
    $doc .= "</online>\n";
1207
    $doc .= "</distribution>\n";
1208
    }
1209
    
1210
    $doc .= "<distribution>\n";
1211
    $doc .= "<offline>\n";
1212
    $doc .= "<mediumName>" . normalize($FORM::dataMedium)." ".normalize($FORM::dataMediumOther);
1213
    $doc .= "</mediumName>\n";
1214
    $doc .= "</offline>\n";
1215
    $doc .= "</distribution>\n";
1216
            
1217
    my $cov = "";
1218

    
1219
    if (hasContent($FORM::endingYear)) {
1220
	$cov .= "<temporalCoverage>\n";
1221
	$cov .= "<rangeOfDates>\n";
1222
	if (hasContent($FORM::beginningMonth)) {
1223
	    my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1224
			 "JUL","AUG","SEP","OCT","NOV","DEC")
1225
		[$FORM::beginningMonth - 1];
1226
	    if (hasContent($FORM::beginningDay)) {
1227
	    	$cov .= "<beginDate>\n";
1228
	    	$cov .= "<calendarDate>";
1229
	    	$cov .= normalize($FORM::beginningYear)."-".normalize($FORM::beginningMonth)."-".normalize($FORM::beginningDay);
1230
	    	$cov .= "</calendarDate>\n";
1231
	    	$cov .= "</beginDate>\n";
1232
	    } else {
1233
	    	$cov .= "<beginDate>\n";
1234
	    	$cov .= "<calendarDate>";
1235
	    	$cov .= normalize($FORM::beginningYear)."-".normalize($FORM::beginningMonth)."-01";
1236
	    	$cov .= "</calendarDate>\n";
1237
	    	$cov .= "</beginDate>\n";
1238
	    }
1239
	} else {
1240
	    $cov .= "<beginDate>\n";
1241
	    $cov .= "<calendarDate>";
1242
	    $cov .= normalize($FORM::beginningYear);
1243
	    $cov .= "</calendarDate>\n";
1244
	    $cov .= "</beginDate>\n";
1245
	}
1246
	
1247
	if (hasContent($FORM::endingMonth)) {
1248
	    my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1249
			 "JUL","AUG","SEP","OCT","NOV","DEC")
1250
		[$FORM::endingMonth - 1];
1251
	
1252
	    if (hasContent($FORM::endingDay)) {
1253
	    	$cov .= "<endDate>\n";
1254
	    	$cov .= "<calendarDate>";
1255
	    	$cov .= normalize($FORM::endingYear)."-".normalize($FORM::endingMonth)."-".normalize($FORM::endingDay);
1256
	    	$cov .= "</calendarDate>\n";
1257
	    	$cov .= "</endDate>\n";
1258
	    } else {
1259
	    	$cov .= "<endDate>\n";
1260
	    	$cov .= "<calendarDate>";
1261
	    	$cov .= normalize($FORM::endingYear)."-".normalize($FORM::endingMonth)."-01";
1262
	    	$cov .= "</calendarDate>\n";
1263
	    	$cov .= "</endDate>\n";
1264
	    }
1265
	} else {
1266
	    $cov .= "<endDate>\n";
1267
	    $cov .= "<calendarDate>";
1268
	    $cov .= normalize($FORM::endingYear);
1269
	    $cov .= "</calendarDate>\n";
1270
	    $cov .= "</endDate>\n";
1271
	}
1272
	$cov .= "</rangeOfDates>\n";
1273
	$cov .= "</temporalCoverage>\n";
1274
    } else {
1275
	if(hasContent($FORM::beginningYear)) {
1276
	    $cov .= "<temporalCoverage>\n";
1277
	    $cov .= "<singleDateTime>\n";
1278
	    if (hasContent($FORM::beginningMonth)) {
1279
		my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1280
			     "JUL","AUG","SEP","OCT","NOV","DEC")
1281
		    [$FORM::beginningMonth - 1];
1282
		
1283
	    	if (hasContent($FORM::beginningDay)) {
1284
		   $cov .= "<calendarDate>";
1285
		   $cov .= normalize($FORM::beginningYear)."-".normalize($FORM::beginningMonth)."-".normalize($FORM::beginningDay);
1286
		   $cov .= "</calendarDate>\n";
1287
		} else {
1288
		   $cov .= "<calendarDate>";
1289
		   $cov .= normalize($FORM::beginningYear)."-".normalize($FORM::beginningMonth)."-01";
1290
		   $cov .= "</calendarDate>\n";
1291
		}
1292
	    } else {
1293
		$cov .= "<calendarDate>";
1294
		$cov .= normalize($FORM::beginningYear);
1295
		$cov .= "</calendarDate>\n";
1296
	    }
1297
	    $cov .= "</singleDateTime>\n";
1298
	    $cov .= "</temporalCoverage>\n";
1299
	}
1300
    }
1301
    
1302
    if(hasContent($FORM::geogdesc) || ($FORM::latDeg1 < 91 && $FORM::latDeg1 > -1 && $FORM::longDeg1 < 181 && $FORM::longDeg1 > -1)) {
1303
	$cov .= "<geographicCoverage>\n";
1304

    
1305
	if(hasContent($FORM::geogdesc)) {
1306
	    $cov .= "<geographicDescription>".normalize($FORM::geogdesc)."</geographicDescription>\n";
1307
	}
1308
	
1309
	if($latDeg1 < 91 && $latDeg1 > -1 && $longDeg1 < 181 && $longDeg1 > -1) {
1310
	    $cov .= "<boundingCoordinates>\n";
1311
	    # if the second latitude is missing, then set the second lat/long pair 
1312
	    # equal to the first this makes a point appear like a rectangle 
1313
	    if ($FORM::useSiteCoord || ($FORM::latDeg2 == "" && $FORM::latMin2 == "" && $FORM::latSec2 == "")) {
1314
		
1315
		$latDeg2 = $latDeg1;
1316
		$latMin2 = $latMin1;
1317
		$latSec2 = $latSec1;
1318
		$hemisphLat2 = $hemisphLat1;
1319
		$longDeg2 = $longDeg1;
1320
		$longMin2 = $longMin1;
1321
		$longSec2 = $longSec1;
1322
		$hemisphLong2 = $hemisphLong1;
1323
	    }
1324
	    else
1325
	    {
1326
		$latDeg2 = $FORM::latDeg2;
1327
		$latMin2 = $FORM::latMin2;
1328
		$latSec2 = $FORM::latSec2;
1329
		$hemisphLat2 = $FORM::hemisphLat2;
1330
		$longDeg2 = $FORM::longDeg2;
1331
		$longMin2 = $FORM::longMin2;
1332
		$longSec2 = $FORM::longSec2;
1333
		$hemisphLong2 = $FORM::hemisphLong2;
1334
	    } 
1335
	
1336
	
1337
	    my $hemisph;
1338
	    $hemisph = ($hemisphLong1 eq "W") ? -1 : 1;
1339
	    $cov .= "<westBoundingCoordinate>";
1340
	    my $var = $hemisph * ($longDeg1 + (60*$longMin1+$longSec1)/3600);
1341
	    $cov .= sprintf("%.4f\n", $var);
1342
	    $cov .= "</westBoundingCoordinate>\n";
1343
	    
1344
	    $hemisph = ($hemisphLong2 eq "W") ? -1 : 1;
1345
	    $cov .= "<eastBoundingCoordinate>";
1346
	    $var = $hemisph * ($longDeg2 + (60*$longMin2+$longSec2)/3600);
1347
	    $cov .= sprintf("%.4f\n", $var);
1348
	    $cov .= "</eastBoundingCoordinate>\n";
1349
	    
1350
	    $hemisph = ($hemisphLat1 eq "S") ? -1 : 1;
1351
	    $cov .= "<northBoundingCoordinate>";
1352
	    $var = $hemisph * ($latDeg1 + (60*$latMin1+$latSec1)/3600);
1353
	    $cov .= sprintf("%.4f\n", $var);	   
1354
	    $cov .= "</northBoundingCoordinate>\n";
1355
	    
1356
	    $hemisph = ($hemisphLat2 eq "S") ? -1 : 1;
1357
	    $cov .= "<southBoundingCoordinate>";
1358
	    $var = $hemisph * ($latDeg2 + (60*$latMin2+$latSec2)/3600);
1359
	    $cov .= sprintf("%.4f\n", $var);
1360
	    $cov .= "</southBoundingCoordinate>\n";
1361
	    
1362
	    $cov .= "</boundingCoordinates>\n";
1363
	}
1364
	$cov .= "</geographicCoverage>\n";
1365
    }
1366

    
1367
    # Write out the taxonomic coverage fields
1368
    my $foundFirstTaxon = 0;
1369
    foreach my $trn (param()) {
1370
        if ($trn =~ /taxonRankName/) {
1371
            my $taxIndex = $trn;
1372
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
1373
            my $trv = "taxonRankValue".$taxIndex;
1374
            if ( $taxIndex =~ /[0-9]/ ){
1375
                if (hasContent(param($trn)) && hasContent(param($trv))) {
1376
                    if (! $foundFirstTaxon) {
1377
                        $cov .= "<taxonomicCoverage>\n";
1378
                        $foundFirstTaxon = 1;
1379
                        if (hasContent($FORM::taxaAuth)) {
1380
                            $cov .= "<generalTaxonomicCoverage>".normalize($FORM::taxaAuth)."</generalTaxonomicCoverage>\n";
1381
                        }
1382
                    }
1383
                    $cov .= "<taxonomicClassification>\n";
1384
                    $cov .= "  <taxonRankName>".normalize(param($trn))."</taxonRankName>\n";
1385
                    $cov .= "  <taxonRankValue>".normalize(param($trv))."</taxonRankValue>\n";
1386
                    $cov .= "</taxonomicClassification>\n";
1387
                }
1388
            }
1389
        }
1390
    }
1391
    if ($foundFirstTaxon) {
1392
        $cov .= "</taxonomicCoverage>\n";
1393
    }
1394

    
1395
    if($cov ne "" ){
1396
	$doc .= "<coverage>".$cov."</coverage>";
1397
    }
1398
    $doc .= $cont;
1399
    $doc .= $publ;
1400
    
1401
    if ((hasContent($FORM::methodTitle)) || scalar(@FORM::methodsPara) > 0 || ($FORM::methodPara[0] ne "")) {
1402
        my $methods = "<methods><methodStep><description><section>\n";
1403
        if (hasContent($FORM::methodTitle)) {
1404
            $methods .= "<title>".normalize($FORM::methodTitle)."</title>\n";
1405
        }
1406
        for (my $i = 0; $i < scalar(@FORM::methodPara); $i++) {
1407
            $methods .= "<para>".normalize($FORM::methodPara[$i])."</para>\n";
1408
        }
1409
        $methods .= "</section></description></methodStep>\n";
1410
        if (hasContent($FORM::studyExtentDescription)) {
1411
            $methods .= "<sampling><studyExtent><description>\n";
1412
            $methods .= "<para>".normalize($FORM::studyExtentDescription)."</para>\n";
1413
            $methods .= "</description></studyExtent>\n";
1414
            $methods .= "<samplingDescription>\n";
1415
            $methods .= "<para>".normalize($FORM::samplingDescription)."</para>\n";
1416
            $methods .= "</samplingDescription>\n";
1417
            $methods .= "</sampling>\n";
1418
        }
1419
        $methods .= "</methods>\n";
1420
        $doc .= $methods;
1421
    }
1422

    
1423
    $doc .= "<access authSystem=\"knb\" order=\"denyFirst\">\n";
1424
    $doc .= "<allow>\n";
1425
    $doc .= "<principal>$username</principal>\n";
1426
    $doc .= "<permission>all</permission>\n";
1427
    $doc .= "</allow>\n";
1428
    $doc .= "<allow>\n";
1429
    $doc .= "<principal>uid=$FORM::username,o=$FORM::organization,dc=ecoinformatics,dc=org</principal>\n";
1430
    $doc .= "<permission>all</permission>\n";
1431
    $doc .= "</allow>\n";
1432
    if($publicReadable eq "true"){
1433
    	$doc .= "<allow>\n";
1434
    	$doc .= "<principal>public</principal>\n";
1435
    	$doc .= "<permission>read</permission>\n";
1436
    	$doc .= "</allow>\n";
1437
    }
1438
    foreach(split(":",$accessPrincipals)){
1439
    	$doc .= "<allow>\n";
1440
    	$doc .= "<principal>".$_."</principal>\n";
1441
    	$doc .= "<permission>".$accessType."</permission>\n";
1442
    	$doc .= "</allow>\n";
1443
    }
1444
    $doc .= "</access>\n";
1445
    
1446
    $doc .= "</dataset>\n</eml:eml>\n";
1447

    
1448
    return $doc;
1449
}
1450

    
1451

    
1452
################################################################################
1453
# 
1454
# send an email message notifying the moderator of a new submission 
1455
#
1456
################################################################################
1457
sub sendNotification {
1458
    my $identifier = shift;
1459
    my $mailhost = shift;
1460
    my $sender = shift;
1461
    my $recipient = shift;
1462

    
1463
    my $smtp = Net::SMTP->new($mailhost);
1464
    $smtp->mail($sender);
1465
    $smtp->to($recipient);
1466

    
1467
    my $message = <<"    ENDOFMESSAGE";
1468
    To: $recipient
1469
    From: $sender
1470
    Subject: New data submission
1471
    
1472
    Data was submitted to the data registry.  
1473
    The identifying information for the new data set is:
1474

    
1475
    Identifier: $identifier
1476
    Title: $FORM::title
1477
    Submitter: $FORM::providerGivenName $FORM::providerSurName
1478

    
1479
    Please review the submmission and grant public read access if appropriate.
1480
    Thanks
1481
    
1482
    ENDOFMESSAGE
1483
    $message =~ s/^[ \t\r\f]+//gm;
1484

    
1485
    $smtp->data($message);
1486
    $smtp->quit;
1487
}
1488

    
1489

    
1490
################################################################################
1491
# 
1492
# read the eml document and send back a form with values filled in. 
1493
#
1494
################################################################################
1495
sub modifyData {
1496
    
1497
    # create metacat instance
1498
    my $metacat;
1499
    my $docid = $FORM::docid;
1500
    my $httpMessage;
1501
    my $doc;
1502
    my $xmldoc;
1503
    my $findType;
1504
    my $parser = XML::LibXML->new();
1505
    my @fileArray;
1506
    my $pushDoc;
1507
    my $alreadyInArray;
1508
    my $node;
1509
    my $response; 
1510
    my $element;
1511
    my $tempfile;
1512

    
1513
    $metacat = Metacat->new();
1514
    if ($metacat) {
1515
        $metacat->set_options( metacatUrl => $metacatUrl );
1516
    } else {
1517
        #die "failed during metacat creation\n";
1518
        push(@errorMessages, "Failed during metacat creation.");
1519
    }
1520
    
1521
    $httpMessage = $metacat->read($docid);
1522
    $doc = $httpMessage->content();
1523
    $xmldoc = $parser->parse_string($doc);
1524

    
1525
    #$tempfile = $xslConvDir.$docid;
1526
    #push (@fileArray, $tempfile);
1527

    
1528
    if ($xmldoc eq "") {
1529
        $error ="Error in parsing the eml document";
1530
        push(@errorMessages, $error);
1531
    } else {
1532
        $findType = $xmldoc->findnodes('//dataset/identifier');
1533
        if ($findType->size() > 0) {
1534
            # This is a eml beta6 document
1535
            # Read the documents mentioned in triples also
1536
        
1537
            $findType = $xmldoc->findnodes('//dataset/triple');
1538
            if ($findType->size() > 0) {
1539
                foreach $node ($findType->get_nodelist) {
1540
                    $pushDoc = findValue($node, 'subject');
1541
            
1542
                    # If the file is already in @fileArray then do not add it 
1543
                    $alreadyInArray = 0;
1544
                    foreach $element (@fileArray) {
1545
                        $tempfile = $tmpdir."/".$pushDoc;
1546
                        if ($element eq $pushDoc) {
1547
                            $alreadyInArray = 1;
1548
                        }
1549
                    }
1550
            
1551
                    if (!$alreadyInArray) {
1552
                        $tempfile = $tmpdir."/".$pushDoc;
1553
                        $response = "";
1554
                        $response = $metacat->read($pushDoc);    
1555
                        if (! $response) {
1556
                            # could not read
1557
                            #push(@errorMessages, $response);
1558
                            push(@errorMessages, $metacat->getMessage());
1559
                            push(@errorMessages, "Failed during reading.\n");
1560
                        } else {
1561
                            my $xdoc = $response->content();
1562
                            #$tempfile = $xslConvDir.$pushDoc;
1563
                            open (TFILE,">$tempfile") || 
1564
                                die ("Cant open xml file... $tempfile\n");
1565
                            print TFILE $xdoc;
1566
                            close(TFILE);
1567
                            push (@fileArray, $tempfile);
1568
                        }
1569
                    }
1570
                }
1571
            }
1572

    
1573
            # Read the main document. 
1574

    
1575
            $tempfile = $tmpdir."/".$docid; #= $xslConvDir.$docid;
1576
            open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1577
            print TFILE $doc;
1578
            close(TFILE);
1579
        
1580
            # Transforming beta6 to eml 2
1581
            my $xslt;
1582
            my $triplesheet;
1583
            my $results;
1584
            my $stylesheet;
1585
            my $resultsheet;
1586
        
1587
            $xslt = XML::LibXSLT->new();
1588
            #$tempfile = $xslConvDir."triple_info.xsl";
1589
            $tempfile = $tmpdir."/"."triple_info.xsl";
1590
    
1591
            $triplesheet = $xslt->parse_stylesheet_file($tempfile);
1592

    
1593
            #$results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1594
            $results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1595

    
1596
            #$tempfile = $xslConvDir."emlb6toeml2.xsl";
1597
            $tempfile = $tmpdir."/"."emlb6toeml2.xsl";
1598
            $stylesheet = $xslt->parse_stylesheet_file($tempfile);
1599
            $resultsheet = $stylesheet->transform($results);
1600
        
1601
            #$tempfile = "/usr/local/apache2/htdocs/xml/test.xml";;
1602
            #open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1603
            #print TFILE $stylesheet->output_string($resultsheet);
1604
            #close(TFILE);
1605

    
1606
            getFormValuesFromEml2($resultsheet);
1607
            
1608
            # Delete the files written earlier. 
1609
            unlink @fileArray;
1610

    
1611
        } else {
1612
            getFormValuesFromEml2($xmldoc);
1613
        }
1614
    }   
1615
    
1616
    if (scalar(@errorMessages)) {
1617
        # if any errors, print them in the response template 
1618
        $$templateVars{'status'} = 'failure_no_resubmit';
1619
        $$templateVars{'errorMessages'} = \@errorMessages;
1620
        $error = 1;
1621
        $$templateVars{'function'} = "modification";
1622
        $$templateVars{'section'} = "Modification Status";
1623
        $template->process( $responseTemplate, $templateVars); 
1624
    } else {
1625
        $$templateVars{'form'} = 're_entry';
1626
        $template->process( $entryFormTemplate, $templateVars);
1627
    }
1628
}
1629

    
1630
################################################################################
1631
# 
1632
# Parse an EML 2.0.0 file and extract the metadata into perl variables for 
1633
# processing and returning to the template processor
1634
#
1635
################################################################################
1636
sub getFormValuesFromEml2 {
1637
    
1638
    my $doc = shift;
1639
    my $results;
1640
    my $error;
1641
    my $node;
1642
    my $tempResult;
1643
    my $tempNode;
1644
    my $aoCount = 1;
1645
    my $foundDSO;
1646

    
1647
    # set variable values
1648
    $$templateVars{'showSiteList'} = $showSiteList;
1649
    $$templateVars{'lsite'} = $lsite;
1650
    $$templateVars{'usite'} = $usite;
1651
    $$templateVars{'showWgList'} = $showWgList;
1652
    $$templateVars{'showOrganization'} = $showOrganization;
1653
    $$templateVars{'hasKeyword'} = $hasKeyword;
1654
    $$templateVars{'hasTemporal'} = $hasTemporal;
1655
    $$templateVars{'hasSpatial'} = $hasSpatial;
1656
    $$templateVars{'hasTaxonomic'} = $hasTaxonomic;
1657
    $$templateVars{'hasMethod'} = $hasMethod;
1658
    $$templateVars{'spatialRequired'} = $spatialRequired;
1659
    $$templateVars{'temporalRequired'} = $temporalRequired;
1660

    
1661
    # find out the tag <alternateIdentifier>. 
1662
    $results = $doc->findnodes('//dataset/alternateIdentifier');
1663
    if ($results->size() > 1) {
1664
        errMoreThanOne("alternateIdentifier");
1665
    } else {
1666
        foreach $node ($results->get_nodelist) {
1667
            $$templateVars{'identifier'} = findValue($node, '../alternateIdentifier');
1668
        }
1669
    }
1670

    
1671
    # find out the tag <title>. 
1672
    $results = $doc->findnodes('//dataset/title');
1673
    if ($results->size() > 1) {
1674
        errMoreThanOne("title");
1675
    } elsif ($results->size() < 1) {
1676
        $error ="Following tag not found: title. Please use Morpho to edit this document";
1677
        push(@errorMessages, $error."\n");
1678
        #if ($DEBUG == 1){ print $error;}
1679
    } else {
1680
        foreach $node ($results->get_nodelist) {
1681
            $$templateVars{'title'} = findValue($node, '../title');
1682
        }
1683
    }
1684

    
1685
    # find out the tag <creator>. 
1686
    $results = $doc->findnodes('//dataset/creator/individualName');
1687
    debug("Registry: Creators: ".$results->size());
1688
     foreach $node ($results->get_nodelist) {
1689
            dontOccur($node, "../positionName|../onlineURL|../userId", 
1690
              "positionName, onlineURL, userId");
1691
        
1692
            dontOccur($node, "./saluation", "saluation");                
1693
        
1694
            debug("Registry: Checking a creator in loop 1...");
1695
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1696
            if($tempResult->size > 0) {
1697
                if($foundDSO == 0) {
1698
                    $foundDSO = 1;
1699
     
1700
                    debug("Registry: Recording a creator in loop 1...");
1701
                    $$templateVars{'origNamefirst0'} = findValue($node, 'givenName');
1702
                    $$templateVars{'origNamelast0'} = findValue($node, 'surName');
1703
            
1704
                    my $tempResult2 = $node->findnodes('../address');
1705
                    if ($tempResult2->size > 1) {
1706
                        errMoreThanOne("address");
1707
                    } else {
1708
                        foreach my $tempNode2 ($tempResult2->get_nodelist) {
1709
                            $$templateVars{'origDelivery'} = findValue($tempNode2, 'deliveryPoint');
1710
                            $$templateVars{'origCity'} = findValue($tempNode2, 'city');
1711
                            $$templateVars{'origState'} = findValue($tempNode2, 'administrativeArea');
1712
                            $$templateVars{'origZIP'} = findValue($tempNode2, 'postalCode');
1713
                            $$templateVars{'origCountry'} = findValue($tempNode2, 'country');
1714
                        }
1715
                    }
1716
            
1717
                    my $tempResult3 = $node->findnodes('../phone');
1718
                    if ($tempResult3->size > 2) {
1719
                        errMoreThanN("phone");
1720
                    } else {
1721
                        foreach my $tempNode2 ($tempResult3->get_nodelist) {
1722
                            if ($tempNode2->hasAttributes()) {
1723
                                my @attlist = $tempNode2->attributes();
1724
                                if ($attlist[0]->value eq "Fax") {
1725
                                    $$templateVars{'origFAX'} = $tempNode2->textContent();
1726
                                } else {
1727
                                    $$templateVars{'origPhone'} = $tempNode2->textContent();
1728
                                }
1729
                            } else {
1730
                                $$templateVars{'origPhone'} = $tempNode2->textContent();
1731
                            }
1732
                        }
1733
                    }
1734
                    $$templateVars{'origEmail'} = findValue($node, '../electronicMailAddress');
1735
                    $$templateVars{'origNameOrg'} = findValue($node, '../organizationName');
1736
                } else {
1737
                    errMoreThanN("address, phone and electronicMailAddress");
1738
                }
1739
            }
1740
        }
1741
        foreach $node ($results->get_nodelist) {
1742
            debug("Registry: Checking a creator in loop 2...");
1743
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1744
            if ($tempResult->size == 0) {
1745
                if ($foundDSO == 0) {
1746
                    debug("Registry: Recording a creator in loop 2 block A...");
1747
                    $foundDSO = 1;
1748
                    $$templateVars{'origNamefirst0'} = findValue($node, 'givenName');
1749
                    $$templateVars{'origNamelast0'} = findValue($node, 'surName');
1750
                    $$templateVars{'origNameOrg'} = findValue($node, '../organizationName');
1751
                } else {
1752
                    debug("Registry: Recording a creator in loop 2 block B...");
1753
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($node, './givenName');
1754
                    $$templateVars{"origNamelast$aoCount"} =  findValue($node, './surName');
1755
                    $$templateVars{"origRole$aoCount"} = "Originator";
1756
                    $aoCount++;
1757
                }
1758
            }
1759
        }
1760

    
1761
    $results = $doc->findnodes('//dataset/creator/organizationName');
1762
    my $wgroups = $doc->findnodes("//dataset/creator/organizationName[contains(text(),'(NCEAS ')]");
1763
    debug("Registry: Number Org: ".$results->size());
1764
    debug("Registry:  Number WG: ".$wgroups->size());
1765
    if ($results->size() - $wgroups->size() > 3) {
1766
        errMoreThanN("creator/organizationName");    
1767
    } else {
1768
        foreach $node ($results->get_nodelist) {
1769
            my $tempValue = findValue($node,'../organizationName');
1770
            $tempResult = $node->findnodes('../individualName');
1771
            if ($tempResult->size == 0 && $tempValue ne $organization) {
1772
                $$templateVars{'site'} = $tempValue;
1773
            }
1774
        }
1775
        if ($FORM::cfg eq 'nceas') {
1776
            my @wg;
1777
            foreach $node ($results->get_nodelist) {
1778
                my $tempValue = findValue($node,'../organizationName');
1779
                $wg[scalar(@wg)] = $tempValue;
1780
            }
1781
            my $projects = getProjectList();
1782
            $$templateVars{'projects'} = $projects;
1783
            $$templateVars{'wg'} = \@wg;
1784
        }
1785
    }
1786

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

    
1810
    $results = $doc->findnodes('//dataset/associatedParty');
1811
    foreach $node ($results->get_nodelist) {
1812
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1813
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in associatedParty");
1814
       
1815
            $tempResult = $node->findnodes('./individualName');
1816
            if ($tempResult->size > 1) {
1817
                errMoreThanOne("associatedParty/indvidualName");
1818
            } else {
1819
                foreach $tempNode ($tempResult->get_nodelist) {
1820
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1821
                    $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1822
                    $$templateVars{"origRole$aoCount"} = findValue($tempNode, '../role');
1823
                    $aoCount++;           
1824
                }
1825
            }
1826
     }
1827

    
1828
    $results = $doc->findnodes('//dataset/publisher');
1829
#    if ($results->size() > 10) {
1830
 #       errMoreThanN("publisher");
1831
 #   } else {
1832
        foreach $node ($results->get_nodelist) {
1833
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1834
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in associatedParty");
1835
       
1836
            $tempResult = $node->findnodes('./individualName');
1837
            if ($tempResult->size > 1) {
1838
                errMoreThanOne("publisher/indvidualName");
1839
            } else {
1840
                foreach $tempNode ($tempResult->get_nodelist) {
1841
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1842
                    $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1843
                    $$templateVars{"origRole$aoCount"} = "Publisher";
1844
                    $aoCount++;           
1845
                }
1846
            }
1847
        }
1848
  #  }
1849

    
1850
  #  if ($aoCount > 11) {
1851
  #      errMoreThanN("Additional Originators");
1852
 #   } 
1853

    
1854
    $$templateVars{'aoCount'} = $aoCount;
1855
    
1856
    dontOccur($doc, "./pubDate", "pubDate");
1857
    dontOccur($doc, "./language", "language");
1858
    dontOccur($doc, "./series", "series");
1859

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

    
1870
    $results = $doc->findnodes('//dataset/keywordSet');
1871

    
1872
    my $count = 1;
1873
    foreach $node ($results->get_nodelist) {
1874
	$tempResult = $node->findnodes('./keyword');
1875
	if ($tempResult->size() > 1) {
1876
	    errMoreThanOne("keyword");
1877
	} else {
1878
	    foreach $tempNode ($tempResult->get_nodelist) {
1879
		$$templateVars{"keyword$count"} = $tempNode->textContent();
1880
		if ($tempNode->hasAttributes()) {
1881
		    my @attlist = $tempNode->attributes();
1882
                    my $tmp = $attlist[0]->value;  #convert the first letter to upper case
1883
		    $tmp =~ s/\b(\w)/\U$1/g;
1884
		    $$templateVars{"kwType$count"} = $tmp;
1885
		}  
1886
	    }
1887
	}
1888
	$$templateVars{"kwTh$count"} = findValue($node, "keywordThesaurus");
1889
        $count++;
1890
    }
1891
    $$templateVars{'keyCount'} = $count;
1892
    if($count > 0 ){
1893
       $$templateVars{'hasKeyword'} = "true";
1894
    }
1895

    
1896
    $results = $doc->findnodes('//dataset/additionalInfo');
1897
    if ($results->size() > 1) {
1898
        errMoreThanOne("additionalInfo");
1899
    } else {
1900
        foreach $node ($results->get_nodelist) {
1901
            dontOccur($node, "./section", "section");
1902
            $$templateVars{'addComments'} = findValueNoChild($node, "para");
1903
        }
1904
    }
1905

    
1906
    $$templateVars{'useConstraints'} = "";
1907
    $results = $doc->findnodes('//dataset/intellectualRights');
1908
    if ($results->size() > 1) {
1909
        errMoreThanOne("intellectualRights");
1910
    } else {
1911
        foreach $node ($results->get_nodelist) {
1912
            dontOccur($node, "./section", "section in intellectualRights");
1913

    
1914
            $tempResult = $node->findnodes("para");
1915
            if ($tempResult->size > 2) {
1916
                   errMoreThanN("para");
1917
            } else {
1918
                foreach $tempNode ($tempResult->get_nodelist) {
1919
                    my $childNodes = $tempNode->childNodes;
1920
                    if ($childNodes->size() > 1) {
1921
                        $error ="The tag para in intellectualRights has children which cannot be shown using the form. Please use Morpho to edit this document";    
1922
                        push(@errorMessages, $error);
1923
                        #if ($DEBUG == 1){ print $error."\n";}
1924
                    } else {
1925
                        #print $tempNode->nodeName().":".$tempNode->textContent();
1926
                        #print "\n";
1927
                        if ($$templateVars{'useConstraints'} eq "") {
1928
                            $$templateVars{'useConstraints'} = $tempNode->textContent();
1929
                        } else {
1930
                            $$templateVars{'useConstraintsOther'} = $tempNode->textContent();
1931
                        }
1932
                    }
1933
                }
1934
            }
1935
        }
1936
    }
1937

    
1938
    $results = $doc->findnodes('//dataset/distribution/online');
1939
    if ($results->size() > 1) {
1940
        errMoreThanOne("distribution/online");
1941
    } else {
1942
        foreach my $tempNode ($results->get_nodelist){
1943
            $$templateVars{'url'} = findValue($tempNode, "url");
1944
            dontOccur($tempNode, "./connection", "/distribution/online/connection");
1945
            dontOccur($tempNode, "./connectionDefinition", "/distribution/online/connectionDefinition");
1946
        }
1947
    }
1948

    
1949
    $results = $doc->findnodes('//dataset/distribution/offline');
1950
    if ($results->size() > 1) {
1951
        errMoreThanOne("distribution/online");
1952
    } else {
1953
        foreach my $tempNode ($results->get_nodelist) {
1954
            my $temp = findValue($tempNode, "mediumName");
1955
            if(substr($temp, 0, 5) eq "other"){
1956
                $$templateVars{'dataMedium'} = substr($temp, 0, 5);
1957
                $$templateVars{'dataMediumOther'} = substr($temp, 5);
1958
            } else {
1959
                $$templateVars{'dataMedium'} = $temp;
1960
            }
1961
            dontOccur($tempNode, "./mediumDensity", "/distribution/offline/mediumDensity");
1962
            dontOccur($tempNode, "./mediumDensityUnits", "/distribution/offline/mediumDensityUnits");
1963
            dontOccur($tempNode, "./mediumVolume", "/distribution/offline/mediumVolume");
1964
            dontOccur($tempNode, "./mediumFormat", "/distribution/offline/mediumFormat");
1965
            dontOccur($tempNode, "./mediumNote", "/distribution/offline/mediumNote");
1966
        }
1967
    }
1968

    
1969
    dontOccur($doc, "./inline", "//dataset/distribution/inline");
1970

    
1971
    $results = $doc->findnodes('//dataset/coverage');
1972
    if ($results->size() > 1) {
1973
        errMoreThanOne("coverage");
1974
    } else {
1975
        foreach $node ($results->get_nodelist) {
1976
            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");
1977

    
1978
            $tempResult = $node->findnodes('./temporalCoverage');
1979
            if ($tempResult->size > 1) {
1980
                   errMoreThanOne("temporalCoverage");
1981
            } else {
1982
                foreach $tempNode ($tempResult->get_nodelist) {
1983
                    my $x;
1984
                    my $y;
1985
                    my $z;
1986
                    my $tempdate = findValue($tempNode, "rangeOfDates/beginDate/calendarDate");
1987
                    ($x, $y, $z) = split("-", $tempdate); 
1988
                    $$templateVars{'beginningYear'} = $x;
1989
                    $$templateVars{'beginningMonth'} = $y;
1990
                    $$templateVars{'beginningDay'} = $z;
1991
    
1992
                    $tempdate = findValue($tempNode, "rangeOfDates/endDate/calendarDate");
1993
                    ($x, $y, $z) = split("-", $tempdate);
1994
                    $$templateVars{'endingYear'} = $x;
1995
                    $$templateVars{'endingMonth'} = $y;
1996
                    $$templateVars{'endingDay'} = $z;
1997

    
1998
                    $tempdate = "";
1999
                    $tempdate = findValue($tempNode, "singleDateTime/calendarDate");
2000
                    if($tempdate ne ""){
2001
                        ($x, $y, $z) = split("-", $tempdate);
2002
                        $$templateVars{'beginningYear'} = $x;
2003
                        $$templateVars{'beginningMonth'} = $y;
2004
                        $$templateVars{'beginningDay'} = $z;
2005
                    }  
2006
		    
2007
		    $$templateVars{'hasTemporal'} = "true";
2008
                }
2009
            }
2010

    
2011
            $tempResult = $node->findnodes('./geographicCoverage');
2012
            if ($tempResult->size > 1) {
2013
                errMoreThanOne("geographicCoverage");
2014
            } else {
2015
                foreach $tempNode ($tempResult->get_nodelist) {
2016
                    my $geogdesc = findValue($tempNode, "geographicDescription");
2017
                    debug("Registry: geogdesc from xml is: $geogdesc");
2018
                    $$templateVars{'geogdesc'} = $geogdesc;
2019
                    my $coord = findValue($tempNode, "boundingCoordinates/westBoundingCoordinate");
2020
                    if ($coord > 0) {
2021
                        #print "+";
2022
                        $$templateVars{'hemisphLong1'} = "E";
2023
                    } else {
2024
                        #print "-";
2025
                        eval($coord = $coord * -1);
2026
                        $$templateVars{'hemisphLong1'} = "W";
2027
                    }
2028
                    eval($$templateVars{'longDeg1'} = int($coord));
2029
                    eval($coord = ($coord - int($coord))*60);
2030
                    eval($$templateVars{'longMin1'} = int($coord));
2031
                    eval($coord = ($coord - int($coord))*60);
2032
                    eval($$templateVars{'longSec1'} = int($coord));
2033
                    
2034
                    $coord = findValue($tempNode, "boundingCoordinates/southBoundingCoordinate");
2035
                    if ($coord > 0) {
2036
                        #print "+";
2037
                        $$templateVars{'hemisphLat2'} = "N";
2038
                    } else {
2039
                        #print "-";
2040
                        eval($coord = $coord * -1);
2041
                        $$templateVars{'hemisphLat2'} = "S";
2042
                    }
2043
                    eval($$templateVars{'latDeg2'} = int($coord));
2044
                    eval($coord = ($coord - int($coord))*60);
2045
                    eval($$templateVars{'latMin2'} = int($coord));
2046
                    eval($coord = ($coord - int($coord))*60);
2047
                    eval($$templateVars{'latSec2'} = int($coord));
2048
        
2049
                    $coord = findValue($tempNode, "boundingCoordinates/northBoundingCoordinate");
2050
                    if ($coord > 0) {
2051
                        #print "+";
2052
                        $$templateVars{'hemisphLat1'} = "N";
2053
                    } else {
2054
                        #print "-";
2055
                        eval($coord = $coord * -1);
2056
                        $$templateVars{'hemisphLat1'} = "S";
2057
                    }
2058
                    eval($$templateVars{'latDeg1'} = int($coord));
2059
                    eval($coord = ($coord - int($coord))*60);
2060
                    eval($$templateVars{'latMin1'} = int($coord));
2061
                    eval($coord = ($coord - int($coord))*60);
2062
                    eval($$templateVars{'latSec1'} = int($coord));
2063
        
2064
                    $coord = findValue($tempNode, "boundingCoordinates/eastBoundingCoordinate");
2065
                    if ($coord > 0) {
2066
                        #print "+";
2067
                        $$templateVars{'hemisphLong2'} = "E";
2068
                    } else {
2069
                        #print "-";
2070
                        eval($coord = $coord * -1);
2071
                        $$templateVars{'hemisphLong2'} = "W";
2072
                    }
2073
                    eval($$templateVars{'longDeg2'} = int($coord));
2074
                    eval($coord = ($coord - int($coord))*60);
2075
                    eval($$templateVars{'longMin2'} = int($coord));
2076
                    eval($coord = ($coord - int($coord))*60);
2077
                    eval($$templateVars{'longSec2'} = int($coord));
2078

    
2079
		            $$templateVars{'hasSpatial'} = "true";
2080
                }
2081
            }
2082

    
2083
            $tempResult = $node->findnodes('./taxonomicCoverage/taxonomicClassification');
2084
            my $taxonIndex = 0;
2085
            foreach $tempNode ($tempResult->get_nodelist) {
2086
                $taxonIndex++;
2087
                my $taxonRankName = findValue($tempNode, "taxonRankName");
2088
                my $taxonRankValue = findValue($tempNode, "taxonRankValue");
2089
                $$templateVars{"taxonRankName".$taxonIndex} = $taxonRankName;
2090
                $$templateVars{"taxonRankValue".$taxonIndex} = $taxonRankValue;
2091
		
2092
		$$templateVars{'hasTaxonomic'} = "true";
2093
            }
2094
            $$templateVars{'taxaCount'} = $taxonIndex;
2095
            my $taxaAuth = findValue($node, "./taxonomicCoverage/generalTaxonomicCoverage");
2096
            $$templateVars{'taxaAuth'} = $taxaAuth;
2097
        }
2098
    }
2099
    dontOccur($doc, "./purpose", "purpose");
2100
    dontOccur($doc, "./maintenance", "maintnance");
2101

    
2102
    $results = $doc->findnodes('//dataset/contact/individualName');
2103
    if ($results->size() > 1) {
2104
        errMoreThanOne("contact/individualName");
2105
    } else {
2106
        foreach $node ($results->get_nodelist) {
2107
            dontOccur($node, "../positionName|../onlineURL|../userId", 
2108
              "positionName, onlineURL, userId in contact tag");
2109
            dontOccur($node, "./saluation", "saluation in contact tag");                
2110
        
2111
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
2112
            if ($tempResult->size > 0) {
2113
                $$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
2114
                $$templateVars{'origNamelastContact'} = findValue($node, 'surName');
2115
    
2116
                my $tempResult2 = $node->findnodes('../address');
2117
                if ($tempResult2->size > 1) {
2118
                    errMoreThanOne("address");
2119
                } else {
2120
                    foreach my $tempNode2 ($tempResult2->get_nodelist) {
2121
                        $$templateVars{'origDeliveryContact'} = findValue($tempNode2, 'deliveryPoint');
2122
                        $$templateVars{'origCityContact'} = findValue($tempNode2, 'city');
2123
                        $$templateVars{'origStateContact'} = findValue($tempNode2, 'administrativeArea');
2124
                        $$templateVars{'origZIPContact'} = findValue($tempNode2, 'postalCode');
2125
                        $$templateVars{'origCountryContact'} = findValue($tempNode2, 'country');
2126
                    }
2127
                }
2128
            
2129
                my $tempResult3 = $node->findnodes('../phone');
2130
                if ($tempResult3->size > 2) {
2131
                    errMoreThanN("phone");
2132
                } else {
2133
                    foreach my $tempNode2 ($tempResult3->get_nodelist) {
2134
                        if ($tempNode2->hasAttributes()) {
2135
                            my @attlist = $tempNode2->attributes();
2136
                            if ($attlist[0]->value eq "Fax") {
2137
                                $$templateVars{'origFAXContact'} = $tempNode2->textContent();
2138
                            } else {
2139
                                $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
2140
                            }
2141
                        } else {
2142
                            $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
2143
                        }
2144
                    }
2145
                }
2146
                $$templateVars{'origEmailContact'} = findValue($node, '../electronicMailAddress');
2147
                $$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
2148
            } else {
2149
                $$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
2150
                $$templateVars{'origNamelastContact'} = findValue($node, 'surName');
2151
                $$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
2152
            }
2153
        }
2154
    }
2155
    
2156
    $results = $doc->findnodes(
2157
            '//dataset/methods/methodStep/description/section');
2158
    debug("Registry: Number methods: ".$results->size());
2159
    if ($results->size() > 1) {
2160
        errMoreThanN("methods/methodStep/description/section");    
2161
    } else {
2162

    
2163
        my @methodPara;
2164
        foreach $node ($results->get_nodelist) {
2165
            my @children = $node->childNodes;
2166
            for (my $i = 0; $i < scalar(@children); $i++) {
2167
                debug("Registry: Method child loop ($i)");
2168
                my $child = $children[$i];
2169
                if ($child->nodeName eq 'title') {
2170
                    my $title = $child->textContent();
2171
                    debug("Registry: Method title ($title)");
2172
                    $$templateVars{'methodTitle'} = $title;
2173
                } elsif ($child->nodeName eq 'para') {
2174
                    my $para = $child->textContent();
2175
                    debug("Registry: Method para ($para)");
2176
                    $methodPara[scalar(@methodPara)] = $para;
2177
                }
2178
            }
2179
	    $$templateVars{'hasMethod'} = "true";
2180
        }
2181
        if (scalar(@methodPara) > 0) {
2182
            $$templateVars{'methodPara'} = \@methodPara;
2183
        }
2184
    }
2185

    
2186
    $results = $doc->findnodes(
2187
            '//dataset/methods/sampling/studyExtent/description/para');
2188
    if ($results->size() > 1) {
2189
        errMoreThanN("methods/sampling/studyExtent/description/para");    
2190
    } else {
2191
        foreach $node ($results->get_nodelist) {
2192
            my $studyExtentDescription = $node->textContent();
2193
            $$templateVars{'studyExtentDescription'} = $studyExtentDescription;
2194

    
2195
	    $$templateVars{'hasMethod'} = "true";
2196
        }
2197
    }
2198

    
2199
    $results = $doc->findnodes(
2200
            '//dataset/methods/sampling/samplingDescription/para');
2201
    if ($results->size() > 1) {
2202
        errMoreThanN("methods/sampling/samplingDescription/para");    
2203
    } else {
2204
        foreach $node ($results->get_nodelist) {
2205
            my $samplingDescription = $node->textContent();
2206
            $$templateVars{'samplingDescription'} = $samplingDescription;
2207

    
2208
	    $$templateVars{'hasMethod'} = "true";
2209
        }
2210
    }
2211

    
2212
    dontOccur($doc, "//methodStep/citation", "methodStep/citation");
2213
    dontOccur($doc, "//methodStep/protocol", "methodStep/protocol");
2214
    dontOccur($doc, "//methodStep/instrumentation", "methodStep/instrumentation");
2215
    dontOccur($doc, "//methodStep/software", "methodStep/software");
2216
    dontOccur($doc, "//methodStep/subStep", "methodStep/subStep");
2217
    dontOccur($doc, "//methodStep/dataSource", "methodStep/dataSource");
2218
    dontOccur($doc, "//methods/qualityControl", "methods/qualityControl");
2219

    
2220
    dontOccur($doc, "//methods/sampling/spatialSamplingUnits", "methods/sampling/spatialSamplingUnits");
2221
    dontOccur($doc, "//methods/sampling/citation", "methods/sampling/citation");
2222
    dontOccur($doc, "./pubPlace", "pubPlace");
2223
    dontOccur($doc, "./project", "project");
2224
    
2225
    ############ Code for checking ACL #####################
2226
    dontOccur($doc, "//dataset/access/deny", "dataset/access/deny");
2227

    
2228
    $results = $doc->findnodes('//dataset/access/allow');
2229
    if ($results->size() != 3) {
2230
        errMoreThanN("dataset/access/allow");
2231
    } else {
2232
	my $accessError = 0;
2233
        foreach $node ($results->get_nodelist) {
2234
            my @children = $node->childNodes;
2235
	    my $principal = "";
2236
	    my $permission = "";
2237
            for (my $i = 0; $i < scalar(@children); $i++) {
2238
                my $child = $children[$i];
2239
                if ($child->nodeName eq 'principal') {
2240
                    $principal = $child->textContent();
2241
                } elsif ($child->nodeName eq 'permission') {
2242
                    $permission = $child->textContent();
2243
                }
2244
            }
2245
	
2246
	    if ($principal eq 'public' && $permission ne 'read') { $accessError = 1; }
2247
	    if ($principal eq $username && $permission ne 'all') { $accessError = 2; }
2248
	    if ($principal ne 'public' && $principal ne $username && $permission ne 'all') { $accessError = 3; }
2249
	}
2250
 
2251
	if ($accessError != 0) {
2252
	    my $error ="The ACL for this document has been changed outside the registry. Please use Morpho to edit this document";
2253
            push(@errorMessages, $error."\n");
2254
	}     
2255
    }
2256
    ########################################################
2257

    
2258

    
2259
    dontOccur($doc, "./dataTable", "dataTable");
2260
    dontOccur($doc, "./spatialRaster", "spatialRaster");
2261
    dontOccur($doc, "./spatialVector", "spatialVector");
2262
    dontOccur($doc, "./storedProcedure", "storedProcedure");
2263
    dontOccur($doc, "./view", "view");
2264
    dontOccur($doc, "./otherEntity", "otherEntity");
2265
    dontOccur($doc, "./references", "references");
2266
    
2267
    dontOccur($doc, "//citation", "citation");
2268
    dontOccur($doc, "//software", "software");
2269
    dontOccur($doc, "//protocol", "protocol");
2270
    dontOccur($doc, "//additionalMetadata", "additionalMetadata");    
2271
}
2272

    
2273
################################################################################
2274
# 
2275
# Delete the eml file that has been requested for deletion. 
2276
#
2277
################################################################################
2278
sub deleteData {
2279
    my $deleteAll = shift;
2280
    
2281
    # create metacat instance
2282
    my $metacat;
2283
    my $docid = $FORM::docid;
2284
    
2285
    $metacat = Metacat->new();
2286
    if ($metacat) {
2287
        $metacat->set_options( metacatUrl => $metacatUrl );
2288
    } else {
2289
        #die "failed during metacat creation\n";
2290
        push(@errorMessages, "Failed during metacat creation.");
2291
    }
2292

    
2293
    # Login to metacat
2294
    my $userDN = $FORM::username;
2295
    my $userOrg = $FORM::organization;
2296
    my $userPass = $FORM::password;
2297
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
2298
    
2299
    my $errorMessage = "";
2300
    my $response = $metacat->login($dname, $userPass);
2301

    
2302
    if (! $response) {
2303
    # Could not login
2304
        push(@errorMessages, $metacat->getMessage());
2305
        push(@errorMessages, "Failed during login.\n");
2306

    
2307
    } else {
2308
    #Able to login - try to delete the file    
2309

    
2310
    my $parser;
2311
    my @fileArray;
2312
    my $httpMessage;
2313
    my $xmldoc;
2314
    my $doc;
2315
    my $pushDoc;
2316
    my $alreadyInArray;
2317
    my $findType;
2318
        my $node;
2319
    my $response; 
2320
    my $element;
2321

    
2322
    push (@fileArray, $docid);
2323
    $parser = XML::LibXML->new();
2324

    
2325
        $httpMessage = $metacat->read($docid);
2326
    $doc = $httpMessage->content();    
2327
    $doc = delNormalize($doc);
2328
    $xmldoc = $parser->parse_string($doc);
2329

    
2330
    if ($xmldoc eq "") {
2331
        $error ="Error in parsing the eml document";
2332
        push(@errorMessages, $error);
2333
    } else {
2334

    
2335
        $findType = $xmldoc->findnodes('//dataset/identifier');
2336
        if($findType->size() > 0){
2337
        # This is a eml beta6 document
2338
        # Delete the documents mentioned in triples also
2339
        
2340
        $findType = $xmldoc->findnodes('//dataset/triple');
2341
        if($findType->size() > 0){
2342
            foreach $node ($findType->get_nodelist){
2343
            $pushDoc = findValue($node, 'subject');
2344
            
2345
            # If the file is already in the @fileArray then do not add it 
2346
            $alreadyInArray = 0;
2347
            foreach $element (@fileArray){
2348
                if($element eq $pushDoc){
2349
                $alreadyInArray = 1;
2350
                }
2351
            }
2352
            
2353
            if(!$alreadyInArray){
2354
                # If not already in array then delete the file. 
2355
                push (@fileArray, $pushDoc);
2356
                $response = $metacat->delete($pushDoc);
2357
                
2358
                if (! $response) {
2359
                # Could not delete
2360
                #push(@errorMessages, $response);
2361
                push(@errorMessages, $metacat->getMessage());
2362
                push(@errorMessages, "Failed during deleting $pushDoc. Please check if you are authorized to delete this document.\n");
2363
                }
2364
            }
2365
            }
2366
        }
2367
        }
2368
    }
2369
    
2370
    # Delete the main document. 
2371
    if($deleteAll){
2372
        $response = $metacat->delete($docid);  
2373
        if (! $response) {
2374
        # Could not delete
2375
        #push(@errorMessages, $response);
2376
        push(@errorMessages, $metacat->getMessage());
2377
        push(@errorMessages, "Failed during deleting $docid. Please check if you are authorized to delete this document.\n");
2378
        }
2379
    }
2380
    }
2381
    
2382
    if (scalar(@errorMessages)) {
2383
    # If any errors, print them in the response template 
2384
    $$templateVars{'status'} = 'failure';
2385
    $$templateVars{'errorMessages'} = \@errorMessages;
2386
    $error = 1;
2387
    }
2388
    
2389
    # Process the response template
2390
    if($deleteAll){
2391

    
2392
    $$templateVars{'function'} = "deleted";
2393
    $$templateVars{'section'} = "Deletion Status";
2394
    $template->process( $responseTemplate, $templateVars);
2395
    }
2396
}
2397

    
2398

    
2399
################################################################################
2400
# 
2401
# Do data validation and send the data to confirm data template.
2402
#
2403
################################################################################
2404
sub toConfirmData{
2405
    # Check if any invalid parameters
2406
 
2407
    my $invalidParams;
2408
    if (! $error) {
2409
    $invalidParams = validateParameters(0);
2410
    if (scalar(@$invalidParams)) {
2411
        $$templateVars{'status'} = 'failure';
2412
        $$templateVars{'invalidParams'} = $invalidParams;
2413
        $error = 1;
2414
    }
2415
    }
2416

    
2417

    
2418
    $$templateVars{'providerGivenName'} = normalizeCD($FORM::providerGivenName);
2419
    $$templateVars{'providerSurName'} = normalizeCD($FORM::providerSurName);
2420
    if($FORM::site eq "Select your station here."){
2421
        $$templateVars{'site'} = "";
2422
    }else{
2423
        $$templateVars{'site'} = $FORM::site;
2424
    }
2425
    if($FORM::cfg eq "nceas"){
2426
        $$templateVars{'wg'} = \@FORM::wg;
2427
    }
2428
    $$templateVars{'identifier'} = normalizeCD($FORM::identifier);
2429
    $$templateVars{'title'} = normalizeCD($FORM::title);
2430
    $$templateVars{'origNamefirst0'} = normalizeCD($FORM::origNamefirst0);
2431
    $$templateVars{'origNamelast0'} = normalizeCD($FORM::origNamelast0);
2432
    $$templateVars{'origNameOrg'} = normalizeCD($FORM::origNameOrg);
2433
    # $$templateVars{'origRole0'} = $FORM::origRole0;
2434
    $$templateVars{'origDelivery'} = normalizeCD($FORM::origDelivery);
2435
    $$templateVars{'origCity'} = normalizeCD($FORM::origCity);
2436
    if($FORM::origState eq "Select State Here."){
2437
        $$templateVars{'origState'} = "";
2438
    }else{
2439
        $$templateVars{'origState'} = $FORM::origState;
2440
    }
2441
    $$templateVars{'origStateOther'} = normalizeCD($FORM::origStateOther);
2442
    $$templateVars{'origZIP'} = normalizeCD($FORM::origZIP);
2443
    $$templateVars{'origCountry'} = normalizeCD($FORM::origCountry);
2444
    $$templateVars{'origPhone'} = normalizeCD($FORM::origPhone);
2445
    $$templateVars{'origFAX'} = normalizeCD($FORM::origFAX);
2446
    $$templateVars{'origEmail'} = normalizeCD($FORM::origEmail);
2447
    $$templateVars{'useOrigAddress'} = normalizeCD($FORM::useOrigAddress);
2448
    if($FORM::useOrigAddress eq "on"){
2449
        $$templateVars{'origNamefirstContact'} = normalizeCD($FORM::origNamefirst0);
2450
        $$templateVars{'origNamelastContact'} = normalizeCD($FORM::origNamelast0);
2451
        $$templateVars{'origNameOrgContact'} = normalizeCD($FORM::origNameOrg);
2452
        $$templateVars{'origDeliveryContact'} = normalizeCD($FORM::origDelivery); 
2453
        $$templateVars{'origCityContact'} = normalizeCD($FORM::origCity);
2454
        if($FORM::origState eq "Select State Here."){
2455
        $$templateVars{'origStateContact'} = "";
2456
        }else{
2457
        $$templateVars{'origStateContact'} = $FORM::origState;
2458
        }
2459
        $$templateVars{'origStateOtherContact'} = normalizeCD($FORM::origStateOther);
2460
        $$templateVars{'origZIPContact'} = normalizeCD($FORM::origZIP);
2461
        $$templateVars{'origCountryContact'} = normalizeCD($FORM::origCountry);
2462
        $$templateVars{'origPhoneContact'} = normalizeCD($FORM::origPhone);
2463
        $$templateVars{'origFAXContact'} = normalizeCD($FORM::origFAX);
2464
        $$templateVars{'origEmailContact'} = normalizeCD($FORM::origEmail);
2465
    }else{
2466
        $$templateVars{'origNamefirstContact'} = normalizeCD($FORM::origNamefirstContact);
2467
        $$templateVars{'origNamelastContact'} = normalizeCD($FORM::origNamelastContact);
2468
        $$templateVars{'origNameOrgContact'} = normalizeCD($FORM::origNameOrgContact);
2469
        $$templateVars{'origDeliveryContact'} = normalizeCD($FORM::origDeliveryContact); 
2470
        $$templateVars{'origCityContact'} = normalizeCD($FORM::origCityContact);
2471
        if($FORM::origStateContact eq "Select State Here."){
2472
        $$templateVars{'origStateContact'} = "";
2473
        }else{
2474
        $$templateVars{'origStateContact'} = $FORM::origStateContact;
2475
        }
2476
        $$templateVars{'origStateOtherContact'} = normalizeCD($FORM::origStateOtherContact);
2477
        $$templateVars{'origZIPContact'} = normalizeCD($FORM::origZIPContact);
2478
        $$templateVars{'origCountryContact'} = normalizeCD($FORM::origCountryContact);
2479
        $$templateVars{'origPhoneContact'} = normalizeCD($FORM::origPhoneContact);
2480
        $$templateVars{'origFAXContact'} = normalizeCD($FORM::origFAXContact);
2481
        $$templateVars{'origEmailContact'} = normalizeCD($FORM::origEmailContact);    
2482
    }
2483

    
2484
    my $aoFNArray = \@FORM::aoFirstName;
2485
    my $aoLNArray = \@FORM::aoLastName;
2486
    my $aoRoleArray = \@FORM::aoRole;
2487
    my $aoCount = 1;
2488

    
2489
    for(my $i = 0; $i <= $#$aoRoleArray; $i++){
2490
        if (hasContent($aoFNArray->[$i]) && hasContent($aoLNArray->[$i])) {
2491
            debug("Registry processing Associated Party: origName = ".$aoFNArray->[$i]
2492
                  ." origNamelast = ".$aoLNArray->[$i]." origRole = "
2493
                  .$aoRoleArray->[$i]);
2494
            $$templateVars{"origNamefirst".$aoCount} = normalizeCD($aoFNArray->[$i]);
2495
            $$templateVars{"origNamelast".$aoCount} = normalizeCD($aoLNArray->[$i]);
2496
            $$templateVars{"origRole".$aoCount} = normalizeCD($aoRoleArray->[$i]);
2497
            $aoCount++;
2498
	}    
2499
    }
2500

    
2501
    $$templateVars{'aoCount'} = $aoCount;
2502
    $$templateVars{'abstract'} = normalizeCD($FORM::abstract);
2503
   
2504
   
2505
    my $keywordArray = \@FORM::keyword;
2506
    my $keywordTypeArray = \@FORM::keywordType;
2507
    my $keywordThArray = \@FORM::keywordTh;
2508
    my $keyCount = 1;
2509
   
2510
    for(my $i = 0; $i <= $#$keywordArray; $i++){
2511
        if (hasContent($keywordArray->[$i])) {
2512
            debug("Registry processing keyword: keyword = ".$keywordArray->[$i]."
2513
                  keywordType = ".$keywordTypeArray->[$i]."
2514
                  keywordTh = ".$keywordThArray->[$i]);
2515
            $$templateVars{"keyword".$keyCount} = normalizeCD($keywordArray->[$i]);
2516
            $$templateVars{"kwType".$keyCount} = normalizeCD($keywordTypeArray->[$i]);
2517
            $$templateVars{"kwTh".$keyCount} = normalizeCD($keywordThArray->[$i]);
2518
            $keyCount++;
2519
	}    
2520
    }    
2521
    $$templateVars{'keyCount'} = $keyCount;
2522
    
2523
    $$templateVars{'addComments'} = normalizeCD($FORM::addComments);
2524
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2525
    if($FORM::useConstraints eq "other"){
2526
        $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2527
    }
2528
    $$templateVars{'url'} = $FORM::url;
2529
    $$templateVars{'dataMedium'} = $FORM::dataMedium;
2530
    if($FORM::dataMedium eq "other"){
2531
        $$templateVars{'dataMediumOther'} = normalizeCD($FORM::dataMediumOther);
2532
    }
2533
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2534
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2535
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2536
    $$templateVars{'endingYear'} = $FORM::endingYear;
2537
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2538
    $$templateVars{'endingDay'} = $FORM::endingDay;
2539
    $$templateVars{'geogdesc'} = normalizeCD($FORM::geogdesc);
2540
    $$templateVars{'useSiteCoord'} = $FORM::useSiteCoord;
2541
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2542
    $$templateVars{'latMin1'} = $FORM::latMin1;
2543
    $$templateVars{'latSec1'} = $FORM::latSec1;
2544
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2545
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2546
    $$templateVars{'longMin1'} = $FORM::longMin1;
2547
    $$templateVars{'longSec1'} = $FORM::longSec1;
2548
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2549
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2550
    $$templateVars{'latMin2'} = $FORM::latMin2;
2551
    $$templateVars{'latSec2'} = $FORM::latSec2;
2552
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2553
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2554
    $$templateVars{'longMin2'} = $FORM::longMin2;
2555
    $$templateVars{'longSec2'} = $FORM::longSec2;
2556
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2557

    
2558
    my $taxonRankArray = \@FORM::taxonRank;
2559
    my $taxonNameArray = \@FORM::taxonName;
2560
    my $taxonCount = 1;
2561

    
2562
    for(my $i = 0; $i <= $#$taxonNameArray; $i++){
2563
        if (hasContent($taxonRankArray->[$i]) && hasContent($taxonNameArray->[$i])) {
2564
            debug("Registry processing keyword: trv = ".$taxonRankArray->[$i]
2565
                    ." trn = ".$taxonNameArray->[$i]);
2566
            $$templateVars{"taxonRankName".$taxonCount} = normalizeCD($taxonNameArray->[$i]);
2567
            $$templateVars{"taxonRankValue".$taxonCount} = normalizeCD($taxonRankArray->[$i]);
2568
            $taxonCount++;
2569
	}    
2570
    }
2571

    
2572
    $$templateVars{'taxaCount'} = $taxonCount-1;
2573
    $$templateVars{'taxaAuth'} = normalizeCD($FORM::taxaAuth);
2574

    
2575
    $$templateVars{'methodTitle'} = normalizeCD($FORM::methodTitle);
2576
 
2577
    my @tempMethodPara;
2578
    for (my $i = 0; $i < scalar(@FORM::methodPara); $i++) {
2579
	$tempMethodPara[$i] = normalizeCD($FORM::methodPara[$i]);
2580
    }
2581
    $$templateVars{'methodPara'} = \@tempMethodPara;
2582
    $$templateVars{'studyExtentDescription'} = normalizeCD($FORM::studyExtentDescription);
2583
    $$templateVars{'samplingDescription'} = normalizeCD($FORM::samplingDescription);
2584
    $$templateVars{'origStateContact'} = $FORM::origState;
2585

    
2586
    $$templateVars{'showSiteList'} = $FORM::showSiteList;
2587
    $$templateVars{'lsite'} = $FORM::lsite;
2588
    $$templateVars{'usite'} = $FORM::usite;
2589
    $$templateVars{'showWgList'} = $FORM::showWgList;
2590
    $$templateVars{'showOrganization'} = $FORM::showOrganization;
2591
    $$templateVars{'hasKeyword'} = $FORM::hasKeyword;
2592
    $$templateVars{'hasTemporal'} = $FORM::hasTemporal;
2593
    $$templateVars{'hasSpatial'} = $FORM::hasSpatial;
2594
    $$templateVars{'hasTaxonomic'} = $FORM::hasTaxonomic;
2595
    $$templateVars{'hasMethod'} = $FORM::hasMethod;
2596
    $$templateVars{'spatialRequired'} = $FORM::spatialRequired;
2597
    $$templateVars{'temporalRequired'} = $FORM::temporalRequired;
2598

    
2599
    $$templateVars{'docid'} = $FORM::docid;
2600

    
2601
    if (! $error) {
2602
	# If no errors, then print out data in confirm Data template
2603

    
2604
	$$templateVars{'section'} = "Confirm Data";
2605
	$template->process( $confirmDataTemplate, $templateVars);
2606

    
2607
    } else{    
2608
    # Errors from validation function. print the errors out using the response template
2609
    if (scalar(@errorMessages)) {
2610
        $$templateVars{'status'} = 'failure';
2611
        $$templateVars{'errorMessages'} = \@errorMessages;
2612
        $error = 1;
2613
    }
2614
        # Create our HTML response and send it back
2615
    $$templateVars{'function'} = "submitted";
2616
    $$templateVars{'section'} = "Submission Status";
2617
    $template->process( $responseTemplate, $templateVars);
2618
    }
2619
}
2620

    
2621

    
2622
################################################################################
2623
# 
2624
# From confirm Data template - user wants to make some changes.
2625
#
2626
################################################################################
2627
sub confirmDataToReEntryData{
2628
    my @sortedSites;
2629
    foreach my $site (sort @sitelist) {
2630
        push(@sortedSites, $site);
2631
    }
2632

    
2633
    $$templateVars{'siteList'} = \@sortedSites;
2634
    $$templateVars{'section'} = "Re-Entry Form";
2635
    copyFormToTemplateVars();
2636
    $$templateVars{'docid'} = $FORM::docid;
2637

    
2638
    $$templateVars{'form'} = 're_entry';
2639
    $template->process( $entryFormTemplate, $templateVars);
2640
}
2641

    
2642

    
2643
################################################################################
2644
# 
2645
# Copy form data to templateVars.....
2646
#
2647
################################################################################
2648
sub copyFormToTemplateVars{
2649
    $$templateVars{'providerGivenName'} = $FORM::providerGivenName;
2650
    $$templateVars{'providerSurName'} = $FORM::providerSurName;
2651
    $$templateVars{'site'} = $FORM::site;
2652
    if ($FORM::cfg eq "nceas") {
2653
        my $projects = getProjectList();
2654
        $$templateVars{'projects'} = $projects;
2655
        $$templateVars{'wg'} = \@FORM::wg;
2656
    }
2657
    $$templateVars{'identifier'} = $FORM::identifier;
2658
    $$templateVars{'title'} = $FORM::title;
2659
    $$templateVars{'origNamefirst0'} = $FORM::origNamefirst0;
2660
    $$templateVars{'origNamelast0'} = $FORM::origNamelast0;
2661
    $$templateVars{'origNameOrg'} = $FORM::origNameOrg;
2662
 #   $$templateVars{'origRole0'} = $FORM::origRole0;
2663
    $$templateVars{'origDelivery'} = $FORM::origDelivery;
2664
    $$templateVars{'origCity'} = $FORM::origCity;
2665
    $$templateVars{'origState'} = $FORM::origState;
2666
    $$templateVars{'origStateOther'} = $FORM::origStateOther;
2667
    $$templateVars{'origZIP'} = $FORM::origZIP;
2668
    $$templateVars{'origCountry'} = $FORM::origCountry;
2669
    $$templateVars{'origPhone'} = $FORM::origPhone;
2670
    $$templateVars{'origFAX'} = $FORM::origFAX;
2671
    $$templateVars{'origEmail'} = $FORM::origEmail;
2672
    if ($FORM::useSiteCoord ne "") {
2673
        $$templateVars{'useOrigAddress'} = "CHECKED";
2674
    }else{
2675
        $$templateVars{'useOrigAddress'} = $FORM::useOrigAddress;
2676
    }
2677
    $$templateVars{'origNamefirstContact'} = $FORM::origNamefirstContact;
2678
    $$templateVars{'origNamelastContact'} = $FORM::origNamelastContact;
2679
    $$templateVars{'origNameOrgContact'} = $FORM::origNameOrgContact;
2680
    $$templateVars{'origDeliveryContact'} = $FORM::origDeliveryContact; 
2681
    $$templateVars{'origCityContact'} = $FORM::origCityContact;
2682
    $$templateVars{'origStateContact'} = $FORM::origStateContact;
2683
    $$templateVars{'origStateOtherContact'} = $FORM::origStateOtherContact;
2684
    $$templateVars{'origZIPContact'} = $FORM::origZIPContact;
2685
    $$templateVars{'origCountryContact'} = $FORM::origCountryContact;
2686
    $$templateVars{'origPhoneContact'} = $FORM::origPhoneContact;
2687
    $$templateVars{'origFAXContact'} = $FORM::origFAXContact;
2688
    $$templateVars{'origEmailContact'} = $FORM::origEmailContact;    
2689
    
2690
    $$templateVars{'aoCount'} = $FORM::aoCount;
2691
    foreach my $origName (param()) {
2692
	if ($origName =~ /origNamefirst/) {
2693
	    my $origNameIndex = $origName;
2694
	    $origNameIndex =~ s/origNamefirst//; # get the index of the parameter 0, ..., 10
2695
	    my $origNamelast = "origNamelast".$origNameIndex;
2696
	    my $origRole = "origRole".$origNameIndex;
2697
	    if ( $origNameIndex =~ /[0-9]/  && $origNameIndex > 0){
2698
		if (hasContent(param($origName)) && hasContent(param($origNamelast)) && hasContent(param($origRole))) {
2699
		    debug("Registry processing keyword: $origName = ".param($origName)." $origNamelast = ".param($origNamelast)." $origRole = ".param($origRole));
2700
		    $$templateVars{$origName} = normalizeCD(param($origName));
2701
		    $$templateVars{$origNamelast} = normalizeCD(param($origNamelast));
2702
		    $$templateVars{$origRole} = normalizeCD(param($origRole));
2703
		}
2704
	    }
2705
	}
2706
    }
2707

    
2708
    $$templateVars{'abstract'} = $FORM::abstract;
2709
    $$templateVars{'keyCount'} = $FORM::keyCount;
2710
    foreach my $kyd (param()) {
2711
	if ($kyd =~ /keyword/) {
2712
	    my $keyIndex = $kyd;
2713
	    $keyIndex =~ s/keyword//; # get the index of the parameter 0, ..., 10
2714
	    my $keyType = "kwType".$keyIndex;
2715
	    my $keyTh = "kwTh".$keyIndex;
2716
	    if ( $keyIndex =~ /[0-9]/ ){
2717
		if (hasContent(param($kyd)) && hasContent(param($keyType)) && hasContent(param($keyTh))) {
2718
		    debug("Registry processing keyword: $kyd = ".param($kyd)." $keyType = ".param($keyType)." $keyTh = ".param($keyTh));
2719
		    $$templateVars{$kyd} = param($kyd); 
2720
                    my $tmp = param($keyType);  #convert the first letter to upper case
2721
		    $tmp =~ s/\b(\w)/\U$1/g;
2722
                    $$templateVars{$keyType} = $tmp;
2723
		    $$templateVars{$keyTh} = param($keyTh);
2724
		}
2725
	    }
2726
	}
2727
    }
2728
    $$templateVars{'addComments'} = $FORM::addComments;
2729
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2730
    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2731
    $$templateVars{'url'} = $FORM::url;
2732
    $$templateVars{'dataMedium'} = $FORM::dataMedium;
2733
    $$templateVars{'dataMediumOther'} = $FORM::dataMediumOther;
2734
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2735
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2736
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2737
    $$templateVars{'endingYear'} = $FORM::endingYear;
2738
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2739
    $$templateVars{'endingDay'} = $FORM::endingDay;
2740
    $$templateVars{'geogdesc'} = $FORM::geogdesc;
2741
    if($FORM::useSiteCoord ne ""){
2742
    $$templateVars{'useSiteCoord'} = "CHECKED";
2743
    }else{
2744
    $$templateVars{'useSiteCoord'} = "";
2745
    }
2746
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2747
    $$templateVars{'latMin1'} = $FORM::latMin1;
2748
    $$templateVars{'latSec1'} = $FORM::latSec1;
2749
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2750
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2751
    $$templateVars{'longMin1'} = $FORM::longMin1;
2752
    $$templateVars{'longSec1'} = $FORM::longSec1;
2753
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2754
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2755
    $$templateVars{'latMin2'} = $FORM::latMin2;
2756
    $$templateVars{'latSec2'} = $FORM::latSec2;
2757
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2758
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2759
    $$templateVars{'longMin2'} = $FORM::longMin2;
2760
    $$templateVars{'longSec2'} = $FORM::longSec2;
2761
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2762
    $$templateVars{'taxaCount'} = $FORM::taxaCount;
2763
    foreach my $trn (param()) {
2764
        if ($trn =~ /taxonRankName/) {
2765
            my $taxIndex = $trn;
2766
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
2767
            my $trv = "taxonRankValue".$taxIndex;
2768
            if ( $taxIndex =~ /[0-9]/ ){
2769
                if (hasContent(param($trn)) && hasContent(param($trv))) {
2770
                    debug("Registry processing taxon: $trn = ".param($trn)." $trv = ".param($trv));
2771
                    $$templateVars{$trn} = param($trn);
2772
                    $$templateVars{$trv} = param($trv);
2773
                }
2774
            }
2775
        }
2776
    }
2777
    $$templateVars{'taxaAuth'} = $FORM::taxaAuth;
2778
    $$templateVars{'methodTitle'} = $FORM::methodTitle;
2779
    $$templateVars{'methodPara'} = \@FORM::methodPara;
2780
    $$templateVars{'studyExtentDescription'} = $FORM::studyExtentDescription;
2781
    $$templateVars{'samplingDescription'} = $FORM::samplingDescription;
2782
    
2783
    $$templateVars{'showSiteList'} = $FORM::showSiteList;
2784
    $$templateVars{'lsite'} = $FORM::lsite;
2785
    $$templateVars{'usite'} = $FORM::usite;
2786
    $$templateVars{'showWgList'} = $FORM::showWgList;
2787
    $$templateVars{'showOrganization'} = $FORM::showOrganization;
2788
    $$templateVars{'hasKeyword'} = $FORM::hasKeyword;
2789
    $$templateVars{'hasTemporal'} = $FORM::hasTemporal;
2790
    $$templateVars{'hasSpatial'} = $FORM::hasSpatial;
2791
    $$templateVars{'hasTaxonomic'} = $FORM::hasTaxonomic;
2792
    $$templateVars{'hasMethod'} = $FORM::hasMethod;
2793
    $$templateVars{'spatialRequired'} = $FORM::spatialRequired;
2794
    $$templateVars{'temporalRequired'} = $FORM::temporalRequired;
2795
}
2796

    
2797
################################################################################
2798
# 
2799
# check if there is multiple occurence of the given tag and find its value.
2800
#
2801
################################################################################
2802

    
2803
sub findValue {
2804
    my $node = shift;
2805
    my $value = shift;
2806
    my $result;
2807
    my $tempNode;
2808

    
2809
    $result = $node->findnodes("./$value");
2810
    if ($result->size > 1) {
2811
        errMoreThanOne("$value");
2812
    } else {
2813
        foreach $tempNode ($result->get_nodelist){
2814
            #print $tempNode->nodeName().":".$tempNode->textContent();
2815
            #print "\n";
2816
            return $tempNode->textContent();
2817
        }
2818
    }
2819
}
2820

    
2821

    
2822
################################################################################
2823
# 
2824
# check if given tags has any children. if not return the value
2825
#
2826
################################################################################
2827
sub findValueNoChild {
2828
    my $node = shift;
2829
    my $value = shift;
2830
    my $tempNode;
2831
    my $childNodes;
2832
    my $result;
2833
    my $error;
2834

    
2835
    $result = $node->findnodes("./$value");
2836
    if($result->size > 1){
2837
       errMoreThanOne("$value");
2838
    } else {
2839
        foreach $tempNode ($result->get_nodelist) {
2840
            $childNodes = $tempNode->childNodes;
2841
            if ($childNodes->size() > 1) {
2842
                $error ="The tag $value has children which cannot be shown using the form. Please use Morpho to edit this document";    
2843
                push(@errorMessages, $error);
2844
                #if ($DEBUG == 1){ print $error."\n";}
2845
            } else {
2846
                #print $tempNode->nodeName().":".$tempNode->textContent();
2847
                #print "\n";
2848
                return $tempNode->textContent();
2849
            }
2850
        }
2851
    }
2852
}
2853

    
2854

    
2855
################################################################################
2856
# 
2857
# check if given tags are children of given node.
2858
#
2859
################################################################################
2860
sub dontOccur {
2861
    my $node = shift;
2862
    my $value = shift;
2863
    my $errVal = shift;
2864

    
2865
    my $result = $node->findnodes("$value");
2866
    if($result->size > 0){
2867
        $error ="One of the following tags found: $errVal. Please use Morpho to edit this document";
2868
        push(@errorMessages, $error."\n");
2869
        #if ($DEBUG == 1){ print $error;}
2870
    } 
2871
}
2872

    
2873

    
2874
################################################################################
2875
# 
2876
# print out error for more than one occurence of a given tag
2877
#
2878
################################################################################
2879
sub errMoreThanOne {
2880
    my $value = shift;
2881
    my $error ="More than one occurence of the tag $value found. Please use Morpho to edit this document";
2882
    push(@errorMessages, $error."\n");
2883
    # if ($DEBUG == 1){ print $error;}
2884
}
2885

    
2886

    
2887
################################################################################
2888
# 
2889
# print out error for more than given number of occurences of a given tag
2890
#
2891
################################################################################
2892
sub errMoreThanN {
2893
    my $value = shift;
2894
    my $error ="More occurences of the tag $value found than that can be shown in the form. Please use Morpho to edit this document";
2895
    push(@errorMessages, $error);
2896
    #if ($DEBUG == 1){ print $error."\n";}
2897
}
2898

    
2899

    
2900
################################################################################
2901
# 
2902
# convert coord to degrees, minutes and seconds form. 
2903
#
2904
################################################################################
2905
#sub convertCoord {
2906
#    my $wx = shift;
2907
#    print $deg." ".$min." ".$sec;
2908
#    print "\n";
2909
#}
2910

    
2911

    
2912
################################################################################
2913
# 
2914
# print debugging messages to stderr
2915
#
2916
################################################################################
2917
sub debug {
2918
    my $msg = shift;
2919
    
2920
    if ($debug) {
2921
        print STDERR "$msg\n";
2922
    }
2923
}
2924

    
2925
################################################################################
2926
# 
2927
# get the list of projects
2928
#
2929
################################################################################
2930
sub getProjectList {
2931
    
2932
    #use NCEAS::AdminDB;
2933
    #my $admindb = NCEAS::AdminDB->new();
2934
    #$admindb->connect($nceas_db, $nceas_db_user, $nceas_db_password);
2935
    #my $projects = $admindb->getProjects();
2936
    my $projects = getTestProjectList();
2937
    return $projects;
2938
}
2939

    
2940
################################################################################
2941
# 
2942
# get a test list of projects for use only in testing where the NCEAS
2943
# admin db is not available.
2944
#
2945
################################################################################
2946
sub getTestProjectList {
2947
    # This block is for testing only!  Remove for production use
2948
    my @row1;
2949
    $row1[0] = 6000; $row1[1] = 'Andelman'; $row1[2] = 'Sandy'; $row1[3] = 'The very long and windy path to an apparent ecological conclusion: statistics lie';
2950
    my @row2; 
2951
    $row2[0] = 7000; $row2[1] = 'Bascompte'; $row2[2] = 'Jordi'; $row2[3] = 'Postdoctoral Fellow';
2952
    my @row3; 
2953
    $row3[0] = 7001; $row3[1] = 'Hackett'; $row3[2] = 'Edward'; $row3[3] = 'Sociology rules the world';
2954
    my @row4; 
2955
    $row4[0] = 7002; $row4[1] = 'Jones'; $row4[2] = 'Matthew'; $row4[3] = 'Informatics rules the world';
2956
    my @row5; 
2957
    $row5[0] = 7003; $row5[1] = 'Schildhauer'; $row5[2] = 'Mark'; $row5[3] = 'Excel rocks my world, assuming a, b, and c';
2958
    my @row6; 
2959
    $row6[0] = 7004; $row6[1] = 'Rogers'; $row6[2] = 'Bill'; $row6[3] = 'Graduate Intern';
2960
    my @row7; 
2961
    $row7[0] = 7005; $row7[1] = 'Zedfried'; $row7[2] = 'Karl'; $row7[3] = 'A multivariate analysis of thing that go bump in the night';
2962
    my @projects;
2963
    $projects[0] = \@row1;
2964
    $projects[1] = \@row2;
2965
    $projects[2] = \@row3;
2966
    $projects[3] = \@row4;
2967
    $projects[4] = \@row5;
2968
    $projects[5] = \@row6;
2969
    $projects[6] = \@row7;
2970
    return \@projects;
2971
}
(6-6/7)