Project

General

Profile

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
316

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

    
322
    my $xmldoc = createXMLDocument();
323

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

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

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

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

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

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

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

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

    
448
debug("Registry: C");
449

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

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

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

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

    
472
exit(0);
473

    
474

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

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

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

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

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

    
535
  return $notunique;
536
}
537

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

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

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

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

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

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

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

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

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

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

    
709

    
710
    if($FORM::hasSpatial eq 'true' && $FORM::spatialRequired eq 'true'){
711
	if ($FORM::useSiteCoord ) {
712
	    push(@invalidParams, "The Data Registry doesn't have latitude and longitude information for the site that you chose. Please go back and enter the spatial information.")
713
		unless(hasContent($latDeg1) && hasContent($longDeg1));
714
	}else{
715
	    push(@invalidParams, "Latitude degrees are missing.")
716
		unless (hasContent($latDeg1) || $FORM::spatialRequired ne 'true');
717
	    push(@invalidParams, "Longitude degrees are missing.")
718
		unless (hasContent($longDeg1) || $FORM::spatialRequired ne 'true');
719
	}
720
	push(@invalidParams, 
721
	     "You must provide a geographic description if you provide latitude and longitude information.")
722
	    if ((hasContent($latDeg1) || (hasContent($longDeg1))) && (!hasContent($FORM::geogdesc)));
723
    }
724

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

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

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

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

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

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

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

    
814

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

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

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

    
828
    my $returnVal = "";
829

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

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

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

    
854

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

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

    
871

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

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

    
890

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

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

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

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

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

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

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

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

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

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

    
988
    $creat .= $dso;
989

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

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

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

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

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

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

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

    
1120
    $doc .= "<abstract>\n";
1121
    $doc .= "<para>".normalize($FORM::abstract)."</para>\n";
1122
    $doc .= "</abstract>\n";
1123

    
1124
    # Keyword information
1125
    foreach my $tmp (param()) {
1126
        if ($tmp =~ /keyword/) {
1127
            my $tmp1 = $tmp;
1128
            $tmp1 =~ s/keyword//; # get the index of the parameter 0, ..., 10
1129
            if ( $tmp1 =~ /[0-9]/ ){
1130
                # don't generate xml for empty keyword fields
1131
                # don't generate taxonomic keyword fields, those go in taxonomic coverage
1132
                if (hasContent(param($tmp))) {
1133
                    $doc .= "<keywordSet>\n";
1134
                    $doc .= "<keyword ";
1135
                    if (hasContent(param("kwType" . $tmp1)) &&
1136
                       (param("kwType" . $tmp1) !~ "None") ) {
1137
                         $doc .= "keywordType=\"";
1138
                         $doc .= lc(param("kwType" . $tmp1));
1139
                         $doc .= "\"";
1140
                    }
1141
                    $doc .= ">";
1142
                    $doc .= normalize(param("keyword" . $tmp1));
1143
                    $doc .= "</keyword>\n";
1144
                    $doc .= "<keywordThesaurus>";
1145
                    $doc .= normalize(param("kwTh" . $tmp1));
1146
                    $doc .= "</keywordThesaurus>\n";
1147
                    $doc .= "</keywordSet>\n";
1148
                }
1149
            }
1150
        }
1151
    }
1152

    
1153
    if (hasContent($FORM::addComments)) {
1154
        $doc .= "<additionalInfo>\n";
1155
        $doc .= "<para>".normalize($FORM::addComments)."</para>\n";
1156
        $doc .= "</additionalInfo>\n";
1157
    }
1158

    
1159
    if (hasContent($FORM::useConstraints) || 
1160
        hasContent($FORM::useConstraintsOther)) {
1161
        $doc .= "<intellectualRights>\n";
1162
        if (hasContent($FORM::useConstraints)) {
1163
            $doc .= "<para>".normalize($FORM::useConstraints)."</para>\n";
1164
        }
1165
        if (hasContent($FORM::useConstraintsOther)) {
1166
            $doc .= "<para>".normalize($FORM::useConstraintsOther)."</para>\n";
1167
        }
1168
        $doc .= "</intellectualRights>\n";
1169
    }
1170

    
1171
    
1172
    if (hasContent($FORM::url)) {
1173
    $doc .= "<distribution>\n";
1174
        $doc .= "<online>\n";
1175
    $doc .= "<url>".normalize($FORM::url)."</url>\n";
1176
    $doc .= "</online>\n";
1177
    $doc .= "</distribution>\n";
1178
    }
1179
    
1180
    $doc .= "<distribution>\n";
1181
    $doc .= "<offline>\n";
1182
    $doc .= "<mediumName>" . normalize($FORM::dataMedium)." ".normalize($FORM::dataMediumOther);
1183
    $doc .= "</mediumName>\n";
1184
    $doc .= "</offline>\n";
1185
    $doc .= "</distribution>\n";
1186
            
1187
    my $cov = "";
1188

    
1189
    if (hasContent($FORM::endingYear)) {
1190
	$cov .= "<temporalCoverage>\n";
1191
	$cov .= "<rangeOfDates>\n";
1192
	if (hasContent($FORM::beginningMonth)) {
1193
	    my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1194
			 "JUL","AUG","SEP","OCT","NOV","DEC")
1195
		[$FORM::beginningMonth - 1];
1196
	    $cov .= "<beginDate>\n";
1197
	    $cov .= "<calendarDate>";
1198
	    $cov .= normalize($FORM::beginningYear)."-".normalize($FORM::beginningMonth)."-".normalize($FORM::beginningDay);
1199
	    $cov .= "</calendarDate>\n";
1200
	    $cov .= "</beginDate>\n";
1201
	} else {
1202
	    $cov .= "<beginDate>\n";
1203
	    $cov .= "<calendarDate>";
1204
	    $cov .= normalize($FORM::beginningYear);
1205
	    $cov .= "</calendarDate>\n";
1206
	    $cov .= "</beginDate>\n";
1207
	}
1208
	
1209
	if (hasContent($FORM::endingMonth)) {
1210
	    my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1211
			 "JUL","AUG","SEP","OCT","NOV","DEC")
1212
		[$FORM::endingMonth - 1];
1213
	    $cov .= "<endDate>\n";
1214
	    $cov .= "<calendarDate>";
1215
	    $cov .= normalize($FORM::endingYear)."-".normalize($FORM::endingMonth)."-".normalize($FORM::endingDay);
1216
	    $cov .= "</calendarDate>\n";
1217
	    $cov .= "</endDate>\n";
1218
	} else {
1219
	    $cov .= "<endDate>\n";
1220
	    $cov .= "<calendarDate>";
1221
	    $cov .= normalize($FORM::endingYear);
1222
	    $cov .= "</calendarDate>\n";
1223
	    $cov .= "</endDate>\n";
1224
	}
1225
	$cov .= "</rangeOfDates>\n";
1226
	$cov .= "</temporalCoverage>\n";
1227
    } else {
1228
	if(hasContent($FORM::beginningYear)) {
1229
	    $cov .= "<temporalCoverage>\n";
1230
	    $cov .= "<singleDateTime>\n";
1231
	    if (hasContent($FORM::beginningMonth)) {
1232
		my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1233
			     "JUL","AUG","SEP","OCT","NOV","DEC")
1234
		    [$FORM::beginningMonth - 1];
1235
		$cov .= "<calendarDate>";
1236
		$cov .= normalize($FORM::beginningYear)."-".normalize($FORM::beginningMonth)."-".normalize($FORM::beginningDay);
1237
		$cov .= "</calendarDate>\n";
1238
	    } else {
1239
		$cov .= "<calendarDate>";
1240
		$cov .= normalize($FORM::beginningYear);
1241
		$cov .= "</calendarDate>\n";
1242
	    }
1243
	    $cov .= "</singleDateTime>\n";
1244
	    $cov .= "</temporalCoverage>\n";
1245
	}
1246
    }
1247
    
1248
    if(hasContent($FORM::geogdesc) || ($FORM::latDeg1 < 91 && $FORM::latDeg1 > -1 && $FORM::longDeg1 < 181 && $FORM::longDeg1 > -1)) {
1249
	$cov .= "<geographicCoverage>\n";
1250

    
1251
	if(hasContent($FORM::geogdesc)) {
1252
	    $cov .= "<geographicDescription>".normalize($FORM::geogdesc)."</geographicDescription>\n";
1253
	}
1254
	
1255
	if($latDeg1 < 91 && $latDeg1 > -1 && $longDeg1 < 181 && $longDeg1 > -1) {
1256
	    $cov .= "<boundingCoordinates>\n";
1257
	    # if the second latitude is missing, then set the second lat/long pair 
1258
	    # equal to the first this makes a point appear like a rectangle 
1259
	    if ($FORM::useSiteCoord || ($FORM::latDeg2 == "" && $FORM::latMin2 == "" && $FORM::latSec2 == "")) {
1260
		
1261
		$latDeg2 = $latDeg1;
1262
		$latMin2 = $latMin1;
1263
		$latSec2 = $latSec1;
1264
		$hemisphLat2 = $hemisphLat1;
1265
		$longDeg2 = $longDeg1;
1266
		$longMin2 = $longMin1;
1267
		$longSec2 = $longSec1;
1268
		$hemisphLong2 = $hemisphLong1;
1269
	    }
1270
	    else
1271
	    {
1272
		$latDeg2 = $FORM::latDeg2;
1273
		$latMin2 = $FORM::latMin2;
1274
		$latSec2 = $FORM::latSec2;
1275
		$hemisphLat2 = $FORM::hemisphLat2;
1276
		$longDeg2 = $FORM::longDeg2;
1277
		$longMin2 = $FORM::longMin2;
1278
		$longSec2 = $FORM::longSec2;
1279
		$hemisphLong2 = $FORM::hemisphLong2;
1280
	    } 
1281
	
1282
	
1283
	    my $hemisph;
1284
	    $hemisph = ($hemisphLong1 eq "W") ? -1 : 1;
1285
	    $cov .= "<westBoundingCoordinate>";
1286
	    my $var = $hemisph * ($longDeg1 + (60*$longMin1+$longSec1)/3600);
1287
	    $cov .= sprintf("%.4f\n", $var);
1288
	    $cov .= "</westBoundingCoordinate>\n";
1289
	    
1290
	    $hemisph = ($hemisphLong2 eq "W") ? -1 : 1;
1291
	    $cov .= "<eastBoundingCoordinate>";
1292
	    $var = $hemisph * ($longDeg2 + (60*$longMin2+$longSec2)/3600);
1293
	    $cov .= sprintf("%.4f\n", $var);
1294
	    $cov .= "</eastBoundingCoordinate>\n";
1295
	    
1296
	    $hemisph = ($hemisphLat1 eq "S") ? -1 : 1;
1297
	    $cov .= "<northBoundingCoordinate>";
1298
	    $var = $hemisph * ($latDeg1 + (60*$latMin1+$latSec1)/3600);
1299
	    $cov .= sprintf("%.4f\n", $var);	   
1300
	    $cov .= "</northBoundingCoordinate>\n";
1301
	    
1302
	    $hemisph = ($hemisphLat2 eq "S") ? -1 : 1;
1303
	    $cov .= "<southBoundingCoordinate>";
1304
	    $var = $hemisph * ($latDeg2 + (60*$latMin2+$latSec2)/3600);
1305
	    $cov .= sprintf("%.4f\n", $var);
1306
	    $cov .= "</southBoundingCoordinate>\n";
1307
	    
1308
	    $cov .= "</boundingCoordinates>\n";
1309
	}
1310
	$cov .= "</geographicCoverage>\n";
1311
    }
1312

    
1313
    # Write out the taxonomic coverage fields
1314
    my $foundFirstTaxon = 0;
1315
    foreach my $trn (param()) {
1316
        if ($trn =~ /taxonRankName/) {
1317
            my $taxIndex = $trn;
1318
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
1319
            my $trv = "taxonRankValue".$taxIndex;
1320
            if ( $taxIndex =~ /[0-9]/ ){
1321
                if (hasContent(param($trn)) && hasContent(param($trv))) {
1322
                    if (! $foundFirstTaxon) {
1323
                        $cov .= "<taxonomicCoverage>\n";
1324
                        $foundFirstTaxon = 1;
1325
                        if (hasContent($FORM::taxaAuth)) {
1326
                            $cov .= "<generalTaxonomicCoverage>".normalize($FORM::taxaAuth)."</generalTaxonomicCoverage>\n";
1327
                        }
1328
                    }
1329
                    $cov .= "<taxonomicClassification>\n";
1330
                    $cov .= "  <taxonRankName>".normalize(param($trn))."</taxonRankName>\n";
1331
                    $cov .= "  <taxonRankValue>".normalize(param($trv))."</taxonRankValue>\n";
1332
                    $cov .= "</taxonomicClassification>\n";
1333
                }
1334
            }
1335
        }
1336
    }
1337
    if ($foundFirstTaxon) {
1338
        $cov .= "</taxonomicCoverage>\n";
1339
    }
1340

    
1341
    if($cov ne "" ){
1342
	$doc .= "<coverage>".$cov."</coverage>";
1343
    }
1344
    $doc .= $cont;
1345
    $doc .= $publ;
1346
    
1347
    if ((hasContent($FORM::methodTitle)) || scalar(@FORM::methodsPara) > 0 || ($FORM::methodPara[0] ne "")) {
1348
        my $methods = "<methods><methodStep><description><section>\n";
1349
        if (hasContent($FORM::methodTitle)) {
1350
            $methods .= "<title>".normalize($FORM::methodTitle)."</title>\n";
1351
        }
1352
        for (my $i = 0; $i < scalar(@FORM::methodPara); $i++) {
1353
            $methods .= "<para>".normalize($FORM::methodPara[$i])."</para>\n";
1354
        }
1355
        $methods .= "</section></description></methodStep>\n";
1356
        if (hasContent($FORM::studyExtentDescription)) {
1357
            $methods .= "<sampling><studyExtent><description>\n";
1358
            $methods .= "<para>".normalize($FORM::studyExtentDescription)."</para>\n";
1359
            $methods .= "</description></studyExtent>\n";
1360
            $methods .= "<samplingDescription>\n";
1361
            $methods .= "<para>".normalize($FORM::samplingDescription)."</para>\n";
1362
            $methods .= "</samplingDescription>\n";
1363
            $methods .= "</sampling>\n";
1364
        }
1365
        $methods .= "</methods>\n";
1366
        $doc .= $methods;
1367
    }
1368

    
1369
    $doc .= "<access authSystem=\"knb\" order=\"denyFirst\">\n";
1370
    $doc .= "<allow>\n";
1371
    $doc .= "<principal>$username</principal>\n";
1372
    $doc .= "<permission>all</permission>\n";
1373
    $doc .= "</allow>\n";
1374
    $doc .= "<allow>\n";
1375
    $doc .= "<principal>uid=$FORM::username,o=$FORM::organization,dc=ecoinformatics,dc=org</principal>\n";
1376
    $doc .= "<permission>all</permission>\n";
1377
    $doc .= "</allow>\n";
1378
    $doc .= "<allow>\n";
1379
    $doc .= "<principal>public</principal>\n";
1380
    $doc .= "<permission>read</permission>\n";
1381
    $doc .= "</allow>\n";
1382
    $doc .= "</access>\n";
1383
    
1384
    $doc .= "</dataset>\n</eml:eml>\n";
1385

    
1386
    return $doc;
1387
}
1388

    
1389

    
1390
################################################################################
1391
# 
1392
# send an email message notifying the moderator of a new submission 
1393
#
1394
################################################################################
1395
sub sendNotification {
1396
    my $identifier = shift;
1397
    my $mailhost = shift;
1398
    my $sender = shift;
1399
    my $recipient = shift;
1400

    
1401
    my $smtp = Net::SMTP->new($mailhost);
1402
    $smtp->mail($sender);
1403
    $smtp->to($recipient);
1404

    
1405
    my $message = <<"    ENDOFMESSAGE";
1406
    To: $recipient
1407
    From: $sender
1408
    Subject: New data submission
1409
    
1410
    Data was submitted to the data registry.  
1411
    The identifying information for the new data set is:
1412

    
1413
    Identifier: $identifier
1414
    Title: $FORM::title
1415
    Submitter: $FORM::providerGivenName $FORM::providerSurName
1416

    
1417
    Please review the submmission and grant public read access if appropriate.
1418
    Thanks
1419
    
1420
    ENDOFMESSAGE
1421
    $message =~ s/^[ \t\r\f]+//gm;
1422

    
1423
    $smtp->data($message);
1424
    $smtp->quit;
1425
}
1426

    
1427

    
1428
################################################################################
1429
# 
1430
# read the eml document and send back a form with values filled in. 
1431
#
1432
################################################################################
1433
sub modifyData {
1434
    
1435
    # create metacat instance
1436
    my $metacat;
1437
    my $docid = $FORM::docid;
1438
    my $httpMessage;
1439
    my $doc;
1440
    my $xmldoc;
1441
    my $findType;
1442
    my $parser = XML::LibXML->new();
1443
    my @fileArray;
1444
    my $pushDoc;
1445
    my $alreadyInArray;
1446
    my $node;
1447
    my $response; 
1448
    my $element;
1449
    my $tempfile;
1450

    
1451
    $metacat = Metacat->new();
1452
    if ($metacat) {
1453
        $metacat->set_options( metacatUrl => $metacatUrl );
1454
    } else {
1455
        #die "failed during metacat creation\n";
1456
        push(@errorMessages, "Failed during metacat creation.");
1457
    }
1458
    
1459
    $httpMessage = $metacat->read($docid);
1460
    $doc = $httpMessage->content();
1461
    $xmldoc = $parser->parse_string($doc);
1462

    
1463
    #$tempfile = $xslConvDir.$docid;
1464
    #push (@fileArray, $tempfile);
1465

    
1466
    if ($xmldoc eq "") {
1467
        $error ="Error in parsing the eml document";
1468
        push(@errorMessages, $error);
1469
    } else {
1470
        $findType = $xmldoc->findnodes('//dataset/identifier');
1471
        if ($findType->size() > 0) {
1472
            # This is a eml beta6 document
1473
            # Read the documents mentioned in triples also
1474
        
1475
            $findType = $xmldoc->findnodes('//dataset/triple');
1476
            if ($findType->size() > 0) {
1477
                foreach $node ($findType->get_nodelist) {
1478
                    $pushDoc = findValue($node, 'subject');
1479
            
1480
                    # If the file is already in @fileArray then do not add it 
1481
                    $alreadyInArray = 0;
1482
                    foreach $element (@fileArray) {
1483
                        $tempfile = $tmpdir."/".$pushDoc;
1484
                        if ($element eq $pushDoc) {
1485
                            $alreadyInArray = 1;
1486
                        }
1487
                    }
1488
            
1489
                    if (!$alreadyInArray) {
1490
                        $tempfile = $tmpdir."/".$pushDoc;
1491
                        $response = "";
1492
                        $response = $metacat->read($pushDoc);    
1493
                        if (! $response) {
1494
                            # could not read
1495
                            #push(@errorMessages, $response);
1496
                            push(@errorMessages, $metacat->getMessage());
1497
                            push(@errorMessages, "Failed during reading.\n");
1498
                        } else {
1499
                            my $xdoc = $response->content();
1500
                            #$tempfile = $xslConvDir.$pushDoc;
1501
                            open (TFILE,">$tempfile") || 
1502
                                die ("Cant open xml file... $tempfile\n");
1503
                            print TFILE $xdoc;
1504
                            close(TFILE);
1505
                            push (@fileArray, $tempfile);
1506
                        }
1507
                    }
1508
                }
1509
            }
1510

    
1511
            # Read the main document. 
1512

    
1513
            $tempfile = $tmpdir."/".$docid; #= $xslConvDir.$docid;
1514
            open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1515
            print TFILE $doc;
1516
            close(TFILE);
1517
        
1518
            # Transforming beta6 to eml 2
1519
            my $xslt;
1520
            my $triplesheet;
1521
            my $results;
1522
            my $stylesheet;
1523
            my $resultsheet;
1524
        
1525
            $xslt = XML::LibXSLT->new();
1526
            #$tempfile = $xslConvDir."triple_info.xsl";
1527
            $tempfile = $tmpdir."/"."triple_info.xsl";
1528
    
1529
            $triplesheet = $xslt->parse_stylesheet_file($tempfile);
1530

    
1531
            #$results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1532
            $results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1533

    
1534
            #$tempfile = $xslConvDir."emlb6toeml2.xsl";
1535
            $tempfile = $tmpdir."/"."emlb6toeml2.xsl";
1536
            $stylesheet = $xslt->parse_stylesheet_file($tempfile);
1537
            $resultsheet = $stylesheet->transform($results);
1538
        
1539
            #$tempfile = "/usr/local/apache2/htdocs/xml/test.xml";;
1540
            #open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1541
            #print TFILE $stylesheet->output_string($resultsheet);
1542
            #close(TFILE);
1543

    
1544
            getFormValuesFromEml2($resultsheet);
1545
            
1546
            # Delete the files written earlier. 
1547
            unlink @fileArray;
1548

    
1549
        } else {
1550
            getFormValuesFromEml2($xmldoc);
1551
        }
1552
    }   
1553
    
1554
    if (scalar(@errorMessages)) {
1555
        # if any errors, print them in the response template 
1556
        $$templateVars{'status'} = 'failure_no_resubmit';
1557
        $$templateVars{'errorMessages'} = \@errorMessages;
1558
        $error = 1;
1559
        $$templateVars{'function'} = "modification";
1560
        $$templateVars{'section'} = "Modification Status";
1561
        $template->process( $responseTemplate, $templateVars); 
1562
    } else {
1563
        $$templateVars{'form'} = 're_entry';
1564
        $template->process( $entryFormTemplate, $templateVars);
1565
    }
1566
}
1567

    
1568
################################################################################
1569
# 
1570
# Parse an EML 2.0.0 file and extract the metadata into perl variables for 
1571
# processing and returning to the template processor
1572
#
1573
################################################################################
1574
sub getFormValuesFromEml2 {
1575
    
1576
    my $doc = shift;
1577
    my $results;
1578
    my $error;
1579
    my $node;
1580
    my $tempResult;
1581
    my $tempNode;
1582
    my $aoCount = 1;
1583
    my $foundDSO;
1584

    
1585
    # set variable values
1586
    $$templateVars{'showSiteList'} = $showSiteList;
1587
    $$templateVars{'lsite'} = $lsite;
1588
    $$templateVars{'usite'} = $usite;
1589
    $$templateVars{'showWgList'} = $showWgList;
1590
    $$templateVars{'showOrganization'} = $showOrganization;
1591
    $$templateVars{'hasKeyword'} = $hasKeyword;
1592
    $$templateVars{'hasTemporal'} = $hasTemporal;
1593
    $$templateVars{'hasSpatial'} = $hasSpatial;
1594
    $$templateVars{'hasTaxonomic'} = $hasTaxonomic;
1595
    $$templateVars{'hasMethod'} = $hasMethod;
1596
    $$templateVars{'spatialRequired'} = $spatialRequired;
1597
    $$templateVars{'temporalRequired'} = $temporalRequired;
1598

    
1599
    # find out the tag <alternateIdentifier>. 
1600
    $results = $doc->findnodes('//dataset/alternateIdentifier');
1601
    if ($results->size() > 1) {
1602
        errMoreThanOne("alternateIdentifier");
1603
    } else {
1604
        foreach $node ($results->get_nodelist) {
1605
            $$templateVars{'identifier'} = findValue($node, '../alternateIdentifier');
1606
        }
1607
    }
1608

    
1609
    # find out the tag <title>. 
1610
    $results = $doc->findnodes('//dataset/title');
1611
    if ($results->size() > 1) {
1612
        errMoreThanOne("title");
1613
    } elsif ($results->size() < 1) {
1614
        $error ="Following tag not found: title. Please use Morpho to edit this document";
1615
        push(@errorMessages, $error."\n");
1616
        #if ($DEBUG == 1){ print $error;}
1617
    } else {
1618
        foreach $node ($results->get_nodelist) {
1619
            $$templateVars{'title'} = findValue($node, '../title');
1620
        }
1621
    }
1622

    
1623
    # find out the tag <creator>. 
1624
    $results = $doc->findnodes('//dataset/creator/individualName');
1625
    debug("Registry: Creators: ".$results->size());
1626
     foreach $node ($results->get_nodelist) {
1627
            dontOccur($node, "../positionName|../onlineURL|../userId", 
1628
              "positionName, onlineURL, userId");
1629
        
1630
            dontOccur($node, "./saluation", "saluation");                
1631
        
1632
            debug("Registry: Checking a creator in loop 1...");
1633
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1634
            if($tempResult->size > 0) {
1635
                if($foundDSO == 0) {
1636
                    $foundDSO = 1;
1637
     
1638
                    debug("Registry: Recording a creator in loop 1...");
1639
                    $$templateVars{'origNamefirst0'} = findValue($node, 'givenName');
1640
                    $$templateVars{'origNamelast0'} = findValue($node, 'surName');
1641
            
1642
                    my $tempResult2 = $node->findnodes('../address');
1643
                    if ($tempResult2->size > 1) {
1644
                        errMoreThanOne("address");
1645
                    } else {
1646
                        foreach my $tempNode2 ($tempResult2->get_nodelist) {
1647
                            $$templateVars{'origDelivery'} = findValue($tempNode2, 'deliveryPoint');
1648
                            $$templateVars{'origCity'} = findValue($tempNode2, 'city');
1649
                            $$templateVars{'origState'} = findValue($tempNode2, 'administrativeArea');
1650
                            $$templateVars{'origZIP'} = findValue($tempNode2, 'postalCode');
1651
                            $$templateVars{'origCountry'} = findValue($tempNode2, 'country');
1652
                        }
1653
                    }
1654
            
1655
                    my $tempResult3 = $node->findnodes('../phone');
1656
                    if ($tempResult3->size > 2) {
1657
                        errMoreThanN("phone");
1658
                    } else {
1659
                        foreach my $tempNode2 ($tempResult3->get_nodelist) {
1660
                            if ($tempNode2->hasAttributes()) {
1661
                                my @attlist = $tempNode2->attributes();
1662
                                if ($attlist[0]->value eq "Fax") {
1663
                                    $$templateVars{'origFAX'} = $tempNode2->textContent();
1664
                                } else {
1665
                                    $$templateVars{'origPhone'} = $tempNode2->textContent();
1666
                                }
1667
                            } else {
1668
                                $$templateVars{'origPhone'} = $tempNode2->textContent();
1669
                            }
1670
                        }
1671
                    }
1672
                    $$templateVars{'origEmail'} = findValue($node, '../electronicMailAddress');
1673
                    $$templateVars{'origNameOrg'} = findValue($node, '../organizationName');
1674
                } else {
1675
                    errMoreThanN("address, phone and electronicMailAddress");
1676
                }
1677
            }
1678
        }
1679
        foreach $node ($results->get_nodelist) {
1680
            debug("Registry: Checking a creator in loop 2...");
1681
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1682
            if ($tempResult->size == 0) {
1683
                if ($foundDSO == 0) {
1684
                    debug("Registry: Recording a creator in loop 2 block A...");
1685
                    $foundDSO = 1;
1686
                    $$templateVars{'origNamefirst0'} = findValue($node, 'givenName');
1687
                    $$templateVars{'origNamelast0'} = findValue($node, 'surName');
1688
                    $$templateVars{'origNameOrg'} = findValue($node, '../organizationName');
1689
                } else {
1690
                    debug("Registry: Recording a creator in loop 2 block B...");
1691
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($node, './givenName');
1692
                    $$templateVars{"origNamelast$aoCount"} =  findValue($node, './surName');
1693
                    $$templateVars{"origRole$aoCount"} = "Originator";
1694
                    $aoCount++;
1695
                }
1696
            }
1697
        }
1698

    
1699
    $results = $doc->findnodes('//dataset/creator/organizationName');
1700
    my $wgroups = $doc->findnodes("//dataset/creator/organizationName[contains(text(),'(NCEAS ')]");
1701
    debug("Registry: Number Org: ".$results->size());
1702
    debug("Registry:  Number WG: ".$wgroups->size());
1703
    if ($results->size() - $wgroups->size() > 3) {
1704
        errMoreThanN("creator/organizationName");    
1705
    } else {
1706
        foreach $node ($results->get_nodelist) {
1707
            my $tempValue = findValue($node,'../organizationName');
1708
            $tempResult = $node->findnodes('../individualName');
1709
            if ($tempResult->size == 0 && $tempValue ne $organization) {
1710
                $$templateVars{'site'} = $tempValue;
1711
            }
1712
        }
1713
        if ($FORM::cfg eq 'nceas') {
1714
            my @wg;
1715
            foreach $node ($results->get_nodelist) {
1716
                my $tempValue = findValue($node,'../organizationName');
1717
                $wg[scalar(@wg)] = $tempValue;
1718
            }
1719
            my $projects = getProjectList();
1720
            $$templateVars{'projects'} = $projects;
1721
            $$templateVars{'wg'} = \@wg;
1722
        }
1723
    }
1724

    
1725
    $results = $doc->findnodes('//dataset/metadataProvider');
1726
    foreach $node ($results->get_nodelist) {
1727
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1728
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in metadataProvider");
1729
        
1730
	    $tempResult = $node->findnodes('./individualName');
1731
            if ($tempResult->size > 1) {
1732
                errMoreThanOne("metadataProvider/indvidualName");
1733
            } else {
1734
                foreach $tempNode ($tempResult->get_nodelist) {
1735
                    if ($$templateVars{'providerGivenName'} ne "") {
1736
                        $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1737
                        $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1738
                        $$templateVars{"origRole$aoCount"} = "Metadata Provider";
1739
                        $aoCount++;
1740
                    } else {
1741
                        $$templateVars{'providerGivenName'} =  findValue($tempNode, './givenName');
1742
                        $$templateVars{'providerSurName'} =  findValue($tempNode, './surName');
1743
                    }
1744
                }
1745
            }
1746
        }
1747

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

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

    
1788
  #  if ($aoCount > 11) {
1789
  #      errMoreThanN("Additional Originators");
1790
 #   } 
1791

    
1792
    $$templateVars{'aoCount'} = $aoCount;
1793
    
1794
    dontOccur($doc, "./pubDate", "pubDate");
1795
    dontOccur($doc, "./language", "language");
1796
    dontOccur($doc, "./series", "series");
1797

    
1798
    $results = $doc->findnodes('//dataset/abstract');
1799
    if ($results->size() > 1) {
1800
        errMoreThanOne("abstract");
1801
    } else {
1802
        foreach my $node ($results->get_nodelist) {
1803
            dontOccur($node, "./section", "section");
1804
            $$templateVars{'abstract'} = findValueNoChild($node, "para");
1805
        }
1806
    }
1807

    
1808
    $results = $doc->findnodes('//dataset/keywordSet');
1809

    
1810
    my $count = 1;
1811
    foreach $node ($results->get_nodelist) {
1812
	$tempResult = $node->findnodes('./keyword');
1813
	if ($tempResult->size() > 1) {
1814
	    errMoreThanOne("keyword");
1815
	} else {
1816
	    foreach $tempNode ($tempResult->get_nodelist) {
1817
		$$templateVars{"keyword$count"} = $tempNode->textContent();
1818
		if ($tempNode->hasAttributes()) {
1819
		    my @attlist = $tempNode->attributes();
1820
                    my $tmp = $attlist[0]->value;  #convert the first letter to upper case
1821
		    $tmp =~ s/\b(\w)/\U$1/g;
1822
		    $$templateVars{"kwType$count"} = $tmp;
1823
		}  
1824
	    }
1825
	}
1826
	$$templateVars{"kwTh$count"} = findValue($node, "keywordThesaurus");
1827
        $count++;
1828
    }
1829
    $$templateVars{'keyCount'} = $count;
1830
    if($count > 0 ){
1831
       $$templateVars{'hasKeyword'} = "true";
1832
    }
1833

    
1834
    $results = $doc->findnodes('//dataset/additionalInfo');
1835
    if ($results->size() > 1) {
1836
        errMoreThanOne("additionalInfo");
1837
    } else {
1838
        foreach $node ($results->get_nodelist) {
1839
            dontOccur($node, "./section", "section");
1840
            $$templateVars{'addComments'} = findValueNoChild($node, "para");
1841
        }
1842
    }
1843

    
1844
    $$templateVars{'useConstraints'} = "";
1845
    $results = $doc->findnodes('//dataset/intellectualRights');
1846
    if ($results->size() > 1) {
1847
        errMoreThanOne("intellectualRights");
1848
    } else {
1849
        foreach $node ($results->get_nodelist) {
1850
            dontOccur($node, "./section", "section in intellectualRights");
1851

    
1852
            $tempResult = $node->findnodes("para");
1853
            if ($tempResult->size > 2) {
1854
                   errMoreThanN("para");
1855
            } else {
1856
                foreach $tempNode ($tempResult->get_nodelist) {
1857
                    my $childNodes = $tempNode->childNodes;
1858
                    if ($childNodes->size() > 1) {
1859
                        $error ="The tag para in intellectualRights has children which cannot be shown using the form. Please use Morpho to edit this document";    
1860
                        push(@errorMessages, $error);
1861
                        #if ($DEBUG == 1){ print $error."\n";}
1862
                    } else {
1863
                        #print $tempNode->nodeName().":".$tempNode->textContent();
1864
                        #print "\n";
1865
                        if ($$templateVars{'useConstraints'} eq "") {
1866
                            $$templateVars{'useConstraints'} = $tempNode->textContent();
1867
                        } else {
1868
                            $$templateVars{'useConstraintsOther'} = $tempNode->textContent();
1869
                        }
1870
                    }
1871
                }
1872
            }
1873
        }
1874
    }
1875

    
1876
    $results = $doc->findnodes('//dataset/distribution/online');
1877
    if ($results->size() > 1) {
1878
        errMoreThanOne("distribution/online");
1879
    } else {
1880
        foreach my $tempNode ($results->get_nodelist){
1881
            $$templateVars{'url'} = findValue($tempNode, "url");
1882
            dontOccur($tempNode, "./connection", "/distribution/online/connection");
1883
            dontOccur($tempNode, "./connectionDefinition", "/distribution/online/connectionDefinition");
1884
        }
1885
    }
1886

    
1887
    $results = $doc->findnodes('//dataset/distribution/offline');
1888
    if ($results->size() > 1) {
1889
        errMoreThanOne("distribution/online");
1890
    } else {
1891
        foreach my $tempNode ($results->get_nodelist) {
1892
            my $temp = findValue($tempNode, "mediumName");
1893
            if(substr($temp, 0, 5) eq "other"){
1894
                $$templateVars{'dataMedium'} = substr($temp, 0, 5);
1895
                $$templateVars{'dataMediumOther'} = substr($temp, 5);
1896
            } else {
1897
                $$templateVars{'dataMedium'} = $temp;
1898
            }
1899
            dontOccur($tempNode, "./mediumDensity", "/distribution/offline/mediumDensity");
1900
            dontOccur($tempNode, "./mediumDensityUnits", "/distribution/offline/mediumDensityUnits");
1901
            dontOccur($tempNode, "./mediumVolume", "/distribution/offline/mediumVolume");
1902
            dontOccur($tempNode, "./mediumFormat", "/distribution/offline/mediumFormat");
1903
            dontOccur($tempNode, "./mediumNote", "/distribution/offline/mediumNote");
1904
        }
1905
    }
1906

    
1907
    dontOccur($doc, "./inline", "//dataset/distribution/inline");
1908

    
1909
    $results = $doc->findnodes('//dataset/coverage');
1910
    if ($results->size() > 1) {
1911
        errMoreThanOne("coverage");
1912
    } else {
1913
        foreach $node ($results->get_nodelist) {
1914
            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");
1915

    
1916
            $tempResult = $node->findnodes('./temporalCoverage');
1917
            if ($tempResult->size > 1) {
1918
                   errMoreThanOne("temporalCoverage");
1919
            } else {
1920
                foreach $tempNode ($tempResult->get_nodelist) {
1921
                    my $x;
1922
                    my $y;
1923
                    my $z;
1924
                    my $tempdate = findValue($tempNode, "rangeOfDates/beginDate/calendarDate");
1925
                    ($x, $y, $z) = split("-", $tempdate); 
1926
                    $$templateVars{'beginningYear'} = $x;
1927
                    $$templateVars{'beginningMonth'} = $y;
1928
                    $$templateVars{'beginningDay'} = $z;
1929
    
1930
                    $tempdate = findValue($tempNode, "rangeOfDates/endDate/calendarDate");
1931
                    ($x, $y, $z) = split("-", $tempdate);
1932
                    $$templateVars{'endingYear'} = $x;
1933
                    $$templateVars{'endingMonth'} = $y;
1934
                    $$templateVars{'endingDay'} = $z;
1935

    
1936
                    $tempdate = "";
1937
                    $tempdate = findValue($tempNode, "singleDateTime/calendarDate");
1938
                    if($tempdate ne ""){
1939
                        ($x, $y, $z) = split("-", $tempdate);
1940
                        $$templateVars{'beginningYear'} = $x;
1941
                        $$templateVars{'beginningMonth'} = $y;
1942
                        $$templateVars{'beginningDay'} = $z;
1943
                    }  
1944
		    
1945
		    $$templateVars{'hasTemporal'} = "true";
1946
                }
1947
            }
1948

    
1949
            $tempResult = $node->findnodes('./geographicCoverage');
1950
            if ($tempResult->size > 1) {
1951
                errMoreThanOne("geographicCoverage");
1952
            } else {
1953
                foreach $tempNode ($tempResult->get_nodelist) {
1954
                    my $geogdesc = findValue($tempNode, "geographicDescription");
1955
                    debug("Registry: geogdesc from xml is: $geogdesc");
1956
                    $$templateVars{'geogdesc'} = $geogdesc;
1957
                    my $coord = findValue($tempNode, "boundingCoordinates/westBoundingCoordinate");
1958
                    if ($coord > 0) {
1959
                        #print "+";
1960
                        $$templateVars{'hemisphLong1'} = "E";
1961
                    } else {
1962
                        #print "-";
1963
                        eval($coord = $coord * -1);
1964
                        $$templateVars{'hemisphLong1'} = "W";
1965
                    }
1966
                    eval($$templateVars{'longDeg1'} = int($coord));
1967
                    eval($coord = ($coord - int($coord))*60);
1968
                    eval($$templateVars{'longMin1'} = int($coord));
1969
                    eval($coord = ($coord - int($coord))*60);
1970
                    eval($$templateVars{'longSec1'} = int($coord));
1971
                    
1972
                    $coord = findValue($tempNode, "boundingCoordinates/southBoundingCoordinate");
1973
                    if ($coord > 0) {
1974
                        #print "+";
1975
                        $$templateVars{'hemisphLat2'} = "N";
1976
                    } else {
1977
                        #print "-";
1978
                        eval($coord = $coord * -1);
1979
                        $$templateVars{'hemisphLat2'} = "S";
1980
                    }
1981
                    eval($$templateVars{'latDeg2'} = int($coord));
1982
                    eval($coord = ($coord - int($coord))*60);
1983
                    eval($$templateVars{'latMin2'} = int($coord));
1984
                    eval($coord = ($coord - int($coord))*60);
1985
                    eval($$templateVars{'latSec2'} = int($coord));
1986
        
1987
                    $coord = findValue($tempNode, "boundingCoordinates/northBoundingCoordinate");
1988
                    if ($coord > 0) {
1989
                        #print "+";
1990
                        $$templateVars{'hemisphLat1'} = "N";
1991
                    } else {
1992
                        #print "-";
1993
                        eval($coord = $coord * -1);
1994
                        $$templateVars{'hemisphLat1'} = "S";
1995
                    }
1996
                    eval($$templateVars{'latDeg1'} = int($coord));
1997
                    eval($coord = ($coord - int($coord))*60);
1998
                    eval($$templateVars{'latMin1'} = int($coord));
1999
                    eval($coord = ($coord - int($coord))*60);
2000
                    eval($$templateVars{'latSec1'} = int($coord));
2001
        
2002
                    $coord = findValue($tempNode, "boundingCoordinates/eastBoundingCoordinate");
2003
                    if ($coord > 0) {
2004
                        #print "+";
2005
                        $$templateVars{'hemisphLong2'} = "E";
2006
                    } else {
2007
                        #print "-";
2008
                        eval($coord = $coord * -1);
2009
                        $$templateVars{'hemisphLong2'} = "W";
2010
                    }
2011
                    eval($$templateVars{'longDeg2'} = int($coord));
2012
                    eval($coord = ($coord - int($coord))*60);
2013
                    eval($$templateVars{'longMin2'} = int($coord));
2014
                    eval($coord = ($coord - int($coord))*60);
2015
                    eval($$templateVars{'longSec2'} = int($coord));
2016

    
2017
		            $$templateVars{'hasSpatial'} = "true";
2018
                }
2019
            }
2020

    
2021
            $tempResult = $node->findnodes('./taxonomicCoverage/taxonomicClassification');
2022
            my $taxonIndex = 0;
2023
            foreach $tempNode ($tempResult->get_nodelist) {
2024
                $taxonIndex++;
2025
                my $taxonRankName = findValue($tempNode, "taxonRankName");
2026
                my $taxonRankValue = findValue($tempNode, "taxonRankValue");
2027
                $$templateVars{"taxonRankName".$taxonIndex} = $taxonRankName;
2028
                $$templateVars{"taxonRankValue".$taxonIndex} = $taxonRankValue;
2029
		
2030
		$$templateVars{'hasTaxonomic'} = "true";
2031
            }
2032
            $$templateVars{'taxaCount'} = $taxonIndex;
2033
            my $taxaAuth = findValue($node, "./taxonomicCoverage/generalTaxonomicCoverage");
2034
            $$templateVars{'taxaAuth'} = $taxaAuth;
2035
        }
2036
    }
2037
    dontOccur($doc, "./purpose", "purpose");
2038
    dontOccur($doc, "./maintenance", "maintnance");
2039

    
2040
    $results = $doc->findnodes('//dataset/contact/individualName');
2041
    if ($results->size() > 1) {
2042
        errMoreThanOne("contact/individualName");
2043
    } else {
2044
        foreach $node ($results->get_nodelist) {
2045
            dontOccur($node, "../positionName|../onlineURL|../userId", 
2046
              "positionName, onlineURL, userId in contact tag");
2047
            dontOccur($node, "./saluation", "saluation in contact tag");                
2048
        
2049
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
2050
            if ($tempResult->size > 0) {
2051
                $$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
2052
                $$templateVars{'origNamelastContact'} = findValue($node, 'surName');
2053
    
2054
                my $tempResult2 = $node->findnodes('../address');
2055
                if ($tempResult2->size > 1) {
2056
                    errMoreThanOne("address");
2057
                } else {
2058
                    foreach my $tempNode2 ($tempResult2->get_nodelist) {
2059
                        $$templateVars{'origDeliveryContact'} = findValue($tempNode2, 'deliveryPoint');
2060
                        $$templateVars{'origCityContact'} = findValue($tempNode2, 'city');
2061
                        $$templateVars{'origStateContact'} = findValue($tempNode2, 'administrativeArea');
2062
                        $$templateVars{'origZIPContact'} = findValue($tempNode2, 'postalCode');
2063
                        $$templateVars{'origCountryContact'} = findValue($tempNode2, 'country');
2064
                    }
2065
                }
2066
            
2067
                my $tempResult3 = $node->findnodes('../phone');
2068
                if ($tempResult3->size > 2) {
2069
                    errMoreThanN("phone");
2070
                } else {
2071
                    foreach my $tempNode2 ($tempResult3->get_nodelist) {
2072
                        if ($tempNode2->hasAttributes()) {
2073
                            my @attlist = $tempNode2->attributes();
2074
                            if ($attlist[0]->value eq "Fax") {
2075
                                $$templateVars{'origFAXContact'} = $tempNode2->textContent();
2076
                            } else {
2077
                                $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
2078
                            }
2079
                        } else {
2080
                            $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
2081
                        }
2082
                    }
2083
                }
2084
                $$templateVars{'origEmailContact'} = findValue($node, '../electronicMailAddress');
2085
                $$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
2086
            } else {
2087
                $$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
2088
                $$templateVars{'origNamelastContact'} = findValue($node, 'surName');
2089
                $$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
2090
            }
2091
        }
2092
    }
2093
    
2094
    $results = $doc->findnodes(
2095
            '//dataset/methods/methodStep/description/section');
2096
    debug("Registry: Number methods: ".$results->size());
2097
    if ($results->size() > 1) {
2098
        errMoreThanN("methods/methodStep/description/section");    
2099
    } else {
2100

    
2101
        my @methodPara;
2102
        foreach $node ($results->get_nodelist) {
2103
            my @children = $node->childNodes;
2104
            for (my $i = 0; $i < scalar(@children); $i++) {
2105
                debug("Registry: Method child loop ($i)");
2106
                my $child = $children[$i];
2107
                if ($child->nodeName eq 'title') {
2108
                    my $title = $child->textContent();
2109
                    debug("Registry: Method title ($title)");
2110
                    $$templateVars{'methodTitle'} = $title;
2111
                } elsif ($child->nodeName eq 'para') {
2112
                    my $para = $child->textContent();
2113
                    debug("Registry: Method para ($para)");
2114
                    $methodPara[scalar(@methodPara)] = $para;
2115
                }
2116
            }
2117
	    $$templateVars{'hasMethod'} = "true";
2118
        }
2119
        if (scalar(@methodPara) > 0) {
2120
            $$templateVars{'methodPara'} = \@methodPara;
2121
        }
2122
    }
2123

    
2124
    $results = $doc->findnodes(
2125
            '//dataset/methods/sampling/studyExtent/description/para');
2126
    if ($results->size() > 1) {
2127
        errMoreThanN("methods/sampling/studyExtent/description/para");    
2128
    } else {
2129
        foreach $node ($results->get_nodelist) {
2130
            my $studyExtentDescription = $node->textContent();
2131
            $$templateVars{'studyExtentDescription'} = $studyExtentDescription;
2132

    
2133
	    $$templateVars{'hasMethod'} = "true";
2134
        }
2135
    }
2136

    
2137
    $results = $doc->findnodes(
2138
            '//dataset/methods/sampling/samplingDescription/para');
2139
    if ($results->size() > 1) {
2140
        errMoreThanN("methods/sampling/samplingDescription/para");    
2141
    } else {
2142
        foreach $node ($results->get_nodelist) {
2143
            my $samplingDescription = $node->textContent();
2144
            $$templateVars{'samplingDescription'} = $samplingDescription;
2145

    
2146
	    $$templateVars{'hasMethod'} = "true";
2147
        }
2148
    }
2149

    
2150
    dontOccur($doc, "//methodStep/citation", "methodStep/citation");
2151
    dontOccur($doc, "//methodStep/protocol", "methodStep/protocol");
2152
    dontOccur($doc, "//methodStep/instrumentation", "methodStep/instrumentation");
2153
    dontOccur($doc, "//methodStep/software", "methodStep/software");
2154
    dontOccur($doc, "//methodStep/subStep", "methodStep/subStep");
2155
    dontOccur($doc, "//methodStep/dataSource", "methodStep/dataSource");
2156
    dontOccur($doc, "//methods/qualityControl", "methods/qualityControl");
2157

    
2158
    dontOccur($doc, "//methods/sampling/spatialSamplingUnits", "methods/sampling/spatialSamplingUnits");
2159
    dontOccur($doc, "//methods/sampling/citation", "methods/sampling/citation");
2160
    dontOccur($doc, "./pubPlace", "pubPlace");
2161
    dontOccur($doc, "./project", "project");
2162
    
2163
    ############ Code for checking ACL #####################
2164
    dontOccur($doc, "//dataset/access/deny", "dataset/access/deny");
2165

    
2166
    $results = $doc->findnodes('//dataset/access/allow');
2167
    if ($results->size() != 3) {
2168
        errMoreThanN("dataset/access/allow");
2169
    } else {
2170
	my $accessError = 0;
2171
        foreach $node ($results->get_nodelist) {
2172
            my @children = $node->childNodes;
2173
	    my $principal = "";
2174
	    my $permission = "";
2175
            for (my $i = 0; $i < scalar(@children); $i++) {
2176
                my $child = $children[$i];
2177
                if ($child->nodeName eq 'principal') {
2178
                    $principal = $child->textContent();
2179
                } elsif ($child->nodeName eq 'permission') {
2180
                    $permission = $child->textContent();
2181
                }
2182
            }
2183
	
2184
	    if ($principal eq 'public' && $permission ne 'read') { $accessError = 1; }
2185
	    if ($principal eq $username && $permission ne 'all') { $accessError = 2; }
2186
	    if ($principal ne 'public' && $principal ne $username && $permission ne 'all') { $accessError = 3; }
2187
	}
2188
 
2189
	if ($accessError != 0) {
2190
	    my $error ="The ACL for this document has been changed outside the registry. Please use Morpho to edit this document";
2191
            push(@errorMessages, $error."\n");
2192
	}     
2193
    }
2194
    ########################################################
2195

    
2196

    
2197
    dontOccur($doc, "./dataTable", "dataTable");
2198
    dontOccur($doc, "./spatialRaster", "spatialRaster");
2199
    dontOccur($doc, "./spatialVector", "spatialVector");
2200
    dontOccur($doc, "./storedProcedure", "storedProcedure");
2201
    dontOccur($doc, "./view", "view");
2202
    dontOccur($doc, "./otherEntity", "otherEntity");
2203
    dontOccur($doc, "./references", "references");
2204
    
2205
    dontOccur($doc, "//citation", "citation");
2206
    dontOccur($doc, "//software", "software");
2207
    dontOccur($doc, "//protocol", "protocol");
2208
    dontOccur($doc, "//additionalMetadata", "additionalMetadata");    
2209
}
2210

    
2211
################################################################################
2212
# 
2213
# Delete the eml file that has been requested for deletion. 
2214
#
2215
################################################################################
2216
sub deleteData {
2217
    my $deleteAll = shift;
2218
    
2219
    # create metacat instance
2220
    my $metacat;
2221
    my $docid = $FORM::docid;
2222
    
2223
    $metacat = Metacat->new();
2224
    if ($metacat) {
2225
        $metacat->set_options( metacatUrl => $metacatUrl );
2226
    } else {
2227
        #die "failed during metacat creation\n";
2228
        push(@errorMessages, "Failed during metacat creation.");
2229
    }
2230

    
2231
    # Login to metacat
2232
    my $userDN = $FORM::username;
2233
    my $userOrg = $FORM::organization;
2234
    my $userPass = $FORM::password;
2235
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
2236
    
2237
    my $errorMessage = "";
2238
    my $response = $metacat->login($dname, $userPass);
2239

    
2240
    if (! $response) {
2241
    # Could not login
2242
        push(@errorMessages, $metacat->getMessage());
2243
        push(@errorMessages, "Failed during login.\n");
2244

    
2245
    } else {
2246
    #Able to login - try to delete the file    
2247

    
2248
    my $parser;
2249
    my @fileArray;
2250
    my $httpMessage;
2251
    my $xmldoc;
2252
    my $doc;
2253
    my $pushDoc;
2254
    my $alreadyInArray;
2255
    my $findType;
2256
        my $node;
2257
    my $response; 
2258
    my $element;
2259

    
2260
    push (@fileArray, $docid);
2261
    $parser = XML::LibXML->new();
2262

    
2263
        $httpMessage = $metacat->read($docid);
2264
    $doc = $httpMessage->content();    
2265
    $doc = delNormalize($doc);
2266
    $xmldoc = $parser->parse_string($doc);
2267

    
2268
    if ($xmldoc eq "") {
2269
        $error ="Error in parsing the eml document";
2270
        push(@errorMessages, $error);
2271
    } else {
2272

    
2273
        $findType = $xmldoc->findnodes('//dataset/identifier');
2274
        if($findType->size() > 0){
2275
        # This is a eml beta6 document
2276
        # Delete the documents mentioned in triples also
2277
        
2278
        $findType = $xmldoc->findnodes('//dataset/triple');
2279
        if($findType->size() > 0){
2280
            foreach $node ($findType->get_nodelist){
2281
            $pushDoc = findValue($node, 'subject');
2282
            
2283
            # If the file is already in the @fileArray then do not add it 
2284
            $alreadyInArray = 0;
2285
            foreach $element (@fileArray){
2286
                if($element eq $pushDoc){
2287
                $alreadyInArray = 1;
2288
                }
2289
            }
2290
            
2291
            if(!$alreadyInArray){
2292
                # If not already in array then delete the file. 
2293
                push (@fileArray, $pushDoc);
2294
                $response = $metacat->delete($pushDoc);
2295
                
2296
                if (! $response) {
2297
                # Could not delete
2298
                #push(@errorMessages, $response);
2299
                push(@errorMessages, $metacat->getMessage());
2300
                push(@errorMessages, "Failed during deleting $pushDoc. Please check if you are authorized to delete this document.\n");
2301
                }
2302
            }
2303
            }
2304
        }
2305
        }
2306
    }
2307
    
2308
    # Delete the main document. 
2309
    if($deleteAll){
2310
        $response = $metacat->delete($docid);  
2311
        if (! $response) {
2312
        # Could not delete
2313
        #push(@errorMessages, $response);
2314
        push(@errorMessages, $metacat->getMessage());
2315
        push(@errorMessages, "Failed during deleting $docid. Please check if you are authorized to delete this document.\n");
2316
        }
2317
    }
2318
    }
2319
    
2320
    if (scalar(@errorMessages)) {
2321
    # If any errors, print them in the response template 
2322
    $$templateVars{'status'} = 'failure';
2323
    $$templateVars{'errorMessages'} = \@errorMessages;
2324
    $error = 1;
2325
    }
2326
    
2327
    # Process the response template
2328
    if($deleteAll){
2329

    
2330
    $$templateVars{'function'} = "deleted";
2331
    $$templateVars{'section'} = "Deletion Status";
2332
    $template->process( $responseTemplate, $templateVars);
2333
    }
2334
}
2335

    
2336

    
2337
################################################################################
2338
# 
2339
# Do data validation and send the data to confirm data template.
2340
#
2341
################################################################################
2342
sub toConfirmData{
2343
    # Check if any invalid parameters
2344
 
2345
    my $invalidParams;
2346
    if (! $error) {
2347
    $invalidParams = validateParameters(0);
2348
    if (scalar(@$invalidParams)) {
2349
        $$templateVars{'status'} = 'failure';
2350
        $$templateVars{'invalidParams'} = $invalidParams;
2351
        $error = 1;
2352
    }
2353
    }
2354

    
2355

    
2356
    $$templateVars{'providerGivenName'} = normalizeCD($FORM::providerGivenName);
2357
    $$templateVars{'providerSurName'} = normalizeCD($FORM::providerSurName);
2358
    if($FORM::site eq "Select your station here."){
2359
        $$templateVars{'site'} = "";
2360
    }else{
2361
        $$templateVars{'site'} = $FORM::site;
2362
    }
2363
    if($FORM::cfg eq "nceas"){
2364
        $$templateVars{'wg'} = \@FORM::wg;
2365
    }
2366
    $$templateVars{'identifier'} = normalizeCD($FORM::identifier);
2367
    $$templateVars{'title'} = normalizeCD($FORM::title);
2368
    $$templateVars{'origNamefirst0'} = normalizeCD($FORM::origNamefirst0);
2369
    $$templateVars{'origNamelast0'} = normalizeCD($FORM::origNamelast0);
2370
    $$templateVars{'origNameOrg'} = normalizeCD($FORM::origNameOrg);
2371
    # $$templateVars{'origRole0'} = $FORM::origRole0;
2372
    $$templateVars{'origDelivery'} = normalizeCD($FORM::origDelivery);
2373
    $$templateVars{'origCity'} = normalizeCD($FORM::origCity);
2374
    if($FORM::origState eq "Select State Here."){
2375
        $$templateVars{'origState'} = "";
2376
    }else{
2377
        $$templateVars{'origState'} = $FORM::origState;
2378
    }
2379
    $$templateVars{'origStateOther'} = normalizeCD($FORM::origStateOther);
2380
    $$templateVars{'origZIP'} = normalizeCD($FORM::origZIP);
2381
    $$templateVars{'origCountry'} = normalizeCD($FORM::origCountry);
2382
    $$templateVars{'origPhone'} = normalizeCD($FORM::origPhone);
2383
    $$templateVars{'origFAX'} = normalizeCD($FORM::origFAX);
2384
    $$templateVars{'origEmail'} = normalizeCD($FORM::origEmail);
2385
    $$templateVars{'useOrigAddress'} = normalizeCD($FORM::useOrigAddress);
2386
    if($FORM::useOrigAddress eq "on"){
2387
        $$templateVars{'origNamefirstContact'} = normalizeCD($FORM::origNamefirst0);
2388
        $$templateVars{'origNamelastContact'} = normalizeCD($FORM::origNamelast0);
2389
        $$templateVars{'origNameOrgContact'} = normalizeCD($FORM::origNameOrg);
2390
        $$templateVars{'origDeliveryContact'} = normalizeCD($FORM::origDelivery); 
2391
        $$templateVars{'origCityContact'} = normalizeCD($FORM::origCity);
2392
        if($FORM::origState eq "Select State Here."){
2393
        $$templateVars{'origStateContact'} = "";
2394
        }else{
2395
        $$templateVars{'origStateContact'} = $FORM::origState;
2396
        }
2397
        $$templateVars{'origStateOtherContact'} = normalizeCD($FORM::origStateOther);
2398
        $$templateVars{'origZIPContact'} = normalizeCD($FORM::origZIP);
2399
        $$templateVars{'origCountryContact'} = normalizeCD($FORM::origCountry);
2400
        $$templateVars{'origPhoneContact'} = normalizeCD($FORM::origPhone);
2401
        $$templateVars{'origFAXContact'} = normalizeCD($FORM::origFAX);
2402
        $$templateVars{'origEmailContact'} = normalizeCD($FORM::origEmail);
2403
    }else{
2404
        $$templateVars{'origNamefirstContact'} = normalizeCD($FORM::origNamefirstContact);
2405
        $$templateVars{'origNamelastContact'} = normalizeCD($FORM::origNamelastContact);
2406
        $$templateVars{'origNameOrgContact'} = normalizeCD($FORM::origNameOrgContact);
2407
        $$templateVars{'origDeliveryContact'} = normalizeCD($FORM::origDeliveryContact); 
2408
        $$templateVars{'origCityContact'} = normalizeCD($FORM::origCityContact);
2409
        if($FORM::origStateContact eq "Select State Here."){
2410
        $$templateVars{'origStateContact'} = "";
2411
        }else{
2412
        $$templateVars{'origStateContact'} = $FORM::origStateContact;
2413
        }
2414
        $$templateVars{'origStateOtherContact'} = normalizeCD($FORM::origStateOtherContact);
2415
        $$templateVars{'origZIPContact'} = normalizeCD($FORM::origZIPContact);
2416
        $$templateVars{'origCountryContact'} = normalizeCD($FORM::origCountryContact);
2417
        $$templateVars{'origPhoneContact'} = normalizeCD($FORM::origPhoneContact);
2418
        $$templateVars{'origFAXContact'} = normalizeCD($FORM::origFAXContact);
2419
        $$templateVars{'origEmailContact'} = normalizeCD($FORM::origEmailContact);    
2420
    }
2421

    
2422
    my $aoFNArray = \@FORM::aoFirstName;
2423
    my $aoLNArray = \@FORM::aoLastName;
2424
    my $aoRoleArray = \@FORM::aoRole;
2425
    my $aoCount = 1;
2426

    
2427
    for(my $i = 0; $i <= $#$aoRoleArray; $i++){
2428
        if (hasContent($aoFNArray->[$i]) && hasContent($aoLNArray->[$i])) {
2429
            debug("Registry processing Associated Party: origName = ".$aoFNArray->[$i]
2430
                  ." origNamelast = ".$aoLNArray->[$i]." origRole = "
2431
                  .$aoRoleArray->[$i]);
2432
            $$templateVars{"origNamefirst".$aoCount} = normalizeCD($aoFNArray->[$i]);
2433
            $$templateVars{"origNamelast".$aoCount} = normalizeCD($aoLNArray->[$i]);
2434
            $$templateVars{"origRole".$aoCount} = normalizeCD($aoRoleArray->[$i]);
2435
            $aoCount++;
2436
	}    
2437
    }
2438

    
2439
    $$templateVars{'aoCount'} = $aoCount;
2440
    $$templateVars{'abstract'} = normalizeCD($FORM::abstract);
2441
   
2442
   
2443
    my $keywordArray = \@FORM::keyword;
2444
    my $keywordTypeArray = \@FORM::keywordType;
2445
    my $keywordThArray = \@FORM::keywordTh;
2446
    my $keyCount = 1;
2447
   
2448
    for(my $i = 0; $i <= $#$keywordArray; $i++){
2449
        if (hasContent($keywordArray->[$i])) {
2450
            debug("Registry processing keyword: keyword = ".$keywordArray->[$i]."
2451
                  keywordType = ".$keywordTypeArray->[$i]."
2452
                  keywordTh = ".$keywordThArray->[$i]);
2453
            $$templateVars{"keyword".$keyCount} = normalizeCD($keywordArray->[$i]);
2454
            $$templateVars{"kwType".$keyCount} = normalizeCD($keywordTypeArray->[$i]);
2455
            $$templateVars{"kwTh".$keyCount} = normalizeCD($keywordThArray->[$i]);
2456
            $keyCount++;
2457
	}    
2458
    }    
2459
    $$templateVars{'keyCount'} = $keyCount;
2460
    
2461
    $$templateVars{'addComments'} = normalizeCD($FORM::addComments);
2462
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2463
    if($FORM::useConstraints eq "other"){
2464
        $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2465
    }
2466
    $$templateVars{'url'} = $FORM::url;
2467
    $$templateVars{'dataMedium'} = $FORM::dataMedium;
2468
    if($FORM::dataMedium eq "other"){
2469
        $$templateVars{'dataMediumOther'} = normalizeCD($FORM::dataMediumOther);
2470
    }
2471
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2472
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2473
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2474
    $$templateVars{'endingYear'} = $FORM::endingYear;
2475
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2476
    $$templateVars{'endingDay'} = $FORM::endingDay;
2477
    $$templateVars{'geogdesc'} = normalizeCD($FORM::geogdesc);
2478
    $$templateVars{'useSiteCoord'} = $FORM::useSiteCoord;
2479
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2480
    $$templateVars{'latMin1'} = $FORM::latMin1;
2481
    $$templateVars{'latSec1'} = $FORM::latSec1;
2482
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2483
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2484
    $$templateVars{'longMin1'} = $FORM::longMin1;
2485
    $$templateVars{'longSec1'} = $FORM::longSec1;
2486
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2487
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2488
    $$templateVars{'latMin2'} = $FORM::latMin2;
2489
    $$templateVars{'latSec2'} = $FORM::latSec2;
2490
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2491
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2492
    $$templateVars{'longMin2'} = $FORM::longMin2;
2493
    $$templateVars{'longSec2'} = $FORM::longSec2;
2494
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2495

    
2496
    my $taxonRankArray = \@FORM::taxonRank;
2497
    my $taxonNameArray = \@FORM::taxonName;
2498
    my $taxonCount = 1;
2499

    
2500
    for(my $i = 0; $i <= $#$taxonNameArray; $i++){
2501
        if (hasContent($taxonRankArray->[$i]) && hasContent($taxonNameArray->[$i])) {
2502
            debug("Registry processing keyword: trv = ".$taxonRankArray->[$i]
2503
                    ." trn = ".$taxonNameArray->[$i]);
2504
            $$templateVars{"taxonRankName".$taxonCount} = normalizeCD($taxonNameArray->[$i]);
2505
            $$templateVars{"taxonRankValue".$taxonCount} = normalizeCD($taxonRankArray->[$i]);
2506
            $taxonCount++;
2507
	}    
2508
    }
2509

    
2510
    $$templateVars{'taxaCount'} = $taxonCount-1;
2511
    $$templateVars{'taxaAuth'} = normalizeCD($FORM::taxaAuth);
2512

    
2513
    $$templateVars{'methodTitle'} = normalizeCD($FORM::methodTitle);
2514
 
2515
    my @tempMethodPara;
2516
    for (my $i = 0; $i < scalar(@FORM::methodPara); $i++) {
2517
	$tempMethodPara[$i] = normalizeCD($FORM::methodPara[$i]);
2518
    }
2519
    $$templateVars{'methodPara'} = \@tempMethodPara;
2520
    $$templateVars{'studyExtentDescription'} = normalizeCD($FORM::studyExtentDescription);
2521
    $$templateVars{'samplingDescription'} = normalizeCD($FORM::samplingDescription);
2522
    $$templateVars{'origStateContact'} = $FORM::origState;
2523

    
2524
    $$templateVars{'showSiteList'} = $FORM::showSiteList;
2525
    $$templateVars{'lsite'} = $FORM::lsite;
2526
    $$templateVars{'usite'} = $FORM::usite;
2527
    $$templateVars{'showWgList'} = $FORM::showWgList;
2528
    $$templateVars{'showOrganization'} = $FORM::showOrganization;
2529
    $$templateVars{'hasKeyword'} = $FORM::hasKeyword;
2530
    $$templateVars{'hasTemporal'} = $FORM::hasTemporal;
2531
    $$templateVars{'hasSpatial'} = $FORM::hasSpatial;
2532
    $$templateVars{'hasTaxonomic'} = $FORM::hasTaxonomic;
2533
    $$templateVars{'hasMethod'} = $FORM::hasMethod;
2534
    $$templateVars{'spatialRequired'} = $FORM::spatialRequired;
2535
    $$templateVars{'temporalRequired'} = $FORM::temporalRequired;
2536

    
2537
    $$templateVars{'docid'} = $FORM::docid;
2538

    
2539
    if (! $error) {
2540
	# If no errors, then print out data in confirm Data template
2541

    
2542
	$$templateVars{'section'} = "Confirm Data";
2543
	$template->process( $confirmDataTemplate, $templateVars);
2544

    
2545
    } else{    
2546
    # Errors from validation function. print the errors out using the response template
2547
    if (scalar(@errorMessages)) {
2548
        $$templateVars{'status'} = 'failure';
2549
        $$templateVars{'errorMessages'} = \@errorMessages;
2550
        $error = 1;
2551
    }
2552
        # Create our HTML response and send it back
2553
    $$templateVars{'function'} = "submitted";
2554
    $$templateVars{'section'} = "Submission Status";
2555
    $template->process( $responseTemplate, $templateVars);
2556
    }
2557
}
2558

    
2559

    
2560
################################################################################
2561
# 
2562
# From confirm Data template - user wants to make some changes.
2563
#
2564
################################################################################
2565
sub confirmDataToReEntryData{
2566
    my @sortedSites;
2567
    foreach my $site (sort @sitelist) {
2568
        push(@sortedSites, $site);
2569
    }
2570

    
2571
    $$templateVars{'siteList'} = \@sortedSites;
2572
    $$templateVars{'section'} = "Re-Entry Form";
2573
    copyFormToTemplateVars();
2574
    $$templateVars{'docid'} = $FORM::docid;
2575

    
2576
    $$templateVars{'form'} = 're_entry';
2577
    $template->process( $entryFormTemplate, $templateVars);
2578
}
2579

    
2580

    
2581
################################################################################
2582
# 
2583
# Copy form data to templateVars.....
2584
#
2585
################################################################################
2586
sub copyFormToTemplateVars{
2587
    $$templateVars{'providerGivenName'} = $FORM::providerGivenName;
2588
    $$templateVars{'providerSurName'} = $FORM::providerSurName;
2589
    $$templateVars{'site'} = $FORM::site;
2590
    if ($FORM::cfg eq "nceas") {
2591
        my $projects = getProjectList();
2592
        $$templateVars{'projects'} = $projects;
2593
        $$templateVars{'wg'} = \@FORM::wg;
2594
    }
2595
    $$templateVars{'identifier'} = $FORM::identifier;
2596
    $$templateVars{'title'} = $FORM::title;
2597
    $$templateVars{'origNamefirst0'} = $FORM::origNamefirst0;
2598
    $$templateVars{'origNamelast0'} = $FORM::origNamelast0;
2599
    $$templateVars{'origNameOrg'} = $FORM::origNameOrg;
2600
 #   $$templateVars{'origRole0'} = $FORM::origRole0;
2601
    $$templateVars{'origDelivery'} = $FORM::origDelivery;
2602
    $$templateVars{'origCity'} = $FORM::origCity;
2603
    $$templateVars{'origState'} = $FORM::origState;
2604
    $$templateVars{'origStateOther'} = $FORM::origStateOther;
2605
    $$templateVars{'origZIP'} = $FORM::origZIP;
2606
    $$templateVars{'origCountry'} = $FORM::origCountry;
2607
    $$templateVars{'origPhone'} = $FORM::origPhone;
2608
    $$templateVars{'origFAX'} = $FORM::origFAX;
2609
    $$templateVars{'origEmail'} = $FORM::origEmail;
2610
    if ($FORM::useSiteCoord ne "") {
2611
        $$templateVars{'useOrigAddress'} = "CHECKED";
2612
    }else{
2613
        $$templateVars{'useOrigAddress'} = $FORM::useOrigAddress;
2614
    }
2615
    $$templateVars{'origNamefirstContact'} = $FORM::origNamefirstContact;
2616
    $$templateVars{'origNamelastContact'} = $FORM::origNamelastContact;
2617
    $$templateVars{'origNameOrgContact'} = $FORM::origNameOrgContact;
2618
    $$templateVars{'origDeliveryContact'} = $FORM::origDeliveryContact; 
2619
    $$templateVars{'origCityContact'} = $FORM::origCityContact;
2620
    $$templateVars{'origStateContact'} = $FORM::origStateContact;
2621
    $$templateVars{'origStateOtherContact'} = $FORM::origStateOtherContact;
2622
    $$templateVars{'origZIPContact'} = $FORM::origZIPContact;
2623
    $$templateVars{'origCountryContact'} = $FORM::origCountryContact;
2624
    $$templateVars{'origPhoneContact'} = $FORM::origPhoneContact;
2625
    $$templateVars{'origFAXContact'} = $FORM::origFAXContact;
2626
    $$templateVars{'origEmailContact'} = $FORM::origEmailContact;    
2627
    
2628
    $$templateVars{'aoCount'} = $FORM::aoCount;
2629
    foreach my $origName (param()) {
2630
	if ($origName =~ /origNamefirst/) {
2631
	    my $origNameIndex = $origName;
2632
	    $origNameIndex =~ s/origNamefirst//; # get the index of the parameter 0, ..., 10
2633
	    my $origNamelast = "origNamelast".$origNameIndex;
2634
	    my $origRole = "origRole".$origNameIndex;
2635
	    if ( $origNameIndex =~ /[0-9]/  && $origNameIndex > 0){
2636
		if (hasContent(param($origName)) && hasContent(param($origNamelast)) && hasContent(param($origRole))) {
2637
		    debug("Registry processing keyword: $origName = ".param($origName)." $origNamelast = ".param($origNamelast)." $origRole = ".param($origRole));
2638
		    $$templateVars{$origName} = normalizeCD(param($origName));
2639
		    $$templateVars{$origNamelast} = normalizeCD(param($origNamelast));
2640
		    $$templateVars{$origRole} = normalizeCD(param($origRole));
2641
		}
2642
	    }
2643
	}
2644
    }
2645

    
2646
    $$templateVars{'abstract'} = $FORM::abstract;
2647
    $$templateVars{'keyCount'} = $FORM::keyCount;
2648
    foreach my $kyd (param()) {
2649
	if ($kyd =~ /keyword/) {
2650
	    my $keyIndex = $kyd;
2651
	    $keyIndex =~ s/keyword//; # get the index of the parameter 0, ..., 10
2652
	    my $keyType = "kwType".$keyIndex;
2653
	    my $keyTh = "kwTh".$keyIndex;
2654
	    if ( $keyIndex =~ /[0-9]/ ){
2655
		if (hasContent(param($kyd)) && hasContent(param($keyType)) && hasContent(param($keyTh))) {
2656
		    debug("Registry processing keyword: $kyd = ".param($kyd)." $keyType = ".param($keyType)." $keyTh = ".param($keyTh));
2657
		    $$templateVars{$kyd} = param($kyd); 
2658
                    my $tmp = param($keyType);  #convert the first letter to upper case
2659
		    $tmp =~ s/\b(\w)/\U$1/g;
2660
                    $$templateVars{$keyType} = $tmp;
2661
		    $$templateVars{$keyTh} = param($keyTh);
2662
		}
2663
	    }
2664
	}
2665
    }
2666
    $$templateVars{'addComments'} = $FORM::addComments;
2667
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2668
    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2669
    $$templateVars{'url'} = $FORM::url;
2670
    $$templateVars{'dataMedium'} = $FORM::dataMedium;
2671
    $$templateVars{'dataMediumOther'} = $FORM::dataMediumOther;
2672
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2673
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2674
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2675
    $$templateVars{'endingYear'} = $FORM::endingYear;
2676
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2677
    $$templateVars{'endingDay'} = $FORM::endingDay;
2678
    $$templateVars{'geogdesc'} = $FORM::geogdesc;
2679
    if($FORM::useSiteCoord ne ""){
2680
    $$templateVars{'useSiteCoord'} = "CHECKED";
2681
    }else{
2682
    $$templateVars{'useSiteCoord'} = "";
2683
    }
2684
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2685
    $$templateVars{'latMin1'} = $FORM::latMin1;
2686
    $$templateVars{'latSec1'} = $FORM::latSec1;
2687
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2688
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2689
    $$templateVars{'longMin1'} = $FORM::longMin1;
2690
    $$templateVars{'longSec1'} = $FORM::longSec1;
2691
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2692
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2693
    $$templateVars{'latMin2'} = $FORM::latMin2;
2694
    $$templateVars{'latSec2'} = $FORM::latSec2;
2695
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2696
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2697
    $$templateVars{'longMin2'} = $FORM::longMin2;
2698
    $$templateVars{'longSec2'} = $FORM::longSec2;
2699
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2700
    $$templateVars{'taxaCount'} = $FORM::taxaCount;
2701
    foreach my $trn (param()) {
2702
        if ($trn =~ /taxonRankName/) {
2703
            my $taxIndex = $trn;
2704
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
2705
            my $trv = "taxonRankValue".$taxIndex;
2706
            if ( $taxIndex =~ /[0-9]/ ){
2707
                if (hasContent(param($trn)) && hasContent(param($trv))) {
2708
                    debug("Registry processing taxon: $trn = ".param($trn)." $trv = ".param($trv));
2709
                    $$templateVars{$trn} = param($trn);
2710
                    $$templateVars{$trv} = param($trv);
2711
                }
2712
            }
2713
        }
2714
    }
2715
    $$templateVars{'taxaAuth'} = $FORM::taxaAuth;
2716
    $$templateVars{'methodTitle'} = $FORM::methodTitle;
2717
    $$templateVars{'methodPara'} = \@FORM::methodPara;
2718
    $$templateVars{'studyExtentDescription'} = $FORM::studyExtentDescription;
2719
    $$templateVars{'samplingDescription'} = $FORM::samplingDescription;
2720
    
2721
    $$templateVars{'showSiteList'} = $FORM::showSiteList;
2722
    $$templateVars{'lsite'} = $FORM::lsite;
2723
    $$templateVars{'usite'} = $FORM::usite;
2724
    $$templateVars{'showWgList'} = $FORM::showWgList;
2725
    $$templateVars{'showOrganization'} = $FORM::showOrganization;
2726
    $$templateVars{'hasKeyword'} = $FORM::hasKeyword;
2727
    $$templateVars{'hasTemporal'} = $FORM::hasTemporal;
2728
    $$templateVars{'hasSpatial'} = $FORM::hasSpatial;
2729
    $$templateVars{'hasTaxonomic'} = $FORM::hasTaxonomic;
2730
    $$templateVars{'hasMethod'} = $FORM::hasMethod;
2731
    $$templateVars{'spatialRequired'} = $FORM::spatialRequired;
2732
    $$templateVars{'temporalRequired'} = $FORM::temporalRequired;
2733
}
2734

    
2735
################################################################################
2736
# 
2737
# check if there is multiple occurence of the given tag and find its value.
2738
#
2739
################################################################################
2740

    
2741
sub findValue {
2742
    my $node = shift;
2743
    my $value = shift;
2744
    my $result;
2745
    my $tempNode;
2746

    
2747
    $result = $node->findnodes("./$value");
2748
    if ($result->size > 1) {
2749
        errMoreThanOne("$value");
2750
    } else {
2751
        foreach $tempNode ($result->get_nodelist){
2752
            #print $tempNode->nodeName().":".$tempNode->textContent();
2753
            #print "\n";
2754
            return $tempNode->textContent();
2755
        }
2756
    }
2757
}
2758

    
2759

    
2760
################################################################################
2761
# 
2762
# check if given tags has any children. if not return the value
2763
#
2764
################################################################################
2765
sub findValueNoChild {
2766
    my $node = shift;
2767
    my $value = shift;
2768
    my $tempNode;
2769
    my $childNodes;
2770
    my $result;
2771
    my $error;
2772

    
2773
    $result = $node->findnodes("./$value");
2774
    if($result->size > 1){
2775
       errMoreThanOne("$value");
2776
    } else {
2777
        foreach $tempNode ($result->get_nodelist) {
2778
            $childNodes = $tempNode->childNodes;
2779
            if ($childNodes->size() > 1) {
2780
                $error ="The tag $value has children which cannot be shown using the form. Please use Morpho to edit this document";    
2781
                push(@errorMessages, $error);
2782
                #if ($DEBUG == 1){ print $error."\n";}
2783
            } else {
2784
                #print $tempNode->nodeName().":".$tempNode->textContent();
2785
                #print "\n";
2786
                return $tempNode->textContent();
2787
            }
2788
        }
2789
    }
2790
}
2791

    
2792

    
2793
################################################################################
2794
# 
2795
# check if given tags are children of given node.
2796
#
2797
################################################################################
2798
sub dontOccur {
2799
    my $node = shift;
2800
    my $value = shift;
2801
    my $errVal = shift;
2802

    
2803
    my $result = $node->findnodes("$value");
2804
    if($result->size > 0){
2805
        $error ="One of the following tags found: $errVal. Please use Morpho to edit this document";
2806
        push(@errorMessages, $error."\n");
2807
        #if ($DEBUG == 1){ print $error;}
2808
    } 
2809
}
2810

    
2811

    
2812
################################################################################
2813
# 
2814
# print out error for more than one occurence of a given tag
2815
#
2816
################################################################################
2817
sub errMoreThanOne {
2818
    my $value = shift;
2819
    my $error ="More than one occurence of the tag $value found. Please use Morpho to edit this document";
2820
    push(@errorMessages, $error."\n");
2821
    # if ($DEBUG == 1){ print $error;}
2822
}
2823

    
2824

    
2825
################################################################################
2826
# 
2827
# print out error for more than given number of occurences of a given tag
2828
#
2829
################################################################################
2830
sub errMoreThanN {
2831
    my $value = shift;
2832
    my $error ="More occurences of the tag $value found than that can be shown in the form. Please use Morpho to edit this document";
2833
    push(@errorMessages, $error);
2834
    #if ($DEBUG == 1){ print $error."\n";}
2835
}
2836

    
2837

    
2838
################################################################################
2839
# 
2840
# convert coord to degrees, minutes and seconds form. 
2841
#
2842
################################################################################
2843
#sub convertCoord {
2844
#    my $wx = shift;
2845
#    print $deg." ".$min." ".$sec;
2846
#    print "\n";
2847
#}
2848

    
2849

    
2850
################################################################################
2851
# 
2852
# print debugging messages to stderr
2853
#
2854
################################################################################
2855
sub debug {
2856
    my $msg = shift;
2857
    
2858
    if ($debug) {
2859
        print STDERR "$msg\n";
2860
    }
2861
}
2862

    
2863
################################################################################
2864
# 
2865
# get the list of projects
2866
#
2867
################################################################################
2868
sub getProjectList {
2869
    
2870
    #use NCEAS::AdminDB;
2871
    #my $admindb = NCEAS::AdminDB->new();
2872
    #$admindb->connect($nceas_db, $nceas_db_user, $nceas_db_password);
2873
    #my $projects = $admindb->getProjects();
2874
    my $projects = getTestProjectList();
2875
    return $projects;
2876
}
2877

    
2878
################################################################################
2879
# 
2880
# get a test list of projects for use only in testing where the NCEAS
2881
# admin db is not available.
2882
#
2883
################################################################################
2884
sub getTestProjectList {
2885
    # This block is for testing only!  Remove for production use
2886
    my @row1;
2887
    $row1[0] = 6000; $row1[1] = 'Andelman'; $row1[2] = 'Sandy'; $row1[3] = 'The very long and windy path to an apparent ecological conclusion: statistics lie';
2888
    my @row2; 
2889
    $row2[0] = 7000; $row2[1] = 'Bascompte'; $row2[2] = 'Jordi'; $row2[3] = 'Postdoctoral Fellow';
2890
    my @row3; 
2891
    $row3[0] = 7001; $row3[1] = 'Hackett'; $row3[2] = 'Edward'; $row3[3] = 'Sociology rules the world';
2892
    my @row4; 
2893
    $row4[0] = 7002; $row4[1] = 'Jones'; $row4[2] = 'Matthew'; $row4[3] = 'Informatics rules the world';
2894
    my @row5; 
2895
    $row5[0] = 7003; $row5[1] = 'Schildhauer'; $row5[2] = 'Mark'; $row5[3] = 'Excel rocks my world, assuming a, b, and c';
2896
    my @row6; 
2897
    $row6[0] = 7004; $row6[1] = 'Rogers'; $row6[2] = 'Bill'; $row6[3] = 'Graduate Intern';
2898
    my @row7; 
2899
    $row7[0] = 7005; $row7[1] = 'Zedfried'; $row7[2] = 'Karl'; $row7[3] = 'A multivariate analysis of thing that go bump in the night';
2900
    my @projects;
2901
    $projects[0] = \@row1;
2902
    $projects[1] = \@row2;
2903
    $projects[2] = \@row3;
2904
    $projects[3] = \@row4;
2905
    $projects[4] = \@row5;
2906
    $projects[5] = \@row6;
2907
    $projects[6] = \@row7;
2908
    return \@projects;
2909
}
(6-6/7)