Project

General

Profile

1
#!/usr/bin/perl
2
#
3
#  '$RCSfile$'
4
#  Copyright: 2000 Regents of the University of California 
5
#
6
#   '$Author: jones $'
7
#     '$Date: 2003-12-19 16:12:33 -0800 (Fri, 19 Dec 2003) $'
8
# '$Revision: 1979 $' 
9
# 
10
# This program is free software; you can redistribute it and/or modify
11
# it under the terms of the GNU General Public License as published by
12
# the Free Software Foundation; either version 2 of the License, or
13
# (at your option) any later version.
14
#
15
# This program is distributed in the hope that it will be useful,
16
# but WITHOUT ANY WARRANTY; without even the implied warranty of
17
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18
# GNU General Public License for more details.
19
#
20
# You should have received a copy of the GNU General Public License
21
# along with this program; if not, write to the Free Software
22
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23
#
24

    
25
#
26
# This is a CGI application for inserting metadata documents into
27
# the Metacat database.  It utilizes the Metacat.pm module for most work.
28
# In this script, we process the form fields passed in from a POST, insert a
29
# metadata document and an ACL document.
30

    
31
use Metacat;
32
use AppConfig qw(:expand :argcount);
33
use XML::LibXML;
34
use XML::LibXSLT;
35
use Template;
36
use Net::LDAP;
37
use Net::SMTP;
38
use CGI qw/:standard :html3/;
39
use strict;
40

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

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

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

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

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

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

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

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

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

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

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

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

    
170

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

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

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

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

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

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

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

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

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

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

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

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

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

    
275

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

    
281
    my $xmldoc = createXMLDocument();
282

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

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

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

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

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

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

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

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

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

    
384
        exit(0);
385
    }
386
}
387

    
388
debug("Registry: C");
389

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

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

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

    
406
exit(0);
407

    
408

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

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

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

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

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

    
465
  return $notunique;
466
}
467

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

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

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

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

    
517
  return $acl;
518
}
519

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

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

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

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

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

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

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

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

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

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

    
658
    return \@invalidParams;
659
}
660

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

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

    
683

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

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

    
701

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1015

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

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

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

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

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

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

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

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

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

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

    
1159
    $doc .= $cont;
1160
    $doc .= $publ;
1161

    
1162
    $doc .= "<access authSystem=\"knb\" order=\"denyFirst\">\n";
1163
    $doc .= "<allow>\n";
1164
    $doc .= "<principal>uid=obfsadmin,o=LTER,dc=ecoinformatics,dc=org</principal>\n";
1165
    $doc .= "<permission>all</permission>\n";
1166
    $doc .= "</allow>\n";
1167
    $doc .= "<allow>\n";
1168
    $doc .= "<principal>uid=$FORM::username,o=$FORM::organization,dc=ecoinformatics,dc=org</principal>\n";
1169
    $doc .= "<permission>all</permission>\n";
1170
    $doc .= "</allow>\n";
1171
    $doc .= "<allow>\n";
1172
    $doc .= "<principal>public</principal>\n";
1173
    $doc .= "<permission>read</permission>\n";
1174
    $doc .= "</allow>\n";
1175
    $doc .= "</access>\n";
1176
    
1177
    $doc .= "</dataset>\n</eml:eml>\n";
1178

    
1179
    return $doc;
1180
}
1181

    
1182

    
1183
################################################################################
1184
# 
1185
# send an email message notifying the moderator of a new submission 
1186
#
1187
################################################################################
1188
sub sendNotification {
1189
    my $identifier = shift;
1190
    my $mailhost = shift;
1191
    my $sender = shift;
1192
    my $recipient = shift;
1193

    
1194
    my $smtp = Net::SMTP->new($mailhost);
1195
    $smtp->mail($sender);
1196
    $smtp->to($recipient);
1197

    
1198
    my $message = <<"    ENDOFMESSAGE";
1199
    To: $recipient
1200
    From: $sender
1201
    Subject: New data submission
1202
    
1203
    Data was submitted to the data registry.  
1204
    The identifying information for the new data set is:
1205

    
1206
    Identifier: $identifier
1207
    Title: $FORM::title
1208
    Submitter: $FORM::providerGivenName $FORM::providerSurName
1209

    
1210
    Please review the submmission and grant public read access if appropriate.
1211
    Thanks
1212
    
1213
    ENDOFMESSAGE
1214
    $message =~ s/^[ \t\r\f]+//gm;
1215

    
1216
    $smtp->data($message);
1217
    $smtp->quit;
1218
}
1219

    
1220

    
1221
################################################################################
1222
# 
1223
# read the eml document and send back a form with values filled in. 
1224
#
1225
################################################################################
1226
sub modifyData {
1227
    
1228
    # create metacat instance
1229
    my $metacat;
1230
    my $docid = $FORM::docid;
1231
    my $httpMessage;
1232
    my $doc;
1233
    my $xmldoc;
1234
    my $findType;
1235
    my $parser = XML::LibXML->new();
1236
    my @fileArray;
1237
    my $pushDoc;
1238
    my $alreadyInArray;
1239
    my $node;
1240
    my $response; 
1241
    my $element;
1242
    my $tempfile;
1243

    
1244
    $metacat = Metacat->new();
1245
    if ($metacat) {
1246
        $metacat->set_options( metacatUrl => $metacatUrl );
1247
    } else {
1248
        #die "failed during metacat creation\n";
1249
        push(@errorMessages, "Failed during metacat creation.");
1250
    }
1251
    
1252
    $httpMessage = $metacat->read($docid);
1253
    $doc = $httpMessage->content();
1254
    $xmldoc = $parser->parse_string($doc);
1255

    
1256
    #$tempfile = $xslConvDir.$docid;
1257
    #push (@fileArray, $tempfile);
1258

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

    
1304
            # Read the main document. 
1305

    
1306
            $tempfile = $tmpdir."/".$docid; #= $xslConvDir.$docid;
1307
            open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1308
            print TFILE $doc;
1309
            close(TFILE);
1310
        
1311
            # Transforming beta6 to eml 2
1312
            my $xslt;
1313
            my $triplesheet;
1314
            my $results;
1315
            my $stylesheet;
1316
            my $resultsheet;
1317
        
1318
            $xslt = XML::LibXSLT->new();
1319
            #$tempfile = $xslConvDir."triple_info.xsl";
1320
            $tempfile = $tmpdir."/"."triple_info.xsl";
1321
    
1322
            $triplesheet = $xslt->parse_stylesheet_file($tempfile);
1323

    
1324
            #$results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1325
            $results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1326

    
1327
            #$tempfile = $xslConvDir."emlb6toeml2.xsl";
1328
            $tempfile = $tmpdir."/"."emlb6toeml2.xsl";
1329
            $stylesheet = $xslt->parse_stylesheet_file($tempfile);
1330
            $resultsheet = $stylesheet->transform($results);
1331
        
1332
            #$tempfile = "/usr/local/apache2/htdocs/xml/test.xml";;
1333
            #open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1334
            #print TFILE $stylesheet->output_string($resultsheet);
1335
            #close(TFILE);
1336

    
1337
            getFormValuesFromEml2($resultsheet);
1338
            
1339
            # Delete the files written earlier. 
1340
            unlink @fileArray;
1341

    
1342
        } else {
1343
            getFormValuesFromEml2($xmldoc);
1344
        }
1345
    }   
1346
    
1347
    if (scalar(@errorMessages)) {
1348
        # if any errors, print them in the response template 
1349
        $$templateVars{'status'} = 'failure';
1350
        $$templateVars{'errorMessages'} = \@errorMessages;
1351
        $error = 1;
1352
        $$templateVars{'function'} = "modification";
1353
        $$templateVars{'section'} = "Modification Status";
1354
        $template->process( $responseTemplate, $templateVars); 
1355
    } else {
1356
        $$templateVars{'form'} = 're_entry';
1357
        $template->process( $entryFormTemplate, $templateVars);
1358
    }
1359
}
1360

    
1361
################################################################################
1362
# 
1363
# Parse an EML 2.0.0 file and extract the metadata into perl variables for 
1364
# processing and returning to the template processor
1365
#
1366
################################################################################
1367
sub getFormValuesFromEml2 {
1368
    
1369
    my $doc = shift;
1370
    my $results;
1371
    my $error;
1372
    my $node;
1373
    my $tempResult;
1374
    my $tempNode;
1375
    my $aoCount = 1;
1376
    my $foundDSO;
1377

    
1378
    # find out the tag <alternateIdentifier>. 
1379
    $results = $doc->findnodes('//dataset/alternateIdentifier');
1380
    if ($results->size() > 1) {
1381
        errMoreThanOne("alternateIdentifier");
1382
    } else {
1383
        foreach $node ($results->get_nodelist) {
1384
            $$templateVars{'identifier'} = findValue($node, '../alternateIdentifier');
1385
        }
1386
    }
1387

    
1388
    # find out the tag <title>. 
1389
    $results = $doc->findnodes('//dataset/title');
1390
    if ($results->size() > 1) {
1391
        errMoreThanOne("title");
1392
    } elsif ($results->size() < 1) {
1393
        $error ="Following tag not found: title. Please use Morpho to edit this document";
1394
        push(@errorMessages, $error."\n");
1395
        #if ($DEBUG == 1){ print $error;}
1396
    } else {
1397
        foreach $node ($results->get_nodelist) {
1398
            $$templateVars{'title'} = findValue($node, '../title');
1399
        }
1400
    }
1401

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

    
1482
    $results = $doc->findnodes('//dataset/creator/organizationName');
1483
    my $wgroups = $doc->findnodes("//dataset/creator/organizationName[contains(text(),'(NCEAS ')]");
1484
    debug("Registry: Number Org: ".$results->size());
1485
    debug("Registry:  Number WG: ".$wgroups->size());
1486
    if ($results->size() - $wgroups->size() > 3) {
1487
        errMoreThanN("creator/organizationName");    
1488
    } else {
1489
        foreach $node ($results->get_nodelist) {
1490
            my $tempValue = findValue($node,'../organizationName');
1491
            $tempResult = $node->findnodes('../individualName');
1492
            if ($tempResult->size == 0 && $tempValue ne $organization) {
1493
                $$templateVars{'site'} = $tempValue;
1494
            }
1495
        }
1496
        if ($FORM::cfg == 'nceas') {
1497
            my @wg;
1498
            foreach $node ($results->get_nodelist) {
1499
                my $tempValue = findValue($node,'../organizationName');
1500
                $wg[scalar(@wg)] = $tempValue;
1501
            }
1502
            my $projects = getProjectList();
1503
            $$templateVars{'projects'} = $projects;
1504
            $$templateVars{'wg'} = \@wg;
1505
        }
1506
    }
1507

    
1508
    $results = $doc->findnodes('//dataset/metadataProvider');
1509
    if ($results->size() > 11) {
1510
        errMoreThanN("metadataProvider");    
1511
    } else {
1512
        foreach $node ($results->get_nodelist) {
1513
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1514
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in metadataProvider");
1515
        
1516
            $tempResult = $node->findnodes('./individualName');
1517
            if ($tempResult->size > 1) {
1518
                errMoreThanOne("metadataProvider/indvidualName");
1519
            } else {
1520
                foreach $tempNode ($tempResult->get_nodelist) {
1521
                    if ($$templateVars{'providerGivenName'} ne "") {
1522
                        $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1523
                        $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1524
                        $$templateVars{"origRole$aoCount"} = "Metadata Provider";
1525
                        $aoCount++;
1526
                    } else {
1527
                        $$templateVars{'providerGivenName'} =  findValue($tempNode, './givenName');
1528
                        $$templateVars{'providerSurName'} =  findValue($tempNode, './surName');
1529
                    }
1530
                }
1531
            }
1532
        }
1533
    }
1534

    
1535
    $results = $doc->findnodes('//dataset/associatedParty');
1536
    if ($results->size() > 10) {
1537
        errMoreThanN("associatedParty");
1538
    } else {
1539
        foreach $node ($results->get_nodelist) {
1540
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1541
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in associatedParty");
1542
       
1543
            $tempResult = $node->findnodes('./individualName');
1544
            if ($tempResult->size > 1) {
1545
                errMoreThanOne("associatedParty/indvidualName");
1546
            } else {
1547
                foreach $tempNode ($tempResult->get_nodelist) {
1548
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1549
                    $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1550
                    $$templateVars{"origRole$aoCount"} = findValue($tempNode, '../role');
1551
                    $aoCount++;           
1552
                }
1553
            }
1554
        }
1555
    }
1556

    
1557
    $results = $doc->findnodes('//dataset/publisher');
1558
    if ($results->size() > 10) {
1559
        errMoreThanN("publisher");
1560
    } else {
1561
        foreach $node ($results->get_nodelist) {
1562
            dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1563
                "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in associatedParty");
1564
       
1565
            $tempResult = $node->findnodes('./individualName');
1566
            if ($tempResult->size > 1) {
1567
                errMoreThanOne("publisher/indvidualName");
1568
            } else {
1569
                foreach $tempNode ($tempResult->get_nodelist) {
1570
                    $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1571
                    $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1572
                    $$templateVars{"origRole$aoCount"} = "Publisher";
1573
                    $aoCount++;           
1574
                }
1575
            }
1576
        }
1577
    }
1578

    
1579
    if ($aoCount > 11) {
1580
        errMoreThanN("Additional Originators");
1581
    } 
1582

    
1583
    dontOccur($doc, "./pubDate", "pubDate");
1584
    dontOccur($doc, "./language", "language");
1585
    dontOccur($doc, "./series", "series");
1586

    
1587
    $results = $doc->findnodes('//dataset/abstract');
1588
    if ($results->size() > 1) {
1589
        errMoreThanOne("abstract");
1590
    } else {
1591
        foreach my $node ($results->get_nodelist) {
1592
            dontOccur($node, "./section", "section");
1593
            $$templateVars{'abstract'} = findValueNoChild($node, "para");
1594
        }
1595
    }
1596

    
1597
    $results = $doc->findnodes('//dataset/keywordSet');
1598
    if ($results->size() > 10) {
1599
        errMoreThanN("keywordSet");
1600
    } else {
1601
        my $count = 0;
1602
        foreach $node ($results->get_nodelist) {
1603
            $tempResult = $node->findnodes('./keyword');
1604
            if ($tempResult->size() > 1) {
1605
                errMoreThanOne("keyword");
1606
            } else {
1607
                foreach $tempNode ($tempResult->get_nodelist) {
1608
                    $$templateVars{"keyword$count"} = $tempNode->textContent();
1609
                    if ($tempNode->hasAttributes()) {
1610
                        my @attlist = $tempNode->attributes();
1611
                        $$templateVars{"kwType$count"} = $attlist[0]->value;
1612
                    }  
1613
                 } 
1614
            }
1615
            $$templateVars{"kwTh$count"} = findValue($node, "keywordThesaurus");
1616
            $count++;
1617
        }
1618
    
1619
        while ($count<11) {
1620
            $$templateVars{"kwType$count"} = "none";
1621
            $$templateVars{"kwTh$count"} = "none";
1622
            $count++;
1623
        }
1624
    }
1625

    
1626
    $results = $doc->findnodes('//dataset/additionalInfo');
1627
    if ($results->size() > 1) {
1628
        errMoreThanOne("additionalInfo");
1629
    } else {
1630
        foreach $node ($results->get_nodelist) {
1631
            dontOccur($node, "./section", "section");
1632
            $$templateVars{'addComments'} = findValueNoChild($node, "para");
1633
        }
1634
    }
1635

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

    
1644
            $tempResult = $node->findnodes("para");
1645
            if ($tempResult->size > 2) {
1646
                   errMoreThanN("para");
1647
            } else {
1648
                foreach $tempNode ($tempResult->get_nodelist) {
1649
                    my $childNodes = $tempNode->childNodes;
1650
                    if ($childNodes->size() > 1) {
1651
                        $error ="The tag para in intellectualRights has children which cannot be shown using the form. Please use Morpho to edit this document";    
1652
                        push(@errorMessages, $error);
1653
                        #if ($DEBUG == 1){ print $error."\n";}
1654
                    } else {
1655
                        #print $tempNode->nodeName().":".$tempNode->textContent();
1656
                        #print "\n";
1657
                        if ($$templateVars{'useConstraints'} eq "") {
1658
                            $$templateVars{'useConstraints'} = $tempNode->textContent();
1659
                        } else {
1660
                            $$templateVars{'useConstraintsOther'} = $tempNode->textContent();
1661
                        }
1662
                    }
1663
                }
1664
            }
1665
        }
1666
    }
1667

    
1668
    $results = $doc->findnodes('//dataset/distribution/online');
1669
    if ($results->size() > 1) {
1670
        errMoreThanOne("distribution/online");
1671
    } else {
1672
        foreach my $tempNode ($results->get_nodelist){
1673
            $$templateVars{'url'} = findValue($tempNode, "url");
1674
            dontOccur($tempNode, "./connection", "/distribution/online/connection");
1675
            dontOccur($tempNode, "./connectionDefinition", "/distribution/online/connectionDefinition");
1676
        }
1677
    }
1678

    
1679
    $results = $doc->findnodes('//dataset/distribution/offline');
1680
    if ($results->size() > 1) {
1681
        errMoreThanOne("distribution/online");
1682
    } else {
1683
        foreach my $tempNode ($results->get_nodelist) {
1684
            $$templateVars{'dataMedium'} = findValue($tempNode, "mediumName");
1685
            dontOccur($tempNode, "./mediumDensity", "/distribution/offline/mediumDensity");
1686
            dontOccur($tempNode, "./mediumDensityUnits", "/distribution/offline/mediumDensityUnits");
1687
            dontOccur($tempNode, "./mediumVolume", "/distribution/offline/mediumVolume");
1688
            dontOccur($tempNode, "./mediumFormat", "/distribution/offline/mediumFormat");
1689
            dontOccur($tempNode, "./mediumNote", "/distribution/offline/mediumNote");
1690
        }
1691
    }
1692

    
1693
    dontOccur($doc, "./inline", "//dataset/distribution/inline");
1694

    
1695
    $results = $doc->findnodes('//dataset/coverage');
1696
    if ($results->size() > 1) {
1697
        errMoreThanOne("coverage");
1698
    } else {
1699
        foreach $node ($results->get_nodelist) {
1700
            dontOccur($node, "./temporalCoverage/rangeOfDates/beginDate/time|./temporalCoverage/rangeOfDates/beginDate/alternativeTimeScale|./temporalCoverage/rangeOfDates/endDate/time|./temporalCoverage/rangeOfDates/endDate/alternativeTimeScale|./taxonomicCoverage|./geographicCoverage/datasetGPolygon|./geographicCoverage/boundingCoordinates/boundingAltitudes", "temporalCoverage/rangeOfDates/beginDate/time, /temporalCoverage/rangeOfDates/beginDate/alternativeTimeScale, /temporalCoverage/rangeOfDates/endDate/time, /temporalCoverage/rangeOfDates/endDate/alternativeTimeScale, /taxonomicCoverage, /geographicCoverage/datasetGPolygon, /geographicCoverage/boundingCoordinates/boundingAltitudes");
1701

    
1702
            $tempResult = $node->findnodes('./temporalCoverage');
1703
            if ($tempResult->size > 1) {
1704
                   errMoreThanOne("temporalCoverage");
1705
            } else {
1706
                foreach $tempNode ($tempResult->get_nodelist) {
1707
                    my $x;
1708
                    my $y;
1709
                    my $z;
1710
                    my $tempdate = findValue($tempNode, "rangeOfDates/beginDate/calendarDate");
1711
                    ($x, $y, $z) = split("-", $tempdate); 
1712
                    $$templateVars{'beginningYear'} = $x;
1713
                    $$templateVars{'beginningMonth'} = $y;
1714
                    $$templateVars{'beginningDay'} = $z;
1715
    
1716
                    $tempdate = findValue($tempNode, "rangeOfDates/endDate/calendarDate");
1717
                    ($x, $y, $z) = split("-", $tempdate);
1718
                    $$templateVars{'endingYear'} = $x;
1719
                    $$templateVars{'endingMonth'} = $y;
1720
                    $$templateVars{'endingDay'} = $z;
1721
                
1722
                    $tempdate = "";
1723
                    $tempdate = findValue($tempNode, "singleDateTime/calendarDate");
1724
                    if($tempdate ne ""){
1725
                        ($x, $y, $z) = split("-", $tempdate);
1726
                        $$templateVars{'beginningYear'} = $x;
1727
                        $$templateVars{'beginningMonth'} = $y;
1728
                        $$templateVars{'beginningDay'} = $z;
1729
                    }  
1730
                }
1731
            }
1732

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

    
1805
    $results = $doc->findnodes('//dataset/contact/individualName');
1806
    if ($results->size() > 1) {
1807
        errMoreThanOne("contact/individualName");
1808
    } else {
1809
        foreach $node ($results->get_nodelist) {
1810
            dontOccur($node, "../positionName|../onlineURL|../userId", 
1811
              "positionName, onlineURL, userId in contact tag");
1812
            dontOccur($node, "./saluation", "saluation in contact tag");                
1813
        
1814
            $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1815
            if ($tempResult->size > 0) {
1816
                $$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
1817
                $$templateVars{'origNamelastContact'} = findValue($node, 'surName');
1818
    
1819
                my $tempResult2 = $node->findnodes('../address');
1820
                if ($tempResult2->size > 1) {
1821
                    errMoreThanOne("address");
1822
                } else {
1823
                    foreach my $tempNode2 ($tempResult2->get_nodelist) {
1824
                        $$templateVars{'origDeliveryContact'} = findValue($tempNode2, 'deliveryPoint');
1825
                        $$templateVars{'origCityContact'} = findValue($tempNode2, 'city');
1826
                        $$templateVars{'origStateContact'} = findValue($tempNode2, 'administrativeArea');
1827
                        $$templateVars{'origZIPContact'} = findValue($tempNode2, 'postalCode');
1828
                        $$templateVars{'origCountryContact'} = findValue($tempNode2, 'country');
1829
                    }
1830
                }
1831
            
1832
                my $tempResult3 = $node->findnodes('../phone');
1833
                if ($tempResult3->size > 2) {
1834
                    errMoreThanN("phone");
1835
                } else {
1836
                    foreach my $tempNode2 ($tempResult3->get_nodelist) {
1837
                        if ($tempNode2->hasAttributes()) {
1838
                            my @attlist = $tempNode2->attributes();
1839
                            if ($attlist[0]->value eq "Fax") {
1840
                                $$templateVars{'origFAXContact'} = $tempNode2->textContent();
1841
                            } else {
1842
                                $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
1843
                            }
1844
                        } else {
1845
                            $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
1846
                        }
1847
                    }
1848
                }
1849
                $$templateVars{'origEmailContact'} = findValue($node, '../electronicMailAddress');
1850
                $$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
1851
            } else {
1852
                $$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
1853
                $$templateVars{'origNamelastContact'} = findValue($node, 'surName');
1854
                $$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
1855
            }
1856
        }
1857
    }
1858
    
1859
    dontOccur($doc, "./pubPlace", "pubPlace");
1860
    dontOccur($doc, "./methods", "methods");
1861
    dontOccur($doc, "./project", "project");
1862
    
1863
    dontOccur($doc, "./dataTable", "dataTable");
1864
    dontOccur($doc, "./spatialRaster", "spatialRaster");
1865
    dontOccur($doc, "./spatialVector", "spatialVector");
1866
    dontOccur($doc, "./storedProcedure", "storedProcedure");
1867
    dontOccur($doc, "./view", "view");
1868
    dontOccur($doc, "./otherEntity", "otherEntity");
1869
    dontOccur($doc, "./references", "references");
1870
    
1871
    dontOccur($doc, "//citation", "citation");
1872
    dontOccur($doc, "//software", "software");
1873
    dontOccur($doc, "//protocol", "protocol");
1874
    dontOccur($doc, "//additionalMetadata", "additionalMetadata");    
1875
}
1876

    
1877
################################################################################
1878
# 
1879
# Delete the eml file that has been requested for deletion. 
1880
#
1881
################################################################################
1882
sub deleteData {
1883
    my $deleteAll = shift;
1884
    
1885
    # create metacat instance
1886
    my $metacat;
1887
    my $docid = $FORM::docid;
1888
    
1889
    $metacat = Metacat->new();
1890
    if ($metacat) {
1891
        $metacat->set_options( metacatUrl => $metacatUrl );
1892
    } else {
1893
        #die "failed during metacat creation\n";
1894
        push(@errorMessages, "Failed during metacat creation.");
1895
    }
1896

    
1897
    # Login to metacat
1898
    my $userDN = $FORM::username;
1899
    my $userOrg = $FORM::organization;
1900
    my $userPass = $FORM::password;
1901
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
1902
    
1903
    my $errorMessage = "";
1904
    my $response = $metacat->login($dname, $userPass);
1905

    
1906
    if (! $response) {
1907
    # Could not login
1908
        push(@errorMessages, $metacat->getMessage());
1909
        push(@errorMessages, "Failed during login.\n");
1910

    
1911
    } else {
1912
    #Able to login - try to delete the file    
1913

    
1914
    my $parser;
1915
    my @fileArray;
1916
    my $httpMessage;
1917
    my $xmldoc;
1918
    my $doc;
1919
    my $pushDoc;
1920
    my $alreadyInArray;
1921
    my $findType;
1922
        my $node;
1923
    my $response; 
1924
    my $element;
1925

    
1926
    push (@fileArray, $docid);
1927
    $parser = XML::LibXML->new();
1928

    
1929
        $httpMessage = $metacat->read($docid);
1930
    $doc = $httpMessage->content();    
1931
    $xmldoc = $parser->parse_string($doc);
1932

    
1933
    if ($xmldoc eq "") {
1934
        $error ="Error in parsing the eml document";
1935
        push(@errorMessages, $error);
1936
    } else {
1937

    
1938
        $findType = $xmldoc->findnodes('//dataset/identifier');
1939
        if($findType->size() > 0){
1940
        # This is a eml beta6 document
1941
        # Delete the documents mentioned in triples also
1942
        
1943
        $findType = $xmldoc->findnodes('//dataset/triple');
1944
        if($findType->size() > 0){
1945
            foreach $node ($findType->get_nodelist){
1946
            $pushDoc = findValue($node, 'subject');
1947
            
1948
            # If the file is already in the @fileArray then do not add it 
1949
            $alreadyInArray = 0;
1950
            foreach $element (@fileArray){
1951
                if($element eq $pushDoc){
1952
                $alreadyInArray = 1;
1953
                }
1954
            }
1955
            
1956
            if(!$alreadyInArray){
1957
                # If not already in array then delete the file. 
1958
                push (@fileArray, $pushDoc);
1959
                $response = $metacat->delete($pushDoc);
1960
                
1961
                if (! $response) {
1962
                # Could not delete
1963
                #push(@errorMessages, $response);
1964
                push(@errorMessages, $metacat->getMessage());
1965
                push(@errorMessages, "Failed during deleting $pushDoc. Please check if you are authorized to delete this document.\n");
1966
                }
1967
            }
1968
            }
1969
        }
1970
        }
1971
    }
1972
    
1973
    # Delete the main document. 
1974
    if($deleteAll){
1975
        $response = $metacat->delete($docid);  
1976
        if (! $response) {
1977
        # Could not delete
1978
        #push(@errorMessages, $response);
1979
        push(@errorMessages, $metacat->getMessage());
1980
        push(@errorMessages, "Failed during deleting $docid. Please check if you are authorized to delete this document.\n");
1981
        }
1982
    }
1983
    }
1984
    
1985
    if (scalar(@errorMessages)) {
1986
    # If any errors, print them in the response template 
1987
    $$templateVars{'status'} = 'failure';
1988
    $$templateVars{'errorMessages'} = \@errorMessages;
1989
    $error = 1;
1990
    }
1991
    
1992
    # Process the response template
1993
    if($deleteAll){
1994

    
1995
    $$templateVars{'function'} = "deleted";
1996
    $$templateVars{'section'} = "Deletion Status";
1997
    $template->process( $responseTemplate, $templateVars);
1998
    }
1999
}
2000

    
2001

    
2002
################################################################################
2003
# 
2004
# Do data validation and send the data to confirm data template.
2005
#
2006
################################################################################
2007
sub toConfirmData{
2008
    # Check if any invalid parameters
2009
 
2010
    my $invalidParams;
2011
    if (! $error) {
2012
    $invalidParams = validateParameters(0);
2013
    if (scalar(@$invalidParams)) {
2014
        $$templateVars{'status'} = 'failure';
2015
        $$templateVars{'invalidParams'} = $invalidParams;
2016
        $error = 1;
2017
    }
2018
    }
2019

    
2020
    if (! $error) {
2021
    # If no errors, then print out data in confirm Data template
2022

    
2023
    $$templateVars{'providerGivenName'} = $FORM::providerGivenName;
2024
    $$templateVars{'providerSurName'} = $FORM::providerSurName;
2025
    if($FORM::site eq "Select your station here."){
2026
        $$templateVars{'site'} = "";
2027
    }else{
2028
        $$templateVars{'site'} = $FORM::site;
2029
    }
2030
    if($FORM::cfg eq "nceas"){
2031
        $$templateVars{'wg'} = \@FORM::wg;
2032
    }
2033
    $$templateVars{'identifier'} = $FORM::identifier;
2034
    $$templateVars{'title'} = $FORM::title;
2035
    $$templateVars{'origNamefirst0'} = $FORM::origNamefirst0;
2036
    $$templateVars{'origNamelast0'} = $FORM::origNamelast0;
2037
    $$templateVars{'origNameOrg'} = $FORM::origNameOrg;
2038
    # $$templateVars{'origRole0'} = $FORM::origRole0;
2039
    $$templateVars{'origDelivery'} = $FORM::origDelivery;
2040
    $$templateVars{'origCity'} = $FORM::origCity;
2041
    if($FORM::origState eq "Select State Here."){
2042
        $$templateVars{'origState'} = "";
2043
    }else{
2044
        $$templateVars{'origState'} = $FORM::origState;
2045
    }
2046
    $$templateVars{'origStateOther'} = $FORM::origStateOther;
2047
    $$templateVars{'origZIP'} = $FORM::origZIP;
2048
    $$templateVars{'origCountry'} = $FORM::origCountry;
2049
    $$templateVars{'origPhone'} = $FORM::origPhone;
2050
    $$templateVars{'origFAX'} = $FORM::origFAX;
2051
    $$templateVars{'origEmail'} = $FORM::origEmail;
2052
    $$templateVars{'useOrigAddress'} = $FORM::useOrigAddress;
2053
    if($FORM::useOrigAddress eq "on"){
2054
        $$templateVars{'origNamefirstContact'} = $FORM::origNamefirst0;
2055
        $$templateVars{'origNamelastContact'} = $FORM::origNamelast0;
2056
        $$templateVars{'origNameOrgContact'} = $FORM::origNameOrg;
2057
        $$templateVars{'origDeliveryContact'} = $FORM::origDelivery; 
2058
        $$templateVars{'origCityContact'} = $FORM::origCity;
2059
        if($FORM::origState eq "Select State Here."){
2060
        $$templateVars{'origStateContact'} = "";
2061
        }else{
2062
        $$templateVars{'origStateContact'} = $FORM::origState;
2063
        }
2064
        $$templateVars{'origStateOtherContact'} = $FORM::origStateOther;
2065
        $$templateVars{'origZIPContact'} = $FORM::origZIP;
2066
        $$templateVars{'origCountryContact'} = $FORM::origCountry;
2067
        $$templateVars{'origPhoneContact'} = $FORM::origPhone;
2068
        $$templateVars{'origFAXContact'} = $FORM::origFAX;
2069
        $$templateVars{'origEmailContact'} = $FORM::origEmail;
2070
    }else{
2071
        $$templateVars{'origNamefirstContact'} = $FORM::origNamefirstContact;
2072
        $$templateVars{'origNamelastContact'} = $FORM::origNamelastContact;
2073
        $$templateVars{'origNameOrgContact'} = $FORM::origNameOrgContact;
2074
        $$templateVars{'origDeliveryContact'} = $FORM::origDeliveryContact; 
2075
        $$templateVars{'origCityContact'} = $FORM::origCityContact;
2076
        if($FORM::origStateContact eq "Select State Here."){
2077
        $$templateVars{'origStateContact'} = "";
2078
        }else{
2079
        $$templateVars{'origStateContact'} = $FORM::origStateContact;
2080
        }
2081
        $$templateVars{'origStateOtherContact'} = $FORM::origStateOtherContact;
2082
        $$templateVars{'origZIPContact'} = $FORM::origZIPContact;
2083
        $$templateVars{'origCountryContact'} = $FORM::origCountryContact;
2084
        $$templateVars{'origPhoneContact'} = $FORM::origPhoneContact;
2085
        $$templateVars{'origFAXContact'} = $FORM::origFAXContact;
2086
        $$templateVars{'origEmailContact'} = $FORM::origEmailContact;    
2087
    }
2088
    $$templateVars{'origNamefirst1'} = $FORM::origNamefirst1;
2089
    $$templateVars{'origNamelast1'} = $FORM::origNamelast1;
2090
    if($FORM::origNamefirst1 eq "" && $FORM::origNamelast1 eq ""){
2091
        $$templateVars{'origRole1'} = "";
2092
    }else{
2093
        $$templateVars{'origRole1'} = $FORM::origRole1;
2094
    }
2095
    $$templateVars{'origNamefirst2'} = $FORM::origNamefirst2;
2096
    $$templateVars{'origNamelast2'} = $FORM::origNamelast2;
2097
    if($FORM::origNamefirst2 eq "" && $FORM::origNamelast2 eq ""){
2098
        $$templateVars{'origRole2'} = "";
2099
    }else{
2100
        $$templateVars{'origRole2'} = $FORM::origRole2;
2101
    }
2102
    $$templateVars{'origNamefirst3'} = $FORM::origNamefirst3;
2103
    $$templateVars{'origNamelast3'} = $FORM::origNamelast3;
2104
    if($FORM::origNamefirst3 eq "" && $FORM::origNamelast3 eq ""){
2105
        $$templateVars{'origRole3'} = "";
2106
    }else{
2107
        $$templateVars{'origRole3'} = $FORM::origRole3;
2108
    }
2109
    $$templateVars{'origNamefirst4'} = $FORM::origNamefirst4;
2110
    $$templateVars{'origNamelast4'} = $FORM::origNamelast4;
2111
    if($FORM::origNamefirst4 eq "" && $FORM::origNamelast4 eq ""){
2112
        $$templateVars{'origRole4'} = "";
2113
    }else{
2114
        $$templateVars{'origRole4'} = $FORM::origRole4;
2115
    }
2116
    $$templateVars{'origNamefirst5'} = $FORM::origNamefirst5;
2117
    $$templateVars{'origNamelast5'} = $FORM::origNamelast5;
2118
    if($FORM::origNamefirst5 eq "" && $FORM::origNamelast5 eq ""){
2119
        $$templateVars{'origRole5'} = "";
2120
    }else{
2121
        $$templateVars{'origRole5'} = $FORM::origRole5;
2122
    }
2123
    $$templateVars{'origNamefirst6'} = $FORM::origNamefirst6;
2124
    $$templateVars{'origNamelast6'} = $FORM::origNamelast6;
2125
    if($FORM::origNamefirst6 eq "" && $FORM::origNamelast6 eq ""){
2126
        $$templateVars{'origRole6'} = "";
2127
    }else{
2128
        $$templateVars{'origRole6'} = $FORM::origRole6;
2129
    }
2130
    $$templateVars{'origNamefirst7'} = $FORM::origNamefirst7;
2131
    $$templateVars{'origNamelast7'} = $FORM::origNamelast7;
2132
    if($FORM::origNamefirst7 eq "" && $FORM::origNamelast7 eq ""){
2133
        $$templateVars{'origRole7'} = "";
2134
    }else{
2135
        $$templateVars{'origRole7'} = $FORM::origRole7;
2136
    }
2137
    $$templateVars{'origNamefirst8'} = $FORM::origNamefirst8;
2138
    $$templateVars{'origNamelast8'} = $FORM::origNamelast8;
2139
    if($FORM::origNamefirst8 eq "" && $FORM::origNamelast8 eq ""){
2140
        $$templateVars{'origRole8'} = "";
2141
    }else{
2142
        $$templateVars{'origRole8'} = $FORM::origRole8;
2143
    }
2144
    $$templateVars{'origNamefirst9'} = $FORM::origNamefirst9;
2145
    $$templateVars{'origNamelast9'} = $FORM::origNamelast9;
2146
    if($FORM::origNamefirst9 eq "" && $FORM::origNamelast9 eq ""){
2147
        $$templateVars{'origRole9'} = "";
2148
    }else{
2149
        $$templateVars{'origRole9'} = $FORM::origRole9;
2150
    }
2151
    $$templateVars{'origNamefirst10'} = $FORM::origNamefirst10;
2152
    $$templateVars{'origNamelast10'} = $FORM::origNamelast10;
2153
    if($FORM::origNamefirst10 eq "" && $FORM::origNamelast10 eq ""){
2154
        $$templateVars{'origRole10'} = "";
2155
    }else{
2156
        $$templateVars{'origRole10'} = $FORM::origRole10;
2157
    }
2158
    $$templateVars{'abstract'} = $FORM::abstract;
2159
    $$templateVars{'keyword0'} = $FORM::keyword0;
2160
    $$templateVars{'kwType0'} = $FORM::kwType0;
2161
    $$templateVars{'kwTh0'} = $FORM::kwTh0;
2162
    $$templateVars{'kwType1'} = $FORM::kwType1;
2163
    $$templateVars{'keyword1'} = $FORM::keyword1;
2164
    $$templateVars{'kwTh1'} = $FORM::kwTh1;
2165
    $$templateVars{'kwType2'} = $FORM::kwType2;
2166
    $$templateVars{'keyword2'} = $FORM::keyword2;
2167
    $$templateVars{'kwTh2'} = $FORM::kwTh2;
2168
    $$templateVars{'kwType3'} = $FORM::kwType3;
2169
    $$templateVars{'keyword3'} = $FORM::keyword3;
2170
    $$templateVars{'kwTh3'} = $FORM::kwTh3;
2171
    $$templateVars{'kwType4'} = $FORM::kwType4;
2172
    $$templateVars{'keyword4'} = $FORM::keyword4;
2173
    $$templateVars{'kwTh4'} = $FORM::kwTh4;
2174
    $$templateVars{'kwType5'} = $FORM::kwType5;
2175
    $$templateVars{'keyword5'} = $FORM::keyword5;
2176
    $$templateVars{'kwTh5'} = $FORM::kwTh5;
2177
    $$templateVars{'kwType6'} = $FORM::kwType6;
2178
    $$templateVars{'keyword6'} = $FORM::keyword6;
2179
    $$templateVars{'kwTh6'} = $FORM::kwTh6;
2180
    $$templateVars{'kwType7'} = $FORM::kwType7;
2181
    $$templateVars{'keyword7'} = $FORM::keyword7;
2182
    $$templateVars{'kwTh7'} = $FORM::kwTh7;
2183
    $$templateVars{'kwType8'} = $FORM::kwType8;
2184
    $$templateVars{'keyword8'} = $FORM::keyword8;
2185
    $$templateVars{'kwTh8'} = $FORM::kwTh8;
2186
    $$templateVars{'kwType9'} = $FORM::kwType9;
2187
    $$templateVars{'keyword9'} = $FORM::keyword9;
2188
    $$templateVars{'kwTh9'} = $FORM::kwTh9;
2189
    $$templateVars{'addComments'} = $FORM::addComments;
2190
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2191
    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2192
    $$templateVars{'url'} = $FORM::url;
2193
    if($FORM::dataMedium eq "Select type of medium here."){
2194
        $$templateVars{'dataMedium'} = "";
2195
    }else{
2196
        $$templateVars{'dataMedium'} = $FORM::dataMedium;
2197
    }    
2198
    $$templateVars{'dataMediumOther'} = $FORM::dataMediumOther;
2199
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2200
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2201
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2202
    $$templateVars{'endingYear'} = $FORM::endingYear;
2203
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2204
    $$templateVars{'endingDay'} = $FORM::endingDay;
2205
    $$templateVars{'useSiteCoord'} = $FORM::useSiteCoord;
2206
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2207
    $$templateVars{'latMin1'} = $FORM::latMin1;
2208
    $$templateVars{'latSec1'} = $FORM::latSec1;
2209
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2210
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2211
    $$templateVars{'longMin1'} = $FORM::longMin1;
2212
    $$templateVars{'longSec1'} = $FORM::longSec1;
2213
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2214
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2215
    $$templateVars{'latMin2'} = $FORM::latMin2;
2216
    $$templateVars{'latSec2'} = $FORM::latSec2;
2217
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2218
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2219
    $$templateVars{'longMin2'} = $FORM::longMin2;
2220
    $$templateVars{'longSec2'} = $FORM::longSec2;
2221
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2222
    $$templateVars{'docid'} = $FORM::docid;
2223

    
2224
    $$templateVars{'section'} = "Confirm Data";
2225
    $template->process( $confirmDataTemplate, $templateVars);
2226

    
2227
    } else{    
2228
    # Errors from validation function. print the errors out using the response template
2229
    if (scalar(@errorMessages)) {
2230
        $$templateVars{'status'} = 'failure';
2231
        $$templateVars{'errorMessages'} = \@errorMessages;
2232
        $error = 1;
2233
    }
2234
        # Create our HTML response and send it back
2235
    $$templateVars{'function'} = "submitted";
2236
    $$templateVars{'section'} = "Submission Status";
2237
    $template->process( $responseTemplate, $templateVars);
2238
    }
2239
}
2240

    
2241

    
2242
################################################################################
2243
# 
2244
# From confirm Data template - user wants to make some changes.
2245
#
2246
################################################################################
2247
sub confirmDataToReEntryData{
2248
    my @sortedSites;
2249
    foreach my $site (sort @sitelist) {
2250
        push(@sortedSites, $site);
2251
    }
2252

    
2253
    $$templateVars{'siteList'} = \@sortedSites;
2254
    $$templateVars{'section'} = "Re-Entry Form";
2255

    
2256
    $$templateVars{'providerGivenName'} = $FORM::providerGivenName;
2257
    $$templateVars{'providerSurName'} = $FORM::providerSurName;
2258
    $$templateVars{'site'} = $FORM::site;
2259
    if($FORM::cfg eq "nceas"){
2260
        my $projects = getProjectList();
2261
        $$templateVars{'projects'} = $projects;
2262
        $$templateVars{'wg'} = \@FORM::wg;
2263
    }
2264
    $$templateVars{'identifier'} = $FORM::identifier;
2265
    $$templateVars{'title'} = $FORM::title;
2266
    $$templateVars{'origNamefirst0'} = $FORM::origNamefirst0;
2267
    $$templateVars{'origNamelast0'} = $FORM::origNamelast0;
2268
    $$templateVars{'origNameOrg'} = $FORM::origNameOrg;
2269
 #   $$templateVars{'origRole0'} = $FORM::origRole0;
2270
    $$templateVars{'origDelivery'} = $FORM::origDelivery;
2271
    $$templateVars{'origCity'} = $FORM::origCity;
2272
    $$templateVars{'origState'} = $FORM::origState;
2273
    $$templateVars{'origStateOther'} = $FORM::origStateOther;
2274
    $$templateVars{'origZIP'} = $FORM::origZIP;
2275
    $$templateVars{'origCountry'} = $FORM::origCountry;
2276
    $$templateVars{'origPhone'} = $FORM::origPhone;
2277
    $$templateVars{'origFAX'} = $FORM::origFAX;
2278
    $$templateVars{'origEmail'} = $FORM::origEmail;
2279
    if ($FORM::useSiteCoord ne "") {
2280
        $$templateVars{'useOrigAddress'} = "CHECKED";
2281
    }else{
2282
        $$templateVars{'useOrigAddress'} = $FORM::useOrigAddress;
2283
    }
2284
    $$templateVars{'origNamefirstContact'} = $FORM::origNamefirstContact;
2285
    $$templateVars{'origNamelastContact'} = $FORM::origNamelastContact;
2286
    $$templateVars{'origNameOrgContact'} = $FORM::origNameOrgContact;
2287
    $$templateVars{'origDeliveryContact'} = $FORM::origDeliveryContact; 
2288
    $$templateVars{'origCityContact'} = $FORM::origCityContact;
2289
    $$templateVars{'origStateContact'} = $FORM::origStateContact;
2290
    $$templateVars{'origStateOtherContact'} = $FORM::origStateOtherContact;
2291
    $$templateVars{'origZIPContact'} = $FORM::origZIPContact;
2292
    $$templateVars{'origCountryContact'} = $FORM::origCountryContact;
2293
    $$templateVars{'origPhoneContact'} = $FORM::origPhoneContact;
2294
    $$templateVars{'origFAXContact'} = $FORM::origFAXContact;
2295
    $$templateVars{'origEmailContact'} = $FORM::origEmailContact;    
2296
    $$templateVars{'origNamefirst1'} = $FORM::origNamefirst1;
2297
    $$templateVars{'origNamelast1'} = $FORM::origNamelast1;
2298
    $$templateVars{'origRole1'} = $FORM::origRole1;
2299
    $$templateVars{'origNamefirst2'} = $FORM::origNamefirst2;
2300
    $$templateVars{'origNamelast2'} = $FORM::origNamelast2;
2301
    $$templateVars{'origRole2'} = $FORM::origRole2;
2302
    $$templateVars{'origNamefirst3'} = $FORM::origNamefirst3;
2303
    $$templateVars{'origNamelast3'} = $FORM::origNamelast3;
2304
    $$templateVars{'origRole3'} = $FORM::origRole3;
2305
    $$templateVars{'origNamefirst4'} = $FORM::origNamefirst4;
2306
    $$templateVars{'origNamelast4'} = $FORM::origNamelast4;
2307
    $$templateVars{'origRole4'} = $FORM::origRole4;
2308
    $$templateVars{'origNamefirst5'} = $FORM::origNamefirst5;
2309
    $$templateVars{'origNamelast5'} = $FORM::origNamelast5;
2310
    $$templateVars{'origRole5'} = $FORM::origRole5;
2311
    $$templateVars{'origNamefirst6'} = $FORM::origNamefirst6;
2312
    $$templateVars{'origNamelast6'} = $FORM::origNamelast6;
2313
    $$templateVars{'origRole6'} = $FORM::origRole6;
2314
    $$templateVars{'origNamefirst7'} = $FORM::origNamefirst7;
2315
    $$templateVars{'origNamelast7'} = $FORM::origNamelast7;
2316
    $$templateVars{'origRole7'} = $FORM::origRole7;
2317
    $$templateVars{'origNamefirst8'} = $FORM::origNamefirst8;
2318
    $$templateVars{'origNamelast8'} = $FORM::origNamelast8;
2319
    $$templateVars{'origRole8'} = $FORM::origRole8;
2320
    $$templateVars{'origNamefirst9'} = $FORM::origNamefirst9;
2321
    $$templateVars{'origNamelast9'} = $FORM::origNamelast9;
2322
    $$templateVars{'origRole9'} = $FORM::origRole9;
2323
    $$templateVars{'origNamefirst10'} = $FORM::origNamefirst10;
2324
    $$templateVars{'origNamelast10'} = $FORM::origNamelast10;
2325
    $$templateVars{'origRole10'} = $FORM::origRole10;
2326
    $$templateVars{'abstract'} = $FORM::abstract;
2327
    $$templateVars{'keyword0'} = $FORM::keyword0;
2328
    $$templateVars{'kwType0'} = $FORM::kwType0;
2329
    $$templateVars{'kwTh0'} = $FORM::kwTh0;
2330
    $$templateVars{'kwType1'} = $FORM::kwType1;
2331
    $$templateVars{'keyword1'} = $FORM::keyword1;
2332
    $$templateVars{'kwTh1'} = $FORM::kwTh1;
2333
    $$templateVars{'kwType2'} = $FORM::kwType2;
2334
    $$templateVars{'keyword2'} = $FORM::keyword2;
2335
    $$templateVars{'kwTh2'} = $FORM::kwTh2;
2336
    $$templateVars{'kwType3'} = $FORM::kwType3;
2337
    $$templateVars{'keyword3'} = $FORM::keyword3;
2338
    $$templateVars{'kwTh3'} = $FORM::kwTh3;
2339
    $$templateVars{'kwType4'} = $FORM::kwType4;
2340
    $$templateVars{'keyword4'} = $FORM::keyword4;
2341
    $$templateVars{'kwTh4'} = $FORM::kwTh4;
2342
    $$templateVars{'kwType5'} = $FORM::kwType5;
2343
    $$templateVars{'keyword5'} = $FORM::keyword5;
2344
    $$templateVars{'kwTh5'} = $FORM::kwTh5;
2345
    $$templateVars{'kwType6'} = $FORM::kwType6;
2346
    $$templateVars{'keyword6'} = $FORM::keyword6;
2347
    $$templateVars{'kwTh6'} = $FORM::kwTh6;
2348
    $$templateVars{'kwType7'} = $FORM::kwType7;
2349
    $$templateVars{'keyword7'} = $FORM::keyword7;
2350
    $$templateVars{'kwTh7'} = $FORM::kwTh7;
2351
    $$templateVars{'kwType8'} = $FORM::kwType8;
2352
    $$templateVars{'keyword8'} = $FORM::keyword8;
2353
    $$templateVars{'kwTh8'} = $FORM::kwTh8;
2354
    $$templateVars{'kwType9'} = $FORM::kwType9;
2355
    $$templateVars{'keyword9'} = $FORM::keyword9;
2356
    $$templateVars{'kwTh9'} = $FORM::kwTh9;
2357
    $$templateVars{'addComments'} = $FORM::addComments;
2358
    $$templateVars{'useConstraints'} = $FORM::useConstraints;
2359
    $$templateVars{'useConstraintsOther'} = $FORM::useConstraintsOther;
2360
    $$templateVars{'url'} = $FORM::url;
2361
    $$templateVars{'dataMedium'} = $FORM::dataMedium;
2362
    $$templateVars{'dataMediumOther'} = $FORM::dataMediumOther;
2363
    $$templateVars{'beginningYear'} = $FORM::beginningYear;
2364
    $$templateVars{'beginningMonth'} = $FORM::beginningMonth;
2365
    $$templateVars{'beginningDay'} = $FORM::beginningDay;
2366
    $$templateVars{'endingYear'} = $FORM::endingYear;
2367
    $$templateVars{'endingMonth'} = $FORM::endingMonth;
2368
    $$templateVars{'endingDay'} = $FORM::endingDay;
2369
    if($FORM::useSiteCoord ne ""){
2370
    $$templateVars{'useSiteCoord'} = "CHECKED";
2371
    }else{
2372
    $$templateVars{'useSiteCoord'} = "";
2373
    }
2374
    $$templateVars{'latDeg1'} = $FORM::latDeg1;
2375
    $$templateVars{'latMin1'} = $FORM::latMin1;
2376
    $$templateVars{'latSec1'} = $FORM::latSec1;
2377
    $$templateVars{'hemisphLat1'} = $FORM::hemisphLat1;
2378
    $$templateVars{'longDeg1'} = $FORM::longDeg1;
2379
    $$templateVars{'longMin1'} = $FORM::longMin1;
2380
    $$templateVars{'longSec1'} = $FORM::longSec1;
2381
    $$templateVars{'hemisphLong1'} = $FORM::hemisphLong1;
2382
    $$templateVars{'latDeg2'} = $FORM::latDeg2;
2383
    $$templateVars{'latMin2'} = $FORM::latMin2;
2384
    $$templateVars{'latSec2'} = $FORM::latSec2;
2385
    $$templateVars{'hemisphLat2'} = $FORM::hemisphLat2;
2386
    $$templateVars{'longDeg2'} = $FORM::longDeg2;
2387
    $$templateVars{'longMin2'} = $FORM::longMin2;
2388
    $$templateVars{'longSec2'} = $FORM::longSec2;
2389
    $$templateVars{'hemisphLong2'} = $FORM::hemisphLong2;
2390
    $$templateVars{'docid'} = $FORM::docid;
2391

    
2392
    $$templateVars{'form'} = 're_entry';
2393
    $template->process( $entryFormTemplate, $templateVars);
2394
}
2395

    
2396

    
2397
################################################################################
2398
# 
2399
# check if there is multiple occurence of the given tag and find its value.
2400
#
2401
################################################################################
2402

    
2403
sub findValue {
2404
    my $node = shift;
2405
    my $value = shift;
2406
    my $result;
2407
    my $tempNode;
2408

    
2409
    $result = $node->findnodes("./$value");
2410
    if ($result->size > 1) {
2411
        errMoreThanOne("$value");
2412
    } else {
2413
        foreach $tempNode ($result->get_nodelist){
2414
            #print $tempNode->nodeName().":".$tempNode->textContent();
2415
            #print "\n";
2416
            return $tempNode->textContent();
2417
        }
2418
    }
2419
}
2420

    
2421

    
2422
################################################################################
2423
# 
2424
# check if given tags has any children. if not return the value
2425
#
2426
################################################################################
2427
sub findValueNoChild {
2428
    my $node = shift;
2429
    my $value = shift;
2430
    my $tempNode;
2431
    my $childNodes;
2432
    my $result;
2433
    my $error;
2434

    
2435
    $result = $node->findnodes("./$value");
2436
    if($result->size > 1){
2437
       errMoreThanOne("$value");
2438
    } else {
2439
        foreach $tempNode ($result->get_nodelist) {
2440
            $childNodes = $tempNode->childNodes;
2441
            if ($childNodes->size() > 1) {
2442
                $error ="The tag $value has children which cannot be shown using the form. Please use Morpho to edit this document";    
2443
                push(@errorMessages, $error);
2444
                #if ($DEBUG == 1){ print $error."\n";}
2445
            } else {
2446
                #print $tempNode->nodeName().":".$tempNode->textContent();
2447
                #print "\n";
2448
                return $tempNode->textContent();
2449
            }
2450
        }
2451
    }
2452
}
2453

    
2454

    
2455
################################################################################
2456
# 
2457
# check if given tags are children of given node.
2458
#
2459
################################################################################
2460
sub dontOccur {
2461
    my $node = shift;
2462
    my $value = shift;
2463
    my $errVal = shift;
2464

    
2465
    my $result = $node->findnodes("$value");
2466
    if($result->size > 0){
2467
        $error ="One of the following tags found: $errVal. Please use Morpho to edit this document";
2468
        push(@errorMessages, $error."\n");
2469
        #if ($DEBUG == 1){ print $error;}
2470
    } 
2471
}
2472

    
2473

    
2474
################################################################################
2475
# 
2476
# print out error for more than one occurence of a given tag
2477
#
2478
################################################################################
2479
sub errMoreThanOne {
2480
    my $value = shift;
2481
    my $error ="More than one occurence of the tag $value found. Please use Morpho to edit this document";
2482
    push(@errorMessages, $error."\n");
2483
    # if ($DEBUG == 1){ print $error;}
2484
}
2485

    
2486

    
2487
################################################################################
2488
# 
2489
# print out error for more than given number of occurences of a given tag
2490
#
2491
################################################################################
2492
sub errMoreThanN {
2493
    my $value = shift;
2494
    my $error ="More occurences of the tag $value found than that can be shown in the form. Please use Morpho to edit this document";
2495
    push(@errorMessages, $error);
2496
    #if ($DEBUG == 1){ print $error."\n";}
2497
}
2498

    
2499

    
2500
################################################################################
2501
# 
2502
# convert coord to degrees, minutes and seconds form. 
2503
#
2504
################################################################################
2505
#sub convertCoord {
2506
#    my $wx = shift;
2507
#    print $deg." ".$min." ".$sec;
2508
#    print "\n";
2509
#}
2510

    
2511

    
2512
################################################################################
2513
# 
2514
# print debugging messages to stderr
2515
#
2516
################################################################################
2517
sub debug {
2518
    my $msg = shift;
2519
    
2520
    if ($debug) {
2521
        print STDERR "$msg\n";
2522
    }
2523
}
2524

    
2525
################################################################################
2526
# 
2527
# get the list of projects
2528
#
2529
################################################################################
2530
sub getProjectList {
2531
    
2532
    #use NCEAS::AdminDB;
2533

    
2534
    #my $admindb = NCEAS::AdminDB->new();
2535
    #$admindb->connect($nceas_db, $nceas_db_user, $nceas_db_password);
2536
    #my $projects = $admindb->getProjects();
2537

    
2538
    # This block is for testing only!  Remove for production use
2539
    my @row1;
2540
    $row1[0] = 6000; $row1[1] = 'Andelman'; $row1[2] = 'Sandy'; $row1[3] = 'The very long and windy path to an apparent ecological conclusion: statistics lie';
2541
    my @row2; 
2542
    $row2[0] = 7000; $row2[1] = 'Bascompte'; $row2[2] = 'Jordi'; $row2[3] = 'Postdoctoral Fellow';
2543
    my @projects;
2544
    $projects[0] = \@row1;
2545
    $projects[1] = \@row2;
2546
    return \@projects;
2547

    
2548
    #return $projects;
2549
}
    (1-1/1)