Project

General

Profile

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

1
#!/usr/bin/perl
2
#
3
#  '$RCSfile$'
4
#  Copyright: 2000 Regents of the University of California 
5
#
6
#   '$Author: jones $'
7
#     '$Date: 2003-12-29 13:57:18 -0800 (Mon, 29 Dec 2003) $'
8
# '$Revision: 1985 $' 
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
                        if (hasContent($FORM::taxaAuth)) {
1143
                            $doc .= "<generalTaxonomicCoverage>".$FORM::taxaAuth."</generalTaxonomicCoverage>\n";
1144
                        }
1145
                    }
1146
                    $doc .= "<taxonomicClassification>\n";
1147
                    $doc .= "  <taxonRankName>".param($trn)."</taxonRankName>\n";
1148
                    $doc .= "  <taxonRankValue>".param($trv)."</taxonRankValue>\n";
1149
                    $doc .= "</taxonomicClassification>\n";
1150
                }
1151
            }
1152
        }
1153
    }
1154
    if ($foundFirstTaxon) {
1155
        $doc .= "</taxonomicCoverage>\n";
1156
    }
1157

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

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

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

    
1192
    return $doc;
1193
}
1194

    
1195

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

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

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

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

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

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

    
1233

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

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

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

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

    
1317
            # Read the main document. 
1318

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1816
            $tempResult = $node->findnodes('./taxonomicCoverage/taxonomicClassification');
1817
            my $taxonIndex = 0;
1818
            foreach $tempNode ($tempResult->get_nodelist) {
1819
                $taxonIndex++;
1820
                my $taxonRankName = findValue($tempNode, "taxonRankName");
1821
                my $taxonRankValue = findValue($tempNode, "taxonRankValue");
1822
                $$templateVars{"taxonRankName".$taxonIndex} = $taxonRankName;
1823
                $$templateVars{"taxonRankValue".$taxonIndex} = $taxonRankValue;
1824
            }
1825
            $$templateVars{'taxaCount'} = $taxonIndex;
1826
            my $taxaAuth = findValue($node, "./taxonomicCoverage/generalTaxonomicCoverage");
1827
            $$templateVars{'taxaAuth'} = $taxaAuth;
1828
        }
1829
    }
1830
    dontOccur($doc, "./purpose", "purpose");
1831
    dontOccur($doc, "./maintenance", "maintnance");
1832

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

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

    
1923
    dontOccur($doc, "./pubPlace", "pubPlace");
1924
    dontOccur($doc, "./project", "project");
1925
    
1926
    dontOccur($doc, "./dataTable", "dataTable");
1927
    dontOccur($doc, "./spatialRaster", "spatialRaster");
1928
    dontOccur($doc, "./spatialVector", "spatialVector");
1929
    dontOccur($doc, "./storedProcedure", "storedProcedure");
1930
    dontOccur($doc, "./view", "view");
1931
    dontOccur($doc, "./otherEntity", "otherEntity");
1932
    dontOccur($doc, "./references", "references");
1933
    
1934
    dontOccur($doc, "//citation", "citation");
1935
    dontOccur($doc, "//software", "software");
1936
    dontOccur($doc, "//protocol", "protocol");
1937
    dontOccur($doc, "//additionalMetadata", "additionalMetadata");    
1938
}
1939

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

    
1960
    # Login to metacat
1961
    my $userDN = $FORM::username;
1962
    my $userOrg = $FORM::organization;
1963
    my $userPass = $FORM::password;
1964
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
1965
    
1966
    my $errorMessage = "";
1967
    my $response = $metacat->login($dname, $userPass);
1968

    
1969
    if (! $response) {
1970
    # Could not login
1971
        push(@errorMessages, $metacat->getMessage());
1972
        push(@errorMessages, "Failed during login.\n");
1973

    
1974
    } else {
1975
    #Able to login - try to delete the file    
1976

    
1977
    my $parser;
1978
    my @fileArray;
1979
    my $httpMessage;
1980
    my $xmldoc;
1981
    my $doc;
1982
    my $pushDoc;
1983
    my $alreadyInArray;
1984
    my $findType;
1985
        my $node;
1986
    my $response; 
1987
    my $element;
1988

    
1989
    push (@fileArray, $docid);
1990
    $parser = XML::LibXML->new();
1991

    
1992
        $httpMessage = $metacat->read($docid);
1993
    $doc = $httpMessage->content();    
1994
    $xmldoc = $parser->parse_string($doc);
1995

    
1996
    if ($xmldoc eq "") {
1997
        $error ="Error in parsing the eml document";
1998
        push(@errorMessages, $error);
1999
    } else {
2000

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

    
2058
    $$templateVars{'function'} = "deleted";
2059
    $$templateVars{'section'} = "Deletion Status";
2060
    $template->process( $responseTemplate, $templateVars);
2061
    }
2062
}
2063

    
2064

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

    
2083
    if (! $error) {
2084
    # If no errors, then print out data in confirm Data template
2085

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

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

    
2304
    $$templateVars{'methodTitle'} = $FORM::methodTitle;
2305
    $$templateVars{'methodPara'} = \@FORM::methodPara;
2306
    $$templateVars{'docid'} = $FORM::docid;
2307

    
2308
    $$templateVars{'section'} = "Confirm Data";
2309
    $template->process( $confirmDataTemplate, $templateVars);
2310

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

    
2325

    
2326
################################################################################
2327
# 
2328
# From confirm Data template - user wants to make some changes.
2329
#
2330
################################################################################
2331
sub confirmDataToReEntryData{
2332
    my @sortedSites;
2333
    foreach my $site (sort @sitelist) {
2334
        push(@sortedSites, $site);
2335
    }
2336

    
2337
    $$templateVars{'siteList'} = \@sortedSites;
2338
    $$templateVars{'section'} = "Re-Entry Form";
2339

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

    
2495
    $$templateVars{'form'} = 're_entry';
2496
    $template->process( $entryFormTemplate, $templateVars);
2497
}
2498

    
2499

    
2500
################################################################################
2501
# 
2502
# check if there is multiple occurence of the given tag and find its value.
2503
#
2504
################################################################################
2505

    
2506
sub findValue {
2507
    my $node = shift;
2508
    my $value = shift;
2509
    my $result;
2510
    my $tempNode;
2511

    
2512
    $result = $node->findnodes("./$value");
2513
    if ($result->size > 1) {
2514
        errMoreThanOne("$value");
2515
    } else {
2516
        foreach $tempNode ($result->get_nodelist){
2517
            #print $tempNode->nodeName().":".$tempNode->textContent();
2518
            #print "\n";
2519
            return $tempNode->textContent();
2520
        }
2521
    }
2522
}
2523

    
2524

    
2525
################################################################################
2526
# 
2527
# check if given tags has any children. if not return the value
2528
#
2529
################################################################################
2530
sub findValueNoChild {
2531
    my $node = shift;
2532
    my $value = shift;
2533
    my $tempNode;
2534
    my $childNodes;
2535
    my $result;
2536
    my $error;
2537

    
2538
    $result = $node->findnodes("./$value");
2539
    if($result->size > 1){
2540
       errMoreThanOne("$value");
2541
    } else {
2542
        foreach $tempNode ($result->get_nodelist) {
2543
            $childNodes = $tempNode->childNodes;
2544
            if ($childNodes->size() > 1) {
2545
                $error ="The tag $value has children which cannot be shown using the form. Please use Morpho to edit this document";    
2546
                push(@errorMessages, $error);
2547
                #if ($DEBUG == 1){ print $error."\n";}
2548
            } else {
2549
                #print $tempNode->nodeName().":".$tempNode->textContent();
2550
                #print "\n";
2551
                return $tempNode->textContent();
2552
            }
2553
        }
2554
    }
2555
}
2556

    
2557

    
2558
################################################################################
2559
# 
2560
# check if given tags are children of given node.
2561
#
2562
################################################################################
2563
sub dontOccur {
2564
    my $node = shift;
2565
    my $value = shift;
2566
    my $errVal = shift;
2567

    
2568
    my $result = $node->findnodes("$value");
2569
    if($result->size > 0){
2570
        $error ="One of the following tags found: $errVal. Please use Morpho to edit this document";
2571
        push(@errorMessages, $error."\n");
2572
        #if ($DEBUG == 1){ print $error;}
2573
    } 
2574
}
2575

    
2576

    
2577
################################################################################
2578
# 
2579
# print out error for more than one occurence of a given tag
2580
#
2581
################################################################################
2582
sub errMoreThanOne {
2583
    my $value = shift;
2584
    my $error ="More than one occurence of the tag $value found. Please use Morpho to edit this document";
2585
    push(@errorMessages, $error."\n");
2586
    # if ($DEBUG == 1){ print $error;}
2587
}
2588

    
2589

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

    
2602

    
2603
################################################################################
2604
# 
2605
# convert coord to degrees, minutes and seconds form. 
2606
#
2607
################################################################################
2608
#sub convertCoord {
2609
#    my $wx = shift;
2610
#    print $deg." ".$min." ".$sec;
2611
#    print "\n";
2612
#}
2613

    
2614

    
2615
################################################################################
2616
# 
2617
# print debugging messages to stderr
2618
#
2619
################################################################################
2620
sub debug {
2621
    my $msg = shift;
2622
    
2623
    if ($debug) {
2624
        print STDERR "$msg\n";
2625
    }
2626
}
2627

    
2628
################################################################################
2629
# 
2630
# get the list of projects
2631
#
2632
################################################################################
2633
sub getProjectList {
2634
    
2635
    #use NCEAS::AdminDB;
2636

    
2637
    #my $admindb = NCEAS::AdminDB->new();
2638
    #$admindb->connect($nceas_db, $nceas_db_user, $nceas_db_password);
2639
    #my $projects = $admindb->getProjects();
2640

    
2641
    # This block is for testing only!  Remove for production use
2642
    my @row1;
2643
    $row1[0] = 6000; $row1[1] = 'Andelman'; $row1[2] = 'Sandy'; $row1[3] = 'The very long and windy path to an apparent ecological conclusion: statistics lie';
2644
    my @row2; 
2645
    $row2[0] = 7000; $row2[1] = 'Bascompte'; $row2[2] = 'Jordi'; $row2[3] = 'Postdoctoral Fellow';
2646
    my @row3; 
2647
    $row3[0] = 7001; $row3[1] = 'Hackett'; $row3[2] = 'Edward'; $row3[3] = 'Sociology rules the world';
2648
    my @row4; 
2649
    $row4[0] = 7002; $row4[1] = 'Jones'; $row4[2] = 'Matthew'; $row4[3] = 'Informatics rules the world';
2650
    my @row5; 
2651
    $row5[0] = 7003; $row5[1] = 'Schildhauer'; $row5[2] = 'Mark'; $row5[3] = 'Excel rocks my world, assuming a, b, and c';
2652
    my @row6; 
2653
    $row6[0] = 7004; $row6[1] = 'Rogers'; $row6[2] = 'Bill'; $row6[3] = 'Graduate Intern';
2654
    my @row7; 
2655
    $row7[0] = 7005; $row7[1] = 'Zedfried'; $row7[2] = 'Karl'; $row7[3] = 'A multivariate analysis of thing that go bump in the night';
2656
    my @projects;
2657
    $projects[0] = \@row1;
2658
    $projects[1] = \@row2;
2659
    $projects[2] = \@row3;
2660
    $projects[3] = \@row4;
2661
    $projects[4] = \@row5;
2662
    $projects[5] = \@row6;
2663
    $projects[6] = \@row7;
2664
    return \@projects;
2665

    
2666
    #return $projects;
2667
}