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-17 17:37:46 -0800 (Wed, 17 Dec 2003) $'
8
# '$Revision: 1974 $' 
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
    $doc .= $creat;
935
    $doc .= $metaP;
936
    $doc .= $apart;
937

    
938
    $doc .= "<abstract>\n";
939
    $doc .= "<para>$FORM::abstract</para>\n";
940
    $doc .= "</abstract>\n";
941

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

    
971
    if (hasContent($FORM::addComments)) {
972
        $doc .= "<additionalInfo>\n";
973
        $doc .= "<para>$FORM::addComments</para>\n";
974
        $doc .= "</additionalInfo>\n";
975
    }
976

    
977
    if (hasContent($FORM::useConstraints) || 
978
        hasContent($FORM::useConstraintsOther)) {
979
        $doc .= "<intellectualRights>\n";
980
        if (hasContent($FORM::useConstraints)) {
981
            $doc .= "<para>$FORM::useConstraints</para>\n";
982
        }
983
        if (hasContent($FORM::useConstraintsOther)) {
984
            $doc .= "<para>$FORM::useConstraintsOther</para>\n";
985
        }
986
        $doc .= "</intellectualRights>\n";
987
    }
988

    
989
    
990
    if (hasContent($FORM::url)) {
991
	$doc .= "<distribution>\n";
992
        $doc .= "<online>\n";
993
	$doc .= "<url>$FORM::url</url>\n";
994
	$doc .= "</online>\n";
995
	$doc .= "</distribution>\n";
996
    }
997
    
998
    $doc .= "<distribution>\n";
999
    $doc .= "<offline>\n";
1000
    $doc .= "<mediumName>" . "$FORM::dataMedium   $FORM::dataMediumOther";
1001
    $doc .= "</mediumName>\n";
1002
    $doc .= "</offline>\n";
1003
    $doc .= "</distribution>\n";
1004
            
1005
    $doc .= "<coverage>\n";
1006
    $doc .= "<temporalCoverage>\n";
1007

    
1008

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

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

    
1062
    $doc .= "</temporalCoverage>\n";
1063
    
1064
    $doc .= "<geographicCoverage>\n";
1065
    $doc .= "<geographicDescription></geographicDescription>\n";
1066
    $doc .= "<boundingCoordinates>\n";
1067

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

    
1100
    $hemisph = ($hemisphLong2 eq "W") ? -1 : 1;
1101
    $doc .= "<eastBoundingCoordinate>";
1102
    $doc .= $hemisph * ($longDeg2 + (60*$longMin2+$longSec2)/3600);
1103
    $doc .= "</eastBoundingCoordinate>\n";
1104

    
1105
    $hemisph = ($hemisphLat1 eq "S") ? -1 : 1;
1106
    $doc .= "<northBoundingCoordinate>";
1107
    $doc .= $hemisph * ($latDeg1 + (60*$latMin1+$latSec1)/3600);
1108
    $doc .= "</northBoundingCoordinate>\n";
1109

    
1110
    $hemisph = ($hemisphLat2 eq "S") ? -1 : 1;
1111
    $doc .= "<southBoundingCoordinate>";
1112
    $doc .= $hemisph * ($latDeg2 + (60*$latMin2+$latSec2)/3600);
1113
    $doc .= "</southBoundingCoordinate>\n";
1114

    
1115
    $doc .= "</boundingCoordinates>\n";
1116
    $doc .= "</geographicCoverage>\n";
1117

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

    
1150
    $doc .= "</coverage>\n";
1151

    
1152
    $doc .= $cont;
1153
    $doc .= $publ;
1154

    
1155
    $doc .= "<access authSystem=\"knb\" order=\"denyFirst\">\n";
1156
    $doc .= "<allow>\n";
1157
    $doc .= "<principal>uid=obfsadmin,o=LTER,dc=ecoinformatics,dc=org</principal>\n";
1158
    $doc .= "<permission>all</permission>\n";
1159
    $doc .= "</allow>\n";
1160
    $doc .= "<allow>\n";
1161
    $doc .= "<principal>uid=$FORM::username,o=$FORM::organization,dc=ecoinformatics,dc=org</principal>\n";
1162
    $doc .= "<permission>all</permission>\n";
1163
    $doc .= "</allow>\n";
1164
    $doc .= "<allow>\n";
1165
    $doc .= "<principal>public</principal>\n";
1166
    $doc .= "<permission>read</permission>\n";
1167
    $doc .= "</allow>\n";
1168
    $doc .= "</access>\n";
1169
    
1170
    $doc .= "</dataset>\n</eml:eml>\n";
1171

    
1172
    return $doc;
1173
}
1174

    
1175

    
1176
################################################################################
1177
# 
1178
# send an email message notifying the moderator of a new submission 
1179
#
1180
################################################################################
1181
sub sendNotification {
1182
    my $identifier = shift;
1183
    my $mailhost = shift;
1184
    my $sender = shift;
1185
    my $recipient = shift;
1186

    
1187
    my $smtp = Net::SMTP->new($mailhost);
1188
    $smtp->mail($sender);
1189
    $smtp->to($recipient);
1190

    
1191
    my $message = <<"    ENDOFMESSAGE";
1192
    To: $recipient
1193
    From: $sender
1194
    Subject: New data submission
1195
    
1196
    Data was submitted to the data registry.  
1197
    The identifying information for the new data set is:
1198

    
1199
    Identifier: $identifier
1200
    Title: $FORM::title
1201
    Submitter: $FORM::providerGivenName $FORM::providerSurName
1202

    
1203
    Please review the submmission and grant public read access if appropriate.
1204
    Thanks
1205
    
1206
    ENDOFMESSAGE
1207
    $message =~ s/^[ \t\r\f]+//gm;
1208

    
1209
    $smtp->data($message);
1210
    $smtp->quit;
1211
}
1212

    
1213

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

    
1237
    $metacat = Metacat->new();
1238
    if ($metacat) {
1239
        $metacat->set_options( metacatUrl => $metacatUrl );
1240
    } else {
1241
        #die "failed during metacat creation\n";
1242
        push(@errorMessages, "Failed during metacat creation.");
1243
    }
1244
    
1245
    $httpMessage = $metacat->read($docid);
1246
    $doc = $httpMessage->content();
1247
    $xmldoc = $parser->parse_string($doc);
1248

    
1249
#    $tempfile = $xslConvDir.$docid;
1250
#    push (@fileArray, $tempfile);
1251

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

    
1296
	    # Read the main document. 
1297

    
1298
	    $tempfile = $tmpdir."/".$docid; #= $xslConvDir.$docid;
1299
	    open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1300
	    print TFILE $doc;
1301
	    close(TFILE);
1302
	    
1303
	    # Transforming beta6 to eml 2
1304
	    my $xslt;
1305
	    my $triplesheet;
1306
	    my $results;
1307
	    my $stylesheet;
1308
	    my $resultsheet;
1309
	    
1310
	    $xslt = XML::LibXSLT->new();
1311
#	    $tempfile = $xslConvDir."triple_info.xsl";
1312
	    $tempfile = $tmpdir."/"."triple_info.xsl";
1313

    
1314
	    $triplesheet = $xslt->parse_stylesheet_file($tempfile);
1315

    
1316
#	    $results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1317
	    $results = $triplesheet->transform($xmldoc, packageDir => "\'$tmpdir/\'", packageName => "\'$docid\'");
1318

    
1319
#	    $tempfile = $xslConvDir."emlb6toeml2.xsl";
1320
	    $tempfile = $tmpdir."/"."emlb6toeml2.xsl";
1321
	    $stylesheet = $xslt->parse_stylesheet_file($tempfile);
1322
	    $resultsheet = $stylesheet->transform($results);
1323
	    
1324
	    #$tempfile = "/usr/local/apache2/htdocs/xml/test.xml";;
1325
	    #open (TFILE,">$tempfile") || die ("Cant open xml file...\n");
1326
	    #print TFILE $stylesheet->output_string($resultsheet);
1327
	    #close(TFILE);
1328

    
1329
	    getFormValuesFromEml2($resultsheet);
1330
	    
1331
	    # Delete the files written earlier. 
1332
	    unlink @fileArray;
1333

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

    
1355

    
1356

    
1357
sub getFormValuesFromEml2 {
1358
    
1359
    my $doc = shift;
1360
    my $results;
1361
    my $error;
1362
    my $node;
1363
    my $tempResult;
1364
    my $tempNode;
1365
    my $aoCount = 1;
1366
    my $foundDSO;
1367

    
1368
    # find out the tag <alternateIdentifier>. 
1369
    $results = $doc->findnodes('//dataset/alternateIdentifier');
1370
    if($results->size() > 1){
1371
	errMoreThanOne("alternateIdentifier");
1372
    } else {
1373
	foreach $node ($results->get_nodelist){
1374
	    $$templateVars{'identifier'} = findValue($node, '../alternateIdentifier');
1375
	}
1376
    }
1377

    
1378
    # find out the tag <title>. 
1379
    $results = $doc->findnodes('//dataset/title');
1380
    if($results->size() > 1){
1381
	errMoreThanOne("title");
1382
    } elsif($results->size() < 1){
1383
	$error ="Following tag not found: title. Please use Morpho to edit this document";
1384
	push(@errorMessages, $error."\n");
1385
	#if ($DEBUG == 1){ print $error;}
1386
    } else {
1387
	foreach $node ($results->get_nodelist){
1388
	$$templateVars{'title'} = findValue($node, '../title');
1389
	}
1390
    }
1391

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

    
1466
    $results = $doc->findnodes('//dataset/creator/organizationName');
1467
    if($results->size() > 3){
1468
	errMoreThanN("creator/organizationName");	
1469
    } else {
1470
	foreach $node ($results->get_nodelist){
1471

    
1472
	    my $tempValue = findValue($node,'../organizationName');
1473
	    $tempResult = $node->findnodes('../individualName');
1474
	    if($tempResult->size == 0 && $tempValue ne $organization){
1475
		$$templateVars{'site'} = $tempValue;
1476
	    }
1477
	}
1478
    }
1479

    
1480
    $results = $doc->findnodes('//dataset/metadataProvider');
1481
    if($results->size() > 11){
1482
	errMoreThanN("metadataProvider");	
1483
    } else {
1484
	foreach $node ($results->get_nodelist){
1485
	    dontOccur($node, "./organizationName|./positionName|./onlineURL|./userId|./electronicMailAddress|./phone|./address", 
1486
		      "organizationName, positionName, onlineURL, userId, electronicMailAddress, phone, address in metadataProvider");
1487
	    
1488
	    $tempResult = $node->findnodes('./individualName');
1489
	    if($tempResult->size > 1){
1490
		errMoreThanOne("metadataProvider/indvidualName");
1491
	    }else{
1492
		foreach $tempNode ($tempResult->get_nodelist){
1493
		    if($$templateVars{'providerGivenName'} ne ""){
1494
			$$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1495
			$$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1496
			$$templateVars{"origRole$aoCount"} = "Metadata Provider";
1497
			$aoCount++;
1498
		    } else {
1499
			$$templateVars{'providerGivenName'} =  findValue($tempNode, './givenName');
1500
			$$templateVars{'providerSurName'} =  findValue($tempNode, './surName');
1501
		    }
1502
		}
1503
	    }
1504
	}
1505
    }
1506

    
1507

    
1508
    $results = $doc->findnodes('//dataset/associatedParty');
1509
    if($results->size() > 10){
1510
	errMoreThanN("associatedParty");
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 associatedParty");
1515
	   
1516
	    $tempResult = $node->findnodes('./individualName');
1517
	    if($tempResult->size > 1){
1518
		errMoreThanOne("associatedParty/indvidualName");
1519
	    }else{
1520
		foreach $tempNode ($tempResult->get_nodelist){
1521
		    $$templateVars{"origNamefirst$aoCount"} =  findValue($tempNode, './givenName');
1522
		    $$templateVars{"origNamelast$aoCount"} =  findValue($tempNode, './surName');
1523
		    $$templateVars{"origRole$aoCount"} = findValue($tempNode, '../role');
1524
		    $aoCount++;		   
1525
		}
1526
	    }
1527
	}
1528
    }
1529

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

    
1552
    if($aoCount > 11){
1553
	errMoreThanN("Additional Originators");
1554
    } 
1555

    
1556
    dontOccur($doc, "./pubDate", "pubDate");
1557
    dontOccur($doc, "./language", "language");
1558
    dontOccur($doc, "./series", "series");
1559
    
1560

    
1561
    $results = $doc->findnodes('//dataset/abstract');
1562
    if($results->size() > 1){
1563
	errMoreThanOne("abstract");
1564
    } else {
1565
	foreach my $node ($results->get_nodelist){
1566
	    dontOccur($node, "./section", "section");
1567
	    $$templateVars{'abstract'} = findValueNoChild($node, "para");
1568
	}
1569
    }
1570

    
1571
    $results = $doc->findnodes('//dataset/keywordSet');
1572
    if($results->size() > 10){
1573
	errMoreThanN("keywordSet");
1574
    } else {
1575
	my $count = 0;
1576
	foreach $node ($results->get_nodelist){
1577
	    $tempResult = $node->findnodes('./keyword');
1578
	    if($tempResult->size() > 1){
1579
		errMoreThanOne("keyword");
1580
	    } else {
1581
		foreach $tempNode ($tempResult->get_nodelist){
1582
		    $$templateVars{"keyword$count"} = $tempNode->textContent();
1583
		    if($tempNode->hasAttributes()){
1584
			my @attlist = $tempNode->attributes();
1585
			$$templateVars{"kwType$count"} = $attlist[0]->value;
1586
		    }  
1587
	 	} 
1588
	    }
1589
	    $$templateVars{"kwTh$count"} = findValue($node, "keywordThesaurus");
1590
	    $count++;
1591
	}
1592
	
1593
	while($count<11){
1594
	    $$templateVars{"kwType$count"} = "none";
1595
	    $$templateVars{"kwTh$count"} = "none";
1596
	    $count++;
1597
	}
1598
    }
1599

    
1600

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

    
1611
    $$templateVars{'useConstraints'} = "";
1612
    $results = $doc->findnodes('//dataset/intellectualRights');
1613
    if($results->size() > 1){
1614
	errMoreThanOne("intellectualRights");
1615
    } else {
1616
	foreach $node ($results->get_nodelist){
1617
	    dontOccur($node, "./section", "section in intellectualRights");
1618

    
1619
	    $tempResult = $node->findnodes("para");
1620
	    if($tempResult->size > 2){
1621
	   	errMoreThanN("para");
1622
	    } else {
1623
		foreach $tempNode ($tempResult->get_nodelist){
1624
		    my $childNodes = $tempNode->childNodes;
1625
		    if($childNodes->size() > 1){
1626
			$error ="The tag para in intellectualRights has children which cannot be shown using the form. Please use Morpho to edit this document";	
1627
			push(@errorMessages, $error);
1628
			#if ($DEBUG == 1){ print $error."\n";}
1629
		    }else{
1630
			#print $tempNode->nodeName().":".$tempNode->textContent();
1631
			#print "\n";
1632
			if($$templateVars{'useConstraints'} eq ""){
1633
			    $$templateVars{'useConstraints'} = $tempNode->textContent();
1634
			} else {
1635
			    $$templateVars{'useConstraintsOther'} = $tempNode->textContent();
1636
			}
1637
		    }
1638
		}
1639
	    }
1640
	}
1641
    }
1642

    
1643

    
1644
    $results = $doc->findnodes('//dataset/distribution/online');
1645
    if($results->size() > 1){
1646
	errMoreThanOne("distribution/online");
1647
    } else {
1648
	foreach my $tempNode ($results->get_nodelist){
1649
	    $$templateVars{'url'} = findValue($tempNode, "url");
1650
	    dontOccur($tempNode, "./connection", "/distribution/online/connection");
1651
	    dontOccur($tempNode, "./connectionDefinition", "/distribution/online/connectionDefinition");
1652
	}
1653
    }
1654

    
1655

    
1656
    $results = $doc->findnodes('//dataset/distribution/offline');
1657
    if($results->size() > 1){
1658
	errMoreThanOne("distribution/online");
1659
    } else {
1660
	foreach my $tempNode ($results->get_nodelist){
1661
	    $$templateVars{'dataMedium'} = findValue($tempNode, "mediumName");
1662
	    dontOccur($tempNode, "./mediumDensity", "/distribution/offline/mediumDensity");
1663
	    dontOccur($tempNode, "./mediumDensityUnits", "/distribution/offline/mediumDensityUnits");
1664
	    dontOccur($tempNode, "./mediumVolume", "/distribution/offline/mediumVolume");
1665
	    dontOccur($tempNode, "./mediumFormat", "/distribution/offline/mediumFormat");
1666
	    dontOccur($tempNode, "./mediumNote", "/distribution/offline/mediumNote");
1667
	}
1668
    }
1669

    
1670
    dontOccur($doc, "./inline", "//dataset/distribution/inline");
1671

    
1672

    
1673
    $results = $doc->findnodes('//dataset/coverage');
1674
    if($results->size() > 1){
1675
	errMoreThanOne("coverage");
1676
    } else {
1677
	foreach $node ($results->get_nodelist){
1678
	    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");
1679

    
1680
	    $tempResult = $node->findnodes('./temporalCoverage');
1681
	    if($tempResult->size > 1){
1682
	       	errMoreThanOne("temporalCoverage");
1683
	    }else{
1684
		foreach $tempNode ($tempResult->get_nodelist){
1685
		    my $x;
1686
		    my $y;
1687
		    my $z;
1688
		    my $tempdate = findValue($tempNode, "rangeOfDates/beginDate/calendarDate");
1689
		    ($x, $y, $z) = split("-", $tempdate); 
1690
		    $$templateVars{'beginningYear'} = $x;
1691
		    $$templateVars{'beginningMonth'} = $y;
1692
		    $$templateVars{'beginningDay'} = $z;
1693

    
1694
		    $tempdate = findValue($tempNode, "rangeOfDates/endDate/calendarDate");
1695
		    ($x, $y, $z) = split("-", $tempdate);
1696
		    $$templateVars{'endingYear'} = $x;
1697
		    $$templateVars{'endingMonth'} = $y;
1698
		    $$templateVars{'endingDay'} = $z;
1699
		    
1700
		    $tempdate = "";
1701
		    $tempdate = findValue($tempNode, "singleDateTime/calendarDate");
1702
		    if($tempdate ne ""){
1703
			($x, $y, $z) = split("-", $tempdate);
1704
			$$templateVars{'beginningYear'} = $x;
1705
			$$templateVars{'beginningMonth'} = $y;
1706
			$$templateVars{'beginningDay'} = $z;
1707
		    }  
1708
		}
1709
	    }
1710

    
1711
	    $tempResult = $node->findnodes('./geographicCoverage');
1712
	    if($tempResult->size > 1){
1713
		errMoreThanOne("geographicCoverage");
1714
	    }else{
1715
		foreach $tempNode ($tempResult->get_nodelist){
1716

    
1717
		    my $coord;
1718

    
1719
		    $coord = findValue($tempNode, "boundingCoordinates/westBoundingCoordinate");
1720
		    if($coord > 0){
1721
			#print "+";
1722
			$$templateVars{'hemisphLong1'} = "E";
1723
		    } else {
1724
			#print "-";
1725
			eval($coord = $coord * -1);
1726
			$$templateVars{'hemisphLong1'} = "W";
1727
		    }
1728
		    eval($$templateVars{'longDeg1'} = int($coord));
1729
		    eval($coord = ($coord - int($coord))*60);
1730
		    eval($$templateVars{'longMin1'} = int($coord));
1731
		    eval($coord = ($coord - int($coord))*60);
1732
		    eval($$templateVars{'longSec1'} = int($coord));
1733
		    
1734

    
1735
		    $coord = findValue($tempNode, "boundingCoordinates/southBoundingCoordinate");
1736
		    if($coord > 0){
1737
			#print "+";
1738
			$$templateVars{'hemisphLat2'} = "N";
1739
		    } else {
1740
			#print "-";
1741
			eval($coord = $coord * -1);
1742
			$$templateVars{'hemisphLat2'} = "S";
1743
		    }
1744
		    eval($$templateVars{'latDeg2'} = int($coord));
1745
		    eval($coord = ($coord - int($coord))*60);
1746
		    eval($$templateVars{'latMin2'} = int($coord));
1747
		    eval($coord = ($coord - int($coord))*60);
1748
		    eval($$templateVars{'latSec2'} = int($coord));
1749

    
1750

    
1751
		    $coord = findValue($tempNode, "boundingCoordinates/northBoundingCoordinate");
1752
		    if($coord > 0){
1753
			#print "+";
1754
			$$templateVars{'hemisphLat1'} = "N";
1755
		    } else {
1756
			#print "-";
1757
			eval($coord = $coord * -1);
1758
			$$templateVars{'hemisphLat1'} = "S";
1759
		    }
1760
		    eval($$templateVars{'latDeg1'} = int($coord));
1761
		    eval($coord = ($coord - int($coord))*60);
1762
		    eval($$templateVars{'latMin1'} = int($coord));
1763
		    eval($coord = ($coord - int($coord))*60);
1764
		    eval($$templateVars{'latSec1'} = int($coord));
1765

    
1766

    
1767
		    $coord = findValue($tempNode, "boundingCoordinates/eastBoundingCoordinate");
1768
		    if($coord > 0){
1769
			#print "+";
1770
			$$templateVars{'hemisphLong2'} = "E";
1771
		    } else {
1772
			#print "-";
1773
			eval($coord = $coord * -1);
1774
			$$templateVars{'hemisphLong2'} = "W";
1775
		    }
1776
		    eval($$templateVars{'longDeg2'} = int($coord));
1777
		    eval($coord = ($coord - int($coord))*60);
1778
		    eval($$templateVars{'longMin2'} = int($coord));
1779
		    eval($coord = ($coord - int($coord))*60);
1780
		    eval($$templateVars{'longSec2'} = int($coord));
1781
		}
1782
	    }
1783
	}
1784
    }
1785

    
1786
    dontOccur($doc, "./purpose", "purpose");
1787
    dontOccur($doc, "./maintenance", "maintnance");
1788

    
1789

    
1790
    $results = $doc->findnodes('//dataset/contact/individualName');
1791
    if($results->size() > 1){
1792
	errMoreThanOne("contact/individualName");
1793
    } else {
1794
	foreach $node ($results->get_nodelist){
1795
	    dontOccur($node, "../positionName|../onlineURL|../userId", 
1796
		      "positionName, onlineURL, userId in contact tag");
1797
	    
1798
	    dontOccur($node, "./saluation", "saluation in contact tag");			    
1799
	    
1800
	    $tempResult = $node->findnodes('../address|../phone|../electronicmailAddress|../organizationName');
1801
	    if($tempResult->size > 0){
1802
		
1803
		$$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
1804
		$$templateVars{'origNamelastContact'} = findValue($node, 'surName');
1805
	
1806
		my $tempResult2 = $node->findnodes('../address');
1807
		if($tempResult2->size > 1){
1808
		    errMoreThanOne("address");
1809
		} else {
1810
		    foreach my $tempNode2 ($tempResult2->get_nodelist){
1811
			$$templateVars{'origDeliveryContact'} = findValue($tempNode2, 'deliveryPoint');
1812
			$$templateVars{'origCityContact'} = findValue($tempNode2, 'city');
1813
			$$templateVars{'origStateContact'} = findValue($tempNode2, 'administrativeArea');
1814
			$$templateVars{'origZIPContact'} = findValue($tempNode2, 'postalCode');
1815
			$$templateVars{'origCountryContact'} = findValue($tempNode2, 'country');
1816
		    }
1817
		}
1818
		
1819
		my $tempResult3 = $node->findnodes('../phone');
1820
		if($tempResult3->size > 2){
1821
		    errMoreThanN("phone");
1822
		} else {
1823
		    foreach my $tempNode2 ($tempResult3->get_nodelist){
1824
			if($tempNode2->hasAttributes()){
1825
			    my @attlist = $tempNode2->attributes();
1826
			    if($attlist[0]->value eq "Fax"){
1827
				$$templateVars{'origFAXContact'} = $tempNode2->textContent();
1828
			    } else {
1829
				$$templateVars{'origPhoneContact'} = $tempNode2->textContent();
1830
			    }
1831
			}else{
1832
			    $$templateVars{'origPhoneContact'} = $tempNode2->textContent();
1833
			}
1834
		    }
1835
		}
1836
		$$templateVars{'origEmailContact'} = findValue($node, '../electronicMailAddress');
1837
		$$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
1838
	    } else {
1839
		$$templateVars{'origNamefirstContact'} = findValue($node, 'givenName');
1840
		$$templateVars{'origNamelastContact'} = findValue($node, 'surName');
1841
		$$templateVars{'origNameOrgContact'} = findValue($node, '../organizationName');
1842
	    }
1843
	}
1844
    }
1845

    
1846
    
1847
    dontOccur($doc, "./pubPlace", "pubPlace");
1848
    dontOccur($doc, "./methods", "methods");
1849
    dontOccur($doc, "./project", "project");
1850
    
1851
    dontOccur($doc, "./dataTable", "dataTable");
1852
    dontOccur($doc, "./spatialRaster", "spatialRaster");
1853
    dontOccur($doc, "./spatialVector", "spatialVector");
1854
    dontOccur($doc, "./storedProcedure", "storedProcedure");
1855
    dontOccur($doc, "./view", "view");
1856
    dontOccur($doc, "./otherEntity", "otherEntity");
1857
    dontOccur($doc, "./references", "references");
1858
    
1859
    dontOccur($doc, "//citation", "citation");
1860
    dontOccur($doc, "//software", "software");
1861
    dontOccur($doc, "//protocol", "protocol");
1862
    dontOccur($doc, "//additionalMetadata", "additionalMetadata");    
1863
}
1864

    
1865

    
1866
################################################################################
1867
# 
1868
# Delete the eml file that has been requested for deletion. 
1869
#
1870
################################################################################
1871
sub deleteData {
1872
    my $deleteAll = shift;
1873
    
1874
    # create metacat instance
1875
    my $metacat;
1876
    my $docid = $FORM::docid;
1877
    
1878
    $metacat = Metacat->new();
1879
    if ($metacat) {
1880
        $metacat->set_options( metacatUrl => $metacatUrl );
1881
    } else {
1882
        #die "failed during metacat creation\n";
1883
        push(@errorMessages, "Failed during metacat creation.");
1884
    }
1885

    
1886
    # Login to metacat
1887
    my $userDN = $FORM::username;
1888
    my $userOrg = $FORM::organization;
1889
    my $userPass = $FORM::password;
1890
    my $dname = "uid=$userDN,o=$userOrg,dc=ecoinformatics,dc=org";
1891
    
1892
    my $errorMessage = "";
1893
    my $response = $metacat->login($dname, $userPass);
1894

    
1895
    if (! $response) {
1896
	# Could not login
1897
        push(@errorMessages, $metacat->getMessage());
1898
        push(@errorMessages, "Failed during login.\n");
1899

    
1900
    } else {
1901
	#Able to login - try to delete the file	
1902

    
1903
	my $parser;
1904
	my @fileArray;
1905
	my $httpMessage;
1906
	my $xmldoc;
1907
	my $doc;
1908
	my $pushDoc;
1909
	my $alreadyInArray;
1910
	my $findType;
1911
        my $node;
1912
	my $response; 
1913
	my $element;
1914

    
1915
	push (@fileArray, $docid);
1916
	$parser = XML::LibXML->new();
1917

    
1918
        $httpMessage = $metacat->read($docid);
1919
	$doc = $httpMessage->content();	
1920
	$xmldoc = $parser->parse_string($doc);
1921

    
1922
	if ($xmldoc eq "") {
1923
	    $error ="Error in parsing the eml document";
1924
	    push(@errorMessages, $error);
1925
	} else {
1926

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

    
1984
	$$templateVars{'function'} = "deleted";
1985
	$$templateVars{'section'} = "Deletion Status";
1986
	$template->process( $responseTemplate, $templateVars);
1987
    }
1988
}
1989

    
1990

    
1991
################################################################################
1992
# 
1993
# Do data validation and send the data to confirm data template.
1994
#
1995
################################################################################
1996
sub toConfirmData{
1997
    # Check if any invalid parameters
1998
 
1999
    my $invalidParams;
2000
    if (! $error) {
2001
	$invalidParams = validateParameters(0);
2002
	if (scalar(@$invalidParams)) {
2003
	    $$templateVars{'status'} = 'failure';
2004
	    $$templateVars{'invalidParams'} = $invalidParams;
2005
	    $error = 1;
2006
	}
2007
    }
2008

    
2009
    if (! $error) {
2010
	# If no errors, then print out data in confirm Data template
2011

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

    
2210
	$$templateVars{'section'} = "Confirm Data";
2211
	$template->process( $confirmDataTemplate, $templateVars);
2212

    
2213
    } else{	
2214
	# Errors from validation function. print the errors out using the response template
2215
	if (scalar(@errorMessages)) {
2216
	    $$templateVars{'status'} = 'failure';
2217
	    $$templateVars{'errorMessages'} = \@errorMessages;
2218
	    $error = 1;
2219
	}
2220
        # Create our HTML response and send it back
2221
	$$templateVars{'function'} = "submitted";
2222
	$$templateVars{'section'} = "Submission Status";
2223
	$template->process( $responseTemplate, $templateVars);
2224
    }
2225
}
2226

    
2227

    
2228
################################################################################
2229
# 
2230
# From confirm Data template - user wants to make some changes.
2231
#
2232
################################################################################
2233
sub confirmDataToReEntryData{
2234
    my @sortedSites;
2235
    foreach my $site (sort @sitelist) {
2236
        push(@sortedSites, $site);
2237
    }
2238

    
2239
    $$templateVars{'siteList'} = \@sortedSites;
2240
    $$templateVars{'section'} = "Re-Entry Form";
2241

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

    
2373
    $$templateVars{'form'} = 're_entry';
2374
    $template->process( $entryFormTemplate, $templateVars);
2375
}
2376

    
2377

    
2378
################################################################################
2379
# 
2380
# check if there is multiple occurence of the given tag and find its value.
2381
#
2382
################################################################################
2383

    
2384
sub findValue {
2385
    my $node = shift;
2386
    my $value = shift;
2387
    my $result;
2388
    my $tempNode;
2389

    
2390
    $result = $node->findnodes("./$value");
2391
    if($result->size > 1){
2392
	errMoreThanOne("$value");
2393
    } else {
2394
	foreach $tempNode ($result->get_nodelist){
2395
	    #print $tempNode->nodeName().":".$tempNode->textContent();
2396
	    #print "\n";
2397
	    return $tempNode->textContent();
2398
	}
2399
    }
2400
}
2401

    
2402

    
2403
################################################################################
2404
# 
2405
# check if given tags has any children. if not return the value
2406
#
2407
################################################################################
2408
sub findValueNoChild {
2409
    my $node = shift;
2410
    my $value = shift;
2411
    my $tempNode;
2412
    my $childNodes;
2413
    my $result;
2414
    my $error;
2415

    
2416
    $result = $node->findnodes("./$value");
2417
	    if($result->size > 1){
2418
	   	errMoreThanOne("$value");
2419
	    } else {
2420
		foreach $tempNode ($result->get_nodelist){
2421
		    $childNodes = $tempNode->childNodes;
2422
		    if($childNodes->size() > 1){
2423
			$error ="The tag $value has children which cannot be shown using the form. Please use Morpho to edit this document";	
2424
			push(@errorMessages, $error);
2425
			#if ($DEBUG == 1){ print $error."\n";}
2426
		    }else{
2427
			#print $tempNode->nodeName().":".$tempNode->textContent();
2428
			#print "\n";
2429
			return $tempNode->textContent();
2430
		    }
2431
		}
2432
	    }
2433
}
2434

    
2435

    
2436
################################################################################
2437
# 
2438
# check if given tags are children of given node.
2439
#
2440
################################################################################
2441
sub dontOccur {
2442
    my $node = shift;
2443
    my $value = shift;
2444
    my $errVal = shift;
2445

    
2446
    my $result = $node->findnodes("$value");
2447
    if($result->size > 0){
2448
	$error ="One of the following tags found: $errVal. Please use Morpho to edit this document";
2449
	push(@errorMessages, $error."\n");
2450
	#if ($DEBUG == 1){ print $error;}
2451
    } 
2452
}
2453

    
2454

    
2455
################################################################################
2456
# 
2457
# print out error for more than one occurence of a given tag
2458
#
2459
################################################################################
2460
sub errMoreThanOne {
2461
    my $value = shift;
2462
    my $error ="More than one occurence of the tag $value found. Please use Morpho to edit this document";
2463
    push(@errorMessages, $error."\n");
2464
    # if ($DEBUG == 1){ print $error;}
2465
}
2466

    
2467

    
2468
################################################################################
2469
# 
2470
# print out error for more than given number of occurences of a given tag
2471
#
2472
################################################################################
2473
sub errMoreThanN {
2474
    my $value = shift;
2475
    my $error ="More occurences of the tag $value found than that can be shown in the form. Please use Morpho to edit this document";
2476
    push(@errorMessages, $error);
2477
    #if ($DEBUG == 1){ print $error."\n";}
2478
}
2479

    
2480

    
2481
################################################################################
2482
# 
2483
# convert coord to degrees, minutes and seconds form. 
2484
#
2485
################################################################################
2486
#sub convertCoord {
2487
#    my $wx = shift;
2488
#    print $deg." ".$min." ".$sec;
2489
#    print "\n";
2490
#}
2491

    
2492

    
2493
################################################################################
2494
# 
2495
# print debugging messages to stderr
2496
#
2497
################################################################################
2498
sub debug {
2499
    my $msg = shift;
2500
    
2501
    if ($debug) {
2502
        print STDERR "$msg\n";
2503
    }
2504
}
2505

    
2506
################################################################################
2507
# 
2508
# get the list of projects
2509
#
2510
################################################################################
2511
sub getProjectList {
2512
    
2513
    #use NCEAS::AdminDB;
2514

    
2515
    #my $admindb = NCEAS::AdminDB->new();
2516
    #$admindb->connect($nceas_db, $nceas_db_user, $nceas_db_password);
2517
    #my $projects = $admindb->getProjects();
2518

    
2519
    # This block is for testing only!  Remove for production use
2520
    my @row1;
2521
    $row1[0] = 6000; $row1[1] = 'Andelman'; $row1[2] = 'Sandy'; $row1[3] = 'The very long and windy path to an apparent ecological conclusion: statistics lie';
2522
    my @row2; 
2523
    $row2[0] = 7000; $row2[1] = 'Bascompte'; $row2[2] = 'Jordi'; $row2[3] = 'Postdoctoral Fellow';
2524
    my @projects;
2525
    $projects[0] = \@row1;
2526
    $projects[1] = \@row2;
2527
    return \@projects;
2528

    
2529
    #return $projects;
2530
}
    (1-1/1)