Project

General

Profile

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 18:22:24 -0800 (Tue, 23 Dec 2003) $'
8
# '$Revision: 1984 $' 
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
debug("Registry: Initialized");
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
    debug("Registry: Sending form");
226
    my @sortedSites;
227
    foreach my $site (sort @sitelist) {
228
        push(@sortedSites, $site);
229
    }
230
    
231
    if ($FORM::cfg eq 'nceas') {
232
        my $projects = getProjectList();
233
        $$templateVars{'projects'} = $projects;
234
        $$templateVars{'wg'} = \@FORM::wg;
235
    }
236

    
237
    $$templateVars{'siteList'} = \@sortedSites;
238
    $$templateVars{'section'} = "Entry Form";
239
    $$templateVars{'docid'} = "";
240
    debug("Registry: Sending form: ready to process template");
241
    $template->process( $entryFormTemplate, $templateVars);
242
    debug("Registry: Sending form: template processed");
243
    exit(0);
244
}
245

    
246
# Confirm stage has been reached. Enter the data into metacat. 
247

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

    
266
# validate the input form parameters
267
my $invalidParams;
268

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

    
278

    
279
my $metacat;
280
my $docid;
281
if (! $error) {
282
    # Parameters have been validated and Create the XML document
283

    
284
    my $xmldoc = createXMLDocument();
285

    
286
    # Write out the XML file for debugging purposes
287
    #my $testFile = $tmpdir . "/test.xml";
288

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

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

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

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

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

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

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

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

    
387
        exit(0);
388
    }
389
}
390

    
391
debug("Registry: C");
392

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

    
400
#if (! $error) {
401
#sendNotification($docid, $mailhost, $sender, $recipient);
402
#}
403

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

    
409
exit(0);
410

    
411

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

    
420
  my $errormsg = 0;
421
  my $docid = $metacat->getLastId($scope);
422

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

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

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

    
468
  return $notunique;
469
}
470

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

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

    
495
  my $docroot = "$scope.$lastid.";
496
  my $docid = $docroot . $docrev;
497
  return $docid;
498
}
499

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

    
520
  return $acl;
521
}
522

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

    
533
  my $parser = XML::LibXML->new();
534
  my $dom = $parser->parse_string($docstring);
535

    
536
  my $root = $dom->documentElement;
537
  my $name = $root->getName();
538

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

    
575
  return $dom->toString();
576
}
577

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

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

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

    
637
    if ($FORM::useSiteCoord) {
638
    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.")
639
        unless(hasContent($latDeg1) && hasContent($longDeg1));
640
    }else{
641
    push(@invalidParams, "Latitude degrees are missing.")
642
        unless hasContent($latDeg1);
643
    push(@invalidParams, "Longitude degrees are missing.")
644
        unless hasContent($longDeg1);
645
    }
646

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

    
663
    return \@invalidParams;
664
}
665

    
666
################################################################################
667
# 
668
# Validate the parameters username and password.
669
#
670
################################################################################
671
sub validateUserPass {
672
    my $userDN = $FORM::username;
673
    my $userOrg = $FORM::organization;
674
    my $userPass = $FORM::password;
675
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
676

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

    
688

    
689
################################################################################
690
# 
691
# utility function to determine if a paramter is defined and not an empty string
692
#
693
################################################################################
694
sub hasContent {
695
    my $param = shift;
696

    
697
    my $paramHasContent;
698
    if (!defined($param) || $param eq '') { 
699
        $paramHasContent = 0;
700
    } else {
701
        $paramHasContent = 1;
702
    }
703
    return $paramHasContent;
704
}
705

    
706

    
707
################################################################################
708
# 
709
# Create the XML document from the HTML form input
710
# returns the XML document as a string
711
#
712
################################################################################
713
sub createXMLDocument {
714

    
715
    my $orig  = "";
716
    my $role  = "associatedParty";
717
    my $creat = "";
718
    my $metaP = "";
719
    my $apart = "";
720
    my $cont  = "";
721
    my $publ  = "";
722
    my $dso   = "";
723
    my $gmt = gmtime($now);
724
    my $doc =  "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n";
725

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

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

    
748
    if (hasContent($FORM::origNamelast0)) {
749
    $role = "creator";
750
        $orig .= "<individualName>\n";
751
        $orig .= "<givenName>$FORM::origNamefirst0</givenName>\n";
752
        $orig .= "<surName>$FORM::origNamelast0</surName>\n";
753
        $orig .= "</individualName>\n";
754
    }
755

    
756
    if (hasContent($FORM::origNameOrg)) {
757
        $orig .= "<organizationName>$FORM::origNameOrg</organizationName>\n";
758
    }
759

    
760
    if (hasContent($FORM::origDelivery) || hasContent($FORM::origCity) ||
761
        (hasContent($FORM::origState   ) &&
762
        ($FORM::origState !~ "Select state here.")) ||
763
        hasContent($FORM::origStateOther) ||
764
        hasContent($FORM::origZIP ) || hasContent($FORM::origCountry)) {
765
        $orig .= "<address>\n";
766

    
767
        if (hasContent($FORM::origDelivery)) {
768
            $orig .= "<deliveryPoint>$FORM::origDelivery</deliveryPoint>\n";
769
        }
770
        if (hasContent($FORM::origCity)) {
771
            $orig .= "<city>$FORM::origCity</city>\n";
772
        }
773

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

    
791
    if (hasContent($FORM::origPhone)) {
792
        $orig .= "<phone>$FORM::origPhone</phone>\n";
793
    }
794
    if (hasContent($FORM::origFAX)) {
795
        $orig .= "<phone phonetype=\"Fax\">$FORM::origFAX</phone>\n";
796
    }
797
    if (hasContent($FORM::origEmail)) {
798
        $orig .= "<electronicMailAddress>$FORM::origEmail";
799
        $orig .= "</electronicMailAddress>\n";
800
    }
801
    $dso = "<$role>\n$orig</$role>\n";
802
    
803
    $creat .= $dso;
804

    
805
    if ($FORM::useOrigAddress) {
806
        # Add a contact originator like the original with a different role
807
            $cont .= "<contact>\n";
808
        $cont .= $orig;
809
        $cont .= "</contact>\n";
810
    } else {
811
        $cont .= "<contact>\n";
812

    
813
        $cont .= "<individualName>\n";
814
        $cont .= "<givenName>$FORM::origNamefirstContact</givenName>\n";
815
        $cont .= "<surName>$FORM::origNamelastContact</surName>\n";
816
        $cont .= "</individualName>\n";
817
 
818
    if (hasContent($FORM::origNameOrgContact)) {
819
        $cont .= "<organizationName>$FORM::origNameOrgContact</organizationName>\n";
820
    }
821

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

    
866
    $metaP .= "<metadataProvider>\n";
867
    $metaP .= "<individualName>\n";
868
    $metaP .= "<givenName>$FORM::providerGivenName</givenName>\n";
869
    $metaP .= "<surName>$FORM::providerSurName</surName>\n";
870
    $metaP .= "</individualName>\n";
871
    $metaP .= "</metadataProvider>\n";
872

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

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

    
931
    $creat .= "<creator>\n";
932
    $creat .= "<organizationName>$FORM::site</organizationName>\n";
933
    $creat .= "</creator>\n";
934

    
935
    $creat .= "<creator>\n";
936
    $creat .= "<organizationName>$organization</organizationName>\n";
937
    $creat .= "</creator>\n";
938

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

    
950
    $doc .= "<abstract>\n";
951
    $doc .= "<para>$FORM::abstract</para>\n";
952
    $doc .= "</abstract>\n";
953

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

    
983
    if (hasContent($FORM::addComments)) {
984
        $doc .= "<additionalInfo>\n";
985
        $doc .= "<para>$FORM::addComments</para>\n";
986
        $doc .= "</additionalInfo>\n";
987
    }
988

    
989
    if (hasContent($FORM::useConstraints) || 
990
        hasContent($FORM::useConstraintsOther)) {
991
        $doc .= "<intellectualRights>\n";
992
        if (hasContent($FORM::useConstraints)) {
993
            $doc .= "<para>$FORM::useConstraints</para>\n";
994
        }
995
        if (hasContent($FORM::useConstraintsOther)) {
996
            $doc .= "<para>$FORM::useConstraintsOther</para>\n";
997
        }
998
        $doc .= "</intellectualRights>\n";
999
    }
1000

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

    
1020

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

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

    
1074
    $doc .= "</temporalCoverage>\n";
1075
    
1076
    $doc .= "<geographicCoverage>\n";
1077
    $doc .= "<geographicDescription>$FORM::geogdesc</geographicDescription>\n";
1078
    $doc .= "<boundingCoordinates>\n";
1079

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

    
1112
    $hemisph = ($hemisphLong2 eq "W") ? -1 : 1;
1113
    $doc .= "<eastBoundingCoordinate>";
1114
    $doc .= $hemisph * ($longDeg2 + (60*$longMin2+$longSec2)/3600);
1115
    $doc .= "</eastBoundingCoordinate>\n";
1116

    
1117
    $hemisph = ($hemisphLat1 eq "S") ? -1 : 1;
1118
    $doc .= "<northBoundingCoordinate>";
1119
    $doc .= $hemisph * ($latDeg1 + (60*$latMin1+$latSec1)/3600);
1120
    $doc .= "</northBoundingCoordinate>\n";
1121

    
1122
    $hemisph = ($hemisphLat2 eq "S") ? -1 : 1;
1123
    $doc .= "<southBoundingCoordinate>";
1124
    $doc .= $hemisph * ($latDeg2 + (60*$latMin2+$latSec2)/3600);
1125
    $doc .= "</southBoundingCoordinate>\n";
1126

    
1127
    $doc .= "</boundingCoordinates>\n";
1128
    $doc .= "</geographicCoverage>\n";
1129

    
1130
    # Write out the taxonomic coverage fields
1131
    my $foundFirstTaxon = 0;
1132
    foreach my $trn (param()) {
1133
        if ($trn =~ /taxonRankName/) {
1134
            my $taxIndex = $trn;
1135
            $taxIndex =~ s/taxonRankName//; # get the index of the parameter 0, ..., 10
1136
            my $trv = "taxonRankValue".$taxIndex;
1137
            if ( $taxIndex =~ /[0-9]/ ){
1138
                if (hasContent(param($trn)) && hasContent(param($trv))) {
1139
                    if (! $foundFirstTaxon) {
1140
                        $doc .= "<taxonomicCoverage>\n";
1141
                        $foundFirstTaxon = 1;
1142
                    }
1143
                    $doc .= "<taxonomicClassification>\n";
1144
                    $doc .= "  <taxonRankName>".param($trn)."</taxonRankName>\n";
1145
                    $doc .= "  <taxonRankValue>".param($trv)."</taxonRankValue>\n";
1146
                    $doc .= "</taxonomicClassification>\n";
1147
                }
1148
            }
1149
        }
1150
    }
1151
    if ($foundFirstTaxon) {
1152
        $doc .= "</taxonomicCoverage>\n";
1153
    }
1154

    
1155
    $doc .= "</coverage>\n";
1156

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

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

    
1189
    return $doc;
1190
}
1191

    
1192

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

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

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

    
1216
    Identifier: $identifier
1217
    Title: $FORM::title
1218
    Submitter: $FORM::providerGivenName $FORM::providerSurName
1219

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

    
1226
    $smtp->data($message);
1227
    $smtp->quit;
1228
}
1229

    
1230

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

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

    
1266
    #$tempfile = $xslConvDir.$docid;
1267
    #push (@fileArray, $tempfile);
1268

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

    
1314
            # Read the main document. 
1315

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1593
    dontOccur($doc, "./pubDate", "pubDate");
1594
    dontOccur($doc, "./language", "language");
1595
    dontOccur($doc, "./series", "series");
1596

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

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

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

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

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

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

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

    
1703
    dontOccur($doc, "./inline", "//dataset/distribution/inline");
1704

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

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

    
1743
            $tempResult = $node->findnodes('./geographicCoverage');
1744
            if ($tempResult->size > 1) {
1745
                errMoreThanOne("geographicCoverage");
1746
            } else {
1747
                foreach $tempNode ($tempResult->get_nodelist) {
1748
                    my $geogdesc = findValue($tempNode, "geographicDescription");
1749
                    debug("Registry: geogdesc from xml is: $geogdesc");
1750
                    $$templateVars{'geogdesc'} = $geogdesc;
1751
                    my $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
            $tempResult = $node->findnodes('./taxonomicCoverage/taxonomicClassification');
1814
            my $taxonIndex = 0;
1815
            foreach $tempNode ($tempResult->get_nodelist) {
1816
                $taxonIndex++;
1817
                my $taxonRankName = findValue($tempNode, "taxonRankName");
1818
                my $taxonRankValue = findValue($tempNode, "taxonRankValue");
1819
                $$templateVars{"taxonRankName".$taxonIndex} = $taxonRankName;
1820
                $$templateVars{"taxonRankValue".$taxonIndex} = $taxonRankValue;
1821
            }
1822
            $$templateVars{'taxaCount'} = $taxonIndex;
1823
        }
1824
    }
1825
    dontOccur($doc, "./purpose", "purpose");
1826
    dontOccur($doc, "./maintenance", "maintnance");
1827

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

    
1896
        my @methodPara;
1897
        foreach $node ($results->get_nodelist) {
1898
            my @children = $node->childNodes;
1899
            for (my $i = 0; $i < scalar(@children); $i++) {
1900
                debug("Registry: Method child loop ($i)");
1901
                my $child = $children[$i];
1902
                if ($child->nodeName eq 'title') {
1903
                    my $title = $child->textContent();
1904
                    debug("Registry: Method title ($title)");
1905
                    $$templateVars{'methodTitle'} = $title;
1906
                } elsif ($child->nodeName eq 'para') {
1907
                    my $para = $child->textContent();
1908
                    debug("Registry: Method para ($para)");
1909
                    $methodPara[scalar(@methodPara)] = $para;
1910
                }
1911
            }
1912
        }
1913
        if (scalar(@methodPara) > 0) {
1914
            $$templateVars{'methodPara'} = \@methodPara;
1915
        }
1916
    }
1917

    
1918
    dontOccur($doc, "./pubPlace", "pubPlace");
1919
    dontOccur($doc, "./project", "project");
1920
    
1921
    dontOccur($doc, "./dataTable", "dataTable");
1922
    dontOccur($doc, "./spatialRaster", "spatialRaster");
1923
    dontOccur($doc, "./spatialVector", "spatialVector");
1924
    dontOccur($doc, "./storedProcedure", "storedProcedure");
1925
    dontOccur($doc, "./view", "view");
1926
    dontOccur($doc, "./otherEntity", "otherEntity");
1927
    dontOccur($doc, "./references", "references");
1928
    
1929
    dontOccur($doc, "//citation", "citation");
1930
    dontOccur($doc, "//software", "software");
1931
    dontOccur($doc, "//protocol", "protocol");
1932
    dontOccur($doc, "//additionalMetadata", "additionalMetadata");    
1933
}
1934

    
1935
################################################################################
1936
# 
1937
# Delete the eml file that has been requested for deletion. 
1938
#
1939
################################################################################
1940
sub deleteData {
1941
    my $deleteAll = shift;
1942
    
1943
    # create metacat instance
1944
    my $metacat;
1945
    my $docid = $FORM::docid;
1946
    
1947
    $metacat = Metacat->new();
1948
    if ($metacat) {
1949
        $metacat->set_options( metacatUrl => $metacatUrl );
1950
    } else {
1951
        #die "failed during metacat creation\n";
1952
        push(@errorMessages, "Failed during metacat creation.");
1953
    }
1954

    
1955
    # Login to metacat
1956
    my $userDN = $FORM::username;
1957
    my $userOrg = $FORM::organization;
1958
    my $userPass = $FORM::password;
1959
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
1960
    
1961
    my $errorMessage = "";
1962
    my $response = $metacat->login($dname, $userPass);
1963

    
1964
    if (! $response) {
1965
    # Could not login
1966
        push(@errorMessages, $metacat->getMessage());
1967
        push(@errorMessages, "Failed during login.\n");
1968

    
1969
    } else {
1970
    #Able to login - try to delete the file    
1971

    
1972
    my $parser;
1973
    my @fileArray;
1974
    my $httpMessage;
1975
    my $xmldoc;
1976
    my $doc;
1977
    my $pushDoc;
1978
    my $alreadyInArray;
1979
    my $findType;
1980
        my $node;
1981
    my $response; 
1982
    my $element;
1983

    
1984
    push (@fileArray, $docid);
1985
    $parser = XML::LibXML->new();
1986

    
1987
        $httpMessage = $metacat->read($docid);
1988
    $doc = $httpMessage->content();    
1989
    $xmldoc = $parser->parse_string($doc);
1990

    
1991
    if ($xmldoc eq "") {
1992
        $error ="Error in parsing the eml document";
1993
        push(@errorMessages, $error);
1994
    } else {
1995

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

    
2053
    $$templateVars{'function'} = "deleted";
2054
    $$templateVars{'section'} = "Deletion Status";
2055
    $template->process( $responseTemplate, $templateVars);
2056
    }
2057
}
2058

    
2059

    
2060
################################################################################
2061
# 
2062
# Do data validation and send the data to confirm data template.
2063
#
2064
################################################################################
2065
sub toConfirmData{
2066
    # Check if any invalid parameters
2067
 
2068
    my $invalidParams;
2069
    if (! $error) {
2070
    $invalidParams = validateParameters(0);
2071
    if (scalar(@$invalidParams)) {
2072
        $$templateVars{'status'} = 'failure';
2073
        $$templateVars{'invalidParams'} = $invalidParams;
2074
        $error = 1;
2075
    }
2076
    }
2077

    
2078
    if (! $error) {
2079
    # If no errors, then print out data in confirm Data template
2080

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

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

    
2298
    $$templateVars{'methodTitle'} = $FORM::methodTitle;
2299
    $$templateVars{'methodPara'} = \@FORM::methodPara;
2300
    $$templateVars{'docid'} = $FORM::docid;
2301

    
2302
    $$templateVars{'section'} = "Confirm Data";
2303
    $template->process( $confirmDataTemplate, $templateVars);
2304

    
2305
    } else{    
2306
    # Errors from validation function. print the errors out using the response template
2307
    if (scalar(@errorMessages)) {
2308
        $$templateVars{'status'} = 'failure';
2309
        $$templateVars{'errorMessages'} = \@errorMessages;
2310
        $error = 1;
2311
    }
2312
        # Create our HTML response and send it back
2313
    $$templateVars{'function'} = "submitted";
2314
    $$templateVars{'section'} = "Submission Status";
2315
    $template->process( $responseTemplate, $templateVars);
2316
    }
2317
}
2318

    
2319

    
2320
################################################################################
2321
# 
2322
# From confirm Data template - user wants to make some changes.
2323
#
2324
################################################################################
2325
sub confirmDataToReEntryData{
2326
    my @sortedSites;
2327
    foreach my $site (sort @sitelist) {
2328
        push(@sortedSites, $site);
2329
    }
2330

    
2331
    $$templateVars{'siteList'} = \@sortedSites;
2332
    $$templateVars{'section'} = "Re-Entry Form";
2333

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

    
2475
    $$templateVars{'form'} = 're_entry';
2476
    $template->process( $entryFormTemplate, $templateVars);
2477
}
2478

    
2479

    
2480
################################################################################
2481
# 
2482
# check if there is multiple occurence of the given tag and find its value.
2483
#
2484
################################################################################
2485

    
2486
sub findValue {
2487
    my $node = shift;
2488
    my $value = shift;
2489
    my $result;
2490
    my $tempNode;
2491

    
2492
    $result = $node->findnodes("./$value");
2493
    if ($result->size > 1) {
2494
        errMoreThanOne("$value");
2495
    } else {
2496
        foreach $tempNode ($result->get_nodelist){
2497
            #print $tempNode->nodeName().":".$tempNode->textContent();
2498
            #print "\n";
2499
            return $tempNode->textContent();
2500
        }
2501
    }
2502
}
2503

    
2504

    
2505
################################################################################
2506
# 
2507
# check if given tags has any children. if not return the value
2508
#
2509
################################################################################
2510
sub findValueNoChild {
2511
    my $node = shift;
2512
    my $value = shift;
2513
    my $tempNode;
2514
    my $childNodes;
2515
    my $result;
2516
    my $error;
2517

    
2518
    $result = $node->findnodes("./$value");
2519
    if($result->size > 1){
2520
       errMoreThanOne("$value");
2521
    } else {
2522
        foreach $tempNode ($result->get_nodelist) {
2523
            $childNodes = $tempNode->childNodes;
2524
            if ($childNodes->size() > 1) {
2525
                $error ="The tag $value has children which cannot be shown using the form. Please use Morpho to edit this document";    
2526
                push(@errorMessages, $error);
2527
                #if ($DEBUG == 1){ print $error."\n";}
2528
            } else {
2529
                #print $tempNode->nodeName().":".$tempNode->textContent();
2530
                #print "\n";
2531
                return $tempNode->textContent();
2532
            }
2533
        }
2534
    }
2535
}
2536

    
2537

    
2538
################################################################################
2539
# 
2540
# check if given tags are children of given node.
2541
#
2542
################################################################################
2543
sub dontOccur {
2544
    my $node = shift;
2545
    my $value = shift;
2546
    my $errVal = shift;
2547

    
2548
    my $result = $node->findnodes("$value");
2549
    if($result->size > 0){
2550
        $error ="One of the following tags found: $errVal. Please use Morpho to edit this document";
2551
        push(@errorMessages, $error."\n");
2552
        #if ($DEBUG == 1){ print $error;}
2553
    } 
2554
}
2555

    
2556

    
2557
################################################################################
2558
# 
2559
# print out error for more than one occurence of a given tag
2560
#
2561
################################################################################
2562
sub errMoreThanOne {
2563
    my $value = shift;
2564
    my $error ="More than one occurence of the tag $value found. Please use Morpho to edit this document";
2565
    push(@errorMessages, $error."\n");
2566
    # if ($DEBUG == 1){ print $error;}
2567
}
2568

    
2569

    
2570
################################################################################
2571
# 
2572
# print out error for more than given number of occurences of a given tag
2573
#
2574
################################################################################
2575
sub errMoreThanN {
2576
    my $value = shift;
2577
    my $error ="More occurences of the tag $value found than that can be shown in the form. Please use Morpho to edit this document";
2578
    push(@errorMessages, $error);
2579
    #if ($DEBUG == 1){ print $error."\n";}
2580
}
2581

    
2582

    
2583
################################################################################
2584
# 
2585
# convert coord to degrees, minutes and seconds form. 
2586
#
2587
################################################################################
2588
#sub convertCoord {
2589
#    my $wx = shift;
2590
#    print $deg." ".$min." ".$sec;
2591
#    print "\n";
2592
#}
2593

    
2594

    
2595
################################################################################
2596
# 
2597
# print debugging messages to stderr
2598
#
2599
################################################################################
2600
sub debug {
2601
    my $msg = shift;
2602
    
2603
    if ($debug) {
2604
        print STDERR "$msg\n";
2605
    }
2606
}
2607

    
2608
################################################################################
2609
# 
2610
# get the list of projects
2611
#
2612
################################################################################
2613
sub getProjectList {
2614
    
2615
    #use NCEAS::AdminDB;
2616

    
2617
    #my $admindb = NCEAS::AdminDB->new();
2618
    #$admindb->connect($nceas_db, $nceas_db_user, $nceas_db_password);
2619
    #my $projects = $admindb->getProjects();
2620

    
2621
    # This block is for testing only!  Remove for production use
2622
    my @row1;
2623
    $row1[0] = 6000; $row1[1] = 'Andelman'; $row1[2] = 'Sandy'; $row1[3] = 'The very long and windy path to an apparent ecological conclusion: statistics lie';
2624
    my @row2; 
2625
    $row2[0] = 7000; $row2[1] = 'Bascompte'; $row2[2] = 'Jordi'; $row2[3] = 'Postdoctoral Fellow';
2626
    my @row3; 
2627
    $row3[0] = 7001; $row3[1] = 'Hackett'; $row3[2] = 'Edward'; $row3[3] = 'Sociology rules the world';
2628
    my @row4; 
2629
    $row4[0] = 7002; $row4[1] = 'Jones'; $row4[2] = 'Matthew'; $row4[3] = 'Informatics rules the world';
2630
    my @row5; 
2631
    $row5[0] = 7003; $row5[1] = 'Schildhauer'; $row5[2] = 'Mark'; $row5[3] = 'Excel rocks my world, assuming a, b, and c';
2632
    my @row6; 
2633
    $row6[0] = 7004; $row6[1] = 'Rogers'; $row6[2] = 'Bill'; $row6[3] = 'Graduate Intern';
2634
    my @row7; 
2635
    $row7[0] = 7005; $row7[1] = 'Zedfried'; $row7[2] = 'Karl'; $row7[3] = 'A multivariate analysis of thing that go bump in the night';
2636
    my @projects;
2637
    $projects[0] = \@row1;
2638
    $projects[1] = \@row2;
2639
    $projects[2] = \@row3;
2640
    $projects[3] = \@row4;
2641
    $projects[4] = \@row5;
2642
    $projects[5] = \@row6;
2643
    $projects[6] = \@row7;
2644
    return \@projects;
2645

    
2646
    #return $projects;
2647
}
    (1-1/1)