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-04-08 13:34:03 -0700 (Fri, 08 Apr 2005) $'
8
# '$Revision: 2478 $' 
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, "First name of person entering the form is missing.")
577
        unless hasContent($FORM::providerGivenName);
578
    push(@invalidParams, "Last name of person entering the form is missing.")
579
        unless hasContent($FORM::providerSurName);
580
    push(@invalidParams, "Data set title is missing.")
581
        unless hasContent($FORM::title);
582
    push(@invalidParams, "Organization name is missing.")
583
        unless (hasContent($FORM::site) || $FORM::site =~ /elect/ ||
584
                $FORM::cfg eq "nceas");
585
    push(@invalidParams, "First name of principal data set owner is missing.")
586
        unless hasContent($FORM::origNamefirst0);
587
    push(@invalidParams, "Last name of principal data set owner is missing.")
588
        unless hasContent($FORM::origNamelast0);
589
    push(@invalidParams, "Data set abstract is missing.")
590
        unless hasContent($FORM::abstract);
591
    if($FORM::hasTemporal eq 'true'){
592
	push(@invalidParams, "Year of start date is missing.")
593
	    unless (hasContent($FORM::beginningYear) || $FORM::temporalRequired ne 'true');
594
	push(@invalidParams, "Year of stop date has been specified but year of start date is missing.")
595
	    if ((!hasContent($FORM::beginningYear)) && hasContent($FORM::endingYear));
596
    }
597
    push(@invalidParams, "Geographic description is missing.")
598
        unless (hasContent($FORM::geogdesc) || $FORM::spatialRequired ne 'true');
599

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

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

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

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

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

    
707

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

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

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

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

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

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

    
779
    $val =~ s/&/&amp;/g;
780

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

    
812

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

    
822
    $val =~ s/&/&amp;/g;
823

    
824
    $val =~ s/%/&#37;/g;
825

    
826
    my $returnVal = "";
827

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

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

    
848
    $returnVal =~ s/&/%26/g;
849
    return $returnVal;
850
}
851

    
852

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

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

    
869

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

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

    
888

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

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

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

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

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

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

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

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

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

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

    
986
    $creat .= $dso;
987

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

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

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

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

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

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

    
1114
    $doc .= $creat;
1115
    $doc .= $metaP;
1116
    $doc .= $apart;
1117

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

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

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

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

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

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

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

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

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

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

    
1384
    return $doc;
1385
}
1386

    
1387

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

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

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

    
1411
    Identifier: $identifier
1412
    Title: $FORM::title
1413
    Submitter: $FORM::providerGivenName $FORM::providerSurName
1414

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

    
1421
    $smtp->data($message);
1422
    $smtp->quit;
1423
}
1424

    
1425

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

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

    
1461
    #$tempfile = $xslConvDir.$docid;
1462
    #push (@fileArray, $tempfile);
1463

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

    
1509
            # Read the main document. 
1510

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1806
    $results = $doc->findnodes('//dataset/keywordSet');
1807

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

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

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

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

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

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

    
1905
    dontOccur($doc, "./inline", "//dataset/distribution/inline");
1906

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

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

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

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

    
2015
		            $$templateVars{'hasSpatial'} = "true";
2016
                }
2017
            }
2018

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

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

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

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

    
2131
	    $$templateVars{'hasMethod'} = "true";
2132
        }
2133
    }
2134

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

    
2144
	    $$templateVars{'hasMethod'} = "true";
2145
        }
2146
    }
2147

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

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

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

    
2194

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

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

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

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

    
2243
    } else {
2244
    #Able to login - try to delete the file    
2245

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

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

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

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

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

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

    
2334

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

    
2353

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

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

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

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

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

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

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

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

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

    
2535
    $$templateVars{'docid'} = $FORM::docid;
2536

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

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

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

    
2557

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

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

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

    
2578

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

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

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

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

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

    
2757

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

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

    
2790

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

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

    
2809

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

    
2822

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

    
2835

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

    
2847

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

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

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