Project

General

Profile

metacat / src / perl / register-dataset.cgi @ 2148

1
#!/usr/bin/perl
2
#
3
#  '$RCSfile$'
4
#  Copyright: 2000 Regents of the University of California 
5
#
6
#   '$Author: sgarg $'
7
#     '$Date: 2004-04-30 11:09:12 -0700 (Fri, 30 Apr 2004) $'
8
# '$Revision: 2148 $' 
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("hasKeyword", { DEFAULT => 'true'} );
76
$config->define("hasTemporal", { DEFAULT => 'true'} );
77
$config->define("hasSpatial", { DEFAULT => 'true'} );
78
$config->define("hasTaxonomic", { DEFAULT => 'true'} );
79
$config->define("hasMethod", { DEFAULT => 'true'} );
80
$config->define("temporalRequired", { DEFAULT => 'true'} );
81
$config->define("spatialRequired", { DEFAULT => 'true'} );
82
$config->define("mailhost");
83
$config->define("sender");
84
$config->define("recipient");
85
$config->define("adminname");
86
if ($FORM::cfg eq 'nceas') {
87
    $config->define("nceas_db");
88
    $config->define("nceas_db_user");
89
    $config->define("nceas_db_password");
90
}
91
$config->define("responseTemplate", { DEFAULT => 'crap.tmpl'} );
92
$config->define("entryFormTemplate", { DEFAULT => 'crap.tmpl'} );
93
$config->define("guideTemplate", { DEFAULT => 'crap.tmpl'} );
94
$config->define("confirmDataTemplate", { DEFAULT => 'crap.tmpl'} );
95
$config->define("deleteDataTemplate", { DEFAULT => 'crap.tmpl'} );
96
$config->define("debug", { DEFAULT => '0'} );
97
$config->define("lat", { ARGCOUNT => ARGCOUNT_HASH} );
98
$config->define("lon", { ARGCOUNT => ARGCOUNT_HASH} );
99

    
100
if (! hasContent($FORM::cfg)) {
101
    $error = "Application misconfigured.  Please contact the administrator.";
102
    push(@errorMessages, $error);
103
} else {
104
    my $cfgfile = $cfgdir . "/" . $FORM::cfg . "/" . $FORM::cfg . ".cfg";
105
    $config->file($cfgfile);
106
}
107

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

    
150
# Convert the lat and lon configs into usable data structures
151
my @sitelist;
152
my %siteLatDMS;
153
my %siteLongDMS;
154
foreach my $newsite (keys %$lat) {
155
    my ($latd, $latm, $lats, $latdir) = split(':', $lat->{$newsite});
156
    my ($lond, $lonm, $lons, $londir) = split(':', $lon->{$newsite});
157
    push(@sitelist, $newsite);
158
    $siteLatDMS{$newsite} = [ $latd, $latm, $lats, $latdir ];
159
    $siteLongDMS{$newsite} = [ $lond, $lonm, $lons, $londir ];
160
}
161

    
162
# set some configuration options for the template object
163
my $ttConfig = {
164
             INCLUDE_PATH => $templatesdir, 
165
             INTERPOLATE  => 0,                    
166
             POST_CHOMP   => 1,                   
167
             };
168

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

    
172
print "Content-type: text/html\n\n";
173

    
174
# Set up the template information that is common to all forms
175
$$templateVars{'cfg'} = $FORM::cfg;
176
$$templateVars{'recipient'} = $recipient;
177
$$templateVars{'adminname'} = $adminname;
178
$$templateVars{'organization'} = $organization;
179
$$templateVars{'orgabbrev'} = $orgabbrev;
180
$$templateVars{'orgurl'} = $orgurl;
181
$$templateVars{'orgfilter'} = $orgfilter;
182

    
183
debug("Registry: Initialized");
184
# Process the form based on stage parameter. 
185
if ($FORM::stage =~ "guide") {
186
    # Send back the information on how to fill the form
187
    $$templateVars{'section'} = "Guide on How to Complete Registry Entries";
188
    $template->process( $guideTemplate, $templateVars);
189
    exit(0);
190

    
191
} elsif ($FORM::stage =~ "insert") {
192
    # The user has entered the data. Do data validation and send back data 
193
    # to confirm the data that has been entered. 
194
    toConfirmData();
195
    exit(0);
196

    
197
}elsif ($FORM::dataWrong =~ "No, go back to editing" && $FORM::stage =~ "confirmed") {
198
    # The user wants to correct the data that he has entered. 
199
    # Hence show the data again in entryData form. 
200
    confirmDataToReEntryData();
201
    exit(0);
202

    
203
}elsif ($FORM::stage =~ "modify") {
204
    # Modification of a file has been requested. 
205
    # Show the form will all the values filled in.
206
    my @sortedSites;
207
    foreach my $site (sort @sitelist) {
208
        push(@sortedSites, $site);
209
    }
210
    $$templateVars{'siteList'} = \@sortedSites;
211
    $$templateVars{'section'} = "Modification Form";
212
    $$templateVars{'docid'} = $FORM::docid;
213
    modifyData();
214
    exit(0);
215

    
216
}elsif ($FORM::stage =~ "delete_confirm") {
217

    
218
    # Result from deleteData form. 
219
    if($FORM::deleteData =~ "Delete data"){
220
    # delete Data
221
    deleteData(1);    
222
    exit(0);
223
    } else {
224
    # go back to search page. 
225
    exit(0);
226
    }
227

    
228
}elsif ($FORM::stage =~ "delete") {
229
    # Deletion of a file has been requested. 
230
    # Ask for username and password using deleteDataForm
231
    $$templateVars{'docid'} = $FORM::docid;
232
    $template->process( $deleteDataTemplate, $templateVars);
233
    exit(0);
234

    
235
}elsif ($FORM::stage !~ "confirmed") {
236
    # None of the stages have been reached and data is not being confirmed. 
237
    # Hence, send back entry form for entry of data.  
238
    debug("Registry: Sending form");
239
    my @sortedSites;
240
    foreach my $site (sort @sitelist) {
241
        push(@sortedSites, $site);
242
    }
243
    
244
    if ($FORM::cfg eq 'nceas') {
245
        my $projects = getProjectList();
246
        $$templateVars{'projects'} = $projects;
247
        $$templateVars{'wg'} = \@FORM::wg;
248
    }
249

    
250
    $$templateVars{'hasKeyword'} = $hasKeyword;
251
    $$templateVars{'hasTemporal'} = $hasTemporal;
252
    $$templateVars{'hasSpatial'} = $hasSpatial;
253
    $$templateVars{'hasTaxonomic'} = $hasTaxonomic;
254
    $$templateVars{'hasMethod'} = $hasMethod;
255
    $$templateVars{'temporalRequired'} = $temporalRequired;
256
    $$templateVars{'spatialRequired'} = $spatialRequired;
257

    
258
    $$templateVars{'siteList'} = \@sortedSites;
259
    $$templateVars{'section'} = "Entry Form";
260
    $$templateVars{'docid'} = "";
261
    debug("Registry: Sending form: ready to process template");
262
    $template->process( $entryFormTemplate, $templateVars);
263
    debug("Registry: Sending form: template processed");
264
    exit(0);
265
}
266

    
267
# Confirm stage has been reached. Enter the data into metacat. 
268

    
269
# Initialize some global vars
270
my $latDeg1 = "";
271
my $latMin1 = "";
272
my $latSec1 = "";
273
my $hemisphLat1 = "";
274
my $longDeg1 = "";
275
my $longMin1 = "";
276
my $longSec1 = "";
277
my $hemisphLong1 = "";
278
my $latDeg2 = "";
279
my $latMin2 = "";
280
my $latSec2 = "";
281
my $hemisphLat2 = "";
282
my $longDeg2 = "";
283
my $longMin2 = "";
284
my $longSec2 = "";
285
my $hemisphLong2 = "";
286

    
287
# validate the input form parameters
288
my $invalidParams;
289

    
290
if (! $error) {
291
    $invalidParams = validateParameters(1);
292
    if (scalar(@$invalidParams)) {
293
        $$templateVars{'status'} = 'failure';
294
        $$templateVars{'invalidParams'} = $invalidParams;
295
        $error = 1;
296
    }
297
}
298

    
299

    
300
my $metacat;
301
my $docid;
302
if (! $error) {
303
    # Parameters have been validated and Create the XML document
304

    
305
    my $xmldoc = createXMLDocument();
306

    
307
    # Write out the XML file for debugging purposes
308
    #my $testFile = $tmpdir . "/test.xml";
309

    
310
    # Create a  metacat object
311
    $metacat = Metacat->new();
312
    if ($metacat) {
313
        $metacat->set_options( metacatUrl => $metacatUrl );
314
    } else {
315
        #die "failed during metacat creation\n";
316
        push(@errorMessages, "Failed during metacat creation.");
317
    }
318

    
319
    # Login to metacat
320
    my $userDN = $FORM::username;
321
    my $userOrg = $FORM::organization;
322
    my $userPass = $FORM::password;
323
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
324
    
325
    my $xmldocWithDocID = $xmldoc;
326
    
327
    my $errorMessage = "";
328
    my $response = $metacat->login($dname, $userPass);
329
    if (! $response) {
330
        push(@errorMessages, $metacat->getMessage());
331
        push(@errorMessages, "Failed during login.\n");
332
    }
333

    
334
    debug( "Registry: A");
335
    if ($FORM::docid eq "") {
336
        debug( "Registry: B1");
337
        # document is being inserted 
338
        my $notunique = "NOT_UNIQUE";
339
        while ($notunique eq "NOT_UNIQUE") {
340
            $docid = newAccessionNumber($defaultScope);
341
            
342
	    $xmldocWithDocID = $xmldoc;
343
            $xmldocWithDocID =~ s/docid/$docid/;
344

    
345
	    # Code for testing the xml file being inserted####
346
            #my $testFile = "/tmp/test.xml";
347
            #open (TFILE,">$testFile") || die ("Cant open xml file...\n");
348
            #print TFILE $xmldoc;
349
            #close(TFILE);
350
	    ####
351
    
352
            $notunique = insertMetadata($xmldocWithDocID, $docid);
353
            #  if (!$notunique) {
354
            # Write out the XML file for debugging purposes
355
            #my $testFile = $tmpdir . "/test-new.xml";
356
            #open (TFILE,">$testFile") || die ("Cant open xml file...\n");
357
            #print TFILE $newdoc;
358
            #close(TFILE);
359
            #   }
360

    
361
            # The id wasn't unique, so update our lastid file
362
            if ($notunique eq "NOT_UNIQUE") {
363
                debug( "Registry: Updating lastid (B1.1)");
364
                updateLastId($defaultScope);
365
            }
366
        }
367
        debug("Registry: B2");
368
        if ($notunique ne "SUCCESS") {
369
            debug("Registry: NO SUCCESS");
370
            debug("Message is: $notunique");
371
            push(@errorMessages, $notunique);
372
        }
373

    
374
        debug("Registry: B3");
375
    } else {
376
        # document is being modified
377
        $docid = $FORM::docid;
378
    
379
        my $x;
380
        my $y;
381
        my $z;
382

    
383
        ($x, $y, $z) = split(/\./, $docid); 
384
        $z++;
385
        $docid = "$x.$y.$z";
386
    
387
        $xmldoc =~ s/docid/$docid/;
388
        
389
        my $response = $metacat->update($docid, $xmldoc);
390

    
391
        if (! $response) {
392
            push(@errorMessages, $metacat->getMessage());
393
            push(@errorMessages, "Failed while updating.\n");  
394
        }
395

    
396
        if (scalar(@errorMessages)) {
397
            debug("Registry: ErrorMessages defined in modify.");
398

    
399
	    $$templateVars{'docid'} = $FORM::docid;
400
	    copyFormToTemplateVars();
401
            $$templateVars{'status'} = 'failure';
402
            $$templateVars{'errorMessages'} = \@errorMessages;
403
            $error = 1;
404
        } else {
405
	    $$templateVars{'docid'} = $docid;
406
	    $$templateVars{'cfg'} = $FORM::cfg;
407
	}
408

    
409
        #if (! $error) {
410
            #sendNotification($docid, $mailhost, $sender, $recipient);
411
        #}
412
    
413
        # Create our HTML response and send it back
414
        $$templateVars{'function'} = "modified";
415
        $$templateVars{'section'} = "Modification Status";
416
        $template->process( $responseTemplate, $templateVars);
417

    
418
        exit(0);
419
    }
420
}
421

    
422
debug("Registry: C");
423

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

    
436
#if (! $error) {
437
#sendNotification($docid, $mailhost, $sender, $recipient);
438
#}
439

    
440
# Create our HTML response and send it back
441
$$templateVars{'function'} = "submitted";
442
$$templateVars{'section'} = "Submission Status";
443

    
444
$template->process( $responseTemplate, $templateVars);
445

    
446
exit(0);
447

    
448

    
449
################################################################################
450
#
451
# Subroutine for updating a metacat id for a given scope to the highest value
452
#
453
################################################################################
454
sub updateLastId {
455
  my $scope = shift;
456

    
457
  my $errormsg = 0;
458
  my $docid = $metacat->getLastId($scope);
459

    
460
  if ($docid =~ /null/) {
461
      # No docids with this scope present, so do nothing
462
  } elsif ($docid) {
463
      # Update the lastid file for this scope
464
      (my $foundScope, my $id, my $rev) = split(/\./, $docid);
465
      debug("Docid is: $docid\n");
466
      debug("Lastid is: $id");
467
      my $scopeFile = $cfgdir . "/" . $FORM::cfg . "/" . $scope . ".lastid";
468
      open(LASTID, ">$scopeFile") or 
469
          die "Failed to open lastid file for writing!";
470
      print LASTID $id, "\n";
471
      close(LASTID);
472
  } else {
473
    $errormsg = $metacat->getMessage();
474
    debug("Error in getLastId: $errormsg");
475
  }
476
}
477

    
478
################################################################################
479
#
480
# Subroutine for inserting a document to metacat
481
#
482
################################################################################
483
sub insertMetadata {
484
  my $xmldoc = shift;
485
  my $docid = shift;
486

    
487
  my $notunique = "SUCCESS";
488
  debug("Registry: Starting insert (D1)");
489
  my $response = $metacat->insert($docid, $xmldoc);
490
  if (! $response) {
491
    debug("Registry: Response gotten (D2)");
492
    my $errormsg = $metacat->getMessage();
493
    debug("Registry: Error is (D3): ".$errormsg);
494
    if ($errormsg =~ /is already in use/) {
495
      $notunique = "NOT_UNIQUE";
496
      #print "Accession number already used: $docid\n";
497
    } elsif ($errormsg =~ /<login>/) {
498
      $notunique = "SUCCESS";
499
    } else {
500
      #print "<p>Dumping error on failure...</p>\n";
501
      #print "<p>", $errormsg, "</p>\n";
502
      #die "Failed during insert\n";
503
      #print "<p>Failed during insert</p>\n";
504
      $notunique = $errormsg;
505
    }
506
  }
507
  debug("Registry: Ending insert (D4)");
508

    
509
  return $notunique;
510
}
511

    
512
################################################################################
513
#
514
# Subroutine for generating a new accession number
515
#  Note: this is not threadsafe, assumes only one running process at a time
516
#  Also: need to check metacat for max id # used in this scope already
517
################################################################################
518
sub newAccessionNumber {
519
  my $scope = shift;
520
    
521
  my $docrev = 1;
522
  my $lastid = 1;
523

    
524
  my $scopeFile = $cfgdir . "/" . $FORM::cfg . "/" . $scope . ".lastid";
525
  if (-e $scopeFile) {
526
    open(LASTID, "<$scopeFile") or die "Failed to generate accession number!";
527
    $lastid = <LASTID>;
528
    chomp($lastid);
529
    $lastid++;
530
    close(LASTID);
531
  }
532
  open(LASTID, ">$scopeFile") or die "Failed to open lastid file for writing!";
533
  print LASTID $lastid, "\n";
534
  close(LASTID);
535

    
536
  my $docroot = "$scope.$lastid.";
537
  my $docid = $docroot . $docrev;
538
  return $docid;
539
}
540

    
541
################################################################################
542
# 
543
# Validate the parameters to make sure that required params are provided
544
#
545
################################################################################
546
sub validateParameters {
547
    my $chkUser = shift;
548
    my @invalidParams;
549

    
550
    push(@invalidParams, "Provider's first name is missing.")
551
        unless hasContent($FORM::providerGivenName);
552
    push(@invalidParams, "Provider's last name is missing.")
553
        unless hasContent($FORM::providerSurName);
554
    push(@invalidParams, "Name of site is missing.")
555
        unless (hasContent($FORM::site) || $FORM::site =~ /elect/ ||
556
                $FORM::cfg eq "nceas");
557
    push(@invalidParams, "Data set title is missing.")
558
        unless hasContent($FORM::title);
559
    push(@invalidParams, "Originator's first name is missing.")
560
        unless hasContent($FORM::origNamefirst0);
561
    push(@invalidParams, "Originator's last name is missing.")
562
        unless hasContent($FORM::origNamelast0);
563
    push(@invalidParams, "Abstract is missing.")
564
        unless hasContent($FORM::abstract);
565
    push(@invalidParams, "Beginning year of data set is missing.")
566
        unless (hasContent($FORM::beginningYear) || $FORM::temporalRequired ne 'true');
567
    push(@invalidParams, "Geographic description is missing.")
568
        unless (hasContent($FORM::geogdesc) || $FORM::spatialRequired ne 'true');
569

    
570
    # If the "use site" coord. box is checked and if the site is in 
571
    # the longitude hash ...  && ($siteLatDMS{$FORM::site})
572
   
573
    if($FORM::hasSpatial eq 'true'){
574
	if (($FORM::useSiteCoord) && ($siteLatDMS{$FORM::site}) ) {
575
        
576
	    $latDeg1 = $siteLatDMS{$FORM::site}[0];
577
	    $latMin1 = $siteLatDMS{$FORM::site}[1];
578
	    $latSec1 = $siteLatDMS{$FORM::site}[2];
579
	    $hemisphLat1 = $siteLatDMS{$FORM::site}[3];
580
	    $longDeg1 = $siteLongDMS{$FORM::site}[0];
581
	    $longMin1 = $siteLongDMS{$FORM::site}[1];
582
	    $longSec1 = $siteLongDMS{$FORM::site}[2];
583
	    $hemisphLong1 = $siteLongDMS{$FORM::site}[3];
584
	    
585
	}  else {
586
	    
587
	    $latDeg1 = $FORM::latDeg1;
588
	    $latMin1 = $FORM::latMin1;
589
	    $latSec1 = $FORM::latSec1;
590
	    $hemisphLat1 = $FORM::hemisphLat1;
591
	    $longDeg1 = $FORM::longDeg1;
592
	    $longMin1 = $FORM::longMin1;
593
	    $longSec1 = $FORM::longSec1;
594
	    $hemisphLong1 = $FORM::hemisphLong1;
595
	}
596
    }
597
    
598
    # Check if latDeg1 and longDeg1 has values if useSiteCoord is used. 
599
    # This check is required because some of the sites dont have lat 
600
    # and long mentioned in the config file. 
601

    
602

    
603
    if($FORM::hasSpatial eq 'true'){
604
	if ($FORM::useSiteCoord ) {
605
	    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.")
606
		unless(hasContent($latDeg1) && hasContent($longDeg1));
607
	}else{
608
	    push(@invalidParams, "Latitude degrees are missing.")
609
		unless hasContent($latDeg1);
610
	    push(@invalidParams, "Longitude degrees are missing.")
611
		unless hasContent($longDeg1);
612
	}
613
    }
614

    
615
    if($FORM::hasMethod eq 'true'){
616
	push(@invalidParams, 
617
	     "You must provide a method description if you provide a method title.")
618
	    if (hasContent($FORM::methodTitle) && ( !(scalar(@FORM::methodPara) > 0) 
619
						    || (! hasContent($FORM::methodPara[0]))));
620
	push(@invalidParams, 
621
	     "You must provide a method description if you provide a study extent description.")
622
	    if (hasContent($FORM::studyExtentDescription) && (!(scalar(@FORM::methodPara) > 0) 
623
							      || (! hasContent($FORM::methodPara[0]))));
624
	push(@invalidParams, 
625
	     "You must provide both a study extent description and a sampling description, or neither.")
626
	    if (
627
                (hasContent($FORM::studyExtentDescription) && !hasContent($FORM::samplingDescription)) ||
628
                (!hasContent($FORM::studyExtentDescription) && hasContent($FORM::samplingDescription))
629
		);
630
    }
631

    
632
    push(@invalidParams, "Contact first name is missing.")
633
    unless (hasContent($FORM::origNamefirstContact) || 
634
        $FORM::useOrigAddress);
635
    push(@invalidParams, "Contact last name is missing.")
636
    unless (hasContent($FORM::origNamelastContact) || 
637
        $FORM::useOrigAddress);
638
    push(@invalidParams, "Data medium is missing.")
639
    unless (hasContent($FORM::dataMedium) || $FORM::dataMedium =~ /elect/);
640
    
641
    return \@invalidParams;
642
}
643

    
644
################################################################################
645
# 
646
# utility function to determine if a paramter is defined and not an empty string
647
#
648
################################################################################
649
sub hasContent {
650
    my $param = shift;
651

    
652
    my $paramHasContent;
653
    if (!defined($param) || $param eq '') { 
654
        $paramHasContent = 0;
655
    } else {
656
        $paramHasContent = 1;
657
    }
658
    return $paramHasContent;
659
}
660

    
661
################################################################################
662
#
663
# Subroutine for replacing characters not recognizable by XML and otherwise. 
664
#
665
################################################################################
666
sub normalize{
667
    my $val = shift;
668

    
669
    $val =~ s/&/&amp;/g;
670

    
671
    $val =~ s/</&lt;/g;
672
    $val =~ s/>/&gt;/g;
673
    $val =~ s/\"/&quot;/g;
674
    
675
    my $returnVal = "";
676
    
677
    foreach (split(//,$val)){
678
	my $var = unpack "C*", $_; 
679
	
680
	if($var<128 && $var>31){
681
	    $returnVal=$returnVal.$_;
682
	} elsif ($var<32){
683
	    if($var == 10){
684
		$returnVal=$returnVal.$_;
685
	    }
686
	    if($var == 13){
687
		$returnVal=$returnVal.$_;
688
	    }
689
	    if($var == 9){
690
		$returnVal=$returnVal.$_;
691
	    }
692
	} else { 
693
	    $returnVal=$returnVal."&#".$var.";";
694
	}
695
    }
696
    
697
    $returnVal =~ s/&/%26/g;    
698
    return $returnVal;
699
}
700

    
701

    
702
################################################################################
703
#
704
# Subroutine for replacing characters that might create problem in HTML. 
705
# Specifically written for " being used in any text field. This create a 
706
# problem in confirmData template, when you specify input name value pair 
707
# with value having a " in it.  
708
#
709
################################################################################
710
sub normalizeCD{
711
    my $val = shift;
712

    
713
    $val =~ s/\"/&quot;/g;
714
    
715
    return $val;
716
}
717

    
718

    
719
################################################################################
720
# 
721
# Create the XML document from the HTML form input
722
# returns the XML document as a string
723
#
724
################################################################################
725
sub createXMLDocument {
726

    
727
    my $orig  = "";
728
    my $role  = "associatedParty";
729
    my $creat = "";
730
    my $metaP = "";
731
    my $apart = "";
732
    my $cont  = "";
733
    my $publ  = "";
734
    my $dso   = "";
735
    my $gmt = gmtime($now);
736

    
737

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

    
740
    $doc .= "<eml:eml\n 
741
                     \t packageId=\"docid\" system=\"knb\"\n 
742
                     \t xmlns:eml=\"eml://ecoinformatics.org/eml-2.0.0\"\n
743
                     \t xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n 
744
                     \t xmlns:ds=\"eml://ecoinformatics.org/dataset-2.0.0\"\n 
745
                     \t xmlns:stmml=\"http://www.xml-cml.org/schema/stmml\"\n 
746
                     \t xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.0.0 eml.xsd\">\n";
747

    
748
    $doc .= "<!-- Person who filled in the catalog entry form: ";
749
    $doc .= normalize($FORM::providerGivenName)." ".normalize($FORM::providerSurName)." -->\n";
750
    $doc .= "<!-- Form filled out at $gmt GMT -->\n";
751
    $doc .= "<dataset>\n";
752
    
753
    if (hasContent($FORM::identifier)) {
754
        $doc .= "<alternateIdentifier system=\"$FORM::site\">";
755
        $doc .= normalize($FORM::identifier) . "</alternateIdentifier>\n";
756
    }
757
    
758
    if (hasContent($FORM::title)) {
759
        $doc .= "<title>".normalize($FORM::title)."</title>\n";
760
    }
761

    
762
    if (hasContent($FORM::origNamelast0)) {
763
    $role = "creator";
764
        $orig .= "<individualName>\n";
765
        $orig .= "<givenName>".normalize($FORM::origNamefirst0)."</givenName>\n";
766
        $orig .= "<surName>".normalize($FORM::origNamelast0)."</surName>\n";
767
        $orig .= "</individualName>\n";
768
    }
769

    
770
    if (hasContent($FORM::origNameOrg)) {
771
        $orig .= "<organizationName>".normalize($FORM::origNameOrg)."</organizationName>\n";
772
    }
773

    
774
    if (hasContent($FORM::origDelivery) || hasContent($FORM::origCity) ||
775
        (hasContent($FORM::origState   ) &&
776
        ($FORM::origState !~ "Select state here.")) ||
777
        hasContent($FORM::origStateOther) ||
778
        hasContent($FORM::origZIP ) || hasContent($FORM::origCountry)) {
779
        $orig .= "<address>\n";
780

    
781
        if (hasContent($FORM::origDelivery)) {
782
            $orig .= "<deliveryPoint>".normalize($FORM::origDelivery)."</deliveryPoint>\n";
783
        }
784
        if (hasContent($FORM::origCity)) {
785
            $orig .= "<city>".normalize($FORM::origCity)."</city>\n";
786
        }
787

    
788
    if (hasContent($FORM::origState) && 
789
            ($FORM::origState !~ "Select state here.")) {
790
            $orig .= "<administrativeArea>".normalize($FORM::origState);
791
            $orig .= "</administrativeArea>\n";
792
        } elsif (hasContent($FORM::origStateOther)) {
793
            $orig .= "<administrativeArea>".normalize($FORM::origStateOther);
794
            $orig .= "</administrativeArea>\n";
795
        }
796
        if (hasContent($FORM::origZIP)) {
797
            $orig .= "<postalCode>".normalize($FORM::origZIP)."</postalCode>\n";
798
        }
799
        if (hasContent($FORM::origCountry)) {
800
            $orig .= "<country>".normalize($FORM::origCountry)."</country>\n";
801
        }
802
        $orig .= "</address>\n";
803
    }
804

    
805
    if (hasContent($FORM::origPhone)) {
806
        $orig .= "<phone>".normalize($FORM::origPhone)."</phone>\n";
807
    }
808
    if (hasContent($FORM::origFAX)) {
809
        $orig .= "<phone phonetype=\"Fax\">".normalize($FORM::origFAX)."</phone>\n";
810
    }
811
    if (hasContent($FORM::origEmail)) {
812
        $orig .= "<electronicMailAddress>".normalize($FORM::origEmail);
813
        $orig .= "</electronicMailAddress>\n";
814
    }
815
    $dso = "<$role>\n$orig</$role>\n";
816
    
817
    if ($FORM::cfg eq 'nceas') {
818
        for (my $i = 0; $i < scalar(@FORM::wg); $i++) {
819
            $creat .= "<creator>\n";
820
            $creat .= "<organizationName>".normalize($FORM::wg[$i])."</organizationName>\n";
821
            $creat .= "</creator>\n";
822
        }
823
    } else {
824
	    $creat .= "<creator>\n";
825
	    $creat .= "<organizationName>".normalize($FORM::site)."</organizationName>\n";
826
	    $creat .= "</creator>\n";
827
    }
828

    
829
    if ($FORM::cfg ne 'knb') {
830
        $creat .= "<creator>\n";
831
        $creat .= "<organizationName>".normalize($organization)."</organizationName>\n";
832
        $creat .= "</creator>\n";
833
    }
834

    
835
    $creat .= $dso;
836

    
837
    if ($FORM::useOrigAddress) {
838
        # Add a contact originator like the original with a different role
839
            $cont .= "<contact>\n";
840
        $cont .= $orig;
841
        $cont .= "</contact>\n";
842
    } else {
843
        $cont .= "<contact>\n";
844

    
845
        $cont .= "<individualName>\n";
846
        $cont .= "<givenName>".normalize($FORM::origNamefirstContact)."</givenName>\n";
847
        $cont .= "<surName>".normalize($FORM::origNamelastContact)."</surName>\n";
848
        $cont .= "</individualName>\n";
849
 
850
    if (hasContent($FORM::origNameOrgContact)) {
851
        $cont .= "<organizationName>".normalize($FORM::origNameOrgContact)."</organizationName>\n";
852
    }
853

    
854
        if (hasContent($FORM::origDeliveryContact) || 
855
            hasContent($FORM::origCityContact) ||
856
            (hasContent($FORM::origStateContact) &&
857
            ($FORM::origStateContact !~ "Select state here.")) ||
858
            hasContent($FORM::origStateOtherContact) ||
859
            hasContent($FORM::origZIPContact) || 
860
            hasContent($FORM::origCountryContact)) {
861
            $cont .= "<address>\n";
862
            if (hasContent($FORM::origDeliveryContact)) {
863
                $cont .= "<deliveryPoint>".normalize($FORM::origDeliveryContact);
864
                $cont .= "</deliveryPoint>\n";
865
            }
866
            if (hasContent($FORM::origCityContact)) {
867
                $cont .= "<city>".normalize($FORM::origCityContact)."</city>\n";
868
            }
869
            if (hasContent($FORM::origStateContact) && 
870
                ($FORM::origStateContact !~ "Select state here.")) {
871
                $cont .= "<administrativeArea>".normalize($FORM::origStateContact);
872
                $cont .= "</administrativeArea>\n";
873
            } elsif (hasContent($FORM::origStateOtherContact)) {
874
                $cont .= "<administrativeArea>".normalize($FORM::origStateOtherContact);
875
                $cont .= "</administrativeArea>\n";
876
            }
877
            if (hasContent($FORM::origZIPContact)) {
878
                $cont .= "<postalCode>".normalize($FORM::origZIPContact)."</postalCode>\n";
879
            }
880
            if (hasContent($FORM::origCountryContact)) {
881
                $cont .= "<country>".normalize($FORM::origCountryContact)."</country>\n";
882
            }
883
            $cont .= "</address>\n";
884
        }
885
        if (hasContent($FORM::origPhoneContact)) {
886
            $cont .= "<phone>".normalize($FORM::origPhoneContact)."</phone>\n";
887
        }
888
    if (hasContent($FORM::origFAXContact)) {
889
        $cont .= "<phone phonetype=\"Fax\">".normalize($FORM::origFAXContact)."</phone>\n";
890
    }
891
        if (hasContent($FORM::origEmailContact)) {
892
            $cont .= "<electronicMailAddress>".normalize($FORM::origEmailContact);
893
            $cont .= "</electronicMailAddress>\n";
894
        }
895
    $cont .= "</contact>\n";
896
    }
897

    
898
    $metaP .= "<metadataProvider>\n";
899
    $metaP .= "<individualName>\n";
900
    $metaP .= "<givenName>".normalize($FORM::providerGivenName)."</givenName>\n";
901
    $metaP .= "<surName>".normalize($FORM::providerSurName)."</surName>\n";
902
    $metaP .= "</individualName>\n";
903
    $metaP .= "</metadataProvider>\n";
904

    
905
    # Additional originators
906
    foreach my $tmp (param()) {
907
        if ($tmp =~ /origNamelast/){
908
            my $tmp1 = $tmp;
909
            $tmp1 =~ s/origNamelast//; # get the index of the parameter 0 to 10
910
            if ( $tmp1 eq '1' 
911
                 || $tmp1 eq '2'
912
                 || $tmp1 eq '3'
913
                 || $tmp1 eq '4'
914
                 || $tmp1 eq '5'
915
                 || $tmp1 eq '6'
916
                 || $tmp1 eq '7'
917
                 || $tmp1 eq '8'
918
                 || $tmp1 eq '9'
919
                 || $tmp1 eq '10'
920
                 ) {
921
     
922
                # do not generate XML for empty originator fields 
923
                if (hasContent(param("origNamefirst" . $tmp1))) {    
924

    
925
            my $add = "";
926
            $add .= "<individualName>\n";
927
            $add .= "<givenName>";
928
            $add .= normalize(param("origNamefirst" . $tmp1));
929
            $add .= "</givenName>\n";
930
            $add .= "<surName>";
931
            $add .= normalize(param("origNamelast" . $tmp1));
932
            $add .= "</surName>\n";
933
            $add .= "</individualName>\n";
934
            
935
            if(param("origRole" . $tmp1) eq "Originator"){
936
            $creat .= "<creator>\n";
937
            $creat .= $add;
938
            $creat .= "</creator>\n";
939
            }
940
            elsif(param("origRole" . $tmp1) eq "Metadata Provider"){
941
            $metaP .= "<metadataProvider>\n";
942
            $metaP .= $add;
943
            $metaP .= "</metadataProvider>\n";
944
            }
945
            elsif((param("origRole" . $tmp1) eq "Publisher")  && ($publ eq "")){
946
            $publ .= "<publisher>\n";
947
            $publ .= $add;
948
            $publ .= "</publisher>\n";
949
            }
950
            else{
951
            $apart .= "<associatedParty>\n";
952
            $apart .= $add;
953
            $apart .= "<role>";
954
            $apart .= param("origRole" . $tmp1);
955
            $apart .= "</role>\n";
956
            $apart .= "</associatedParty>\n";
957
            }
958
        }
959
            }
960
        }
961
    }
962

    
963
    $doc .= $creat;
964
    $doc .= $metaP;
965
    $doc .= $apart;
966

    
967
    $doc .= "<abstract>\n";
968
    $doc .= "<para>".normalize($FORM::abstract)."</para>\n";
969
    $doc .= "</abstract>\n";
970

    
971
    # Keyword information
972
    foreach my $tmp (param()) {
973
        if ($tmp =~ /keyword/) {
974
            my $tmp1 = $tmp;
975
            $tmp1 =~ s/keyword//; # get the index of the parameter 0, ..., 10
976
            if ( $tmp1 =~ /[0-9]/ ){
977
                # don't generate xml for empty keyword fields
978
                # don't generate taxonomic keyword fields, those go in taxonomic coverage
979
                if (hasContent(param($tmp))) {
980
                    $doc .= "<keywordSet>\n";
981
                    $doc .= "<keyword ";
982
                    if (hasContent(param("kwType" . $tmp1)) &&
983
                       (param("kwType" . $tmp1) !~ "none") ) {
984
                         $doc .= "keywordType=\"";
985
                         $doc .= param("kwType" . $tmp1);
986
                         $doc .= "\"";
987
                    }
988
                    $doc .= ">";
989
                    $doc .= normalize(param("keyword" . $tmp1));
990
                    $doc .= "</keyword>\n";
991
                    $doc .= "<keywordThesaurus>";
992
                    $doc .= normalize(param("kwTh" . $tmp1));
993
                    $doc .= "</keywordThesaurus>\n";
994
                    $doc .= "</keywordSet>\n";
995
                }
996
            }
997
        }
998
    }
999

    
1000
    if (hasContent($FORM::addComments)) {
1001
        $doc .= "<additionalInfo>\n";
1002
        $doc .= "<para>".normalize($FORM::addComments)."</para>\n";
1003
        $doc .= "</additionalInfo>\n";
1004
    }
1005

    
1006
    if (hasContent($FORM::useConstraints) || 
1007
        hasContent($FORM::useConstraintsOther)) {
1008
        $doc .= "<intellectualRights>\n";
1009
        if (hasContent($FORM::useConstraints)) {
1010
            $doc .= "<para>".normalize($FORM::useConstraints)."</para>\n";
1011
        }
1012
        if (hasContent($FORM::useConstraintsOther)) {
1013
            $doc .= "<para>".normalize($FORM::useConstraintsOther)."</para>\n";
1014
        }
1015
        $doc .= "</intellectualRights>\n";
1016
    }
1017

    
1018
    
1019
    if (hasContent($FORM::url)) {
1020
    $doc .= "<distribution>\n";
1021
        $doc .= "<online>\n";
1022
    $doc .= "<url>".normalize($FORM::url)."</url>\n";
1023
    $doc .= "</online>\n";
1024
    $doc .= "</distribution>\n";
1025
    }
1026
    
1027
    $doc .= "<distribution>\n";
1028
    $doc .= "<offline>\n";
1029
    $doc .= "<mediumName>" . normalize($FORM::dataMedium)." ".normalize($FORM::dataMediumOther);
1030
    $doc .= "</mediumName>\n";
1031
    $doc .= "</offline>\n";
1032
    $doc .= "</distribution>\n";
1033
            
1034
    my $cov = "";
1035

    
1036
    if (hasContent($FORM::endingYear)) {
1037
	$cov .= "<temporalCoverage>\n";
1038
	$cov .= "<rangeOfDates>\n";
1039
	if (hasContent($FORM::beginningMonth)) {
1040
	    my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1041
			 "JUL","AUG","SEP","OCT","NOV","DEC")
1042
		[$FORM::beginningMonth - 1];
1043
	    $cov .= "<beginDate>\n";
1044
	    $cov .= "<calendarDate>";
1045
	    $cov .= normalize($FORM::beginningYear)."-".normalize($FORM::beginningMonth)."-".normalize($FORM::beginningDay);
1046
	    $cov .= "</calendarDate>\n";
1047
	    $cov .= "</beginDate>\n";
1048
	} else {
1049
	    $cov .= "<beginDate>\n";
1050
	    $cov .= "<calendarDate>";
1051
	    $cov .= normalize($FORM::beginningYear);
1052
	    $cov .= "</calendarDate>\n";
1053
	    $cov .= "</beginDate>\n";
1054
	}
1055
	
1056
	if (hasContent($FORM::endingMonth)) {
1057
	    my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1058
			 "JUL","AUG","SEP","OCT","NOV","DEC")
1059
		[$FORM::endingMonth - 1];
1060
	    $cov .= "<endDate>\n";
1061
	    $cov .= "<calendarDate>";
1062
	    $cov .= normalize($FORM::endingYear)."-".normalize($FORM::endingMonth)."-".normalize($FORM::endingDay);
1063
	    $cov .= "</calendarDate>\n";
1064
	    $cov .= "</endDate>\n";
1065
	} else {
1066
	    $cov .= "<endDate>\n";
1067
	    $cov .= "<calendarDate>";
1068
	    $cov .= normalize($FORM::endingYear);
1069
	    $cov .= "</calendarDate>\n";
1070
	    $cov .= "</endDate>\n";
1071
	}
1072
	$cov .= "</rangeOfDates>\n";
1073
	$cov .= "</temporalCoverage>\n";
1074
    } else {
1075
	if(hasContent($FORM::beginningYear)) {
1076
	    $cov .= "<temporalCoverage>\n";
1077
	    $cov .= "<singleDateTime>\n";
1078
	    if (hasContent($FORM::beginningMonth)) {
1079
		my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1080
			     "JUL","AUG","SEP","OCT","NOV","DEC")
1081
		    [$FORM::beginningMonth - 1];
1082
		$cov .= "<calendarDate>";
1083
		$cov .= normalize($FORM::beginningYear)."-".normalize($FORM::beginningMonth)."-".normalize($FORM::beginningDay);
1084
		$cov .= "</calendarDate>\n";
1085
	    } else {
1086
		$cov .= "<calendarDate>";
1087
		$cov .= normalize($FORM::beginningYear);
1088
		$cov .= "</calendarDate>\n";
1089
	    }
1090
	    $cov .= "</singleDateTime>\n";
1091
	    $cov .= "</temporalCoverage>\n";
1092
	}
1093
    }
1094
    
1095
    if(hasContent($FORM::geodesc) || ($FORM::latDeg1 != 0 && $FORM::longDeg1 != 0)) {
1096
	$cov .= "<geographicCoverage>\n";
1097

    
1098
	if(hasContent($FORM::geodesc)) {
1099
	    $cov .= "<geographicDescription>".normalize($FORM::geogdesc)."</geographicDescription>\n";
1100
	}
1101
	
1102
	if($FORM::latDeg1 != 0 && $FORM::longDeg1 != 0) {
1103
	    $cov .= "<boundingCoordinates>\n";
1104
	    # if the second latitude is missing, then set the second lat/long pair 
1105
	    # equal to the first this makes a point appear like a rectangle 
1106
	    if ($FORM::latDeg2 == 0 && $FORM::latMin2 == 0 && $FORM::latSec2 == 0) {
1107
		
1108
		$latDeg2 = $latDeg1;
1109
		$latMin2 = $latMin1;
1110
		$latSec2 = $latSec1;
1111
		$hemisphLat2 = $hemisphLat1;
1112
		$longDeg2 = $longDeg1;
1113
		$longMin2 = $longMin1;
1114
		$longSec2 = $longSec1;
1115
		$hemisphLong2 = $hemisphLong1;
1116
	    }
1117
	    else
1118
	    {
1119
		$latDeg2 = $FORM::latDeg2;
1120
		$latMin2 = $FORM::latMin2;
1121
		$latSec2 = $FORM::latSec2;
1122
		$hemisphLat2 = $FORM::hemisphLat2;
1123
		$longDeg2 = $FORM::longDeg2;
1124
		$longMin2 = $FORM::longMin2;
1125
		$longSec2 = $FORM::longSec2;
1126
		$hemisphLong2 = $FORM::hemisphLong2;
1127
	    } 
1128
	
1129
	
1130
	    my $hemisph;
1131
	    $hemisph = ($hemisphLong1 eq "W") ? -1 : 1;
1132
	    $cov .= "<westBoundingCoordinate>";
1133
	    $cov .= $hemisph * ($longDeg1 + (60*$longMin1+$longSec1)/3600);
1134
	    $cov .= "</westBoundingCoordinate>\n";
1135
	    
1136
	    $hemisph = ($hemisphLong2 eq "W") ? -1 : 1;
1137
	    $cov .= "<eastBoundingCoordinate>";
1138
	    $cov .= $hemisph * ($longDeg2 + (60*$longMin2+$longSec2)/3600);
1139
	    $cov .= "</eastBoundingCoordinate>\n";
1140
	    
1141
	    $hemisph = ($hemisphLat1 eq "S") ? -1 : 1;
1142
	    $cov .= "<northBoundingCoordinate>";
1143
	    $cov .= $hemisph * ($latDeg1 + (60*$latMin1+$latSec1)/3600);
1144
	    $cov .= "</northBoundingCoordinate>\n";
1145
	    
1146
	    $hemisph = ($hemisphLat2 eq "S") ? -1 : 1;
1147
	    $cov .= "<southBoundingCoordinate>";
1148
	    $cov .= $hemisph * ($latDeg2 + (60*$latMin2+$latSec2)/3600);
1149
	    $cov .= "</southBoundingCoordinate>\n";
1150
	    
1151
	    $cov .= "</boundingCoordinates>\n";
1152
	}
1153
	$cov .= "</geographicCoverage>\n";
1154
    }
1155

    
1156
    # Write out the taxonomic coverage fields
1157
    my $foundFirstTaxon = 0;
1158
    foreach my $trn (param()) {
1159
        if ($trn =~ /taxonRankName/) {
1160
            my $taxIndex = $trn;
1161
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
1162
            my $trv = "taxonRankValue".$taxIndex;
1163
            if ( $taxIndex =~ /[0-9]/ ){
1164
                if (hasContent(param($trn)) && hasContent(param($trv))) {
1165
                    if (! $foundFirstTaxon) {
1166
                        $cov .= "<taxonomicCoverage>\n";
1167
                        $foundFirstTaxon = 1;
1168
                        if (hasContent($FORM::taxaAuth)) {
1169
                            $cov .= "<generalTaxonomicCoverage>".normalize($FORM::taxaAuth)."</generalTaxonomicCoverage>\n";
1170
                        }
1171
                    }
1172
                    $cov .= "<taxonomicClassification>\n";
1173
                    $cov .= "  <taxonRankName>".normalize(param($trn))."</taxonRankName>\n";
1174
                    $cov .= "  <taxonRankValue>".normalize(param($trv))."</taxonRankValue>\n";
1175
                    $cov .= "</taxonomicClassification>\n";
1176
                }
1177
            }
1178
        }
1179
    }
1180
    if ($foundFirstTaxon) {
1181
        $cov .= "</taxonomicCoverage>\n";
1182
    }
1183

    
1184
    $doc .= $cov;
1185
    $doc .= $cont;
1186
    $doc .= $publ;
1187
    
1188
    if ((hasContent($FORM::methodTitle)) || scalar(@FORM::methodsPara) > 0) {
1189
        my $methods = "<methods><methodStep><description><section>\n";
1190
        if (hasContent($FORM::methodTitle)) {
1191
            $methods .= "<title>".normalize($FORM::methodTitle)."</title>\n";
1192
        }
1193
        for (my $i = 0; $i < scalar(@FORM::methodPara); $i++) {
1194
            $methods .= "<para>".normalize($FORM::methodPara[$i])."</para>\n";
1195
        }
1196
        $methods .= "</section></description></methodStep>\n";
1197
        if (hasContent($FORM::studyExtentDescription)) {
1198
            $methods .= "<sampling><studyExtent><description>\n";
1199
            $methods .= "<para>".normalize($FORM::studyExtentDescription)."</para>\n";
1200
            $methods .= "</description></studyExtent>\n";
1201
            $methods .= "<samplingDescription>\n";
1202
            $methods .= "<para>".normalize($FORM::samplingDescription)."</para>\n";
1203
            $methods .= "</samplingDescription>\n";
1204
            $methods .= "</sampling>\n";
1205
        }
1206
        $methods .= "</methods>\n";
1207
        $doc .= $methods;
1208
    }
1209

    
1210
    $doc .= "<access authSystem=\"knb\" order=\"denyFirst\">\n";
1211
    $doc .= "<allow>\n";
1212
    $doc .= "<principal>$username</principal>\n";
1213
    $doc .= "<permission>all</permission>\n";
1214
    $doc .= "</allow>\n";
1215
    $doc .= "<allow>\n";
1216
    $doc .= "<principal>uid=$FORM::username,o=$FORM::organization,dc=ecoinformatics,dc=org</principal>\n";
1217
    $doc .= "<permission>all</permission>\n";
1218
    $doc .= "</allow>\n";
1219
    $doc .= "<allow>\n";
1220
    $doc .= "<principal>public</principal>\n";
1221
    $doc .= "<permission>read</permission>\n";
1222
    $doc .= "</allow>\n";
1223
    $doc .= "</access>\n";
1224
    
1225
    $doc .= "</dataset>\n</eml:eml>\n";
1226

    
1227
    return $doc;
1228
}
1229

    
1230

    
1231
################################################################################
1232
# 
1233
# send an email message notifying the moderator of a new submission 
1234
#
1235
################################################################################
1236
sub sendNotification {
1237
    my $identifier = shift;
1238
    my $mailhost = shift;
1239
    my $sender = shift;
1240
    my $recipient = shift;
1241

    
1242
    my $smtp = Net::SMTP->new($mailhost);
1243
    $smtp->mail($sender);
1244
    $smtp->to($recipient);
1245

    
1246
    my $message = <<"    ENDOFMESSAGE";
1247
    To: $recipient
1248
    From: $sender
1249
    Subject: New data submission
1250
    
1251
    Data was submitted to the data registry.  
1252
    The identifying information for the new data set is:
1253

    
1254
    Identifier: $identifier
1255
    Title: $FORM::title
1256
    Submitter: $FORM::providerGivenName $FORM::providerSurName
1257

    
1258
    Please review the submmission and grant public read access if appropriate.
1259
    Thanks
1260
    
1261
    ENDOFMESSAGE
1262
    $message =~ s/^[ \t\r\f]+//gm;
1263

    
1264
    $smtp->data($message);
1265
    $smtp->quit;
1266
}
1267

    
1268

    
1269
################################################################################
1270
# 
1271
# read the eml document and send back a form with values filled in. 
1272
#
1273
################################################################################
1274
sub modifyData {
1275
    
1276
    # create metacat instance
1277
    my $metacat;
1278
    my $docid = $FORM::docid;
1279
    my $httpMessage;
1280
    my $doc;
1281
    my $xmldoc;
1282
    my $findType;
1283
    my $parser = XML::LibXML->new();
1284
    my @fileArray;
1285
    my $pushDoc;
1286
    my $alreadyInArray;
1287
    my $node;
1288
    my $response; 
1289
    my $element;
1290
    my $tempfile;
1291

    
1292
    $metacat = Metacat->new();
1293
    if ($metacat) {
1294
        $metacat->set_options( metacatUrl => $metacatUrl );
1295
    } else {
1296
        #die "failed during metacat creation\n";
1297
        push(@errorMessages, "Failed during metacat creation.");
1298
    }
1299
    
1300
    $httpMessage = $metacat->read($docid);
1301
    $doc = $httpMessage->content();
1302
    $xmldoc = $parser->parse_string($doc);
1303

    
1304
    #$tempfile = $xslConvDir.$docid;
1305
    #push (@fileArray, $tempfile);
1306

    
1307
    if ($xmldoc eq "") {
1308
        $error ="Error in parsing the eml document";
1309
        push(@errorMessages, $error);
1310
    } else {
1311
        $findType = $xmldoc->findnodes('//dataset/identifier');
1312
        if ($findType->size() > 0) {
1313
            # This is a eml beta6 document
1314
            # Read the documents mentioned in triples also
1315
        
1316
            $findType = $xmldoc->findnodes('//dataset/triple');
1317
            if ($findType->size() > 0) {
1318
                foreach $node ($findType->get_nodelist) {
1319
                    $pushDoc = findValue($node, 'subject');
1320
            
1321
                    # If the file is already in @fileArray then do not add it 
1322
                    $alreadyInArray = 0;
1323
                    foreach $element (@fileArray) {
1324
                        $tempfile = $tmpdir."/".$pushDoc;
1325
                        if ($element eq $pushDoc) {
1326
                            $alreadyInArray = 1;
1327
                        }
1328
                    }
1329
            
1330
                    if (!$alreadyInArray) {
1331
                        $tempfile = $tmpdir."/".$pushDoc;
1332
                        $response = "";
1333
                        $response = $metacat->read($pushDoc);    
1334
                        if (! $response) {
1335
                            # could not read
1336
                            #push(@errorMessages, $response);
1337
                            push(@errorMessages, $metacat->getMessage());
1338
                            push(@errorMessages, "Failed during reading.\n");
1339
                        } else {
1340
                            my $xdoc = $response->content();
1341
                            #$tempfile = $xslConvDir.$pushDoc;
1342
                            open (TFILE,">$tempfile") || 
1343
                                die ("Cant open xml file... $tempfile\n");
1344
                            print TFILE $xdoc;
1345
                            close(TFILE);
1346
                            push (@fileArray, $tempfile);
1347
                        }
1348
                    }
1349
                }
1350
            }
1351

    
1352
            # Read the main document. 
1353

    
1354
            $tempfile = $tmpdir."/".$docid; #= $xslConvDir.$docid;
1355
            open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1356
            print TFILE $doc;
1357
            close(TFILE);
1358
        
1359
            # Transforming beta6 to eml 2
1360
            my $xslt;
1361
            my $triplesheet;
1362
            my $results;
1363
            my $stylesheet;
1364
            my $resultsheet;
1365
        
1366
            $xslt = XML::LibXSLT->new();
1367
            #$tempfile = $xslConvDir."triple_info.xsl";
1368
            $tempfile = $tmpdir."/"."triple_info.xsl";
1369
    
1370
            $triplesheet = $xslt->parse_stylesheet_file($tempfile);
1371

    
1372
            #$results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1373
            $results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1374

    
1375
            #$tempfile = $xslConvDir."emlb6toeml2.xsl";
1376
            $tempfile = $tmpdir."/"."emlb6toeml2.xsl";
1377
            $stylesheet = $xslt->parse_stylesheet_file($tempfile);
1378
            $resultsheet = $stylesheet->transform($results);
1379
        
1380
            #$tempfile = "/usr/local/apache2/htdocs/xml/test.xml";;
1381
            #open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1382
            #print TFILE $stylesheet->output_string($resultsheet);
1383
            #close(TFILE);
1384

    
1385
            getFormValuesFromEml2($resultsheet);
1386
            
1387
            # Delete the files written earlier. 
1388
            unlink @fileArray;
1389

    
1390
        } else {
1391
            getFormValuesFromEml2($xmldoc);
1392
        }
1393
    }   
1394
    
1395
    if (scalar(@errorMessages)) {
1396
        # if any errors, print them in the response template 
1397
        $$templateVars{'status'} = 'failure';
1398
        $$templateVars{'errorMessages'} = \@errorMessages;
1399
        $error = 1;
1400
        $$templateVars{'function'} = "modification";
1401
        $$templateVars{'section'} = "Modification Status";
1402
        $template->process( $responseTemplate, $templateVars); 
1403
    } else {
1404
        $$templateVars{'form'} = 're_entry';
1405
        $template->process( $entryFormTemplate, $templateVars);
1406
    }
1407
}
1408

    
1409
################################################################################
1410
# 
1411
# Parse an EML 2.0.0 file and extract the metadata into perl variables for 
1412
# processing and returning to the template processor
1413
#
1414
################################################################################
1415
sub getFormValuesFromEml2 {
1416
    
1417
    my $doc = shift;
1418
    my $results;
1419
    my $error;
1420
    my $node;
1421
    my $tempResult;
1422
    my $tempNode;
1423
    my $aoCount = 1;
1424
    my $foundDSO;
1425

    
1426
    # set variable values
1427
    $$templateVars{'hasKeyword'} = $hasKeyword;
1428
    $$templateVars{'hasTemporal'} = $hasTemporal;
1429
    $$templateVars{'hasSpatial'} = $hasSpatial;
1430
    $$templateVars{'hasTaxonomic'} = $hasTaxonomic;
1431
    $$templateVars{'hasMethod'} = $hasMethod;
1432
    $$templateVars{'spatialRequired'} = $spatialRequired;
1433
    $$templateVars{'temporalRequired'} = $temporalRequired;
1434

    
1435
    # find out the tag <alternateIdentifier>. 
1436
    $results = $doc->findnodes('//dataset/alternateIdentifier');
1437
    if ($results->size() > 1) {
1438
        errMoreThanOne("alternateIdentifier");
1439
    } else {
1440
        foreach $node ($results->get_nodelist) {
1441
            $$templateVars{'identifier'} = findValue($node, '../alternateIdentifier');
1442
        }
1443
    }
1444

    
1445
    # find out the tag <title>. 
1446
    $results = $doc->findnodes('//dataset/title');
1447
    if ($results->size() > 1) {
1448
        errMoreThanOne("title");
1449
    } elsif ($results->size() < 1) {
1450
        $error ="Following tag not found: title. Please use Morpho to edit this document";
1451
        push(@errorMessages, $error."\n");
1452
        #if ($DEBUG == 1){ print $error;}
1453
    } else {
1454
        foreach $node ($results->get_nodelist) {
1455
            $$templateVars{'title'} = findValue($node, '../title');
1456
        }
1457
    }
1458

    
1459
    # find out the tag <creator>. 
1460
    $results = $doc->findnodes('//dataset/creator/individualName');
1461
    debug("Registry: Creators: ".$results->size());
1462
     foreach $node ($results->get_nodelist) {
1463
            dontOccur($node, "../positionName|../onlineURL|../userId", 
1464
              "positionName, onlineURL, userId");
1465
        
1466
            dontOccur($node, "./saluation", "saluation");                
1467
        
1468
            debug("Registry: Checking a creator in loop 1...");
1469
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1470
            if($tempResult->size > 0) {
1471
                if($foundDSO == 0) {
1472
                    $foundDSO = 1;
1473
     
1474
                    debug("Registry: Recording a creator in loop 1...");
1475
                    $$templateVars{'origNamefirst0'} = findValue($node, 'givenName');
1476
                    $$templateVars{'origNamelast0'} = findValue($node, 'surName');
1477
            
1478
                    my $tempResult2 = $node->findnodes('../address');
1479
                    if ($tempResult2->size > 1) {
1480
                        errMoreThanOne("address");
1481
                    } else {
1482
                        foreach my $tempNode2 ($tempResult2->get_nodelist) {
1483
                            $$templateVars{'origDelivery'} = findValue($tempNode2, 'deliveryPoint');
1484
                            $$templateVars{'origCity'} = findValue($tempNode2, 'city');
1485
                            $$templateVars{'origState'} = findValue($tempNode2, 'administrativeArea');
1486
                            $$templateVars{'origZIP'} = findValue($tempNode2, 'postalCode');
1487
                            $$templateVars{'origCountry'} = findValue($tempNode2, 'country');
1488
                        }
1489
                    }
1490
            
1491
                    my $tempResult3 = $node->findnodes('../phone');
1492
                    if ($tempResult3->size > 2) {
1493
                        errMoreThanN("phone");
1494
                    } else {
1495
                        foreach my $tempNode2 ($tempResult3->get_nodelist) {
1496
                            if ($tempNode2->hasAttributes()) {
1497
                                my @attlist = $tempNode2->attributes();
1498
                                if ($attlist[0]->value eq "Fax") {
1499
                                    $$templateVars{'origFAX'} = $tempNode2->textContent();
1500
                                } else {
1501
                                    $$templateVars{'origPhone'} = $tempNode2->textContent();
1502
                                }
1503
                            } else {
1504
                                $$templateVars{'origPhone'} = $tempNode2->textContent();
1505
                            }
1506
                        }
1507
                    }
1508
                    $$templateVars{'origEmail'} = findValue($node, '../electronicMailAddress');
1509
                    $$templateVars{'origNameOrg'} = findValue($node, '../organizationName');
1510
                } else {
1511
                    errMoreThanN("address, phone and electronicMailAddress");
1512
                }
1513
            }
1514
        }
1515
        foreach $node ($results->get_nodelist) {
1516
            debug("Registry: Checking a creator in loop 2...");
1517
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1518
            if ($tempResult->size == 0) {
1519
                if ($foundDSO == 0) {
1520
                    debug("Registry: Recording a creator in loop 2 block A...");
1521
                    $foundDSO = 1;
1522
                    $$templateVars{'origNamefirst0'} = findValue($node, 'givenName');
1523
                    $$templateVars{'origNamelast0'} = findValue($node, 'surName');
1524
                    $$templateVars{'origNameOrg'} = findValue($node, '../organizationName');
1525
                } else {
1526
                    debug("Registry: Recording a creator in loop 2 block B...");
1527
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($node, './givenName');
1528
                    $$templateVars{"origNamelast$aoCount"} =  findValue($node, './surName');
1529
                    $$templateVars{"origRole$aoCount"} = "Originator";
1530
                    $aoCount++;
1531
                }
1532
            }
1533
        }
1534

    
1535
    $results = $doc->findnodes('//dataset/creator/organizationName');
1536
    my $wgroups = $doc->findnodes("//dataset/creator/organizationName[contains(text(),'(NCEAS ')]");
1537
    debug("Registry: Number Org: ".$results->size());
1538
    debug("Registry:  Number WG: ".$wgroups->size());
1539
    if ($results->size() - $wgroups->size() > 3) {
1540
        errMoreThanN("creator/organizationName");    
1541
    } else {
1542
        foreach $node ($results->get_nodelist) {
1543
            my $tempValue = findValue($node,'../organizationName');
1544
            $tempResult = $node->findnodes('../individualName');
1545
            if ($tempResult->size == 0 && $tempValue ne $organization) {
1546
                $$templateVars{'site'} = $tempValue;
1547
            }
1548
        }
1549
        if ($FORM::cfg eq 'nceas') {
1550
            my @wg;
1551
            foreach $node ($results->get_nodelist) {
1552
                my $tempValue = findValue($node,'../organizationName');
1553
                $wg[scalar(@wg)] = $tempValue;
1554
            }
1555
            my $projects = getProjectList();
1556
            $$templateVars{'projects'} = $projects;
1557
            $$templateVars{'wg'} = \@wg;
1558
        }
1559
    }
1560

    
1561
    $results = $doc->findnodes('//dataset/metadataProvider');
1562
    foreach $node ($results->get_nodelist) {
1563
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1564
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in metadataProvider");
1565
        
1566
	    $tempResult = $node->findnodes('./individualName');
1567
            if ($tempResult->size > 1) {
1568
                errMoreThanOne("metadataProvider/indvidualName");
1569
            } else {
1570
                foreach $tempNode ($tempResult->get_nodelist) {
1571
                    if ($$templateVars{'providerGivenName'} ne "") {
1572
                        $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1573
                        $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1574
                        $$templateVars{"origRole$aoCount"} = "Metadata Provider";
1575
                        $aoCount++;
1576
                    } else {
1577
                        $$templateVars{'providerGivenName'} =  findValue($tempNode, './givenName');
1578
                        $$templateVars{'providerSurName'} =  findValue($tempNode, './surName');
1579
                    }
1580
                }
1581
            }
1582
        }
1583

    
1584
    $results = $doc->findnodes('//dataset/associatedParty');
1585
    foreach $node ($results->get_nodelist) {
1586
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1587
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in associatedParty");
1588
       
1589
            $tempResult = $node->findnodes('./individualName');
1590
            if ($tempResult->size > 1) {
1591
                errMoreThanOne("associatedParty/indvidualName");
1592
            } else {
1593
                foreach $tempNode ($tempResult->get_nodelist) {
1594
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1595
                    $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1596
                    $$templateVars{"origRole$aoCount"} = findValue($tempNode, '../role');
1597
                    $aoCount++;           
1598
                }
1599
            }
1600
     }
1601

    
1602
    $results = $doc->findnodes('//dataset/publisher');
1603
#    if ($results->size() > 10) {
1604
 #       errMoreThanN("publisher");
1605
 #   } else {
1606
        foreach $node ($results->get_nodelist) {
1607
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1608
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in associatedParty");
1609
       
1610
            $tempResult = $node->findnodes('./individualName');
1611
            if ($tempResult->size > 1) {
1612
                errMoreThanOne("publisher/indvidualName");
1613
            } else {
1614
                foreach $tempNode ($tempResult->get_nodelist) {
1615
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1616
                    $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1617
                    $$templateVars{"origRole$aoCount"} = "Publisher";
1618
                    $aoCount++;           
1619
                }
1620
            }
1621
        }
1622
  #  }
1623

    
1624
  #  if ($aoCount > 11) {
1625
  #      errMoreThanN("Additional Originators");
1626
 #   } 
1627

    
1628
    $$templateVars{'aoCount'} = $aoCount-1;
1629
    
1630
    dontOccur($doc, "./pubDate", "pubDate");
1631
    dontOccur($doc, "./language", "language");
1632
    dontOccur($doc, "./series", "series");
1633

    
1634
    $results = $doc->findnodes('//dataset/abstract');
1635
    if ($results->size() > 1) {
1636
        errMoreThanOne("abstract");
1637
    } else {
1638
        foreach my $node ($results->get_nodelist) {
1639
            dontOccur($node, "./section", "section");
1640
            $$templateVars{'abstract'} = findValueNoChild($node, "para");
1641
        }
1642
    }
1643

    
1644
    $results = $doc->findnodes('//dataset/keywordSet');
1645

    
1646
    my $count = 0;
1647
    foreach $node ($results->get_nodelist) {
1648
	$tempResult = $node->findnodes('./keyword');
1649
	if ($tempResult->size() > 1) {
1650
	    errMoreThanOne("keyword");
1651
	} else {
1652
	    $count++;
1653
	    foreach $tempNode ($tempResult->get_nodelist) {
1654
		$$templateVars{"keyword$count"} = $tempNode->textContent();
1655
		if ($tempNode->hasAttributes()) {
1656
		    my @attlist = $tempNode->attributes();
1657
		    $$templateVars{"kwType$count"} = $attlist[0]->value;
1658
		}  
1659
	    }
1660
	}
1661
	$$templateVars{"kwTh$count"} = findValue($node, "keywordThesaurus");
1662
    }
1663
    $$templateVars{'keyCount'} = $count;
1664
    if($count > 0 ){
1665
       $$templateVars{'hasKeyword'} = "true";
1666
    }
1667

    
1668
    $results = $doc->findnodes('//dataset/additionalInfo');
1669
    if ($results->size() > 1) {
1670
        errMoreThanOne("additionalInfo");
1671
    } else {
1672
        foreach $node ($results->get_nodelist) {
1673
            dontOccur($node, "./section", "section");
1674
            $$templateVars{'addComments'} = findValueNoChild($node, "para");
1675
        }
1676
    }
1677

    
1678
    $$templateVars{'useConstraints'} = "";
1679
    $results = $doc->findnodes('//dataset/intellectualRights');
1680
    if ($results->size() > 1) {
1681
        errMoreThanOne("intellectualRights");
1682
    } else {
1683
        foreach $node ($results->get_nodelist) {
1684
            dontOccur($node, "./section", "section in intellectualRights");
1685

    
1686
            $tempResult = $node->findnodes("para");
1687
            if ($tempResult->size > 2) {
1688
                   errMoreThanN("para");
1689
            } else {
1690
                foreach $tempNode ($tempResult->get_nodelist) {
1691
                    my $childNodes = $tempNode->childNodes;
1692
                    if ($childNodes->size() > 1) {
1693
                        $error ="The tag para in intellectualRights has children which cannot be shown using the form. Please use Morpho to edit this document";    
1694
                        push(@errorMessages, $error);
1695
                        #if ($DEBUG == 1){ print $error."\n";}
1696
                    } else {
1697
                        #print $tempNode->nodeName().":".$tempNode->textContent();
1698
                        #print "\n";
1699
                        if ($$templateVars{'useConstraints'} eq "") {
1700
                            $$templateVars{'useConstraints'} = $tempNode->textContent();
1701
                        } else {
1702
                            $$templateVars{'useConstraintsOther'} = $tempNode->textContent();
1703
                        }
1704
                    }
1705
                }
1706
            }
1707
        }
1708
    }
1709

    
1710
    $results = $doc->findnodes('//dataset/distribution/online');
1711
    if ($results->size() > 1) {
1712
        errMoreThanOne("distribution/online");
1713
    } else {
1714
        foreach my $tempNode ($results->get_nodelist){
1715
            $$templateVars{'url'} = findValue($tempNode, "url");
1716
            dontOccur($tempNode, "./connection", "/distribution/online/connection");
1717
            dontOccur($tempNode, "./connectionDefinition", "/distribution/online/connectionDefinition");
1718
        }
1719
    }
1720

    
1721
    $results = $doc->findnodes('//dataset/distribution/offline');
1722
    if ($results->size() > 1) {
1723
        errMoreThanOne("distribution/online");
1724
    } else {
1725
        foreach my $tempNode ($results->get_nodelist) {
1726
            $$templateVars{'dataMedium'} = findValue($tempNode, "mediumName");
1727
            dontOccur($tempNode, "./mediumDensity", "/distribution/offline/mediumDensity");
1728
            dontOccur($tempNode, "./mediumDensityUnits", "/distribution/offline/mediumDensityUnits");
1729
            dontOccur($tempNode, "./mediumVolume", "/distribution/offline/mediumVolume");
1730
            dontOccur($tempNode, "./mediumFormat", "/distribution/offline/mediumFormat");
1731
            dontOccur($tempNode, "./mediumNote", "/distribution/offline/mediumNote");
1732
        }
1733
    }
1734

    
1735
    dontOccur($doc, "./inline", "//dataset/distribution/inline");
1736

    
1737
    $results = $doc->findnodes('//dataset/coverage');
1738
    if ($results->size() > 1) {
1739
        errMoreThanOne("coverage");
1740
    } else {
1741
        foreach $node ($results->get_nodelist) {
1742
            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");
1743

    
1744
            $tempResult = $node->findnodes('./temporalCoverage');
1745
            if ($tempResult->size > 1) {
1746
                   errMoreThanOne("temporalCoverage");
1747
            } else {
1748
                foreach $tempNode ($tempResult->get_nodelist) {
1749
                    my $x;
1750
                    my $y;
1751
                    my $z;
1752
                    my $tempdate = findValue($tempNode, "rangeOfDates/beginDate/calendarDate");
1753
                    ($x, $y, $z) = split("-", $tempdate); 
1754
                    $$templateVars{'beginningYear'} = $x;
1755
                    $$templateVars{'beginningMonth'} = $y;
1756
                    $$templateVars{'beginningDay'} = $z;
1757
    
1758
                    $tempdate = findValue($tempNode, "rangeOfDates/endDate/calendarDate");
1759
                    ($x, $y, $z) = split("-", $tempdate);
1760
                    $$templateVars{'endingYear'} = $x;
1761
                    $$templateVars{'endingMonth'} = $y;
1762
                    $$templateVars{'endingDay'} = $z;
1763

    
1764
                    $tempdate = "";
1765
                    $tempdate = findValue($tempNode, "singleDateTime/calendarDate");
1766
                    if($tempdate ne ""){
1767
                        ($x, $y, $z) = split("-", $tempdate);
1768
                        $$templateVars{'beginningYear'} = $x;
1769
                        $$templateVars{'beginningMonth'} = $y;
1770
                        $$templateVars{'beginningDay'} = $z;
1771
                    }  
1772
		    
1773
		    $$templateVars{'hasTemporal'} = "true";
1774
                }
1775
            }
1776

    
1777
            $tempResult = $node->findnodes('./geographicCoverage');
1778
            if ($tempResult->size > 1) {
1779
                errMoreThanOne("geographicCoverage");
1780
            } else {
1781
                foreach $tempNode ($tempResult->get_nodelist) {
1782
                    my $geogdesc = findValue($tempNode, "geographicDescription");
1783
                    debug("Registry: geogdesc from xml is: $geogdesc");
1784
                    $$templateVars{'geogdesc'} = $geogdesc;
1785
                    my $coord = findValue($tempNode, "boundingCoordinates/westBoundingCoordinate");
1786
                    if ($coord > 0) {
1787
                        #print "+";
1788
                        $$templateVars{'hemisphLong1'} = "E";
1789
                    } else {
1790
                        #print "-";
1791
                        eval($coord = $coord * -1);
1792
                        $$templateVars{'hemisphLong1'} = "W";
1793
                    }
1794
                    eval($$templateVars{'longDeg1'} = int($coord));
1795
                    eval($coord = ($coord - int($coord))*60);
1796
                    eval($$templateVars{'longMin1'} = int($coord));
1797
                    eval($coord = ($coord - int($coord))*60);
1798
                    eval($$templateVars{'longSec1'} = int($coord));
1799
                    
1800
                    $coord = findValue($tempNode, "boundingCoordinates/southBoundingCoordinate");
1801
                    if ($coord > 0) {
1802
                        #print "+";
1803
                        $$templateVars{'hemisphLat2'} = "N";
1804
                    } else {
1805
                        #print "-";
1806
                        eval($coord = $coord * -1);
1807
                        $$templateVars{'hemisphLat2'} = "S";
1808
                    }
1809
                    eval($$templateVars{'latDeg2'} = int($coord));
1810
                    eval($coord = ($coord - int($coord))*60);
1811
                    eval($$templateVars{'latMin2'} = int($coord));
1812
                    eval($coord = ($coord - int($coord))*60);
1813
                    eval($$templateVars{'latSec2'} = int($coord));
1814
        
1815
                    $coord = findValue($tempNode, "boundingCoordinates/northBoundingCoordinate");
1816
                    if ($coord > 0) {
1817
                        #print "+";
1818
                        $$templateVars{'hemisphLat1'} = "N";
1819
                    } else {
1820
                        #print "-";
1821
                        eval($coord = $coord * -1);
1822
                        $$templateVars{'hemisphLat1'} = "S";
1823
                    }
1824
                    eval($$templateVars{'latDeg1'} = int($coord));
1825
                    eval($coord = ($coord - int($coord))*60);
1826
                    eval($$templateVars{'latMin1'} = int($coord));
1827
                    eval($coord = ($coord - int($coord))*60);
1828
                    eval($$templateVars{'latSec1'} = int($coord));
1829
        
1830
                    $coord = findValue($tempNode, "boundingCoordinates/eastBoundingCoordinate");
1831
                    if ($coord > 0) {
1832
                        #print "+";
1833
                        $$templateVars{'hemisphLong2'} = "E";
1834
                    } else {
1835
                        #print "-";
1836
                        eval($coord = $coord * -1);
1837
                        $$templateVars{'hemisphLong2'} = "W";
1838
                    }
1839
                    eval($$templateVars{'longDeg2'} = int($coord));
1840
                    eval($coord = ($coord - int($coord))*60);
1841
                    eval($$templateVars{'longMin2'} = int($coord));
1842
                    eval($coord = ($coord - int($coord))*60);
1843
                    eval($$templateVars{'longSec2'} = int($coord));
1844

    
1845
		    $$templateVars{'hasSpatial'} = "true";
1846
                }
1847
            }
1848

    
1849
            $tempResult = $node->findnodes('./taxonomicCoverage/taxonomicClassification');
1850
            my $taxonIndex = 0;
1851
            foreach $tempNode ($tempResult->get_nodelist) {
1852
                $taxonIndex++;
1853
                my $taxonRankName = findValue($tempNode, "taxonRankName");
1854
                my $taxonRankValue = findValue($tempNode, "taxonRankValue");
1855
                $$templateVars{"taxonRankName".$taxonIndex} = $taxonRankName;
1856
                $$templateVars{"taxonRankValue".$taxonIndex} = $taxonRankValue;
1857
		
1858
		$$templateVars{'hasTaxonomic'} = "true";
1859
            }
1860
            $$templateVars{'taxaCount'} = $taxonIndex;
1861
            my $taxaAuth = findValue($node, "./taxonomicCoverage/generalTaxonomicCoverage");
1862
            $$templateVars{'taxaAuth'} = $taxaAuth;
1863
        }
1864
    }
1865
    dontOccur($doc, "./purpose", "purpose");
1866
    dontOccur($doc, "./maintenance", "maintnance");
1867

    
1868
    $results = $doc->findnodes('//dataset/contact/individualName');
1869
    if ($results->size() > 1) {
1870
        errMoreThanOne("contact/individualName");
1871
    } else {
1872
        foreach $node ($results->get_nodelist) {
1873
            dontOccur($node, "../positionName|../onlineURL|../userId", 
1874
              "positionName, onlineURL, userId in contact tag");
1875
            dontOccur($node, "./saluation", "saluation in contact tag");                
1876
        
1877
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1878
            if ($tempResult->size > 0) {
1879
                $$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
1880
                $$templateVars{'origNamelastContact'} = findValue($node, 'surName');
1881
    
1882
                my $tempResult2 = $node->findnodes('../address');
1883
                if ($tempResult2->size > 1) {
1884
                    errMoreThanOne("address");
1885
                } else {
1886
                    foreach my $tempNode2 ($tempResult2->get_nodelist) {
1887
                        $$templateVars{'origDeliveryContact'} = findValue($tempNode2, 'deliveryPoint');
1888
                        $$templateVars{'origCityContact'} = findValue($tempNode2, 'city');
1889
                        $$templateVars{'origStateContact'} = findValue($tempNode2, 'administrativeArea');
1890
                        $$templateVars{'origZIPContact'} = findValue($tempNode2, 'postalCode');
1891
                        $$templateVars{'origCountryContact'} = findValue($tempNode2, 'country');
1892
                    }
1893
                }
1894
            
1895
                my $tempResult3 = $node->findnodes('../phone');
1896
                if ($tempResult3->size > 2) {
1897
                    errMoreThanN("phone");
1898
                } else {
1899
                    foreach my $tempNode2 ($tempResult3->get_nodelist) {
1900
                        if ($tempNode2->hasAttributes()) {
1901
                            my @attlist = $tempNode2->attributes();
1902
                            if ($attlist[0]->value eq "Fax") {
1903
                                $$templateVars{'origFAXContact'} = $tempNode2->textContent();
1904
                            } else {
1905
                                $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
1906
                            }
1907
                        } else {
1908
                            $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
1909
                        }
1910
                    }
1911
                }
1912
                $$templateVars{'origEmailContact'} = findValue($node, '../electronicMailAddress');
1913
                $$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
1914
            } else {
1915
                $$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
1916
                $$templateVars{'origNamelastContact'} = findValue($node, 'surName');
1917
                $$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
1918
            }
1919
        }
1920
    }
1921
    
1922
    $results = $doc->findnodes(
1923
            '//dataset/methods/methodStep/description/section');
1924
    debug("Registry: Number methods: ".$results->size());
1925
    if ($results->size() > 1) {
1926
        errMoreThanN("methods/methodStep/description/section");    
1927
    } else {
1928

    
1929
        my @methodPara;
1930
        foreach $node ($results->get_nodelist) {
1931
            my @children = $node->childNodes;
1932
            for (my $i = 0; $i < scalar(@children); $i++) {
1933
                debug("Registry: Method child loop ($i)");
1934
                my $child = $children[$i];
1935
                if ($child->nodeName eq 'title') {
1936
                    my $title = $child->textContent();
1937
                    debug("Registry: Method title ($title)");
1938
                    $$templateVars{'methodTitle'} = $title;
1939
                } elsif ($child->nodeName eq 'para') {
1940
                    my $para = $child->textContent();
1941
                    debug("Registry: Method para ($para)");
1942
                    $methodPara[scalar(@methodPara)] = $para;
1943
                }
1944
            }
1945
	    $$templateVars{'hasMethod'} = "true";
1946
        }
1947
        if (scalar(@methodPara) > 0) {
1948
            $$templateVars{'methodPara'} = \@methodPara;
1949
        }
1950
    }
1951

    
1952
    $results = $doc->findnodes(
1953
            '//dataset/methods/sampling/studyExtent/description/para');
1954
    if ($results->size() > 1) {
1955
        errMoreThanN("methods/sampling/studyExtent/description/para");    
1956
    } else {
1957
        foreach $node ($results->get_nodelist) {
1958
            my $studyExtentDescription = $node->textContent();
1959
            $$templateVars{'studyExtentDescription'} = $studyExtentDescription;
1960

    
1961
	    $$templateVars{'hasMethod'} = "true";
1962
        }
1963
    }
1964

    
1965
    $results = $doc->findnodes(
1966
            '//dataset/methods/sampling/samplingDescription/para');
1967
    if ($results->size() > 1) {
1968
        errMoreThanN("methods/sampling/samplingDescription/para");    
1969
    } else {
1970
        foreach $node ($results->get_nodelist) {
1971
            my $samplingDescription = $node->textContent();
1972
            $$templateVars{'samplingDescription'} = $samplingDescription;
1973

    
1974
	    $$templateVars{'hasMethod'} = "true";
1975
        }
1976
    }
1977

    
1978
    dontOccur($doc, "//methodStep/citation", "methodStep/citation");
1979
    dontOccur($doc, "//methodStep/protocol", "methodStep/protocol");
1980
    dontOccur($doc, "//methodStep/instrumentation", "methodStep/instrumentation");
1981
    dontOccur($doc, "//methodStep/software", "methodStep/software");
1982
    dontOccur($doc, "//methodStep/subStep", "methodStep/subStep");
1983
    dontOccur($doc, "//methodStep/dataSource", "methodStep/dataSource");
1984
    dontOccur($doc, "//methods/qualityControl", "methods/qualityControl");
1985

    
1986
    dontOccur($doc, "//methods/sampling/spatialSamplingUnits", "methods/sampling/spatialSamplingUnits");
1987
    dontOccur($doc, "//methods/sampling/citation", "methods/sampling/citation");
1988
    dontOccur($doc, "./pubPlace", "pubPlace");
1989
    dontOccur($doc, "./project", "project");
1990
    
1991
    dontOccur($doc, "./dataTable", "dataTable");
1992
    dontOccur($doc, "./spatialRaster", "spatialRaster");
1993
    dontOccur($doc, "./spatialVector", "spatialVector");
1994
    dontOccur($doc, "./storedProcedure", "storedProcedure");
1995
    dontOccur($doc, "./view", "view");
1996
    dontOccur($doc, "./otherEntity", "otherEntity");
1997
    dontOccur($doc, "./references", "references");
1998
    
1999
    dontOccur($doc, "//citation", "citation");
2000
    dontOccur($doc, "//software", "software");
2001
    dontOccur($doc, "//protocol", "protocol");
2002
    dontOccur($doc, "//additionalMetadata", "additionalMetadata");    
2003
}
2004

    
2005
################################################################################
2006
# 
2007
# Delete the eml file that has been requested for deletion. 
2008
#
2009
################################################################################
2010
sub deleteData {
2011
    my $deleteAll = shift;
2012
    
2013
    # create metacat instance
2014
    my $metacat;
2015
    my $docid = $FORM::docid;
2016
    
2017
    $metacat = Metacat->new();
2018
    if ($metacat) {
2019
        $metacat->set_options( metacatUrl => $metacatUrl );
2020
    } else {
2021
        #die "failed during metacat creation\n";
2022
        push(@errorMessages, "Failed during metacat creation.");
2023
    }
2024

    
2025
    # Login to metacat
2026
    my $userDN = $FORM::username;
2027
    my $userOrg = $FORM::organization;
2028
    my $userPass = $FORM::password;
2029
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
2030
    
2031
    my $errorMessage = "";
2032
    my $response = $metacat->login($dname, $userPass);
2033

    
2034
    if (! $response) {
2035
    # Could not login
2036
        push(@errorMessages, $metacat->getMessage());
2037
        push(@errorMessages, "Failed during login.\n");
2038

    
2039
    } else {
2040
    #Able to login - try to delete the file    
2041

    
2042
    my $parser;
2043
    my @fileArray;
2044
    my $httpMessage;
2045
    my $xmldoc;
2046
    my $doc;
2047
    my $pushDoc;
2048
    my $alreadyInArray;
2049
    my $findType;
2050
        my $node;
2051
    my $response; 
2052
    my $element;
2053

    
2054
    push (@fileArray, $docid);
2055
    $parser = XML::LibXML->new();
2056

    
2057
        $httpMessage = $metacat->read($docid);
2058
    $doc = $httpMessage->content();    
2059
    $xmldoc = $parser->parse_string($doc);
2060

    
2061
    if ($xmldoc eq "") {
2062
        $error ="Error in parsing the eml document";
2063
        push(@errorMessages, $error);
2064
    } else {
2065

    
2066
        $findType = $xmldoc->findnodes('//dataset/identifier');
2067
        if($findType->size() > 0){
2068
        # This is a eml beta6 document
2069
        # Delete the documents mentioned in triples also
2070
        
2071
        $findType = $xmldoc->findnodes('//dataset/triple');
2072
        if($findType->size() > 0){
2073
            foreach $node ($findType->get_nodelist){
2074
            $pushDoc = findValue($node, 'subject');
2075
            
2076
            # If the file is already in the @fileArray then do not add it 
2077
            $alreadyInArray = 0;
2078
            foreach $element (@fileArray){
2079
                if($element eq $pushDoc){
2080
                $alreadyInArray = 1;
2081
                }
2082
            }
2083
            
2084
            if(!$alreadyInArray){
2085
                # If not already in array then delete the file. 
2086
                push (@fileArray, $pushDoc);
2087
                $response = $metacat->delete($pushDoc);
2088
                
2089
                if (! $response) {
2090
                # Could not delete
2091
                #push(@errorMessages, $response);
2092
                push(@errorMessages, $metacat->getMessage());
2093
                push(@errorMessages, "Failed during deleting $pushDoc. Please check if you are authorized to delete this document.\n");
2094
                }
2095
            }
2096
            }
2097
        }
2098
        }
2099
    }
2100
    
2101
    # Delete the main document. 
2102
    if($deleteAll){
2103
        $response = $metacat->delete($docid);  
2104
        if (! $response) {
2105
        # Could not delete
2106
        #push(@errorMessages, $response);
2107
        push(@errorMessages, $metacat->getMessage());
2108
        push(@errorMessages, "Failed during deleting $docid. Please check if you are authorized to delete this document.\n");
2109
        }
2110
    }
2111
    }
2112
    
2113
    if (scalar(@errorMessages)) {
2114
    # If any errors, print them in the response template 
2115
    $$templateVars{'status'} = 'failure';
2116
    $$templateVars{'errorMessages'} = \@errorMessages;
2117
    $error = 1;
2118
    }
2119
    
2120
    # Process the response template
2121
    if($deleteAll){
2122

    
2123
    $$templateVars{'function'} = "deleted";
2124
    $$templateVars{'section'} = "Deletion Status";
2125
    $template->process( $responseTemplate, $templateVars);
2126
    }
2127
}
2128

    
2129

    
2130
################################################################################
2131
# 
2132
# Do data validation and send the data to confirm data template.
2133
#
2134
################################################################################
2135
sub toConfirmData{
2136
    # Check if any invalid parameters
2137
 
2138
    my $invalidParams;
2139
    if (! $error) {
2140
    $invalidParams = validateParameters(0);
2141
    if (scalar(@$invalidParams)) {
2142
        $$templateVars{'status'} = 'failure';
2143
        $$templateVars{'invalidParams'} = $invalidParams;
2144
        $error = 1;
2145
    }
2146
    }
2147

    
2148

    
2149
    $$templateVars{'providerGivenName'} = normalizeCD($FORM::providerGivenName);
2150
    $$templateVars{'providerSurName'} = normalizeCD($FORM::providerSurName);
2151
    if($FORM::site eq "Select your station here."){
2152
        $$templateVars{'site'} = "";
2153
    }else{
2154
        $$templateVars{'site'} = $FORM::site;
2155
    }
2156
    if($FORM::cfg eq "nceas"){
2157
        $$templateVars{'wg'} = \@FORM::wg;
2158
    }
2159
    $$templateVars{'identifier'} = normalizeCD($FORM::identifier);
2160
    $$templateVars{'title'} = normalizeCD($FORM::title);
2161
    $$templateVars{'origNamefirst0'} = normalizeCD($FORM::origNamefirst0);
2162
    $$templateVars{'origNamelast0'} = normalizeCD($FORM::origNamelast0);
2163
    $$templateVars{'origNameOrg'} = normalizeCD($FORM::origNameOrg);
2164
    # $$templateVars{'origRole0'} = $FORM::origRole0;
2165
    $$templateVars{'origDelivery'} = normalizeCD($FORM::origDelivery);
2166
    $$templateVars{'origCity'} = normalizeCD($FORM::origCity);
2167
    if($FORM::origState eq "Select State Here."){
2168
        $$templateVars{'origState'} = "";
2169
    }else{
2170
        $$templateVars{'origState'} = $FORM::origState;
2171
    }
2172
    $$templateVars{'origStateOther'} = normalizeCD($FORM::origStateOther);
2173
    $$templateVars{'origZIP'} = normalizeCD($FORM::origZIP);
2174
    $$templateVars{'origCountry'} = normalizeCD($FORM::origCountry);
2175
    $$templateVars{'origPhone'} = normalizeCD($FORM::origPhone);
2176
    $$templateVars{'origFAX'} = normalizeCD($FORM::origFAX);
2177
    $$templateVars{'origEmail'} = normalizeCD($FORM::origEmail);
2178
    $$templateVars{'useOrigAddress'} = normalizeCD($FORM::useOrigAddress);
2179
    if($FORM::useOrigAddress eq "on"){
2180
        $$templateVars{'origNamefirstContact'} = normalizeCD($FORM::origNamefirst0);
2181
        $$templateVars{'origNamelastContact'} = normalizeCD($FORM::origNamelast0);
2182
        $$templateVars{'origNameOrgContact'} = normalizeCD($FORM::origNameOrg);
2183
        $$templateVars{'origDeliveryContact'} = normalizeCD($FORM::origDelivery); 
2184
        $$templateVars{'origCityContact'} = normalizeCD($FORM::origCity);
2185
        if($FORM::origState eq "Select State Here."){
2186
        $$templateVars{'origStateContact'} = "";
2187
        }else{
2188
        $$templateVars{'origStateContact'} = $FORM::origState;
2189
        }
2190
        $$templateVars{'origStateOtherContact'} = normalizeCD($FORM::origStateOther);
2191
        $$templateVars{'origZIPContact'} = normalizeCD($FORM::origZIP);
2192
        $$templateVars{'origCountryContact'} = normalizeCD($FORM::origCountry);
2193
        $$templateVars{'origPhoneContact'} = normalizeCD($FORM::origPhone);
2194
        $$templateVars{'origFAXContact'} = normalizeCD($FORM::origFAX);
2195
        $$templateVars{'origEmailContact'} = normalizeCD($FORM::origEmail);
2196
    }else{
2197
        $$templateVars{'origNamefirstContact'} = normalizeCD($FORM::origNamefirstContact);
2198
        $$templateVars{'origNamelastContact'} = normalizeCD($FORM::origNamelastContact);
2199
        $$templateVars{'origNameOrgContact'} = normalizeCD($FORM::origNameOrgContact);
2200
        $$templateVars{'origDeliveryContact'} = normalizeCD($FORM::origDeliveryContact); 
2201
        $$templateVars{'origCityContact'} = normalizeCD($FORM::origCityContact);
2202
        if($FORM::origStateContact eq "Select State Here."){
2203
        $$templateVars{'origStateContact'} = "";
2204
        }else{
2205
        $$templateVars{'origStateContact'} = $FORM::origStateContact;
2206
        }
2207
        $$templateVars{'origStateOtherContact'} = normalizeCD($FORM::origStateOtherContact);
2208
        $$templateVars{'origZIPContact'} = normalizeCD($FORM::origZIPContact);
2209
        $$templateVars{'origCountryContact'} = normalizeCD($FORM::origCountryContact);
2210
        $$templateVars{'origPhoneContact'} = normalizeCD($FORM::origPhoneContact);
2211
        $$templateVars{'origFAXContact'} = normalizeCD($FORM::origFAXContact);
2212
        $$templateVars{'origEmailContact'} = normalizeCD($FORM::origEmailContact);    
2213
    }
2214

    
2215
    $$templateVars{'aoCount'} = $FORM::aoCount;
2216
    foreach my $origName (param()) {
2217
	if ($origName =~ /origNamefirst/) {
2218
	    my $origNameIndex = $origName;
2219
	    $origNameIndex =~ s/origNamefirst//; # get the index of the parameter 0, ..., 10
2220
	    my $origNamelast = "origNamelast".$origNameIndex;
2221
	    my $origRole = "origRole".$origNameIndex;
2222
	    if ( $origNameIndex =~ /[0-9]/  && $origNameIndex > 0){
2223
		if (hasContent(param($origName)) && hasContent(param($origNamelast)) && hasContent(param($origRole))) {
2224
		    debug("Registry processing keyword: $origName = ".param($origName)." $origNamelast = ".param($origNamelast)." $origRole = ".param($origRole));
2225
		    $$templateVars{$origName} = normalizeCD(param($origName));
2226
		    $$templateVars{$origNamelast} = normalizeCD(param($origNamelast));
2227
		    $$templateVars{$origRole} = normalizeCD(param($origRole));
2228
		}
2229
	    }
2230
	}
2231
    }
2232

    
2233
    $$templateVars{'abstract'} = normalizeCD($FORM::abstract);
2234
    $$templateVars{'keyCount'} = $FORM::keyCount;
2235
    foreach my $kyd (param()) {
2236
	if ($kyd =~ /keyword/) {
2237
	    my $keyIndex = $kyd;
2238
	    $keyIndex =~ s/keyword//; # get the index of the parameter 0, ..., 10
2239
	    my $keyType = "kwType".$keyIndex;
2240
	    my $keyTh = "kwTh".$keyIndex;
2241
	    if ( $keyIndex =~ /[0-9]/ ){
2242
		if (hasContent(param($kyd)) && hasContent(param($keyType)) && hasContent(param($keyTh))) {
2243
		    debug("Registry processing keyword: $kyd = ".param($kyd)." $keyType = ".param($keyType)." $keyTh = ".param($keyTh));
2244
		    $$templateVars{$kyd} = normalizeCD(param($kyd));
2245
		    $$templateVars{$keyType} = param($keyType);
2246
		    $$templateVars{$keyTh} = param($keyTh);
2247
		}
2248
	    }
2249
	}
2250
    }
2251
    $$templateVars{'addComments'} = normalizeCD($FORM::addComments);
2252
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2253
    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2254
    $$templateVars{'url'} = $FORM::url;
2255
    if($FORM::dataMedium eq "Select type of medium here."){
2256
        $$templateVars{'dataMedium'} = "";
2257
    }else{
2258
        $$templateVars{'dataMedium'} = $FORM::dataMedium;
2259
    }    
2260
    $$templateVars{'dataMediumOther'} = normalizeCD($FORM::dataMediumOther);
2261
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2262
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2263
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2264
    $$templateVars{'endingYear'} = $FORM::endingYear;
2265
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2266
    $$templateVars{'endingDay'} = $FORM::endingDay;
2267
    $$templateVars{'geogdesc'} = normalizeCD($FORM::geogdesc);
2268
    $$templateVars{'useSiteCoord'} = $FORM::useSiteCoord;
2269
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2270
    $$templateVars{'latMin1'} = $FORM::latMin1;
2271
    $$templateVars{'latSec1'} = $FORM::latSec1;
2272
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2273
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2274
    $$templateVars{'longMin1'} = $FORM::longMin1;
2275
    $$templateVars{'longSec1'} = $FORM::longSec1;
2276
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2277
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2278
    $$templateVars{'latMin2'} = $FORM::latMin2;
2279
    $$templateVars{'latSec2'} = $FORM::latSec2;
2280
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2281
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2282
    $$templateVars{'longMin2'} = $FORM::longMin2;
2283
    $$templateVars{'longSec2'} = $FORM::longSec2;
2284
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2285

    
2286
    $$templateVars{'taxaCount'} = $FORM::taxaCount;
2287
    foreach my $trn (param()) {
2288
        if ($trn =~ /taxonRankName/) {
2289
            my $taxIndex = $trn;
2290
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
2291
            my $trv = "taxonRankValue".$taxIndex;
2292
            if ( $taxIndex =~ /[0-9]/ ){
2293
                if (hasContent(param($trn)) && hasContent(param($trv))) {
2294
                    debug("Registry processing taxon: $trn = ".param($trn)." $trv = ".param($trv));
2295
                    $$templateVars{$trn} = normalizeCD(param($trn));
2296
                    $$templateVars{$trv} = normalizeCD(param($trv));
2297
                }
2298
            }
2299
        }
2300
    }
2301
    $$templateVars{'taxaAuth'} = normalizeCD($FORM::taxaAuth);
2302

    
2303
    $$templateVars{'methodTitle'} = normalizeCD($FORM::methodTitle);
2304

    
2305
    my @tempMethodPara;
2306
    for (my $i = 0; $i < scalar(@FORM::methodPara); $i++) {
2307
	$tempMethodPara[$i] = normalizeCD($FORM::methodPara[$i]);
2308
    }
2309
    $$templateVars{'methodPara'} = \@tempMethodPara;
2310
    $$templateVars{'studyExtentDescription'} = normalizeCD($FORM::studyExtentDescription);
2311
    $$templateVars{'samplingDescription'} = normalizeCD($FORM::samplingDescription);
2312
    $$templateVars{'origStateContact'} = $FORM::origState;
2313

    
2314
    $$templateVars{'hasKeyword'} = $FORM::hasKeyword;
2315
    $$templateVars{'hasTemporal'} = $FORM::hasTemporal;
2316
    $$templateVars{'hasSpatial'} = $FORM::hasSpatial;
2317
    $$templateVars{'hasTaxonomic'} = $FORM::hasTaxonomic;
2318
    $$templateVars{'hasMethod'} = $FORM::hasMethod;
2319
    $$templateVars{'spatialRequired'} = $FORM::spatialRequired;
2320
    $$templateVars{'temporalRequired'} = $FORM::temporalRequired;
2321

    
2322
    $$templateVars{'docid'} = $FORM::docid;
2323

    
2324
    if (! $error) {
2325
	# If no errors, then print out data in confirm Data template
2326

    
2327
	$$templateVars{'section'} = "Confirm Data";
2328
	$template->process( $confirmDataTemplate, $templateVars);
2329

    
2330
    } else{    
2331
    # Errors from validation function. print the errors out using the response template
2332
    if (scalar(@errorMessages)) {
2333
        $$templateVars{'status'} = 'failure';
2334
        $$templateVars{'errorMessages'} = \@errorMessages;
2335
        $error = 1;
2336
    }
2337
        # Create our HTML response and send it back
2338
    $$templateVars{'function'} = "submitted";
2339
    $$templateVars{'section'} = "Submission Status";
2340
    $template->process( $responseTemplate, $templateVars);
2341
    }
2342
}
2343

    
2344

    
2345
################################################################################
2346
# 
2347
# From confirm Data template - user wants to make some changes.
2348
#
2349
################################################################################
2350
sub confirmDataToReEntryData{
2351
    my @sortedSites;
2352
    foreach my $site (sort @sitelist) {
2353
        push(@sortedSites, $site);
2354
    }
2355

    
2356
    $$templateVars{'siteList'} = \@sortedSites;
2357
    $$templateVars{'section'} = "Re-Entry Form";
2358
    copyFormToTemplateVars();
2359
    $$templateVars{'docid'} = $FORM::docid;
2360

    
2361
    $$templateVars{'form'} = 're_entry';
2362
    $template->process( $entryFormTemplate, $templateVars);
2363
}
2364

    
2365

    
2366
################################################################################
2367
# 
2368
# Copy form data to templateVars.....
2369
#
2370
################################################################################
2371
sub copyFormToTemplateVars{
2372
    $$templateVars{'providerGivenName'} = $FORM::providerGivenName;
2373
    $$templateVars{'providerSurName'} = $FORM::providerSurName;
2374
    $$templateVars{'site'} = $FORM::site;
2375
    if ($FORM::cfg eq "nceas") {
2376
        my $projects = getProjectList();
2377
        $$templateVars{'projects'} = $projects;
2378
        $$templateVars{'wg'} = \@FORM::wg;
2379
    }
2380
    $$templateVars{'identifier'} = $FORM::identifier;
2381
    $$templateVars{'title'} = $FORM::title;
2382
    $$templateVars{'origNamefirst0'} = $FORM::origNamefirst0;
2383
    $$templateVars{'origNamelast0'} = $FORM::origNamelast0;
2384
    $$templateVars{'origNameOrg'} = $FORM::origNameOrg;
2385
 #   $$templateVars{'origRole0'} = $FORM::origRole0;
2386
    $$templateVars{'origDelivery'} = $FORM::origDelivery;
2387
    $$templateVars{'origCity'} = $FORM::origCity;
2388
    $$templateVars{'origState'} = $FORM::origState;
2389
    $$templateVars{'origStateOther'} = $FORM::origStateOther;
2390
    $$templateVars{'origZIP'} = $FORM::origZIP;
2391
    $$templateVars{'origCountry'} = $FORM::origCountry;
2392
    $$templateVars{'origPhone'} = $FORM::origPhone;
2393
    $$templateVars{'origFAX'} = $FORM::origFAX;
2394
    $$templateVars{'origEmail'} = $FORM::origEmail;
2395
    if ($FORM::useSiteCoord ne "") {
2396
        $$templateVars{'useOrigAddress'} = "CHECKED";
2397
    }else{
2398
        $$templateVars{'useOrigAddress'} = $FORM::useOrigAddress;
2399
    }
2400
    $$templateVars{'origNamefirstContact'} = $FORM::origNamefirstContact;
2401
    $$templateVars{'origNamelastContact'} = $FORM::origNamelastContact;
2402
    $$templateVars{'origNameOrgContact'} = $FORM::origNameOrgContact;
2403
    $$templateVars{'origDeliveryContact'} = $FORM::origDeliveryContact; 
2404
    $$templateVars{'origCityContact'} = $FORM::origCityContact;
2405
    $$templateVars{'origStateContact'} = $FORM::origStateContact;
2406
    $$templateVars{'origStateOtherContact'} = $FORM::origStateOtherContact;
2407
    $$templateVars{'origZIPContact'} = $FORM::origZIPContact;
2408
    $$templateVars{'origCountryContact'} = $FORM::origCountryContact;
2409
    $$templateVars{'origPhoneContact'} = $FORM::origPhoneContact;
2410
    $$templateVars{'origFAXContact'} = $FORM::origFAXContact;
2411
    $$templateVars{'origEmailContact'} = $FORM::origEmailContact;    
2412
    
2413
    $$templateVars{'aoCount'} = $FORM::aoCount;
2414
    foreach my $origName (param()) {
2415
	if ($origName =~ /origNamefirst/) {
2416
	    my $origNameIndex = $origName;
2417
	    $origNameIndex =~ s/origNamefirst//; # get the index of the parameter 0, ..., 10
2418
	    my $origNamelast = "origNamelast".$origNameIndex;
2419
	    my $origRole = "origRole".$origNameIndex;
2420
	    if ( $origNameIndex =~ /[0-9]/  && $origNameIndex > 0){
2421
		if (hasContent(param($origName)) && hasContent(param($origNamelast)) && hasContent(param($origRole))) {
2422
		    debug("Registry processing keyword: $origName = ".param($origName)." $origNamelast = ".param($origNamelast)." $origRole = ".param($origRole));
2423
		    $$templateVars{$origName} = normalizeCD(param($origName));
2424
		    $$templateVars{$origNamelast} = normalizeCD(param($origNamelast));
2425
		    $$templateVars{$origRole} = normalizeCD(param($origRole));
2426
		}
2427
	    }
2428
	}
2429
    }
2430

    
2431
    $$templateVars{'abstract'} = $FORM::abstract;
2432
    $$templateVars{'keyCount'} = $FORM::keyCount;
2433
    foreach my $kyd (param()) {
2434
	if ($kyd =~ /keyword/) {
2435
	    my $keyIndex = $kyd;
2436
	    $keyIndex =~ s/keyword//; # get the index of the parameter 0, ..., 10
2437
	    my $keyType = "kwType".$keyIndex;
2438
	    my $keyTh = "kwTh".$keyIndex;
2439
	    if ( $keyIndex =~ /[0-9]/ ){
2440
		if (hasContent(param($kyd)) && hasContent(param($keyType)) && hasContent(param($keyTh))) {
2441
		    debug("Registry processing keyword: $kyd = ".param($kyd)." $keyType = ".param($keyType)." $keyTh = ".param($keyTh));
2442
		    $$templateVars{$kyd} = param($kyd);
2443
		    $$templateVars{$keyType} = param($keyType);
2444
		    $$templateVars{$keyTh} = param($keyTh);
2445
		}
2446
	    }
2447
	}
2448
    }
2449
    $$templateVars{'addComments'} = $FORM::addComments;
2450
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2451
    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2452
    $$templateVars{'url'} = $FORM::url;
2453
    $$templateVars{'dataMedium'} = $FORM::dataMedium;
2454
    $$templateVars{'dataMediumOther'} = $FORM::dataMediumOther;
2455
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2456
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2457
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2458
    $$templateVars{'endingYear'} = $FORM::endingYear;
2459
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2460
    $$templateVars{'endingDay'} = $FORM::endingDay;
2461
    $$templateVars{'geogdesc'} = $FORM::geogdesc;
2462
    if($FORM::useSiteCoord ne ""){
2463
    $$templateVars{'useSiteCoord'} = "CHECKED";
2464
    }else{
2465
    $$templateVars{'useSiteCoord'} = "";
2466
    }
2467
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2468
    $$templateVars{'latMin1'} = $FORM::latMin1;
2469
    $$templateVars{'latSec1'} = $FORM::latSec1;
2470
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2471
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2472
    $$templateVars{'longMin1'} = $FORM::longMin1;
2473
    $$templateVars{'longSec1'} = $FORM::longSec1;
2474
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2475
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2476
    $$templateVars{'latMin2'} = $FORM::latMin2;
2477
    $$templateVars{'latSec2'} = $FORM::latSec2;
2478
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2479
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2480
    $$templateVars{'longMin2'} = $FORM::longMin2;
2481
    $$templateVars{'longSec2'} = $FORM::longSec2;
2482
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2483
    $$templateVars{'taxaCount'} = $FORM::taxaCount;
2484
    foreach my $trn (param()) {
2485
        if ($trn =~ /taxonRankName/) {
2486
            my $taxIndex = $trn;
2487
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
2488
            my $trv = "taxonRankValue".$taxIndex;
2489
            if ( $taxIndex =~ /[0-9]/ ){
2490
                if (hasContent(param($trn)) && hasContent(param($trv))) {
2491
                    debug("Registry processing taxon: $trn = ".param($trn)." $trv = ".param($trv));
2492
                    $$templateVars{$trn} = param($trn);
2493
                    $$templateVars{$trv} = param($trv);
2494
                }
2495
            }
2496
        }
2497
    }
2498
    $$templateVars{'taxaAuth'} = $FORM::taxaAuth;
2499
    $$templateVars{'methodTitle'} = $FORM::methodTitle;
2500
    $$templateVars{'methodPara'} = \@FORM::methodPara;
2501
    $$templateVars{'studyExtentDescription'} = $FORM::studyExtentDescription;
2502
    $$templateVars{'samplingDescription'} = $FORM::samplingDescription;
2503
    
2504
    $$templateVars{'hasKeyword'} = $FORM::hasKeyword;
2505
    $$templateVars{'hasTemporal'} = $FORM::hasTemporal;
2506
    $$templateVars{'hasSpatial'} = $FORM::hasSpatial;
2507
    $$templateVars{'hasTaxonomic'} = $FORM::hasTaxonomic;
2508
    $$templateVars{'hasMethod'} = $FORM::hasMethod;
2509
    $$templateVars{'spatialRequired'} = $FORM::spatialRequired;
2510
    $$templateVars{'temporalRequired'} = $FORM::temporalRequired;
2511
}
2512

    
2513
################################################################################
2514
# 
2515
# check if there is multiple occurence of the given tag and find its value.
2516
#
2517
################################################################################
2518

    
2519
sub findValue {
2520
    my $node = shift;
2521
    my $value = shift;
2522
    my $result;
2523
    my $tempNode;
2524

    
2525
    $result = $node->findnodes("./$value");
2526
    if ($result->size > 1) {
2527
        errMoreThanOne("$value");
2528
    } else {
2529
        foreach $tempNode ($result->get_nodelist){
2530
            #print $tempNode->nodeName().":".$tempNode->textContent();
2531
            #print "\n";
2532
            return $tempNode->textContent();
2533
        }
2534
    }
2535
}
2536

    
2537

    
2538
################################################################################
2539
# 
2540
# check if given tags has any children. if not return the value
2541
#
2542
################################################################################
2543
sub findValueNoChild {
2544
    my $node = shift;
2545
    my $value = shift;
2546
    my $tempNode;
2547
    my $childNodes;
2548
    my $result;
2549
    my $error;
2550

    
2551
    $result = $node->findnodes("./$value");
2552
    if($result->size > 1){
2553
       errMoreThanOne("$value");
2554
    } else {
2555
        foreach $tempNode ($result->get_nodelist) {
2556
            $childNodes = $tempNode->childNodes;
2557
            if ($childNodes->size() > 1) {
2558
                $error ="The tag $value has children which cannot be shown using the form. Please use Morpho to edit this document";    
2559
                push(@errorMessages, $error);
2560
                #if ($DEBUG == 1){ print $error."\n";}
2561
            } else {
2562
                #print $tempNode->nodeName().":".$tempNode->textContent();
2563
                #print "\n";
2564
                return $tempNode->textContent();
2565
            }
2566
        }
2567
    }
2568
}
2569

    
2570

    
2571
################################################################################
2572
# 
2573
# check if given tags are children of given node.
2574
#
2575
################################################################################
2576
sub dontOccur {
2577
    my $node = shift;
2578
    my $value = shift;
2579
    my $errVal = shift;
2580

    
2581
    my $result = $node->findnodes("$value");
2582
    if($result->size > 0){
2583
        $error ="One of the following tags found: $errVal. Please use Morpho to edit this document";
2584
        push(@errorMessages, $error."\n");
2585
        #if ($DEBUG == 1){ print $error;}
2586
    } 
2587
}
2588

    
2589

    
2590
################################################################################
2591
# 
2592
# print out error for more than one occurence of a given tag
2593
#
2594
################################################################################
2595
sub errMoreThanOne {
2596
    my $value = shift;
2597
    my $error ="More than one occurence of the tag $value found. Please use Morpho to edit this document";
2598
    push(@errorMessages, $error."\n");
2599
    # if ($DEBUG == 1){ print $error;}
2600
}
2601

    
2602

    
2603
################################################################################
2604
# 
2605
# print out error for more than given number of occurences of a given tag
2606
#
2607
################################################################################
2608
sub errMoreThanN {
2609
    my $value = shift;
2610
    my $error ="More occurences of the tag $value found than that can be shown in the form. Please use Morpho to edit this document";
2611
    push(@errorMessages, $error);
2612
    #if ($DEBUG == 1){ print $error."\n";}
2613
}
2614

    
2615

    
2616
################################################################################
2617
# 
2618
# convert coord to degrees, minutes and seconds form. 
2619
#
2620
################################################################################
2621
#sub convertCoord {
2622
#    my $wx = shift;
2623
#    print $deg." ".$min." ".$sec;
2624
#    print "\n";
2625
#}
2626

    
2627

    
2628
################################################################################
2629
# 
2630
# print debugging messages to stderr
2631
#
2632
################################################################################
2633
sub debug {
2634
    my $msg = shift;
2635
    
2636
    if ($debug) {
2637
        print STDERR "$msg\n";
2638
    }
2639
}
2640

    
2641
################################################################################
2642
# 
2643
# get the list of projects
2644
#
2645
################################################################################
2646
sub getProjectList {
2647
    
2648
    use NCEAS::AdminDB;
2649
    my $admindb = NCEAS::AdminDB->new();
2650
    $admindb->connect($nceas_db, $nceas_db_user, $nceas_db_password);
2651
    my $projects = $admindb->getProjects();
2652
    #my $projects = getTestProjectList();
2653
    return $projects;
2654
}
2655

    
2656
################################################################################
2657
# 
2658
# get a test list of projects for use only in testing where the NCEAS
2659
# admin db is not available.
2660
#
2661
################################################################################
2662
sub getTestProjectList {
2663
    # This block is for testing only!  Remove for production use
2664
    my @row1;
2665
    $row1[0] = 6000; $row1[1] = 'Andelman'; $row1[2] = 'Sandy'; $row1[3] = 'The very long and windy path to an apparent ecological conclusion: statistics lie';
2666
    my @row2; 
2667
    $row2[0] = 7000; $row2[1] = 'Bascompte'; $row2[2] = 'Jordi'; $row2[3] = 'Postdoctoral Fellow';
2668
    my @row3; 
2669
    $row3[0] = 7001; $row3[1] = 'Hackett'; $row3[2] = 'Edward'; $row3[3] = 'Sociology rules the world';
2670
    my @row4; 
2671
    $row4[0] = 7002; $row4[1] = 'Jones'; $row4[2] = 'Matthew'; $row4[3] = 'Informatics rules the world';
2672
    my @row5; 
2673
    $row5[0] = 7003; $row5[1] = 'Schildhauer'; $row5[2] = 'Mark'; $row5[3] = 'Excel rocks my world, assuming a, b, and c';
2674
    my @row6; 
2675
    $row6[0] = 7004; $row6[1] = 'Rogers'; $row6[2] = 'Bill'; $row6[3] = 'Graduate Intern';
2676
    my @row7; 
2677
    $row7[0] = 7005; $row7[1] = 'Zedfried'; $row7[2] = 'Karl'; $row7[3] = 'A multivariate analysis of thing that go bump in the night';
2678
    my @projects;
2679
    $projects[0] = \@row1;
2680
    $projects[1] = \@row2;
2681
    $projects[2] = \@row3;
2682
    $projects[3] = \@row4;
2683
    $projects[4] = \@row5;
2684
    $projects[5] = \@row6;
2685
    $projects[6] = \@row7;
2686
    return \@projects;
2687
}