Project

General

Profile

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

1
#!/usr/bin/perl
2
#
3
#  '$RCSfile$'
4
#  Copyright: 2000 Regents of the University of California 
5
#
6
#   '$Author: jones $'
7
#     '$Date: 2003-12-23 11:27:52 -0800 (Tue, 23 Dec 2003) $'
8
# '$Revision: 1982 $' 
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::LDAP;
37
use Net::SMTP;
38
use CGI qw/:standard :html3/;
39
use strict;
40

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

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

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

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

    
64
$config->define("metacatUrl");
65
$config->define("username");
66
$config->define("password");
67
$config->define("ldapUrl");
68
$config->define("defaultScope");
69
$config->define("organization");
70
$config->define("orgabbrev");
71
$config->define("orgurl");
72
$config->define("accesspubid");
73
$config->define("accesssysid");
74
$config->define("datasetpubid");
75
$config->define("datasetsysid");
76
$config->define("mailhost");
77
$config->define("sender");
78
$config->define("recipient");
79
$config->define("adminname");
80
if ($FORM::cfg eq 'nceas') {
81
    $config->define("nceas_db");
82
    $config->define("nceas_db_user");
83
    $config->define("nceas_db_password");
84
}
85
$config->define("responseTemplate", { DEFAULT => 'crap.tmpl'} );
86
$config->define("entryFormTemplate", { DEFAULT => 'crap.tmpl'} );
87
$config->define("guideTemplate", { DEFAULT => 'crap.tmpl'} );
88
$config->define("confirmDataTemplate", { DEFAULT => 'crap.tmpl'} );
89
$config->define("deleteDataTemplate", { DEFAULT => 'crap.tmpl'} );
90
$config->define("debug", { DEFAULT => '0'} );
91
$config->define("lat", { ARGCOUNT => ARGCOUNT_HASH} );
92
$config->define("lon", { ARGCOUNT => ARGCOUNT_HASH} );
93

    
94
if (! hasContent($FORM::cfg)) {
95
    $error = "Application misconfigured.  Please contact the administrator.";
96
    push(@errorMessages, $error);
97
} else {
98
    my $cfgfile = $cfgdir . "/" . $FORM::cfg . "/" . $FORM::cfg . ".cfg";
99
    $config->file($cfgfile);
100
}
101

    
102
my $metacatUrl = $config->metacatUrl();
103
my $username = $config->username();
104
my $password = $config->password();
105
my $ldapUrl = $config->ldapUrl();
106
my $defaultScope = $config->defaultScope();
107
my $organization = $config->organization();
108
my $orgabbrev = $config->orgabbrev();
109
my $orgurl = $config->orgurl();
110
my $orgfilter = $organization;
111
   $orgfilter =~ s/ /%20/g;
112
my $responseTemplate = $config->responseTemplate();
113
my $entryFormTemplate = $config->entryFormTemplate();
114
my $deleteDataTemplate = $config->deleteDataTemplate();
115
my $guideTemplate = $config->guideTemplate();
116
my $confirmDataTemplate = $config->confirmDataTemplate();
117
my $accesspubid = $config->accesspubid();
118
my $accesssysid = $config->accesssysid();
119
my $datasetpubid = $config->datasetpubid();
120
my $datasetsysid = $config->datasetsysid();
121
my $mailhost = $config->mailhost();
122
my $sender = $config->sender();
123
my $recipient = $config->recipient();
124
my $adminname = $config->adminname();
125
my $nceas_db;
126
my $nceas_db_user;
127
my $nceas_db_password;
128
if ($FORM::cfg eq 'nceas') {
129
    $nceas_db = $config->nceas_db();
130
    $nceas_db_user = $config->nceas_db_user();
131
    $nceas_db_password = $config->nceas_db_password();
132
}
133
my $debug = $config->debug();
134
my $lat = $config->get('lat');
135
my $lon = $config->get('lon');
136

    
137
# Convert the lat and lon configs into usable data structures
138
my @sitelist;
139
my %siteLatDMS;
140
my %siteLongDMS;
141
foreach my $newsite (keys %$lat) {
142
    my ($latd, $latm, $lats, $latdir) = split(':', $lat->{$newsite});
143
    my ($lond, $lonm, $lons, $londir) = split(':', $lon->{$newsite});
144
    push(@sitelist, $newsite);
145
    $siteLatDMS{$newsite} = [ $latd, $latm, $lats, $latdir ];
146
    $siteLongDMS{$newsite} = [ $lond, $lonm, $lons, $londir ];
147
}
148

    
149
# set some configuration options for the template object
150
my $ttConfig = {
151
             INCLUDE_PATH => $templatesdir, 
152
             INTERPOLATE  => 0,                    
153
             POST_CHOMP   => 1,                   
154
             };
155

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

    
159
print "Content-type: text/html\n\n";
160

    
161
# Set up the template information that is common to all forms
162
$$templateVars{'cfg'} = $FORM::cfg;
163
$$templateVars{'recipient'} = $recipient;
164
$$templateVars{'adminname'} = $adminname;
165
$$templateVars{'organization'} = $organization;
166
$$templateVars{'orgabbrev'} = $orgabbrev;
167
$$templateVars{'orgurl'} = $orgurl;
168
$$templateVars{'orgfilter'} = $orgfilter;
169

    
170

    
171
# Process the form based on stage parameter. 
172
if ($FORM::stage =~ "guide") {
173
    # Send back the information on how to fill the form
174
    $$templateVars{'section'} = "Guide on How to Complete Registry Entries";
175
    $template->process( $guideTemplate, $templateVars);
176
    exit(0);
177

    
178
} elsif ($FORM::stage =~ "insert") {
179
    # The user has entered the data. Do data validation and send back data 
180
    # to confirm the data that has been entered. 
181
    toConfirmData();
182
    exit(0);
183

    
184
}elsif ($FORM::dataWrong =~ "No, I want to change it!!" && $FORM::stage =~ "confirmed") {
185
    # The user wants to correct the data that he has entered. 
186
    # Hence show the data again in entryData form. 
187
    confirmDataToReEntryData();
188
    exit(0);
189

    
190
}elsif ($FORM::stage =~ "modify") {
191
    # Modification of a file has been requested. 
192
    # Show the form will all the values filled in.
193
    my @sortedSites;
194
    foreach my $site (sort @sitelist) {
195
        push(@sortedSites, $site);
196
    }
197
    $$templateVars{'siteList'} = \@sortedSites;
198
    $$templateVars{'section'} = "Modification Form";
199
    $$templateVars{'docid'} = $FORM::docid;
200
    modifyData();
201
    exit(0);
202

    
203
}elsif ($FORM::stage =~ "delete_confirm") {
204

    
205
    # Result from deleteData form. 
206
    if($FORM::deleteData =~ "Delete data"){
207
    # delete Data
208
    deleteData(1);    
209
    exit(0);
210
    } else {
211
    # go back to search page. 
212
    exit(0);
213
    }
214

    
215
}elsif ($FORM::stage =~ "delete") {
216
    # Deletion of a file has been requested. 
217
    # Ask for username and password using deleteDataForm
218
    $$templateVars{'docid'} = $FORM::docid;
219
    $template->process( $deleteDataTemplate, $templateVars);
220
    exit(0);
221

    
222
}elsif ($FORM::stage !~ "confirmed") {
223
    # None of the stages have been reached and data is not being confirmed. 
224
    # Hence, send back entry form for entry of data.  
225
    my @sortedSites;
226
    foreach my $site (sort @sitelist) {
227
        push(@sortedSites, $site);
228
    }
229
    
230
    if ($FORM::cfg eq 'nceas') {
231
        my $projects = getProjectList();
232
        $$templateVars{'projects'} = $projects;
233
        $$templateVars{'wg'} = \@FORM::wg;
234
    }
235

    
236
    $$templateVars{'siteList'} = \@sortedSites;
237
    $$templateVars{'section'} = "Entry Form";
238
    $$templateVars{'docid'} = "";
239
    $template->process( $entryFormTemplate, $templateVars);
240
    exit(0);
241
}
242

    
243
# Confirm stage has been reached. Enter the data into metacat. 
244

    
245
# Initialize some global vars
246
my $latDeg1 = "";
247
my $latMin1 = "";
248
my $latSec1 = "";
249
my $hemisphLat1 = "";
250
my $longDeg1 = "";
251
my $longMin1 = "";
252
my $longSec1 = "";
253
my $hemisphLong1 = "";
254
my $latDeg2 = "";
255
my $latMin2 = "";
256
my $latSec2 = "";
257
my $hemisphLat2 = "";
258
my $longDeg2 = "";
259
my $longMin2 = "";
260
my $longSec2 = "";
261
my $hemisphLong2 = "";
262

    
263
# validate the input form parameters
264
my $invalidParams;
265

    
266
if (! $error) {
267
    $invalidParams = validateParameters(1);
268
    if (scalar(@$invalidParams)) {
269
        $$templateVars{'status'} = 'failure';
270
        $$templateVars{'invalidParams'} = $invalidParams;
271
        $error = 1;
272
    }
273
}
274

    
275

    
276
my $metacat;
277
my $docid;
278
if (! $error) {
279
    # Parameters have been validated and Create the XML document
280

    
281
    my $xmldoc = createXMLDocument();
282

    
283
    # Write out the XML file for debugging purposes
284
    #my $testFile = $tmpdir . "/test.xml";
285

    
286
    # Create a  metacat object
287
    $metacat = Metacat->new();
288
    if ($metacat) {
289
        $metacat->set_options( metacatUrl => $metacatUrl );
290
    } else {
291
        #die "failed during metacat creation\n";
292
        push(@errorMessages, "Failed during metacat creation.");
293
    }
294

    
295
    # Login to metacat
296
    my $userDN = $FORM::username;
297
    my $userOrg = $FORM::organization;
298
    my $userPass = $FORM::password;
299
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
300
    
301
    my $errorMessage = "";
302
    my $response = $metacat->login($dname, $userPass);
303
    if (! $response) {
304
        #print $metacat->getMessage();
305
        #die "failed during login\n";
306
        #print STDERR "Login response is: $metacat->getMessage()\n";
307
        push(@errorMessages, $metacat->getMessage());
308
        push(@errorMessages, "Failed during login.\n");
309
    }
310

    
311
    debug( "Registry: A");
312
    if ($FORM::docid eq "") {
313
        debug( "Registry: B1");
314
        # document is being inserted 
315
        my $notunique = "NOT_UNIQUE";
316
        while ($notunique eq "NOT_UNIQUE") {
317
            $docid = newAccessionNumber($defaultScope);
318
            
319
            $xmldoc =~ s/docid/$docid/;
320
    
321
            #my $testFile = "/tmp/test.xml";
322
            #open (TFILE,">$testFile") || die ("Cant open xml file...\n");
323
            #print TFILE $xmldoc;
324
            #close(TFILE);
325
    
326
            $notunique = insertMetadata($xmldoc, $docid);
327
            #  if (!$notunique) {
328
            # Write out the XML file for debugging purposes
329
            #my $testFile = $tmpdir . "/test-new.xml";
330
            #open (TFILE,">$testFile") || die ("Cant open xml file...\n");
331
            #print TFILE $newdoc;
332
            #close(TFILE);
333
            #   }
334

    
335
            # The id wasn't unique, so update our lastid file
336
            if ($notunique eq "NOT_UNIQUE") {
337
                updateLastId($defaultScope);
338
            }
339
        }
340
        debug("Registry: B2");
341
        if ($notunique ne "SUCCESS") {
342
            debug("Registry: NO SUCCESS");
343
            debug("Message is: $notunique");
344
            push(@errorMessages, $notunique);
345
        }
346
        debug("Registry: B3");
347
    } else {
348
        # document is being modified
349
        $docid = $FORM::docid;
350
    
351
        my $x;
352
        my $y;
353
        my $z;
354

    
355
        ($x, $y, $z) = split(/\./, $docid); 
356
        $z++;
357
        $docid = "$x.$y.$z";
358
    
359
        $xmldoc =~ s/docid/$docid/;
360
        
361
        my $response = $metacat->update($docid, $xmldoc);
362

    
363
        if (! $response) {
364
            push(@errorMessages, $metacat->getMessage());
365
            push(@errorMessages, "Failed while updating.\n");  
366
        }
367

    
368
        if (scalar(@errorMessages)) {
369
            debug("Registry: ErrorMessages defined in modify.");
370
            $$templateVars{'status'} = 'failure';
371
            $$templateVars{'errorMessages'} = \@errorMessages;
372
            $error = 1;
373
        }
374

    
375
        #if (! $error) {
376
            #sendNotification($docid, $mailhost, $sender, $recipient);
377
        #}
378
    
379
        # Create our HTML response and send it back
380
        $$templateVars{'function'} = "modified";
381
        $$templateVars{'section'} = "Modification Status";
382
        $template->process( $responseTemplate, $templateVars);
383

    
384
        exit(0);
385
    }
386
}
387

    
388
debug("Registry: C");
389

    
390
if (scalar(@errorMessages)) {
391
    debug("Registry: ErrorMessages defined.");
392
    $$templateVars{'status'} = 'failure';
393
    $$templateVars{'errorMessages'} = \@errorMessages;
394
    $error = 1;
395
}
396

    
397
#if (! $error) {
398
#sendNotification($docid, $mailhost, $sender, $recipient);
399
#}
400

    
401
# Create our HTML response and send it back
402
$$templateVars{'function'} = "submitted";
403
$$templateVars{'section'} = "Submission Status";
404
$template->process( $responseTemplate, $templateVars);
405

    
406
exit(0);
407

    
408

    
409
################################################################################
410
#
411
# Subroutine for updating a metacat id for a given scope to the highest value
412
#
413
################################################################################
414
sub updateLastId {
415
  my $scope = shift;
416

    
417
  my $errormsg = 0;
418
  my $docid = $metacat->getLastId($scope);
419

    
420
  if ($docid =~ /null/) {
421
      # No docids with this scope present, so do nothing
422
  } elsif ($docid) {
423
      # Update the lastid file for this scope
424
      (my $foundScope, my $id, my $rev) = split(/\./, $docid);
425
      debug("Docid is: $docid\n");
426
      debug("Lastid is: $id");
427
      my $scopeFile = $cfgdir . "/" . $FORM::cfg . "/" . $scope . ".lastid";
428
      open(LASTID, ">$scopeFile") or 
429
          die "Failed to open lastid file for writing!";
430
      print LASTID $id, "\n";
431
      close(LASTID);
432
  } else {
433
    $errormsg = $metacat->getMessage();
434
    debug("Error in getLastId: $errormsg");
435
  }
436
}
437

    
438
################################################################################
439
#
440
# Subroutine for inserting a document to metacat
441
#
442
################################################################################
443
sub insertMetadata {
444
  my $xmldoc = shift;
445
  my $docid = shift;
446

    
447
  my $notunique = "SUCCESS";
448
  my $response = $metacat->insert($docid, $xmldoc);
449
  if (! $response) {
450
    my $errormsg = $metacat->getMessage();
451
    if ($errormsg =~ /is already in use/) {
452
      $notunique = "NOT_UNIQUE";
453
      #print "Accession number already used: $docid\n";
454
    } elsif ($errormsg =~ /<login>/) {
455
      $notunique = "SUCCESS";
456
    } else {
457
      #print "<p>Dumping error on failure...</p>\n";
458
      #print "<p>", $errormsg, "</p>\n";
459
      #die "Failed during insert\n";
460
      #print "<p>Failed during insert</p>\n";
461
      $notunique = $errormsg;
462
    }
463
  }
464

    
465
  return $notunique;
466
}
467

    
468
################################################################################
469
#
470
# Subroutine for generating a new accession number
471
#  Note: this is not threadsafe, assumes only one running process at a time
472
#  Also: need to check metacat for max id # used in this scope already
473
################################################################################
474
sub newAccessionNumber {
475
  my $scope = shift;
476
    
477
  my $docrev = 1;
478
  my $lastid = 1;
479

    
480
  my $scopeFile = $cfgdir . "/" . $FORM::cfg . "/" . $scope . ".lastid";
481
  if (-e $scopeFile) {
482
    open(LASTID, "<$scopeFile") or die "Failed to generate accession number!";
483
    $lastid = <LASTID>;
484
    chomp($lastid);
485
    $lastid++;
486
    close(LASTID);
487
  }
488
  open(LASTID, ">$scopeFile") or die "Failed to open lastid file for writing!";
489
  print LASTID $lastid, "\n";
490
  close(LASTID);
491

    
492
  my $docroot = "$scope.$lastid.";
493
  my $docid = $docroot . $docrev;
494
  return $docid;
495
}
496

    
497
################################################################################
498
#
499
# Subroutine for generating a new ACL document
500
#
501
################################################################################
502
sub newAccessDocument {
503
  my $aclid = shift;
504
  my $acl = "<?xml version=\"1.0\"?>\n";
505
  $acl .= "<!DOCTYPE acl ";
506
  $acl .= "PUBLIC \"$accesspubid\" \"$accesssysid\">\n";
507
  $acl .= "<acl authSystem=\"ldap://ldap.ecoinformatics.org\" ";
508
  $acl .= "order=\"denyFirst\">\n";
509
  $acl .= "<identifier system=\"knb\">$aclid</identifier>\n";
510
  #$acl .= "<identifier>$aclid</identifier>\n";
511
  $acl .= "<allow><principal>$username</principal>" .
512
          "<permission>all</permission></allow>\n";
513
  #$acl .= "<allow><principal>public</principal>" .
514
  #        "<permission>read</permission></allow>\n";
515
  $acl .= "</acl>\n";
516

    
517
  return $acl;
518
}
519

    
520
################################################################################
521
#
522
# Subroutine for inserting identifers to the metadata document passed to us
523
#
524
################################################################################
525
sub insertIdentifiers {
526
  my $docstring = shift;
527
  my $aclid = shift;
528
  my $docid = shift;
529

    
530
  my $parser = XML::LibXML->new();
531
  my $dom = $parser->parse_string($docstring);
532

    
533
  my $root = $dom->documentElement;
534
  my $name = $root->getName();
535

    
536
  my $addedIdentifier = 0;
537
  my $currentElement = $root->getFirstChild();
538
  $name = $currentElement->getName();
539
  while ("$name" !~ "triple" &&
540
         "$name" !~ "temporalCov" && 
541
         "$name" !~ "geographicCov" && 
542
         "$name" !~ "taxonomicCov"
543
        ) {
544
    if ("$name" =~ "identifier" ||
545
        "$name" =~ "title") {
546
      if (! $addedIdentifier) {
547
      my $idelement = $dom->createElement( "identifier" );
548
        $addedIdentifier = 1;
549
        $idelement->setAttribute("system", "knb");
550
        $idelement->appendTextNode($docid);
551
        $root->insertBefore($idelement, $currentElement);
552
      }
553
    }
554
    $currentElement = $currentElement->getNextSibling();
555
    $name = $currentElement->getName();
556
  }
557
  # Link the document to the access doc
558
  my $element = $dom->createElement( "triple" );
559
  $element->appendTextChild( "subject", $aclid);
560
  $element->appendTextChild( "relationship", 
561
                             "describes access control rules for");
562
  $element->appendTextChild( "object", $docid);
563
  $root->insertBefore($element, $currentElement);
564
  # Link the access doc to the access doc
565
  $element = $dom->createElement( "triple" );
566
  $element->appendTextChild( "subject", $aclid);
567
  $element->appendTextChild( "relationship", 
568
                             "describes access control rules for");
569
  $element->appendTextChild( "object", $aclid);
570
  $root->insertBefore($element, $currentElement);
571

    
572
  return $dom->toString();
573
}
574

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

    
584
    push(@invalidParams, "Provider's first name is missing.")
585
        unless hasContent($FORM::providerGivenName);
586
    push(@invalidParams, "Provider's last name is missing.")
587
        unless hasContent($FORM::providerSurName);
588
    push(@invalidParams, "Name of site is missing.")
589
        unless (hasContent($FORM::site) || $FORM::site =~ /elect/ ||
590
                $FORM::cfg eq "nceas");
591
    push(@invalidParams, "Data set title is missing.")
592
        unless hasContent($FORM::title);
593
    push(@invalidParams, "Originator's first name is missing.")
594
        unless hasContent($FORM::origNamefirst0);
595
    push(@invalidParams, "Originator's last name is missing.")
596
        unless hasContent($FORM::origNamelast0);
597
    push(@invalidParams, "Abstract is missing.")
598
        unless hasContent($FORM::abstract);
599
    push(@invalidParams, "Beginning year of data set is missing.")
600
        unless hasContent($FORM::beginningYear);
601

    
602
    # If the "use site" coord. box is checked and if the site is in 
603
    # the longitude hash ...  && ($siteLatDMS{$FORM::site})
604
   
605
    if (($FORM::useSiteCoord) && ($siteLatDMS{$FORM::site}) ) {
606
        
607
        $latDeg1 = $siteLatDMS{$FORM::site}[0];
608
        $latMin1 = $siteLatDMS{$FORM::site}[1];
609
        $latSec1 = $siteLatDMS{$FORM::site}[2];
610
        $hemisphLat1 = $siteLatDMS{$FORM::site}[3];
611
        $longDeg1 = $siteLongDMS{$FORM::site}[0];
612
        $longMin1 = $siteLongDMS{$FORM::site}[1];
613
        $longSec1 = $siteLongDMS{$FORM::site}[2];
614
        $hemisphLong1 = $siteLongDMS{$FORM::site}[3];
615
     
616
    }  else {
617
    
618
        $latDeg1 = $FORM::latDeg1;
619
        $latMin1 = $FORM::latMin1;
620
        $latSec1 = $FORM::latSec1;
621
        $hemisphLat1 = $FORM::hemisphLat1;
622
        $longDeg1 = $FORM::longDeg1;
623
        $longMin1 = $FORM::longMin1;
624
        $longSec1 = $FORM::longSec1;
625
        $hemisphLong1 = $FORM::hemisphLong1;
626
    }
627
    
628
    # Check if latDeg1 and longDeg1 has values if useSiteCoord is used. 
629
    # This check is required because some of the sites dont have lat 
630
    # and long mentioned in the config file. 
631

    
632
    if ($FORM::useSiteCoord) {
633
    push(@invalidParams, "The Data Registry doesn't have latitude and longitude information for the site that you choose. Please go back and enter the spatial information.")
634
        unless(hasContent($latDeg1) && hasContent($longDeg1));
635
    }else{
636
    push(@invalidParams, "Latitude degrees are missing.")
637
        unless hasContent($latDeg1);
638
    push(@invalidParams, "Longitude degrees are missing.")
639
        unless hasContent($longDeg1);
640
    }
641

    
642
    push(@invalidParams, "Contact first name is missing.")
643
    unless (hasContent($FORM::origNamefirstContact) || 
644
        $FORM::useOrigAddress);
645
    push(@invalidParams, "Contact last name is missing.")
646
    unless (hasContent($FORM::origNamelastContact) || 
647
        $FORM::useOrigAddress);
648
    push(@invalidParams, "Data medium is missing.")
649
    unless (hasContent($FORM::dataMedium) || $FORM::dataMedium =~ /elect/);
650
    
651
    if($chkUser){
652
    my $errorUserPass = validateUserPass();
653
    if($errorUserPass ne ""){
654
        push(@invalidParams, $errorUserPass);
655
    }
656
    }
657

    
658
    return \@invalidParams;
659
}
660

    
661
################################################################################
662
# 
663
# Validate the parameters username and password.
664
#
665
################################################################################
666
sub validateUserPass {
667
    my $userDN = $FORM::username;
668
    my $userOrg = $FORM::organization;
669
    my $userPass = $FORM::password;
670
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
671

    
672
    my $errorMessage = "";
673
    my $ldap = Net::LDAP->new($ldapUrl) or die "$@";
674
    my $bindresult = $ldap->bind( version => 3, dn => $dname, 
675
                                  password => $userPass );
676
    if ($bindresult->code) {
677
        $errorMessage = "Failed to log into metacat. Please check the username, organization and password entered";
678
        return $errorMessage;
679
    }
680
    return $errorMessage;
681
}
682

    
683

    
684
################################################################################
685
# 
686
# utility function to determine if a paramter is defined and not an empty string
687
#
688
################################################################################
689
sub hasContent {
690
    my $param = shift;
691

    
692
    my $paramHasContent;
693
    if (!defined($param) || $param eq '') { 
694
        $paramHasContent = 0;
695
    } else {
696
        $paramHasContent = 1;
697
    }
698
    return $paramHasContent;
699
}
700

    
701

    
702
################################################################################
703
# 
704
# Create the XML document from the HTML form input
705
# returns the XML document as a string
706
#
707
################################################################################
708
sub createXMLDocument {
709

    
710
    my $orig  = "";
711
    my $role  = "associatedParty";
712
    my $creat = "";
713
    my $metaP = "";
714
    my $apart = "";
715
    my $cont  = "";
716
    my $publ  = "";
717
    my $dso   = "";
718
    my $gmt = gmtime($now);
719
    my $doc =  "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
720

    
721
   $doc .= "<eml:eml\n 
722
                     \t packageId=\"docid\" system=\"knb\"\n 
723
                     \t xmlns:eml=\"eml://ecoinformatics.org/eml-2.0.0\"\n
724
                     \t xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n 
725
                     \t xmlns:ds=\"eml://ecoinformatics.org/dataset-2.0.0\"\n 
726
                     \t xmlns:stmml=\"http://www.xml-cml.org/schema/stmml\"\n 
727
                     \t xsi:schemaLocation=\"eml://ecoinformatics.org/eml-2.0.0 eml.xsd\">\n";
728

    
729
    $doc .= "<!-- Person who filled in the catalog entry form: ";
730
    $doc .= "$FORM::providerGivenName $FORM::providerSurName -->\n";
731
    $doc .= "<!-- Form filled out at $gmt GMT -->\n";
732
    $doc .= "<dataset>\n";
733
    
734
    if (hasContent($FORM::identifier)) {
735
        $doc .= "<alternateIdentifier system=\"$FORM::site\">";
736
        $doc .= $FORM::identifier . "</alternateIdentifier>\n";
737
    }
738
    
739
    if (hasContent($FORM::title)) {
740
        $doc .= "<title>$FORM::title</title>\n";
741
    }
742

    
743
    if (hasContent($FORM::origNamelast0)) {
744
    $role = "creator";
745
        $orig .= "<individualName>\n";
746
        $orig .= "<givenName>$FORM::origNamefirst0</givenName>\n";
747
        $orig .= "<surName>$FORM::origNamelast0</surName>\n";
748
        $orig .= "</individualName>\n";
749
    }
750

    
751
    if (hasContent($FORM::origNameOrg)) {
752
        $orig .= "<organizationName>$FORM::origNameOrg</organizationName>\n";
753
    }
754

    
755
    if (hasContent($FORM::origDelivery) || hasContent($FORM::origCity) ||
756
        (hasContent($FORM::origState   ) &&
757
        ($FORM::origState !~ "Select state here.")) ||
758
        hasContent($FORM::origStateOther) ||
759
        hasContent($FORM::origZIP ) || hasContent($FORM::origCountry)) {
760
        $orig .= "<address>\n";
761

    
762
        if (hasContent($FORM::origDelivery)) {
763
            $orig .= "<deliveryPoint>$FORM::origDelivery</deliveryPoint>\n";
764
        }
765
        if (hasContent($FORM::origCity)) {
766
            $orig .= "<city>$FORM::origCity</city>\n";
767
        }
768

    
769
    if (hasContent($FORM::origState) && 
770
            ($FORM::origState !~ "Select state here.")) {
771
            $orig .= "<administrativeArea>$FORM::origState";
772
            $orig .= "</administrativeArea>\n";
773
        } elsif (hasContent($FORM::origStateOther)) {
774
            $orig .= "<administrativeArea>$FORM::origStateOther";
775
            $orig .= "</administrativeArea>\n";
776
        }
777
        if (hasContent($FORM::origZIP)) {
778
            $orig .= "<postalCode>$FORM::origZIP</postalCode>\n";
779
        }
780
        if (hasContent($FORM::origCountry)) {
781
            $orig .= "<country>$FORM::origCountry</country>\n";
782
        }
783
        $orig .= "</address>\n";
784
    }
785

    
786
    if (hasContent($FORM::origPhone)) {
787
        $orig .= "<phone>$FORM::origPhone</phone>\n";
788
    }
789
    if (hasContent($FORM::origFAX)) {
790
        $orig .= "<phone phonetype=\"Fax\">$FORM::origFAX</phone>\n";
791
    }
792
    if (hasContent($FORM::origEmail)) {
793
        $orig .= "<electronicMailAddress>$FORM::origEmail";
794
        $orig .= "</electronicMailAddress>\n";
795
    }
796
    $dso = "<$role>\n$orig</$role>\n";
797
    
798
    $creat .= $dso;
799

    
800
    if ($FORM::useOrigAddress) {
801
        # Add a contact originator like the original with a different role
802
            $cont .= "<contact>\n";
803
        $cont .= $orig;
804
        $cont .= "</contact>\n";
805
    } else {
806
        $cont .= "<contact>\n";
807

    
808
        $cont .= "<individualName>\n";
809
        $cont .= "<givenName>$FORM::origNamefirstContact</givenName>\n";
810
        $cont .= "<surName>$FORM::origNamelastContact</surName>\n";
811
        $cont .= "</individualName>\n";
812
 
813
    if (hasContent($FORM::origNameOrgContact)) {
814
        $cont .= "<organizationName>$FORM::origNameOrgContact</organizationName>\n";
815
    }
816

    
817
        if (hasContent($FORM::origDeliveryContact) || 
818
            hasContent($FORM::origCityContact) ||
819
            (hasContent($FORM::origStateContact) &&
820
            ($FORM::origStateContact !~ "Select state here.")) ||
821
            hasContent($FORM::origStateOtherContact) ||
822
            hasContent($FORM::origZIPContact) || 
823
            hasContent($FORM::origCountryContact)) {
824
            $cont .= "<address>\n";
825
            if (hasContent($FORM::origDeliveryContact)) {
826
                $cont .= "<deliveryPoint>$FORM::origDeliveryContact";
827
                $cont .= "</deliveryPoint>\n";
828
            }
829
            if (hasContent($FORM::origCityContact)) {
830
                $cont .= "<city>$FORM::origCityContact</city>\n";
831
            }
832
            if (hasContent($FORM::origStateContact) && 
833
                ($FORM::origStateContact !~ "Select state here.")) {
834
                $cont .= "<administrativeArea>$FORM::origStateContact";
835
                $cont .= "</administrativeArea>\n";
836
            } elsif (hasContent($FORM::origStateOtherContact)) {
837
                $cont .= "<administrativeArea>$FORM::origStateOtherContact";
838
                $cont .= "</administrativeArea>\n";
839
            }
840
            if (hasContent($FORM::origZIPContact)) {
841
                $cont .= "<postalCode>$FORM::origZIPContact</postalCode>\n";
842
            }
843
            if (hasContent($FORM::origCountryContact)) {
844
                $cont .= "<country>$FORM::origCountryContact</country>\n";
845
            }
846
            $cont .= "</address>\n";
847
        }
848
        if (hasContent($FORM::origPhoneContact)) {
849
            $cont .= "<phone>$FORM::origPhoneContact</phone>\n";
850
        }
851
    if (hasContent($FORM::origFAXContact)) {
852
        $cont .= "<phone phonetype=\"Fax\">$FORM::origFAXContact</phone>\n";
853
    }
854
        if (hasContent($FORM::origEmailContact)) {
855
            $cont .= "<electronicMailAddress>$FORM::origEmailContact";
856
            $cont .= "</electronicMailAddress>\n";
857
        }
858
    $cont .= "</contact>\n";
859
    }
860

    
861
    $metaP .= "<metadataProvider>\n";
862
    $metaP .= "<individualName>\n";
863
    $metaP .= "<givenName>$FORM::providerGivenName</givenName>\n";
864
    $metaP .= "<surName>$FORM::providerSurName</surName>\n";
865
    $metaP .= "</individualName>\n";
866
    $metaP .= "</metadataProvider>\n";
867

    
868
    # Additional originators
869
    foreach my $tmp (param()) {
870
        if ($tmp =~ /origNamelast/){
871
            my $tmp1 = $tmp;
872
            $tmp1 =~ s/origNamelast//; # get the index of the parameter 0 to 10
873
            if ( $tmp1 eq '1' 
874
                 || $tmp1 eq '2'
875
                 || $tmp1 eq '3'
876
                 || $tmp1 eq '4'
877
                 || $tmp1 eq '5'
878
                 || $tmp1 eq '6'
879
                 || $tmp1 eq '7'
880
                 || $tmp1 eq '8'
881
                 || $tmp1 eq '9'
882
                 || $tmp1 eq '10'
883
                 ) {
884
     
885
                # do not generate XML for empty originator fields 
886
                if (hasContent(param("origNamefirst" . $tmp1))) {    
887

    
888
            my $add = "";
889
            $add .= "<individualName>\n";
890
            $add .= "<givenName>";
891
            $add .= param("origNamefirst" . $tmp1);
892
            $add .= "</givenName>\n";
893
            $add .= "<surName>";
894
            $add .= param("origNamelast" . $tmp1);
895
            $add .= "</surName>\n";
896
            $add .= "</individualName>\n";
897
            
898
            if(param("origRole" . $tmp1) eq "Originator"){
899
            $creat .= "<creator>\n";
900
            $creat .= $add;
901
            $creat .= "</creator>\n";
902
            }
903
            elsif(param("origRole" . $tmp1) eq "Metadata Provider"){
904
            $metaP .= "<metadataProvider>\n";
905
            $metaP .= $add;
906
            $metaP .= "</metadataProvider>\n";
907
            }
908
            elsif((param("origRole" . $tmp1) eq "Publisher")  && ($publ eq "")){
909
            $publ .= "<publisher>\n";
910
            $publ .= $add;
911
            $publ .= "</publisher>\n";
912
            }
913
            else{
914
            $apart .= "<associatedParty>\n";
915
            $apart .= $add;
916
            $apart .= "<role>";
917
            $apart .= param("origRole" . $tmp1);
918
            $apart .= "</role>\n";
919
            $apart .= "</associatedParty>\n";
920
            }
921
        }
922
            }
923
        }
924
    }
925

    
926
    $creat .= "<creator>\n";
927
    $creat .= "<organizationName>$FORM::site</organizationName>\n";
928
    $creat .= "</creator>\n";
929

    
930
    $creat .= "<creator>\n";
931
    $creat .= "<organizationName>$organization</organizationName>\n";
932
    $creat .= "</creator>\n";
933

    
934
    if ($FORM::cfg eq 'nceas') {
935
        for (my $i = 0; $i < scalar(@FORM::wg); $i++) {
936
            $creat .= "<creator>\n";
937
            $creat .= "<organizationName>$FORM::wg[$i]</organizationName>\n";
938
            $creat .= "</creator>\n";
939
        }
940
    }
941
    $doc .= $creat;
942
    $doc .= $metaP;
943
    $doc .= $apart;
944

    
945
    $doc .= "<abstract>\n";
946
    $doc .= "<para>$FORM::abstract</para>\n";
947
    $doc .= "</abstract>\n";
948

    
949
    # Keyword information
950
    foreach my $tmp (param()) {
951
        if ($tmp =~ /keyword/) {
952
            my $tmp1 = $tmp;
953
            $tmp1 =~ s/keyword//; # get the index of the parameter 0, ..., 10
954
            if ( $tmp1 =~ /[0-9]/ ){
955
                # don't generate xml for empty keyword fields
956
                # don't generate taxonomic keyword fields, those go in taxonomic coverage
957
                if (hasContent(param($tmp))) {
958
                    $doc .= "<keywordSet>\n";
959
                    $doc .= "<keyword ";
960
                    if (hasContent(param("kwType" . $tmp1)) &&
961
                       (param("kwType" . $tmp1) !~ "none") ) {
962
                         $doc .= "keywordType=\"";
963
                         $doc .= param("kwType" . $tmp1);
964
                         $doc .= "\"";
965
                    }
966
                    $doc .= ">";
967
                    $doc .= param("keyword" . $tmp1);
968
                    $doc .= "</keyword>\n";
969
                    $doc .= "<keywordThesaurus>";
970
                    $doc .= param("kwTh" . $tmp1);
971
                    $doc .= "</keywordThesaurus>\n";
972
                    $doc .= "</keywordSet>\n";
973
                }
974
            }
975
        }
976
    }
977

    
978
    if (hasContent($FORM::addComments)) {
979
        $doc .= "<additionalInfo>\n";
980
        $doc .= "<para>$FORM::addComments</para>\n";
981
        $doc .= "</additionalInfo>\n";
982
    }
983

    
984
    if (hasContent($FORM::useConstraints) || 
985
        hasContent($FORM::useConstraintsOther)) {
986
        $doc .= "<intellectualRights>\n";
987
        if (hasContent($FORM::useConstraints)) {
988
            $doc .= "<para>$FORM::useConstraints</para>\n";
989
        }
990
        if (hasContent($FORM::useConstraintsOther)) {
991
            $doc .= "<para>$FORM::useConstraintsOther</para>\n";
992
        }
993
        $doc .= "</intellectualRights>\n";
994
    }
995

    
996
    
997
    if (hasContent($FORM::url)) {
998
    $doc .= "<distribution>\n";
999
        $doc .= "<online>\n";
1000
    $doc .= "<url>$FORM::url</url>\n";
1001
    $doc .= "</online>\n";
1002
    $doc .= "</distribution>\n";
1003
    }
1004
    
1005
    $doc .= "<distribution>\n";
1006
    $doc .= "<offline>\n";
1007
    $doc .= "<mediumName>" . "$FORM::dataMedium   $FORM::dataMediumOther";
1008
    $doc .= "</mediumName>\n";
1009
    $doc .= "</offline>\n";
1010
    $doc .= "</distribution>\n";
1011
            
1012
    $doc .= "<coverage>\n";
1013
    $doc .= "<temporalCoverage>\n";
1014

    
1015

    
1016
    if (hasContent($FORM::endingYear)) {
1017
    $doc .= "<rangeOfDates>\n";
1018
    if (hasContent($FORM::beginningMonth)) {
1019
        my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1020
             "JUL","AUG","SEP","OCT","NOV","DEC")
1021
        [$FORM::beginningMonth - 1];
1022
        $doc .= "<beginDate>\n";
1023
        $doc .= "<calendarDate>";
1024
        $doc .= "$FORM::beginningYear-$FORM::beginningMonth-$FORM::beginningDay";
1025
        $doc .= "</calendarDate>\n";
1026
        $doc .= "</beginDate>\n";
1027
    } else {
1028
        $doc .= "<beginDate>\n";
1029
        $doc .= "<calendarDate>";
1030
        $doc .= "$FORM::beginningYear";
1031
        $doc .= "</calendarDate>\n";
1032
        $doc .= "</beginDate>\n";
1033
    }
1034

    
1035
    if (hasContent($FORM::endingMonth)) {
1036
        my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1037
             "JUL","AUG","SEP","OCT","NOV","DEC")
1038
        [$FORM::endingMonth - 1];
1039
        $doc .= "<endDate>\n";
1040
        $doc .= "<calendarDate>";
1041
        $doc .= "$FORM::endingYear-$FORM::endingMonth-$FORM::endingDay";
1042
        $doc .= "</calendarDate>\n";
1043
        $doc .= "</endDate>\n";
1044
    } else {
1045
        $doc .= "<endDate>\n";
1046
        $doc .= "<calendarDate>";
1047
        $doc .= "$FORM::endingYear";
1048
        $doc .= "</calendarDate>\n";
1049
        $doc .= "</endDate>\n";
1050
    }
1051
    $doc .= "</rangeOfDates>\n";
1052
    } else {
1053
    $doc .= "<singleDateTime>\n";
1054
    if (hasContent($FORM::beginningMonth)) {
1055
        my $month = ("JAN","FEB","MAR","APR","MAY","JUN",
1056
             "JUL","AUG","SEP","OCT","NOV","DEC")
1057
        [$FORM::beginningMonth - 1];
1058
        $doc .= "<calendarDate>";
1059
        $doc .= "$FORM::beginningYear-$FORM::beginningMonth-$FORM::beginningDay";
1060
        $doc .= "</calendarDate>\n";
1061
    } else {
1062
        $doc .= "<calendarDate>";
1063
        $doc .= "$FORM::beginningYear";
1064
        $doc .= "</calendarDate>\n";
1065
    }
1066
    $doc .= "</singleDateTime>\n";
1067
    }
1068

    
1069
    $doc .= "</temporalCoverage>\n";
1070
    
1071
    $doc .= "<geographicCoverage>\n";
1072
    $doc .= "<geographicDescription></geographicDescription>\n";
1073
    $doc .= "<boundingCoordinates>\n";
1074

    
1075
    # if the second latitude is missing, then set the second lat/long pair 
1076
    # equal to the first this makes a point appear like a rectangle 
1077
    if ($FORM::latDeg2 == 0 && $FORM::latMin2 == 0 && $FORM::latSec2 == 0) {
1078
    
1079
        $latDeg2 = $latDeg1;
1080
        $latMin2 = $latMin1;
1081
        $latSec2 = $latSec1;
1082
        $hemisphLat2 = $hemisphLat1;
1083
        $longDeg2 = $longDeg1;
1084
        $longMin2 = $longMin1;
1085
        $longSec2 = $longSec1;
1086
        $hemisphLong2 = $hemisphLong1;
1087
    }
1088
    else
1089
    {
1090
        $latDeg2 = $FORM::latDeg2;
1091
        $latMin2 = $FORM::latMin2;
1092
        $latSec2 = $FORM::latSec2;
1093
        $hemisphLat2 = $FORM::hemisphLat2;
1094
        $longDeg2 = $FORM::longDeg2;
1095
        $longMin2 = $FORM::longMin2;
1096
        $longSec2 = $FORM::longSec2;
1097
        $hemisphLong2 = $FORM::hemisphLong2;
1098
    } 
1099
    
1100
   
1101
    my $hemisph;
1102
    $hemisph = ($hemisphLong1 eq "W") ? -1 : 1;
1103
    $doc .= "<westBoundingCoordinate>";
1104
    $doc .= $hemisph * ($longDeg1 + (60*$longMin1+$longSec1)/3600);
1105
    $doc .= "</westBoundingCoordinate>\n";
1106

    
1107
    $hemisph = ($hemisphLong2 eq "W") ? -1 : 1;
1108
    $doc .= "<eastBoundingCoordinate>";
1109
    $doc .= $hemisph * ($longDeg2 + (60*$longMin2+$longSec2)/3600);
1110
    $doc .= "</eastBoundingCoordinate>\n";
1111

    
1112
    $hemisph = ($hemisphLat1 eq "S") ? -1 : 1;
1113
    $doc .= "<northBoundingCoordinate>";
1114
    $doc .= $hemisph * ($latDeg1 + (60*$latMin1+$latSec1)/3600);
1115
    $doc .= "</northBoundingCoordinate>\n";
1116

    
1117
    $hemisph = ($hemisphLat2 eq "S") ? -1 : 1;
1118
    $doc .= "<southBoundingCoordinate>";
1119
    $doc .= $hemisph * ($latDeg2 + (60*$latMin2+$latSec2)/3600);
1120
    $doc .= "</southBoundingCoordinate>\n";
1121

    
1122
    $doc .= "</boundingCoordinates>\n";
1123
    $doc .= "</geographicCoverage>\n";
1124

    
1125
    # Taxonomic coverage information
1126
    # my $foundFirstTaxKeyword = 0;
1127
    # foreach my $tmp (param()) {
1128
    #    if ($tmp =~ /keyword/) {
1129
    #        my $tmp1 = $tmp;
1130
    #        $tmp1 =~ s/keyword//; # get the index of the parameter 0, ..., 10
1131
    #        if ( $tmp1 =~ /[0-9]/ ){
1132
    #            # don't generate xml for empty keyword fields
1133
    #            if (hasContent(param($tmp))) {
1134
    #                if (hasContent(param("kwType" . $tmp1)) &&
1135
    #                   (param("kwType" . $tmp1) eq "taxonomic") ) {
1136
    #                    # Opening tags before first taxonomic. keyword.
1137
    #                    if ($foundFirstTaxKeyword == 0) {
1138
    #                        $foundFirstTaxKeyword = 1;
1139
    #                        $doc .= "<taxonomicCoverage>\n";
1140
    #                    }
1141
    #                    $doc .= "<keywtax>\n";
1142
    #                    $doc .= "<taxonkt>".param("kwTh".$tmp1)."</taxonkt>\n";
1143
    #                    $doc .= "<taxonkey>".param("keyword".$tmp1).
1144
    #                            "</taxonkey>\n";
1145
    #                    $doc .= "</keywtax>\n";
1146
    #                }
1147
    #            }
1148
    #        }
1149
    #    }
1150
    # }
1151
    # Closing tag for taxonomic coverage, if there was a tax. keyword
1152
    # if ($foundFirstTaxKeyword == 1) {
1153
    #    $doc .= "<taxoncl></taxoncl>\n";
1154
    #    $doc .= "</taxonomicCoverage>\n";
1155
    # }
1156

    
1157
    $doc .= "</coverage>\n";
1158

    
1159
    $doc .= $cont;
1160
    $doc .= $publ;
1161
    
1162
    if ((hasContent($FORM::methodTitle)) || scalar(@FORM::methodsPara) > 0) {
1163
        my $methods = "<methods><methodStep><description><section>\n";
1164
        if (hasContent($FORM::methodTitle)) {
1165
            $methods .= "<title>$FORM::methodTitle</title>\n";
1166
        }
1167
        for (my $i = 0; $i < scalar(@FORM::methodPara); $i++) {
1168
            $methods .= "<para>$FORM::methodPara[$i]</para>\n";
1169
        }
1170
        $methods .= "</section></description></methodStep></methods>\n";
1171
        $doc .= $methods;
1172
    }
1173

    
1174
    $doc .= "<access authSystem=\"knb\" order=\"denyFirst\">\n";
1175
    $doc .= "<allow>\n";
1176
    $doc .= "<principal>uid=obfsadmin,o=LTER,dc=ecoinformatics,dc=org</principal>\n";
1177
    $doc .= "<permission>all</permission>\n";
1178
    $doc .= "</allow>\n";
1179
    $doc .= "<allow>\n";
1180
    $doc .= "<principal>uid=$FORM::username,o=$FORM::organization,dc=ecoinformatics,dc=org</principal>\n";
1181
    $doc .= "<permission>all</permission>\n";
1182
    $doc .= "</allow>\n";
1183
    $doc .= "<allow>\n";
1184
    $doc .= "<principal>public</principal>\n";
1185
    $doc .= "<permission>read</permission>\n";
1186
    $doc .= "</allow>\n";
1187
    $doc .= "</access>\n";
1188
    
1189
    $doc .= "</dataset>\n</eml:eml>\n";
1190

    
1191
    return $doc;
1192
}
1193

    
1194

    
1195
################################################################################
1196
# 
1197
# send an email message notifying the moderator of a new submission 
1198
#
1199
################################################################################
1200
sub sendNotification {
1201
    my $identifier = shift;
1202
    my $mailhost = shift;
1203
    my $sender = shift;
1204
    my $recipient = shift;
1205

    
1206
    my $smtp = Net::SMTP->new($mailhost);
1207
    $smtp->mail($sender);
1208
    $smtp->to($recipient);
1209

    
1210
    my $message = <<"    ENDOFMESSAGE";
1211
    To: $recipient
1212
    From: $sender
1213
    Subject: New data submission
1214
    
1215
    Data was submitted to the data registry.  
1216
    The identifying information for the new data set is:
1217

    
1218
    Identifier: $identifier
1219
    Title: $FORM::title
1220
    Submitter: $FORM::providerGivenName $FORM::providerSurName
1221

    
1222
    Please review the submmission and grant public read access if appropriate.
1223
    Thanks
1224
    
1225
    ENDOFMESSAGE
1226
    $message =~ s/^[ \t\r\f]+//gm;
1227

    
1228
    $smtp->data($message);
1229
    $smtp->quit;
1230
}
1231

    
1232

    
1233
################################################################################
1234
# 
1235
# read the eml document and send back a form with values filled in. 
1236
#
1237
################################################################################
1238
sub modifyData {
1239
    
1240
    # create metacat instance
1241
    my $metacat;
1242
    my $docid = $FORM::docid;
1243
    my $httpMessage;
1244
    my $doc;
1245
    my $xmldoc;
1246
    my $findType;
1247
    my $parser = XML::LibXML->new();
1248
    my @fileArray;
1249
    my $pushDoc;
1250
    my $alreadyInArray;
1251
    my $node;
1252
    my $response; 
1253
    my $element;
1254
    my $tempfile;
1255

    
1256
    $metacat = Metacat->new();
1257
    if ($metacat) {
1258
        $metacat->set_options( metacatUrl => $metacatUrl );
1259
    } else {
1260
        #die "failed during metacat creation\n";
1261
        push(@errorMessages, "Failed during metacat creation.");
1262
    }
1263
    
1264
    $httpMessage = $metacat->read($docid);
1265
    $doc = $httpMessage->content();
1266
    $xmldoc = $parser->parse_string($doc);
1267

    
1268
    #$tempfile = $xslConvDir.$docid;
1269
    #push (@fileArray, $tempfile);
1270

    
1271
    if ($xmldoc eq "") {
1272
        $error ="Error in parsing the eml document";
1273
        push(@errorMessages, $error);
1274
    } else {
1275
        $findType = $xmldoc->findnodes('//dataset/identifier');
1276
        if ($findType->size() > 0) {
1277
            # This is a eml beta6 document
1278
            # Read the documents mentioned in triples also
1279
        
1280
            $findType = $xmldoc->findnodes('//dataset/triple');
1281
            if ($findType->size() > 0) {
1282
                foreach $node ($findType->get_nodelist) {
1283
                    $pushDoc = findValue($node, 'subject');
1284
            
1285
                    # If the file is already in @fileArray then do not add it 
1286
                    $alreadyInArray = 0;
1287
                    foreach $element (@fileArray) {
1288
                        $tempfile = $tmpdir."/".$pushDoc;
1289
                        if ($element eq $pushDoc) {
1290
                            $alreadyInArray = 1;
1291
                        }
1292
                    }
1293
            
1294
                    if (!$alreadyInArray) {
1295
                        $tempfile = $tmpdir."/".$pushDoc;
1296
                        $response = "";
1297
                        $response = $metacat->read($pushDoc);    
1298
                        if (! $response) {
1299
                            # could not read
1300
                            #push(@errorMessages, $response);
1301
                            push(@errorMessages, $metacat->getMessage());
1302
                            push(@errorMessages, "Failed during reading.\n");
1303
                        } else {
1304
                            my $xdoc = $response->content();
1305
                            #$tempfile = $xslConvDir.$pushDoc;
1306
                            open (TFILE,">$tempfile") || 
1307
                                die ("Cant open xml file... $tempfile\n");
1308
                            print TFILE $xdoc;
1309
                            close(TFILE);
1310
                            push (@fileArray, $tempfile);
1311
                        }
1312
                    }
1313
                }
1314
            }
1315

    
1316
            # Read the main document. 
1317

    
1318
            $tempfile = $tmpdir."/".$docid; #= $xslConvDir.$docid;
1319
            open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1320
            print TFILE $doc;
1321
            close(TFILE);
1322
        
1323
            # Transforming beta6 to eml 2
1324
            my $xslt;
1325
            my $triplesheet;
1326
            my $results;
1327
            my $stylesheet;
1328
            my $resultsheet;
1329
        
1330
            $xslt = XML::LibXSLT->new();
1331
            #$tempfile = $xslConvDir."triple_info.xsl";
1332
            $tempfile = $tmpdir."/"."triple_info.xsl";
1333
    
1334
            $triplesheet = $xslt->parse_stylesheet_file($tempfile);
1335

    
1336
            #$results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1337
            $results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1338

    
1339
            #$tempfile = $xslConvDir."emlb6toeml2.xsl";
1340
            $tempfile = $tmpdir."/"."emlb6toeml2.xsl";
1341
            $stylesheet = $xslt->parse_stylesheet_file($tempfile);
1342
            $resultsheet = $stylesheet->transform($results);
1343
        
1344
            #$tempfile = "/usr/local/apache2/htdocs/xml/test.xml";;
1345
            #open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1346
            #print TFILE $stylesheet->output_string($resultsheet);
1347
            #close(TFILE);
1348

    
1349
            getFormValuesFromEml2($resultsheet);
1350
            
1351
            # Delete the files written earlier. 
1352
            unlink @fileArray;
1353

    
1354
        } else {
1355
            getFormValuesFromEml2($xmldoc);
1356
        }
1357
    }   
1358
    
1359
    if (scalar(@errorMessages)) {
1360
        # if any errors, print them in the response template 
1361
        $$templateVars{'status'} = 'failure';
1362
        $$templateVars{'errorMessages'} = \@errorMessages;
1363
        $error = 1;
1364
        $$templateVars{'function'} = "modification";
1365
        $$templateVars{'section'} = "Modification Status";
1366
        $template->process( $responseTemplate, $templateVars); 
1367
    } else {
1368
        $$templateVars{'form'} = 're_entry';
1369
        $template->process( $entryFormTemplate, $templateVars);
1370
    }
1371
}
1372

    
1373
################################################################################
1374
# 
1375
# Parse an EML 2.0.0 file and extract the metadata into perl variables for 
1376
# processing and returning to the template processor
1377
#
1378
################################################################################
1379
sub getFormValuesFromEml2 {
1380
    
1381
    my $doc = shift;
1382
    my $results;
1383
    my $error;
1384
    my $node;
1385
    my $tempResult;
1386
    my $tempNode;
1387
    my $aoCount = 1;
1388
    my $foundDSO;
1389

    
1390
    # find out the tag <alternateIdentifier>. 
1391
    $results = $doc->findnodes('//dataset/alternateIdentifier');
1392
    if ($results->size() > 1) {
1393
        errMoreThanOne("alternateIdentifier");
1394
    } else {
1395
        foreach $node ($results->get_nodelist) {
1396
            $$templateVars{'identifier'} = findValue($node, '../alternateIdentifier');
1397
        }
1398
    }
1399

    
1400
    # find out the tag <title>. 
1401
    $results = $doc->findnodes('//dataset/title');
1402
    if ($results->size() > 1) {
1403
        errMoreThanOne("title");
1404
    } elsif ($results->size() < 1) {
1405
        $error ="Following tag not found: title. Please use Morpho to edit this document";
1406
        push(@errorMessages, $error."\n");
1407
        #if ($DEBUG == 1){ print $error;}
1408
    } else {
1409
        foreach $node ($results->get_nodelist) {
1410
            $$templateVars{'title'} = findValue($node, '../title');
1411
        }
1412
    }
1413

    
1414
    # find out the tag <creator>. 
1415
    $results = $doc->findnodes('//dataset/creator/individualName');
1416
    debug("Registry: Creators: ".$results->size());
1417
    if ($results->size() > 11) {
1418
        errMoreThanN("creator/individualName");
1419
    } else {
1420
        foreach $node ($results->get_nodelist) {
1421
            dontOccur($node, "../positionName|../onlineURL|../userId", 
1422
              "positionName, onlineURL, userId");
1423
        
1424
            dontOccur($node, "./saluation", "saluation");                
1425
        
1426
            debug("Registry: Checking a creator in loop 1...");
1427
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1428
            if($tempResult->size > 0) {
1429
                if($foundDSO == 0) {
1430
                    $foundDSO = 1;
1431
     
1432
                    debug("Registry: Recording a creator in loop 1...");
1433
                    $$templateVars{'origNamefirst0'} = findValue($node, 'givenName');
1434
                    $$templateVars{'origNamelast0'} = findValue($node, 'surName');
1435
            
1436
                    my $tempResult2 = $node->findnodes('../address');
1437
                    if ($tempResult2->size > 1) {
1438
                        errMoreThanOne("address");
1439
                    } else {
1440
                        foreach my $tempNode2 ($tempResult2->get_nodelist) {
1441
                            $$templateVars{'origDelivery'} = findValue($tempNode2, 'deliveryPoint');
1442
                            $$templateVars{'origCity'} = findValue($tempNode2, 'city');
1443
                            $$templateVars{'origState'} = findValue($tempNode2, 'administrativeArea');
1444
                            $$templateVars{'origZIP'} = findValue($tempNode2, 'postalCode');
1445
                            $$templateVars{'origCountry'} = findValue($tempNode2, 'country');
1446
                        }
1447
                    }
1448
            
1449
                    my $tempResult3 = $node->findnodes('../phone');
1450
                    if ($tempResult3->size > 2) {
1451
                        errMoreThanN("phone");
1452
                    } else {
1453
                        foreach my $tempNode2 ($tempResult3->get_nodelist) {
1454
                            if ($tempNode2->hasAttributes()) {
1455
                                my @attlist = $tempNode2->attributes();
1456
                                if ($attlist[0]->value eq "Fax") {
1457
                                    $$templateVars{'origFAX'} = $tempNode2->textContent();
1458
                                } else {
1459
                                    $$templateVars{'origPhone'} = $tempNode2->textContent();
1460
                                }
1461
                            } else {
1462
                                $$templateVars{'origPhone'} = $tempNode2->textContent();
1463
                            }
1464
                        }
1465
                    }
1466
                    $$templateVars{'origEmail'} = findValue($node, '../electronicMailAddress');
1467
                    $$templateVars{'origNameOrg'} = findValue($node, '../organizationName');
1468
                } else {
1469
                    errMoreThanN("address, phone and electronicMailAddress");
1470
                }
1471
            }
1472
        }
1473
        foreach $node ($results->get_nodelist) {
1474
            debug("Registry: Checking a creator in loop 2...");
1475
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1476
            if ($tempResult->size == 0) {
1477
                if ($foundDSO == 0) {
1478
                    debug("Registry: Recording a creator in loop 2 block A...");
1479
                    $foundDSO = 1;
1480
                    $$templateVars{'origNamefirst0'} = findValue($node, 'givenName');
1481
                    $$templateVars{'origNamelast0'} = findValue($node, 'surName');
1482
                    $$templateVars{'origNameOrg'} = findValue($node, '../organizationName');
1483
                } else {
1484
                    debug("Registry: Recording a creator in loop 2 block B...");
1485
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($node, './givenName');
1486
                    $$templateVars{"origNamelast$aoCount"} =  findValue($node, './surName');
1487
                    $$templateVars{"origRole$aoCount"} = "Originator";
1488
                    $aoCount++;
1489
                }
1490
            }
1491
        }
1492
    }
1493

    
1494
    $results = $doc->findnodes('//dataset/creator/organizationName');
1495
    my $wgroups = $doc->findnodes("//dataset/creator/organizationName[contains(text(),'(NCEAS ')]");
1496
    debug("Registry: Number Org: ".$results->size());
1497
    debug("Registry:  Number WG: ".$wgroups->size());
1498
    if ($results->size() - $wgroups->size() > 3) {
1499
        errMoreThanN("creator/organizationName");    
1500
    } else {
1501
        foreach $node ($results->get_nodelist) {
1502
            my $tempValue = findValue($node,'../organizationName');
1503
            $tempResult = $node->findnodes('../individualName');
1504
            if ($tempResult->size == 0 && $tempValue ne $organization) {
1505
                $$templateVars{'site'} = $tempValue;
1506
            }
1507
        }
1508
        if ($FORM::cfg == 'nceas') {
1509
            my @wg;
1510
            foreach $node ($results->get_nodelist) {
1511
                my $tempValue = findValue($node,'../organizationName');
1512
                $wg[scalar(@wg)] = $tempValue;
1513
            }
1514
            my $projects = getProjectList();
1515
            $$templateVars{'projects'} = $projects;
1516
            $$templateVars{'wg'} = \@wg;
1517
        }
1518
    }
1519

    
1520
    $results = $doc->findnodes('//dataset/metadataProvider');
1521
    if ($results->size() > 11) {
1522
        errMoreThanN("metadataProvider");    
1523
    } else {
1524
        foreach $node ($results->get_nodelist) {
1525
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1526
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in metadataProvider");
1527
        
1528
            $tempResult = $node->findnodes('./individualName');
1529
            if ($tempResult->size > 1) {
1530
                errMoreThanOne("metadataProvider/indvidualName");
1531
            } else {
1532
                foreach $tempNode ($tempResult->get_nodelist) {
1533
                    if ($$templateVars{'providerGivenName'} ne "") {
1534
                        $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1535
                        $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1536
                        $$templateVars{"origRole$aoCount"} = "Metadata Provider";
1537
                        $aoCount++;
1538
                    } else {
1539
                        $$templateVars{'providerGivenName'} =  findValue($tempNode, './givenName');
1540
                        $$templateVars{'providerSurName'} =  findValue($tempNode, './surName');
1541
                    }
1542
                }
1543
            }
1544
        }
1545
    }
1546

    
1547
    $results = $doc->findnodes('//dataset/associatedParty');
1548
    if ($results->size() > 10) {
1549
        errMoreThanN("associatedParty");
1550
    } else {
1551
        foreach $node ($results->get_nodelist) {
1552
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1553
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in associatedParty");
1554
       
1555
            $tempResult = $node->findnodes('./individualName');
1556
            if ($tempResult->size > 1) {
1557
                errMoreThanOne("associatedParty/indvidualName");
1558
            } else {
1559
                foreach $tempNode ($tempResult->get_nodelist) {
1560
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1561
                    $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1562
                    $$templateVars{"origRole$aoCount"} = findValue($tempNode, '../role');
1563
                    $aoCount++;           
1564
                }
1565
            }
1566
        }
1567
    }
1568

    
1569
    $results = $doc->findnodes('//dataset/publisher');
1570
    if ($results->size() > 10) {
1571
        errMoreThanN("publisher");
1572
    } else {
1573
        foreach $node ($results->get_nodelist) {
1574
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1575
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in associatedParty");
1576
       
1577
            $tempResult = $node->findnodes('./individualName');
1578
            if ($tempResult->size > 1) {
1579
                errMoreThanOne("publisher/indvidualName");
1580
            } else {
1581
                foreach $tempNode ($tempResult->get_nodelist) {
1582
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1583
                    $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1584
                    $$templateVars{"origRole$aoCount"} = "Publisher";
1585
                    $aoCount++;           
1586
                }
1587
            }
1588
        }
1589
    }
1590

    
1591
    if ($aoCount > 11) {
1592
        errMoreThanN("Additional Originators");
1593
    } 
1594

    
1595
    dontOccur($doc, "./pubDate", "pubDate");
1596
    dontOccur($doc, "./language", "language");
1597
    dontOccur($doc, "./series", "series");
1598

    
1599
    $results = $doc->findnodes('//dataset/abstract');
1600
    if ($results->size() > 1) {
1601
        errMoreThanOne("abstract");
1602
    } else {
1603
        foreach my $node ($results->get_nodelist) {
1604
            dontOccur($node, "./section", "section");
1605
            $$templateVars{'abstract'} = findValueNoChild($node, "para");
1606
        }
1607
    }
1608

    
1609
    $results = $doc->findnodes('//dataset/keywordSet');
1610
    if ($results->size() > 10) {
1611
        errMoreThanN("keywordSet");
1612
    } else {
1613
        my $count = 0;
1614
        foreach $node ($results->get_nodelist) {
1615
            $tempResult = $node->findnodes('./keyword');
1616
            if ($tempResult->size() > 1) {
1617
                errMoreThanOne("keyword");
1618
            } else {
1619
                foreach $tempNode ($tempResult->get_nodelist) {
1620
                    $$templateVars{"keyword$count"} = $tempNode->textContent();
1621
                    if ($tempNode->hasAttributes()) {
1622
                        my @attlist = $tempNode->attributes();
1623
                        $$templateVars{"kwType$count"} = $attlist[0]->value;
1624
                    }  
1625
                 } 
1626
            }
1627
            $$templateVars{"kwTh$count"} = findValue($node, "keywordThesaurus");
1628
            $count++;
1629
        }
1630
    
1631
        while ($count<11) {
1632
            $$templateVars{"kwType$count"} = "none";
1633
            $$templateVars{"kwTh$count"} = "none";
1634
            $count++;
1635
        }
1636
    }
1637

    
1638
    $results = $doc->findnodes('//dataset/additionalInfo');
1639
    if ($results->size() > 1) {
1640
        errMoreThanOne("additionalInfo");
1641
    } else {
1642
        foreach $node ($results->get_nodelist) {
1643
            dontOccur($node, "./section", "section");
1644
            $$templateVars{'addComments'} = findValueNoChild($node, "para");
1645
        }
1646
    }
1647

    
1648
    $$templateVars{'useConstraints'} = "";
1649
    $results = $doc->findnodes('//dataset/intellectualRights');
1650
    if ($results->size() > 1) {
1651
        errMoreThanOne("intellectualRights");
1652
    } else {
1653
        foreach $node ($results->get_nodelist) {
1654
            dontOccur($node, "./section", "section in intellectualRights");
1655

    
1656
            $tempResult = $node->findnodes("para");
1657
            if ($tempResult->size > 2) {
1658
                   errMoreThanN("para");
1659
            } else {
1660
                foreach $tempNode ($tempResult->get_nodelist) {
1661
                    my $childNodes = $tempNode->childNodes;
1662
                    if ($childNodes->size() > 1) {
1663
                        $error ="The tag para in intellectualRights has children which cannot be shown using the form. Please use Morpho to edit this document";    
1664
                        push(@errorMessages, $error);
1665
                        #if ($DEBUG == 1){ print $error."\n";}
1666
                    } else {
1667
                        #print $tempNode->nodeName().":".$tempNode->textContent();
1668
                        #print "\n";
1669
                        if ($$templateVars{'useConstraints'} eq "") {
1670
                            $$templateVars{'useConstraints'} = $tempNode->textContent();
1671
                        } else {
1672
                            $$templateVars{'useConstraintsOther'} = $tempNode->textContent();
1673
                        }
1674
                    }
1675
                }
1676
            }
1677
        }
1678
    }
1679

    
1680
    $results = $doc->findnodes('//dataset/distribution/online');
1681
    if ($results->size() > 1) {
1682
        errMoreThanOne("distribution/online");
1683
    } else {
1684
        foreach my $tempNode ($results->get_nodelist){
1685
            $$templateVars{'url'} = findValue($tempNode, "url");
1686
            dontOccur($tempNode, "./connection", "/distribution/online/connection");
1687
            dontOccur($tempNode, "./connectionDefinition", "/distribution/online/connectionDefinition");
1688
        }
1689
    }
1690

    
1691
    $results = $doc->findnodes('//dataset/distribution/offline');
1692
    if ($results->size() > 1) {
1693
        errMoreThanOne("distribution/online");
1694
    } else {
1695
        foreach my $tempNode ($results->get_nodelist) {
1696
            $$templateVars{'dataMedium'} = findValue($tempNode, "mediumName");
1697
            dontOccur($tempNode, "./mediumDensity", "/distribution/offline/mediumDensity");
1698
            dontOccur($tempNode, "./mediumDensityUnits", "/distribution/offline/mediumDensityUnits");
1699
            dontOccur($tempNode, "./mediumVolume", "/distribution/offline/mediumVolume");
1700
            dontOccur($tempNode, "./mediumFormat", "/distribution/offline/mediumFormat");
1701
            dontOccur($tempNode, "./mediumNote", "/distribution/offline/mediumNote");
1702
        }
1703
    }
1704

    
1705
    dontOccur($doc, "./inline", "//dataset/distribution/inline");
1706

    
1707
    $results = $doc->findnodes('//dataset/coverage');
1708
    if ($results->size() > 1) {
1709
        errMoreThanOne("coverage");
1710
    } else {
1711
        foreach $node ($results->get_nodelist) {
1712
            dontOccur($node, "./temporalCoverage/rangeOfDates/beginDate/time|./temporalCoverage/rangeOfDates/beginDate/alternativeTimeScale|./temporalCoverage/rangeOfDates/endDate/time|./temporalCoverage/rangeOfDates/endDate/alternativeTimeScale|./taxonomicCoverage|./geographicCoverage/datasetGPolygon|./geographicCoverage/boundingCoordinates/boundingAltitudes", "temporalCoverage/rangeOfDates/beginDate/time, /temporalCoverage/rangeOfDates/beginDate/alternativeTimeScale, /temporalCoverage/rangeOfDates/endDate/time, /temporalCoverage/rangeOfDates/endDate/alternativeTimeScale, /taxonomicCoverage, /geographicCoverage/datasetGPolygon, /geographicCoverage/boundingCoordinates/boundingAltitudes");
1713

    
1714
            $tempResult = $node->findnodes('./temporalCoverage');
1715
            if ($tempResult->size > 1) {
1716
                   errMoreThanOne("temporalCoverage");
1717
            } else {
1718
                foreach $tempNode ($tempResult->get_nodelist) {
1719
                    my $x;
1720
                    my $y;
1721
                    my $z;
1722
                    my $tempdate = findValue($tempNode, "rangeOfDates/beginDate/calendarDate");
1723
                    ($x, $y, $z) = split("-", $tempdate); 
1724
                    $$templateVars{'beginningYear'} = $x;
1725
                    $$templateVars{'beginningMonth'} = $y;
1726
                    $$templateVars{'beginningDay'} = $z;
1727
    
1728
                    $tempdate = findValue($tempNode, "rangeOfDates/endDate/calendarDate");
1729
                    ($x, $y, $z) = split("-", $tempdate);
1730
                    $$templateVars{'endingYear'} = $x;
1731
                    $$templateVars{'endingMonth'} = $y;
1732
                    $$templateVars{'endingDay'} = $z;
1733
                
1734
                    $tempdate = "";
1735
                    $tempdate = findValue($tempNode, "singleDateTime/calendarDate");
1736
                    if($tempdate ne ""){
1737
                        ($x, $y, $z) = split("-", $tempdate);
1738
                        $$templateVars{'beginningYear'} = $x;
1739
                        $$templateVars{'beginningMonth'} = $y;
1740
                        $$templateVars{'beginningDay'} = $z;
1741
                    }  
1742
                }
1743
            }
1744

    
1745
            $tempResult = $node->findnodes('./geographicCoverage');
1746
            if ($tempResult->size > 1) {
1747
                errMoreThanOne("geographicCoverage");
1748
            } else {
1749
                foreach $tempNode ($tempResult->get_nodelist) {
1750
                    my $coord;
1751
                    $coord = findValue($tempNode, "boundingCoordinates/westBoundingCoordinate");
1752
                    if ($coord > 0) {
1753
                        #print "+";
1754
                        $$templateVars{'hemisphLong1'} = "E";
1755
                    } else {
1756
                        #print "-";
1757
                        eval($coord = $coord * -1);
1758
                        $$templateVars{'hemisphLong1'} = "W";
1759
                    }
1760
                    eval($$templateVars{'longDeg1'} = int($coord));
1761
                    eval($coord = ($coord - int($coord))*60);
1762
                    eval($$templateVars{'longMin1'} = int($coord));
1763
                    eval($coord = ($coord - int($coord))*60);
1764
                    eval($$templateVars{'longSec1'} = int($coord));
1765
                    
1766
                    $coord = findValue($tempNode, "boundingCoordinates/southBoundingCoordinate");
1767
                    if ($coord > 0) {
1768
                        #print "+";
1769
                        $$templateVars{'hemisphLat2'} = "N";
1770
                    } else {
1771
                        #print "-";
1772
                        eval($coord = $coord * -1);
1773
                        $$templateVars{'hemisphLat2'} = "S";
1774
                    }
1775
                    eval($$templateVars{'latDeg2'} = int($coord));
1776
                    eval($coord = ($coord - int($coord))*60);
1777
                    eval($$templateVars{'latMin2'} = int($coord));
1778
                    eval($coord = ($coord - int($coord))*60);
1779
                    eval($$templateVars{'latSec2'} = int($coord));
1780
        
1781
                    $coord = findValue($tempNode, "boundingCoordinates/northBoundingCoordinate");
1782
                    if ($coord > 0) {
1783
                        #print "+";
1784
                        $$templateVars{'hemisphLat1'} = "N";
1785
                    } else {
1786
                        #print "-";
1787
                        eval($coord = $coord * -1);
1788
                        $$templateVars{'hemisphLat1'} = "S";
1789
                    }
1790
                    eval($$templateVars{'latDeg1'} = int($coord));
1791
                    eval($coord = ($coord - int($coord))*60);
1792
                    eval($$templateVars{'latMin1'} = int($coord));
1793
                    eval($coord = ($coord - int($coord))*60);
1794
                    eval($$templateVars{'latSec1'} = int($coord));
1795
        
1796
                    $coord = findValue($tempNode, "boundingCoordinates/eastBoundingCoordinate");
1797
                    if ($coord > 0) {
1798
                        #print "+";
1799
                        $$templateVars{'hemisphLong2'} = "E";
1800
                    } else {
1801
                        #print "-";
1802
                        eval($coord = $coord * -1);
1803
                        $$templateVars{'hemisphLong2'} = "W";
1804
                    }
1805
                    eval($$templateVars{'longDeg2'} = int($coord));
1806
                    eval($coord = ($coord - int($coord))*60);
1807
                    eval($$templateVars{'longMin2'} = int($coord));
1808
                    eval($coord = ($coord - int($coord))*60);
1809
                    eval($$templateVars{'longSec2'} = int($coord));
1810
                }
1811
            }
1812
        }
1813
    }
1814
    dontOccur($doc, "./purpose", "purpose");
1815
    dontOccur($doc, "./maintenance", "maintnance");
1816

    
1817
    $results = $doc->findnodes('//dataset/contact/individualName');
1818
    if ($results->size() > 1) {
1819
        errMoreThanOne("contact/individualName");
1820
    } else {
1821
        foreach $node ($results->get_nodelist) {
1822
            dontOccur($node, "../positionName|../onlineURL|../userId", 
1823
              "positionName, onlineURL, userId in contact tag");
1824
            dontOccur($node, "./saluation", "saluation in contact tag");                
1825
        
1826
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1827
            if ($tempResult->size > 0) {
1828
                $$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
1829
                $$templateVars{'origNamelastContact'} = findValue($node, 'surName');
1830
    
1831
                my $tempResult2 = $node->findnodes('../address');
1832
                if ($tempResult2->size > 1) {
1833
                    errMoreThanOne("address");
1834
                } else {
1835
                    foreach my $tempNode2 ($tempResult2->get_nodelist) {
1836
                        $$templateVars{'origDeliveryContact'} = findValue($tempNode2, 'deliveryPoint');
1837
                        $$templateVars{'origCityContact'} = findValue($tempNode2, 'city');
1838
                        $$templateVars{'origStateContact'} = findValue($tempNode2, 'administrativeArea');
1839
                        $$templateVars{'origZIPContact'} = findValue($tempNode2, 'postalCode');
1840
                        $$templateVars{'origCountryContact'} = findValue($tempNode2, 'country');
1841
                    }
1842
                }
1843
            
1844
                my $tempResult3 = $node->findnodes('../phone');
1845
                if ($tempResult3->size > 2) {
1846
                    errMoreThanN("phone");
1847
                } else {
1848
                    foreach my $tempNode2 ($tempResult3->get_nodelist) {
1849
                        if ($tempNode2->hasAttributes()) {
1850
                            my @attlist = $tempNode2->attributes();
1851
                            if ($attlist[0]->value eq "Fax") {
1852
                                $$templateVars{'origFAXContact'} = $tempNode2->textContent();
1853
                            } else {
1854
                                $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
1855
                            }
1856
                        } else {
1857
                            $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
1858
                        }
1859
                    }
1860
                }
1861
                $$templateVars{'origEmailContact'} = findValue($node, '../electronicMailAddress');
1862
                $$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
1863
            } else {
1864
                $$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
1865
                $$templateVars{'origNamelastContact'} = findValue($node, 'surName');
1866
                $$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
1867
            }
1868
        }
1869
    }
1870
    
1871
    $results = $doc->findnodes('//dataset/methods/methodStep/description/section');
1872
    debug("Registry: Number methods: ".$results->size());
1873
    if ($results->size() > 1) {
1874
        errMoreThanN("methods/methodStep/description/section");    
1875
    } else {
1876
        dontOccur($doc, "//methodStep/citation", "methodStep/citation");
1877
        dontOccur($doc, "//methodStep/protocol", "methodStep/protocol");
1878
        dontOccur($doc, "//methodStep/instrumentation", "methodStep/instrumentation");
1879
        dontOccur($doc, "//methodStep/software", "methodStep/software");
1880
        dontOccur($doc, "//methodStep/subStep", "methodStep/subStep");
1881
        dontOccur($doc, "//methodStep/dataSource", "methodStep/dataSource");
1882
        dontOccur($doc, "//methods/sampling", "methods/sampling");
1883
        dontOccur($doc, "//methods/qualityControl", "methods/qualityControl");
1884

    
1885
        my @methodPara;
1886
        foreach $node ($results->get_nodelist) {
1887
            my @children = $node->childNodes;
1888
            for (my $i = 0; $i < scalar(@children); $i++) {
1889
                debug("Registry: Method child loop ($i)");
1890
                my $child = $children[$i];
1891
                if ($child->nodeName eq 'title') {
1892
                    my $title = $child->textContent();
1893
                    debug("Registry: Method title ($title)");
1894
                    $$templateVars{'methodTitle'} = $title;
1895
                } elsif ($child->nodeName eq 'para') {
1896
                    my $para = $child->textContent();
1897
                    debug("Registry: Method para ($para)");
1898
                    $methodPara[scalar(@methodPara)] = $para;
1899
                }
1900
            }
1901
        }
1902
        if (scalar(@methodPara) > 0) {
1903
            $$templateVars{'methodPara'} = \@methodPara;
1904
        }
1905
    }
1906

    
1907
    dontOccur($doc, "./pubPlace", "pubPlace");
1908
    dontOccur($doc, "./project", "project");
1909
    
1910
    dontOccur($doc, "./dataTable", "dataTable");
1911
    dontOccur($doc, "./spatialRaster", "spatialRaster");
1912
    dontOccur($doc, "./spatialVector", "spatialVector");
1913
    dontOccur($doc, "./storedProcedure", "storedProcedure");
1914
    dontOccur($doc, "./view", "view");
1915
    dontOccur($doc, "./otherEntity", "otherEntity");
1916
    dontOccur($doc, "./references", "references");
1917
    
1918
    dontOccur($doc, "//citation", "citation");
1919
    dontOccur($doc, "//software", "software");
1920
    dontOccur($doc, "//protocol", "protocol");
1921
    dontOccur($doc, "//additionalMetadata", "additionalMetadata");    
1922
}
1923

    
1924
################################################################################
1925
# 
1926
# Delete the eml file that has been requested for deletion. 
1927
#
1928
################################################################################
1929
sub deleteData {
1930
    my $deleteAll = shift;
1931
    
1932
    # create metacat instance
1933
    my $metacat;
1934
    my $docid = $FORM::docid;
1935
    
1936
    $metacat = Metacat->new();
1937
    if ($metacat) {
1938
        $metacat->set_options( metacatUrl => $metacatUrl );
1939
    } else {
1940
        #die "failed during metacat creation\n";
1941
        push(@errorMessages, "Failed during metacat creation.");
1942
    }
1943

    
1944
    # Login to metacat
1945
    my $userDN = $FORM::username;
1946
    my $userOrg = $FORM::organization;
1947
    my $userPass = $FORM::password;
1948
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
1949
    
1950
    my $errorMessage = "";
1951
    my $response = $metacat->login($dname, $userPass);
1952

    
1953
    if (! $response) {
1954
    # Could not login
1955
        push(@errorMessages, $metacat->getMessage());
1956
        push(@errorMessages, "Failed during login.\n");
1957

    
1958
    } else {
1959
    #Able to login - try to delete the file    
1960

    
1961
    my $parser;
1962
    my @fileArray;
1963
    my $httpMessage;
1964
    my $xmldoc;
1965
    my $doc;
1966
    my $pushDoc;
1967
    my $alreadyInArray;
1968
    my $findType;
1969
        my $node;
1970
    my $response; 
1971
    my $element;
1972

    
1973
    push (@fileArray, $docid);
1974
    $parser = XML::LibXML->new();
1975

    
1976
        $httpMessage = $metacat->read($docid);
1977
    $doc = $httpMessage->content();    
1978
    $xmldoc = $parser->parse_string($doc);
1979

    
1980
    if ($xmldoc eq "") {
1981
        $error ="Error in parsing the eml document";
1982
        push(@errorMessages, $error);
1983
    } else {
1984

    
1985
        $findType = $xmldoc->findnodes('//dataset/identifier');
1986
        if($findType->size() > 0){
1987
        # This is a eml beta6 document
1988
        # Delete the documents mentioned in triples also
1989
        
1990
        $findType = $xmldoc->findnodes('//dataset/triple');
1991
        if($findType->size() > 0){
1992
            foreach $node ($findType->get_nodelist){
1993
            $pushDoc = findValue($node, 'subject');
1994
            
1995
            # If the file is already in the @fileArray then do not add it 
1996
            $alreadyInArray = 0;
1997
            foreach $element (@fileArray){
1998
                if($element eq $pushDoc){
1999
                $alreadyInArray = 1;
2000
                }
2001
            }
2002
            
2003
            if(!$alreadyInArray){
2004
                # If not already in array then delete the file. 
2005
                push (@fileArray, $pushDoc);
2006
                $response = $metacat->delete($pushDoc);
2007
                
2008
                if (! $response) {
2009
                # Could not delete
2010
                #push(@errorMessages, $response);
2011
                push(@errorMessages, $metacat->getMessage());
2012
                push(@errorMessages, "Failed during deleting $pushDoc. Please check if you are authorized to delete this document.\n");
2013
                }
2014
            }
2015
            }
2016
        }
2017
        }
2018
    }
2019
    
2020
    # Delete the main document. 
2021
    if($deleteAll){
2022
        $response = $metacat->delete($docid);  
2023
        if (! $response) {
2024
        # Could not delete
2025
        #push(@errorMessages, $response);
2026
        push(@errorMessages, $metacat->getMessage());
2027
        push(@errorMessages, "Failed during deleting $docid. Please check if you are authorized to delete this document.\n");
2028
        }
2029
    }
2030
    }
2031
    
2032
    if (scalar(@errorMessages)) {
2033
    # If any errors, print them in the response template 
2034
    $$templateVars{'status'} = 'failure';
2035
    $$templateVars{'errorMessages'} = \@errorMessages;
2036
    $error = 1;
2037
    }
2038
    
2039
    # Process the response template
2040
    if($deleteAll){
2041

    
2042
    $$templateVars{'function'} = "deleted";
2043
    $$templateVars{'section'} = "Deletion Status";
2044
    $template->process( $responseTemplate, $templateVars);
2045
    }
2046
}
2047

    
2048

    
2049
################################################################################
2050
# 
2051
# Do data validation and send the data to confirm data template.
2052
#
2053
################################################################################
2054
sub toConfirmData{
2055
    # Check if any invalid parameters
2056
 
2057
    my $invalidParams;
2058
    if (! $error) {
2059
    $invalidParams = validateParameters(0);
2060
    if (scalar(@$invalidParams)) {
2061
        $$templateVars{'status'} = 'failure';
2062
        $$templateVars{'invalidParams'} = $invalidParams;
2063
        $error = 1;
2064
    }
2065
    }
2066

    
2067
    if (! $error) {
2068
    # If no errors, then print out data in confirm Data template
2069

    
2070
    $$templateVars{'providerGivenName'} = $FORM::providerGivenName;
2071
    $$templateVars{'providerSurName'} = $FORM::providerSurName;
2072
    if($FORM::site eq "Select your station here."){
2073
        $$templateVars{'site'} = "";
2074
    }else{
2075
        $$templateVars{'site'} = $FORM::site;
2076
    }
2077
    if($FORM::cfg eq "nceas"){
2078
        $$templateVars{'wg'} = \@FORM::wg;
2079
    }
2080
    $$templateVars{'identifier'} = $FORM::identifier;
2081
    $$templateVars{'title'} = $FORM::title;
2082
    $$templateVars{'origNamefirst0'} = $FORM::origNamefirst0;
2083
    $$templateVars{'origNamelast0'} = $FORM::origNamelast0;
2084
    $$templateVars{'origNameOrg'} = $FORM::origNameOrg;
2085
    # $$templateVars{'origRole0'} = $FORM::origRole0;
2086
    $$templateVars{'origDelivery'} = $FORM::origDelivery;
2087
    $$templateVars{'origCity'} = $FORM::origCity;
2088
    if($FORM::origState eq "Select State Here."){
2089
        $$templateVars{'origState'} = "";
2090
    }else{
2091
        $$templateVars{'origState'} = $FORM::origState;
2092
    }
2093
    $$templateVars{'origStateOther'} = $FORM::origStateOther;
2094
    $$templateVars{'origZIP'} = $FORM::origZIP;
2095
    $$templateVars{'origCountry'} = $FORM::origCountry;
2096
    $$templateVars{'origPhone'} = $FORM::origPhone;
2097
    $$templateVars{'origFAX'} = $FORM::origFAX;
2098
    $$templateVars{'origEmail'} = $FORM::origEmail;
2099
    $$templateVars{'useOrigAddress'} = $FORM::useOrigAddress;
2100
    if($FORM::useOrigAddress eq "on"){
2101
        $$templateVars{'origNamefirstContact'} = $FORM::origNamefirst0;
2102
        $$templateVars{'origNamelastContact'} = $FORM::origNamelast0;
2103
        $$templateVars{'origNameOrgContact'} = $FORM::origNameOrg;
2104
        $$templateVars{'origDeliveryContact'} = $FORM::origDelivery; 
2105
        $$templateVars{'origCityContact'} = $FORM::origCity;
2106
        if($FORM::origState eq "Select State Here."){
2107
        $$templateVars{'origStateContact'} = "";
2108
        }else{
2109
        $$templateVars{'origStateContact'} = $FORM::origState;
2110
        }
2111
        $$templateVars{'origStateOtherContact'} = $FORM::origStateOther;
2112
        $$templateVars{'origZIPContact'} = $FORM::origZIP;
2113
        $$templateVars{'origCountryContact'} = $FORM::origCountry;
2114
        $$templateVars{'origPhoneContact'} = $FORM::origPhone;
2115
        $$templateVars{'origFAXContact'} = $FORM::origFAX;
2116
        $$templateVars{'origEmailContact'} = $FORM::origEmail;
2117
    }else{
2118
        $$templateVars{'origNamefirstContact'} = $FORM::origNamefirstContact;
2119
        $$templateVars{'origNamelastContact'} = $FORM::origNamelastContact;
2120
        $$templateVars{'origNameOrgContact'} = $FORM::origNameOrgContact;
2121
        $$templateVars{'origDeliveryContact'} = $FORM::origDeliveryContact; 
2122
        $$templateVars{'origCityContact'} = $FORM::origCityContact;
2123
        if($FORM::origStateContact eq "Select State Here."){
2124
        $$templateVars{'origStateContact'} = "";
2125
        }else{
2126
        $$templateVars{'origStateContact'} = $FORM::origStateContact;
2127
        }
2128
        $$templateVars{'origStateOtherContact'} = $FORM::origStateOtherContact;
2129
        $$templateVars{'origZIPContact'} = $FORM::origZIPContact;
2130
        $$templateVars{'origCountryContact'} = $FORM::origCountryContact;
2131
        $$templateVars{'origPhoneContact'} = $FORM::origPhoneContact;
2132
        $$templateVars{'origFAXContact'} = $FORM::origFAXContact;
2133
        $$templateVars{'origEmailContact'} = $FORM::origEmailContact;    
2134
    }
2135
    $$templateVars{'origNamefirst1'} = $FORM::origNamefirst1;
2136
    $$templateVars{'origNamelast1'} = $FORM::origNamelast1;
2137
    if($FORM::origNamefirst1 eq "" && $FORM::origNamelast1 eq ""){
2138
        $$templateVars{'origRole1'} = "";
2139
    }else{
2140
        $$templateVars{'origRole1'} = $FORM::origRole1;
2141
    }
2142
    $$templateVars{'origNamefirst2'} = $FORM::origNamefirst2;
2143
    $$templateVars{'origNamelast2'} = $FORM::origNamelast2;
2144
    if($FORM::origNamefirst2 eq "" && $FORM::origNamelast2 eq ""){
2145
        $$templateVars{'origRole2'} = "";
2146
    }else{
2147
        $$templateVars{'origRole2'} = $FORM::origRole2;
2148
    }
2149
    $$templateVars{'origNamefirst3'} = $FORM::origNamefirst3;
2150
    $$templateVars{'origNamelast3'} = $FORM::origNamelast3;
2151
    if($FORM::origNamefirst3 eq "" && $FORM::origNamelast3 eq ""){
2152
        $$templateVars{'origRole3'} = "";
2153
    }else{
2154
        $$templateVars{'origRole3'} = $FORM::origRole3;
2155
    }
2156
    $$templateVars{'origNamefirst4'} = $FORM::origNamefirst4;
2157
    $$templateVars{'origNamelast4'} = $FORM::origNamelast4;
2158
    if($FORM::origNamefirst4 eq "" && $FORM::origNamelast4 eq ""){
2159
        $$templateVars{'origRole4'} = "";
2160
    }else{
2161
        $$templateVars{'origRole4'} = $FORM::origRole4;
2162
    }
2163
    $$templateVars{'origNamefirst5'} = $FORM::origNamefirst5;
2164
    $$templateVars{'origNamelast5'} = $FORM::origNamelast5;
2165
    if($FORM::origNamefirst5 eq "" && $FORM::origNamelast5 eq ""){
2166
        $$templateVars{'origRole5'} = "";
2167
    }else{
2168
        $$templateVars{'origRole5'} = $FORM::origRole5;
2169
    }
2170
    $$templateVars{'origNamefirst6'} = $FORM::origNamefirst6;
2171
    $$templateVars{'origNamelast6'} = $FORM::origNamelast6;
2172
    if($FORM::origNamefirst6 eq "" && $FORM::origNamelast6 eq ""){
2173
        $$templateVars{'origRole6'} = "";
2174
    }else{
2175
        $$templateVars{'origRole6'} = $FORM::origRole6;
2176
    }
2177
    $$templateVars{'origNamefirst7'} = $FORM::origNamefirst7;
2178
    $$templateVars{'origNamelast7'} = $FORM::origNamelast7;
2179
    if($FORM::origNamefirst7 eq "" && $FORM::origNamelast7 eq ""){
2180
        $$templateVars{'origRole7'} = "";
2181
    }else{
2182
        $$templateVars{'origRole7'} = $FORM::origRole7;
2183
    }
2184
    $$templateVars{'origNamefirst8'} = $FORM::origNamefirst8;
2185
    $$templateVars{'origNamelast8'} = $FORM::origNamelast8;
2186
    if($FORM::origNamefirst8 eq "" && $FORM::origNamelast8 eq ""){
2187
        $$templateVars{'origRole8'} = "";
2188
    }else{
2189
        $$templateVars{'origRole8'} = $FORM::origRole8;
2190
    }
2191
    $$templateVars{'origNamefirst9'} = $FORM::origNamefirst9;
2192
    $$templateVars{'origNamelast9'} = $FORM::origNamelast9;
2193
    if($FORM::origNamefirst9 eq "" && $FORM::origNamelast9 eq ""){
2194
        $$templateVars{'origRole9'} = "";
2195
    }else{
2196
        $$templateVars{'origRole9'} = $FORM::origRole9;
2197
    }
2198
    $$templateVars{'origNamefirst10'} = $FORM::origNamefirst10;
2199
    $$templateVars{'origNamelast10'} = $FORM::origNamelast10;
2200
    if($FORM::origNamefirst10 eq "" && $FORM::origNamelast10 eq ""){
2201
        $$templateVars{'origRole10'} = "";
2202
    }else{
2203
        $$templateVars{'origRole10'} = $FORM::origRole10;
2204
    }
2205
    $$templateVars{'abstract'} = $FORM::abstract;
2206
    $$templateVars{'keyword0'} = $FORM::keyword0;
2207
    $$templateVars{'kwType0'} = $FORM::kwType0;
2208
    $$templateVars{'kwTh0'} = $FORM::kwTh0;
2209
    $$templateVars{'kwType1'} = $FORM::kwType1;
2210
    $$templateVars{'keyword1'} = $FORM::keyword1;
2211
    $$templateVars{'kwTh1'} = $FORM::kwTh1;
2212
    $$templateVars{'kwType2'} = $FORM::kwType2;
2213
    $$templateVars{'keyword2'} = $FORM::keyword2;
2214
    $$templateVars{'kwTh2'} = $FORM::kwTh2;
2215
    $$templateVars{'kwType3'} = $FORM::kwType3;
2216
    $$templateVars{'keyword3'} = $FORM::keyword3;
2217
    $$templateVars{'kwTh3'} = $FORM::kwTh3;
2218
    $$templateVars{'kwType4'} = $FORM::kwType4;
2219
    $$templateVars{'keyword4'} = $FORM::keyword4;
2220
    $$templateVars{'kwTh4'} = $FORM::kwTh4;
2221
    $$templateVars{'kwType5'} = $FORM::kwType5;
2222
    $$templateVars{'keyword5'} = $FORM::keyword5;
2223
    $$templateVars{'kwTh5'} = $FORM::kwTh5;
2224
    $$templateVars{'kwType6'} = $FORM::kwType6;
2225
    $$templateVars{'keyword6'} = $FORM::keyword6;
2226
    $$templateVars{'kwTh6'} = $FORM::kwTh6;
2227
    $$templateVars{'kwType7'} = $FORM::kwType7;
2228
    $$templateVars{'keyword7'} = $FORM::keyword7;
2229
    $$templateVars{'kwTh7'} = $FORM::kwTh7;
2230
    $$templateVars{'kwType8'} = $FORM::kwType8;
2231
    $$templateVars{'keyword8'} = $FORM::keyword8;
2232
    $$templateVars{'kwTh8'} = $FORM::kwTh8;
2233
    $$templateVars{'kwType9'} = $FORM::kwType9;
2234
    $$templateVars{'keyword9'} = $FORM::keyword9;
2235
    $$templateVars{'kwTh9'} = $FORM::kwTh9;
2236
    $$templateVars{'addComments'} = $FORM::addComments;
2237
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2238
    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2239
    $$templateVars{'url'} = $FORM::url;
2240
    if($FORM::dataMedium eq "Select type of medium here."){
2241
        $$templateVars{'dataMedium'} = "";
2242
    }else{
2243
        $$templateVars{'dataMedium'} = $FORM::dataMedium;
2244
    }    
2245
    $$templateVars{'dataMediumOther'} = $FORM::dataMediumOther;
2246
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2247
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2248
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2249
    $$templateVars{'endingYear'} = $FORM::endingYear;
2250
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2251
    $$templateVars{'endingDay'} = $FORM::endingDay;
2252
    $$templateVars{'useSiteCoord'} = $FORM::useSiteCoord;
2253
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2254
    $$templateVars{'latMin1'} = $FORM::latMin1;
2255
    $$templateVars{'latSec1'} = $FORM::latSec1;
2256
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2257
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2258
    $$templateVars{'longMin1'} = $FORM::longMin1;
2259
    $$templateVars{'longSec1'} = $FORM::longSec1;
2260
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2261
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2262
    $$templateVars{'latMin2'} = $FORM::latMin2;
2263
    $$templateVars{'latSec2'} = $FORM::latSec2;
2264
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2265
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2266
    $$templateVars{'longMin2'} = $FORM::longMin2;
2267
    $$templateVars{'longSec2'} = $FORM::longSec2;
2268
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2269
    $$templateVars{'methodTitle'} = $FORM::methodTitle;
2270
    $$templateVars{'methodPara'} = \@FORM::methodPara;
2271
    $$templateVars{'docid'} = $FORM::docid;
2272

    
2273
    $$templateVars{'section'} = "Confirm Data";
2274
    $template->process( $confirmDataTemplate, $templateVars);
2275

    
2276
    } else{    
2277
    # Errors from validation function. print the errors out using the response template
2278
    if (scalar(@errorMessages)) {
2279
        $$templateVars{'status'} = 'failure';
2280
        $$templateVars{'errorMessages'} = \@errorMessages;
2281
        $error = 1;
2282
    }
2283
        # Create our HTML response and send it back
2284
    $$templateVars{'function'} = "submitted";
2285
    $$templateVars{'section'} = "Submission Status";
2286
    $template->process( $responseTemplate, $templateVars);
2287
    }
2288
}
2289

    
2290

    
2291
################################################################################
2292
# 
2293
# From confirm Data template - user wants to make some changes.
2294
#
2295
################################################################################
2296
sub confirmDataToReEntryData{
2297
    my @sortedSites;
2298
    foreach my $site (sort @sitelist) {
2299
        push(@sortedSites, $site);
2300
    }
2301

    
2302
    $$templateVars{'siteList'} = \@sortedSites;
2303
    $$templateVars{'section'} = "Re-Entry Form";
2304

    
2305
    $$templateVars{'providerGivenName'} = $FORM::providerGivenName;
2306
    $$templateVars{'providerSurName'} = $FORM::providerSurName;
2307
    $$templateVars{'site'} = $FORM::site;
2308
    if ($FORM::cfg eq "nceas") {
2309
        my $projects = getProjectList();
2310
        $$templateVars{'projects'} = $projects;
2311
        $$templateVars{'wg'} = \@FORM::wg;
2312
    }
2313
    $$templateVars{'identifier'} = $FORM::identifier;
2314
    $$templateVars{'title'} = $FORM::title;
2315
    $$templateVars{'origNamefirst0'} = $FORM::origNamefirst0;
2316
    $$templateVars{'origNamelast0'} = $FORM::origNamelast0;
2317
    $$templateVars{'origNameOrg'} = $FORM::origNameOrg;
2318
 #   $$templateVars{'origRole0'} = $FORM::origRole0;
2319
    $$templateVars{'origDelivery'} = $FORM::origDelivery;
2320
    $$templateVars{'origCity'} = $FORM::origCity;
2321
    $$templateVars{'origState'} = $FORM::origState;
2322
    $$templateVars{'origStateOther'} = $FORM::origStateOther;
2323
    $$templateVars{'origZIP'} = $FORM::origZIP;
2324
    $$templateVars{'origCountry'} = $FORM::origCountry;
2325
    $$templateVars{'origPhone'} = $FORM::origPhone;
2326
    $$templateVars{'origFAX'} = $FORM::origFAX;
2327
    $$templateVars{'origEmail'} = $FORM::origEmail;
2328
    if ($FORM::useSiteCoord ne "") {
2329
        $$templateVars{'useOrigAddress'} = "CHECKED";
2330
    }else{
2331
        $$templateVars{'useOrigAddress'} = $FORM::useOrigAddress;
2332
    }
2333
    $$templateVars{'origNamefirstContact'} = $FORM::origNamefirstContact;
2334
    $$templateVars{'origNamelastContact'} = $FORM::origNamelastContact;
2335
    $$templateVars{'origNameOrgContact'} = $FORM::origNameOrgContact;
2336
    $$templateVars{'origDeliveryContact'} = $FORM::origDeliveryContact; 
2337
    $$templateVars{'origCityContact'} = $FORM::origCityContact;
2338
    $$templateVars{'origStateContact'} = $FORM::origStateContact;
2339
    $$templateVars{'origStateOtherContact'} = $FORM::origStateOtherContact;
2340
    $$templateVars{'origZIPContact'} = $FORM::origZIPContact;
2341
    $$templateVars{'origCountryContact'} = $FORM::origCountryContact;
2342
    $$templateVars{'origPhoneContact'} = $FORM::origPhoneContact;
2343
    $$templateVars{'origFAXContact'} = $FORM::origFAXContact;
2344
    $$templateVars{'origEmailContact'} = $FORM::origEmailContact;    
2345
    $$templateVars{'origNamefirst1'} = $FORM::origNamefirst1;
2346
    $$templateVars{'origNamelast1'} = $FORM::origNamelast1;
2347
    $$templateVars{'origRole1'} = $FORM::origRole1;
2348
    $$templateVars{'origNamefirst2'} = $FORM::origNamefirst2;
2349
    $$templateVars{'origNamelast2'} = $FORM::origNamelast2;
2350
    $$templateVars{'origRole2'} = $FORM::origRole2;
2351
    $$templateVars{'origNamefirst3'} = $FORM::origNamefirst3;
2352
    $$templateVars{'origNamelast3'} = $FORM::origNamelast3;
2353
    $$templateVars{'origRole3'} = $FORM::origRole3;
2354
    $$templateVars{'origNamefirst4'} = $FORM::origNamefirst4;
2355
    $$templateVars{'origNamelast4'} = $FORM::origNamelast4;
2356
    $$templateVars{'origRole4'} = $FORM::origRole4;
2357
    $$templateVars{'origNamefirst5'} = $FORM::origNamefirst5;
2358
    $$templateVars{'origNamelast5'} = $FORM::origNamelast5;
2359
    $$templateVars{'origRole5'} = $FORM::origRole5;
2360
    $$templateVars{'origNamefirst6'} = $FORM::origNamefirst6;
2361
    $$templateVars{'origNamelast6'} = $FORM::origNamelast6;
2362
    $$templateVars{'origRole6'} = $FORM::origRole6;
2363
    $$templateVars{'origNamefirst7'} = $FORM::origNamefirst7;
2364
    $$templateVars{'origNamelast7'} = $FORM::origNamelast7;
2365
    $$templateVars{'origRole7'} = $FORM::origRole7;
2366
    $$templateVars{'origNamefirst8'} = $FORM::origNamefirst8;
2367
    $$templateVars{'origNamelast8'} = $FORM::origNamelast8;
2368
    $$templateVars{'origRole8'} = $FORM::origRole8;
2369
    $$templateVars{'origNamefirst9'} = $FORM::origNamefirst9;
2370
    $$templateVars{'origNamelast9'} = $FORM::origNamelast9;
2371
    $$templateVars{'origRole9'} = $FORM::origRole9;
2372
    $$templateVars{'origNamefirst10'} = $FORM::origNamefirst10;
2373
    $$templateVars{'origNamelast10'} = $FORM::origNamelast10;
2374
    $$templateVars{'origRole10'} = $FORM::origRole10;
2375
    $$templateVars{'abstract'} = $FORM::abstract;
2376
    $$templateVars{'keyword0'} = $FORM::keyword0;
2377
    $$templateVars{'kwType0'} = $FORM::kwType0;
2378
    $$templateVars{'kwTh0'} = $FORM::kwTh0;
2379
    $$templateVars{'kwType1'} = $FORM::kwType1;
2380
    $$templateVars{'keyword1'} = $FORM::keyword1;
2381
    $$templateVars{'kwTh1'} = $FORM::kwTh1;
2382
    $$templateVars{'kwType2'} = $FORM::kwType2;
2383
    $$templateVars{'keyword2'} = $FORM::keyword2;
2384
    $$templateVars{'kwTh2'} = $FORM::kwTh2;
2385
    $$templateVars{'kwType3'} = $FORM::kwType3;
2386
    $$templateVars{'keyword3'} = $FORM::keyword3;
2387
    $$templateVars{'kwTh3'} = $FORM::kwTh3;
2388
    $$templateVars{'kwType4'} = $FORM::kwType4;
2389
    $$templateVars{'keyword4'} = $FORM::keyword4;
2390
    $$templateVars{'kwTh4'} = $FORM::kwTh4;
2391
    $$templateVars{'kwType5'} = $FORM::kwType5;
2392
    $$templateVars{'keyword5'} = $FORM::keyword5;
2393
    $$templateVars{'kwTh5'} = $FORM::kwTh5;
2394
    $$templateVars{'kwType6'} = $FORM::kwType6;
2395
    $$templateVars{'keyword6'} = $FORM::keyword6;
2396
    $$templateVars{'kwTh6'} = $FORM::kwTh6;
2397
    $$templateVars{'kwType7'} = $FORM::kwType7;
2398
    $$templateVars{'keyword7'} = $FORM::keyword7;
2399
    $$templateVars{'kwTh7'} = $FORM::kwTh7;
2400
    $$templateVars{'kwType8'} = $FORM::kwType8;
2401
    $$templateVars{'keyword8'} = $FORM::keyword8;
2402
    $$templateVars{'kwTh8'} = $FORM::kwTh8;
2403
    $$templateVars{'kwType9'} = $FORM::kwType9;
2404
    $$templateVars{'keyword9'} = $FORM::keyword9;
2405
    $$templateVars{'kwTh9'} = $FORM::kwTh9;
2406
    $$templateVars{'addComments'} = $FORM::addComments;
2407
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2408
    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2409
    $$templateVars{'url'} = $FORM::url;
2410
    $$templateVars{'dataMedium'} = $FORM::dataMedium;
2411
    $$templateVars{'dataMediumOther'} = $FORM::dataMediumOther;
2412
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2413
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2414
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2415
    $$templateVars{'endingYear'} = $FORM::endingYear;
2416
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2417
    $$templateVars{'endingDay'} = $FORM::endingDay;
2418
    if($FORM::useSiteCoord ne ""){
2419
    $$templateVars{'useSiteCoord'} = "CHECKED";
2420
    }else{
2421
    $$templateVars{'useSiteCoord'} = "";
2422
    }
2423
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2424
    $$templateVars{'latMin1'} = $FORM::latMin1;
2425
    $$templateVars{'latSec1'} = $FORM::latSec1;
2426
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2427
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2428
    $$templateVars{'longMin1'} = $FORM::longMin1;
2429
    $$templateVars{'longSec1'} = $FORM::longSec1;
2430
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2431
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2432
    $$templateVars{'latMin2'} = $FORM::latMin2;
2433
    $$templateVars{'latSec2'} = $FORM::latSec2;
2434
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2435
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2436
    $$templateVars{'longMin2'} = $FORM::longMin2;
2437
    $$templateVars{'longSec2'} = $FORM::longSec2;
2438
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2439
    if ($FORM::cfg eq "nceas") {
2440
        $$templateVars{'methodsTitle'} = $FORM::methodsTitle;
2441
        $$templateVars{'methodsPara'} = \@FORM::methodsPara;
2442
    }
2443
    $$templateVars{'docid'} = $FORM::docid;
2444

    
2445
    $$templateVars{'form'} = 're_entry';
2446
    $template->process( $entryFormTemplate, $templateVars);
2447
}
2448

    
2449

    
2450
################################################################################
2451
# 
2452
# check if there is multiple occurence of the given tag and find its value.
2453
#
2454
################################################################################
2455

    
2456
sub findValue {
2457
    my $node = shift;
2458
    my $value = shift;
2459
    my $result;
2460
    my $tempNode;
2461

    
2462
    $result = $node->findnodes("./$value");
2463
    if ($result->size > 1) {
2464
        errMoreThanOne("$value");
2465
    } else {
2466
        foreach $tempNode ($result->get_nodelist){
2467
            #print $tempNode->nodeName().":".$tempNode->textContent();
2468
            #print "\n";
2469
            return $tempNode->textContent();
2470
        }
2471
    }
2472
}
2473

    
2474

    
2475
################################################################################
2476
# 
2477
# check if given tags has any children. if not return the value
2478
#
2479
################################################################################
2480
sub findValueNoChild {
2481
    my $node = shift;
2482
    my $value = shift;
2483
    my $tempNode;
2484
    my $childNodes;
2485
    my $result;
2486
    my $error;
2487

    
2488
    $result = $node->findnodes("./$value");
2489
    if($result->size > 1){
2490
       errMoreThanOne("$value");
2491
    } else {
2492
        foreach $tempNode ($result->get_nodelist) {
2493
            $childNodes = $tempNode->childNodes;
2494
            if ($childNodes->size() > 1) {
2495
                $error ="The tag $value has children which cannot be shown using the form. Please use Morpho to edit this document";    
2496
                push(@errorMessages, $error);
2497
                #if ($DEBUG == 1){ print $error."\n";}
2498
            } else {
2499
                #print $tempNode->nodeName().":".$tempNode->textContent();
2500
                #print "\n";
2501
                return $tempNode->textContent();
2502
            }
2503
        }
2504
    }
2505
}
2506

    
2507

    
2508
################################################################################
2509
# 
2510
# check if given tags are children of given node.
2511
#
2512
################################################################################
2513
sub dontOccur {
2514
    my $node = shift;
2515
    my $value = shift;
2516
    my $errVal = shift;
2517

    
2518
    my $result = $node->findnodes("$value");
2519
    if($result->size > 0){
2520
        $error ="One of the following tags found: $errVal. Please use Morpho to edit this document";
2521
        push(@errorMessages, $error."\n");
2522
        #if ($DEBUG == 1){ print $error;}
2523
    } 
2524
}
2525

    
2526

    
2527
################################################################################
2528
# 
2529
# print out error for more than one occurence of a given tag
2530
#
2531
################################################################################
2532
sub errMoreThanOne {
2533
    my $value = shift;
2534
    my $error ="More than one occurence of the tag $value found. Please use Morpho to edit this document";
2535
    push(@errorMessages, $error."\n");
2536
    # if ($DEBUG == 1){ print $error;}
2537
}
2538

    
2539

    
2540
################################################################################
2541
# 
2542
# print out error for more than given number of occurences of a given tag
2543
#
2544
################################################################################
2545
sub errMoreThanN {
2546
    my $value = shift;
2547
    my $error ="More occurences of the tag $value found than that can be shown in the form. Please use Morpho to edit this document";
2548
    push(@errorMessages, $error);
2549
    #if ($DEBUG == 1){ print $error."\n";}
2550
}
2551

    
2552

    
2553
################################################################################
2554
# 
2555
# convert coord to degrees, minutes and seconds form. 
2556
#
2557
################################################################################
2558
#sub convertCoord {
2559
#    my $wx = shift;
2560
#    print $deg." ".$min." ".$sec;
2561
#    print "\n";
2562
#}
2563

    
2564

    
2565
################################################################################
2566
# 
2567
# print debugging messages to stderr
2568
#
2569
################################################################################
2570
sub debug {
2571
    my $msg = shift;
2572
    
2573
    if ($debug) {
2574
        print STDERR "$msg\n";
2575
    }
2576
}
2577

    
2578
################################################################################
2579
# 
2580
# get the list of projects
2581
#
2582
################################################################################
2583
sub getProjectList {
2584
    
2585
    #use NCEAS::AdminDB;
2586

    
2587
    #my $admindb = NCEAS::AdminDB->new();
2588
    #$admindb->connect($nceas_db, $nceas_db_user, $nceas_db_password);
2589
    #my $projects = $admindb->getProjects();
2590

    
2591
    # This block is for testing only!  Remove for production use
2592
    my @row1;
2593
    $row1[0] = 6000; $row1[1] = 'Andelman'; $row1[2] = 'Sandy'; $row1[3] = 'The very long and windy path to an apparent ecological conclusion: statistics lie';
2594
    my @row2; 
2595
    $row2[0] = 7000; $row2[1] = 'Bascompte'; $row2[2] = 'Jordi'; $row2[3] = 'Postdoctoral Fellow';
2596
    my @row3; 
2597
    $row3[0] = 7001; $row3[1] = 'Hackett'; $row3[2] = 'Edward'; $row3[3] = 'Sociology rules the world';
2598
    my @row4; 
2599
    $row4[0] = 7002; $row4[1] = 'Jones'; $row4[2] = 'Matthew'; $row4[3] = 'Informatics rules the world';
2600
    my @row5; 
2601
    $row5[0] = 7003; $row5[1] = 'Schildhauer'; $row5[2] = 'Mark'; $row5[3] = 'Excel rocks my world, assuming a, b, and c';
2602
    my @row6; 
2603
    $row6[0] = 7004; $row6[1] = 'Rogers'; $row6[2] = 'Bill'; $row6[3] = 'Graduate Intern';
2604
    my @row7; 
2605
    $row7[0] = 7005; $row7[1] = 'Zedfried'; $row7[2] = 'Karl'; $row7[3] = 'A multivariate analysis of thing that go bump in the night';
2606
    my @projects;
2607
    $projects[0] = \@row1;
2608
    $projects[1] = \@row2;
2609
    $projects[2] = \@row3;
2610
    $projects[3] = \@row4;
2611
    $projects[4] = \@row5;
2612
    $projects[5] = \@row6;
2613
    $projects[6] = \@row7;
2614
    return \@projects;
2615

    
2616
    #return $projects;
2617
}